Hunter  Krajcik

Hunter Krajcik

1672412520

Merlin: Context Sensitive Completion for OCaml in Vim and Emacs

Emacs and Vim support is provided out-of-the-box. To get editor support with Merlin in other editors, see this.

merlin completion in vim

Easy Installation With opam

If you have a working opam installation, install Merlin running the following two commands in terminal:

opam install merlin
opam user-setup install

opam-user-setup takes care of configuring Emacs and Vim to make best use of your current install. You can also configure the editor yourself, if you prefer.

Manually Building and Installing Merlin

Since version 4.0, Merlin's repository has a dedicated branch for each version of OCaml, and the branch name consists of the concatenation of OCaml major versions and minor versions. So, for instance, OCaml 4.11.* maps to branch 411. The main branch is usually synchronised with the branch compatible with the latest (almost-)released version of OCaml.

Note: if you're using an older version of OCaml (between 4.02 and 4.10), you will want to build the 3.4 branch, although it won't contain the most recent features.

Compilation

Dependencies: ocamlfind, yojson >= 2.0.0, dune >= 2.7.

dune build -p dot-merlin-reader,merlin

Note: if you want to work on Merlin, you'll want to avoid the -p merlin to build in dev mode, with some extra warnings enabled. In that case, you'll also need an extra dependency: Menhir.

Installation

If you haven't encountered any errors in the previous step, just run:

dune install -p dot-merlin-reader,merlin

You can pass an explicit prefix to Dune, using --prefix. It defaults to your current opam switch.

Editor Setup

To set up Emacs and Vim, you need to instruct them to run the appropriate script when an OCaml file is opened.

In the rest of the document, <SHARE_DIR> refers to the directory where Merlin data files are installed.

It will usually be:

  • printed by the command opam var share, if you used opam
  • "<prefix>/share" if you explicitly specified a prefix when configuring Merlin

Vim Setup

Makes sure that ocamlmerlin binary can be found in PATH.

The only setup needed is to have the following directory in the Vim runtime path (append this to your .vimrc):

:set rtp+=<SHARE_DIR>/merlin/vim

The default configuration can be seen in:

<SHARE_DIR>/merlin/vim/plugin/merlin.vim

After adding Merlin to Vim's runtime path, you will probably want to run :helptags <SHARE_DIR>/merlin/vim/doc to register Merlin documentation inside Vim.

A more comprehensive documentation can be found on the vim-from-scratch wiki.

Emacs Setup

Manual Setup

Merlin comes with an Emacs library (file: emacs/merlin.el) that implements a minor-mode that is supposed to be used on top of tuareg-mode.

Just add the following to your .emacs file:

(push "<SHARE_DIR>/emacs/site-lisp" load-path) ; directory containing merlin.el
(setq merlin-command "<BIN_DIR>/ocamlmerlin")  ; needed only if ocamlmerlin not already in your PATH
(autoload 'merlin-mode "merlin" "Merlin mode" t)
(add-hook 'tuareg-mode-hook #'merlin-mode)
(add-hook 'caml-mode-hook #'merlin-mode)
;; Uncomment these lines if you want to enable integration with the corresponding packages
;; (require 'merlin-iedit)       ; iedit.el editing of occurrences
;; (require 'merlin-company)     ; company.el completion
;; (require 'merlin-ac)          ; auto-complete.el completion

More comprehensive documentation can be found on the emacs-from-scratch wiki.

Setup via package.el

An installable core Merlin package is available via MELPA, along with further small integration packages merlin-company, merlin-iedit, and merlin-ac, which users can install according to their needs.

Having installed the required packages, the following code in your Emacs startup file is sufficient:

(setq merlin-command "<BIN_DIR>/ocamlmerlin")  ; needed only if ocamlmerlin not already in your PATH
(add-hook 'tuareg-mode-hook #'merlin-mode)
(add-hook 'caml-mode-hook #'merlin-mode)
;; Uncomment these lines if you want to enable integration with the corresponding packages
;; (require 'merlin-iedit)       ; iedit.el editing of occurrences
;; (require 'merlin-company)     ; company.el completion
;; (require 'merlin-ac)          ; auto-complete.el completion

Other Editors

Merlin only supports Vim and Emacs out-of-the-box. This section describes shortly how to get Merlin-based editor support in other editors.

Visual Studio Code

OCaml has official support for Visual Studio Code through an extension called "OCaml Platform," available in the Visual Studio Marketplace. Project source is available here. Note that it requires OCaml-LSP, an official Language Server Protocol(LSP) implementation for OCaml based on Merlin. It can be installed by running opam install ocaml-lsp-server.

Editors Without Official Support

Consider using OCaml-LSP along with your editor's plugin for LSP if there is one.

The wiki also contains pages for:

External contributors have implemented modes for more editors:

Merlin as a library

Merlin can also be used as a library. Some projects already rely on this:

  • OCaml LSP - The official OCaml's Language Server Protocol implementation

If you're building editor tools, you might also want to use Merlin as a library!

Note, however, that Merlin's public API is not stable, and we don't guarantee backward-compatibility between releases. If you're a Merlin user and depend on our public API, we recommend that you contact us or open an issue.

Next Steps

To use Merlin with a multi-file project, it is necessary to have a .merlin file, unless your project is built using Dune. Note that, in a project using Dune, user-created .merlin files will take precedence over the configuration provided by Dune to Merlin.

Read more in the wiki to learn how to make full use of Merlin in your projects.

Development of Merlin

Most of the development happens through the GitHub page.

The mailing list welcomes general questions and discussions.

Merlin Labels

Area/Emacs: Related to Emacs

Area/Vim: Related to Vim

Kind/Bug: This issue describes a problem.

Kind/Docs: This issue describes a documentation change.

Kind/Feature-Request: Solving this issue requires implementing a new feature.

Kind/To-discuss: Discussion needed to converge on a solution, often aesthetic. See mailing list for discussion.

Status/0-More-info-needed: More information is needed before this issue can be triaged.

Status/0-Triage: This issue needs triaging.

Status/1-Acknowledged: This issue has been triaged and is being investigated.

Status/2-Regression: Known workaround to be applied and tested.

Status/3-Fixed-need-test: This issue has been fixed and needs checking.

Status/4-Fixed: This issue has been fixed!

Status/5-Awaiting-feedback: This issue requires feedback on a previous fix.

You can see current areas of development in our Merlin Project Roadmaps that we keep up to date.

Contributing to Merlin

Merlin needs your help and contributions!

Reporting Issues

When you encounter an issue, please report it with as much detail as possible. A thorough bug report is always appreciated :)

Check that our issue database doesn't already include that problem/suggestion. You can click "subscribe" on issues to follow their progress and updates.

When reporting issues, please include:

  • Steps to reproduce the problem, if possible with some code triggering the issue
  • Version of the tools you are using: operating system, editor, OCaml

Try to be as specific as possible:

  • Avoid generic phrasing such as "doesn't work." Explain what is happening (editor is freezing, you got an error message, the answer is not what was expected, etc.).
  • Include the content of error messages if there are any.

If it seems relevant, also include information about your development environment:

  • The opam version and switch in use
  • Other toolchains involved (OCaml flavors, Cygwin, C compiler, shell, ...)
  • How the editor was setup

Pull Requests

Found a bug and know how to fix it? Or have a feature you can implement directly? We appreciate pull requests to improve Merlin. Please note: any significant fix should start life as an issue first.

Documentation and Wiki

Help is greatly appreciated, the wiki needs love.

If the wiki didn't cover a topic and you found out the answer, updating the page or pointing out the issue will be very useful for future users.

Discussing With Other Merlin Users and Contributors

Together with commenting on issues with direct feedback and relevant information, we use the mailing list to discuss ideas and current designs/implementations. User input helps us to converge on solutions, especially those for aesthetic and user-oriented topics.

List of Contributors

We would like to thank all people who contributed to Merlin.

Main collaborators:

Contributors:

Sponsoring and Donations

We would like to thank Jane Street for sponsoring and OCaml Labs for providing support and management.

And many thanks to our Bountysource backers.

Other Acknowledgements

Distribution and configuration:

Support for other editors:

Download Details:

Author: Ocaml
Source Code: https://github.com/ocaml/merlin 
License: MIT license

#atom #vim #emacs #ocaml 

What is GEEK

Buddha Community

Merlin: Context Sensitive Completion for OCaml in Vim and Emacs
Hunter  Krajcik

Hunter Krajcik

1672412520

Merlin: Context Sensitive Completion for OCaml in Vim and Emacs

Emacs and Vim support is provided out-of-the-box. To get editor support with Merlin in other editors, see this.

merlin completion in vim

Easy Installation With opam

If you have a working opam installation, install Merlin running the following two commands in terminal:

opam install merlin
opam user-setup install

opam-user-setup takes care of configuring Emacs and Vim to make best use of your current install. You can also configure the editor yourself, if you prefer.

Manually Building and Installing Merlin

Since version 4.0, Merlin's repository has a dedicated branch for each version of OCaml, and the branch name consists of the concatenation of OCaml major versions and minor versions. So, for instance, OCaml 4.11.* maps to branch 411. The main branch is usually synchronised with the branch compatible with the latest (almost-)released version of OCaml.

Note: if you're using an older version of OCaml (between 4.02 and 4.10), you will want to build the 3.4 branch, although it won't contain the most recent features.

Compilation

Dependencies: ocamlfind, yojson >= 2.0.0, dune >= 2.7.

dune build -p dot-merlin-reader,merlin

Note: if you want to work on Merlin, you'll want to avoid the -p merlin to build in dev mode, with some extra warnings enabled. In that case, you'll also need an extra dependency: Menhir.

Installation

If you haven't encountered any errors in the previous step, just run:

dune install -p dot-merlin-reader,merlin

You can pass an explicit prefix to Dune, using --prefix. It defaults to your current opam switch.

Editor Setup

To set up Emacs and Vim, you need to instruct them to run the appropriate script when an OCaml file is opened.

In the rest of the document, <SHARE_DIR> refers to the directory where Merlin data files are installed.

It will usually be:

  • printed by the command opam var share, if you used opam
  • "<prefix>/share" if you explicitly specified a prefix when configuring Merlin

Vim Setup

Makes sure that ocamlmerlin binary can be found in PATH.

The only setup needed is to have the following directory in the Vim runtime path (append this to your .vimrc):

:set rtp+=<SHARE_DIR>/merlin/vim

The default configuration can be seen in:

<SHARE_DIR>/merlin/vim/plugin/merlin.vim

After adding Merlin to Vim's runtime path, you will probably want to run :helptags <SHARE_DIR>/merlin/vim/doc to register Merlin documentation inside Vim.

A more comprehensive documentation can be found on the vim-from-scratch wiki.

Emacs Setup

Manual Setup

Merlin comes with an Emacs library (file: emacs/merlin.el) that implements a minor-mode that is supposed to be used on top of tuareg-mode.

Just add the following to your .emacs file:

(push "<SHARE_DIR>/emacs/site-lisp" load-path) ; directory containing merlin.el
(setq merlin-command "<BIN_DIR>/ocamlmerlin")  ; needed only if ocamlmerlin not already in your PATH
(autoload 'merlin-mode "merlin" "Merlin mode" t)
(add-hook 'tuareg-mode-hook #'merlin-mode)
(add-hook 'caml-mode-hook #'merlin-mode)
;; Uncomment these lines if you want to enable integration with the corresponding packages
;; (require 'merlin-iedit)       ; iedit.el editing of occurrences
;; (require 'merlin-company)     ; company.el completion
;; (require 'merlin-ac)          ; auto-complete.el completion

More comprehensive documentation can be found on the emacs-from-scratch wiki.

Setup via package.el

An installable core Merlin package is available via MELPA, along with further small integration packages merlin-company, merlin-iedit, and merlin-ac, which users can install according to their needs.

Having installed the required packages, the following code in your Emacs startup file is sufficient:

(setq merlin-command "<BIN_DIR>/ocamlmerlin")  ; needed only if ocamlmerlin not already in your PATH
(add-hook 'tuareg-mode-hook #'merlin-mode)
(add-hook 'caml-mode-hook #'merlin-mode)
;; Uncomment these lines if you want to enable integration with the corresponding packages
;; (require 'merlin-iedit)       ; iedit.el editing of occurrences
;; (require 'merlin-company)     ; company.el completion
;; (require 'merlin-ac)          ; auto-complete.el completion

Other Editors

Merlin only supports Vim and Emacs out-of-the-box. This section describes shortly how to get Merlin-based editor support in other editors.

Visual Studio Code

OCaml has official support for Visual Studio Code through an extension called "OCaml Platform," available in the Visual Studio Marketplace. Project source is available here. Note that it requires OCaml-LSP, an official Language Server Protocol(LSP) implementation for OCaml based on Merlin. It can be installed by running opam install ocaml-lsp-server.

Editors Without Official Support

Consider using OCaml-LSP along with your editor's plugin for LSP if there is one.

The wiki also contains pages for:

External contributors have implemented modes for more editors:

Merlin as a library

Merlin can also be used as a library. Some projects already rely on this:

  • OCaml LSP - The official OCaml's Language Server Protocol implementation

If you're building editor tools, you might also want to use Merlin as a library!

Note, however, that Merlin's public API is not stable, and we don't guarantee backward-compatibility between releases. If you're a Merlin user and depend on our public API, we recommend that you contact us or open an issue.

Next Steps

To use Merlin with a multi-file project, it is necessary to have a .merlin file, unless your project is built using Dune. Note that, in a project using Dune, user-created .merlin files will take precedence over the configuration provided by Dune to Merlin.

Read more in the wiki to learn how to make full use of Merlin in your projects.

Development of Merlin

Most of the development happens through the GitHub page.

The mailing list welcomes general questions and discussions.

Merlin Labels

Area/Emacs: Related to Emacs

Area/Vim: Related to Vim

Kind/Bug: This issue describes a problem.

Kind/Docs: This issue describes a documentation change.

Kind/Feature-Request: Solving this issue requires implementing a new feature.

Kind/To-discuss: Discussion needed to converge on a solution, often aesthetic. See mailing list for discussion.

Status/0-More-info-needed: More information is needed before this issue can be triaged.

Status/0-Triage: This issue needs triaging.

Status/1-Acknowledged: This issue has been triaged and is being investigated.

Status/2-Regression: Known workaround to be applied and tested.

Status/3-Fixed-need-test: This issue has been fixed and needs checking.

Status/4-Fixed: This issue has been fixed!

Status/5-Awaiting-feedback: This issue requires feedback on a previous fix.

You can see current areas of development in our Merlin Project Roadmaps that we keep up to date.

Contributing to Merlin

Merlin needs your help and contributions!

Reporting Issues

When you encounter an issue, please report it with as much detail as possible. A thorough bug report is always appreciated :)

Check that our issue database doesn't already include that problem/suggestion. You can click "subscribe" on issues to follow their progress and updates.

When reporting issues, please include:

  • Steps to reproduce the problem, if possible with some code triggering the issue
  • Version of the tools you are using: operating system, editor, OCaml

Try to be as specific as possible:

  • Avoid generic phrasing such as "doesn't work." Explain what is happening (editor is freezing, you got an error message, the answer is not what was expected, etc.).
  • Include the content of error messages if there are any.

If it seems relevant, also include information about your development environment:

  • The opam version and switch in use
  • Other toolchains involved (OCaml flavors, Cygwin, C compiler, shell, ...)
  • How the editor was setup

Pull Requests

Found a bug and know how to fix it? Or have a feature you can implement directly? We appreciate pull requests to improve Merlin. Please note: any significant fix should start life as an issue first.

Documentation and Wiki

Help is greatly appreciated, the wiki needs love.

If the wiki didn't cover a topic and you found out the answer, updating the page or pointing out the issue will be very useful for future users.

Discussing With Other Merlin Users and Contributors

Together with commenting on issues with direct feedback and relevant information, we use the mailing list to discuss ideas and current designs/implementations. User input helps us to converge on solutions, especially those for aesthetic and user-oriented topics.

List of Contributors

We would like to thank all people who contributed to Merlin.

Main collaborators:

Contributors:

Sponsoring and Donations

We would like to thank Jane Street for sponsoring and OCaml Labs for providing support and management.

And many thanks to our Bountysource backers.

Other Acknowledgements

Distribution and configuration:

Support for other editors:

Download Details:

Author: Ocaml
Source Code: https://github.com/ocaml/merlin 
License: MIT license

#atom #vim #emacs #ocaml 

YouCompleteMe: A Code Completion Engine for Vim

YouCompleteMe: a code-completion engine for Vim

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 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.

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.

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
  • 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

Here's an explanation of what happens 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

YCM also provides semantic IDE-like features in a number of languages, including:

For example, here's a demo of signature help:

Signature Help Early Demo

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 with FixIt
  • Not shown in the GIF is GoToImplementation and GoToType for servers that support it.

YouCompleteMe GIF subcommands demo

And here's some documentation being shown in a hover popup, automatically and manually:

hover demo

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.

Installation

Requirements

Supported Vim Versions

Our policy is to support the Vim version that's in the latest LTS of Ubuntu. That's currently Ubuntu 20.04 which contains vim-nox at v8.1.2269.

Vim must have a working Python 3.6 runtime, compiled with --enable-shared (or --enable-framework). You can check with :py3 import sys; print( sys.version ).

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 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:

CompilerCurrent Min
GCC8
Clang7
MSVC15.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 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 (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:

  • Option 1: Installing a Vim that supports Python 3
brew install vim
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

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 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. 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 and add --cs-completer when calling install.py.
  • Go support: install Go and add --go-completer when calling install.py.
  • JavaScript and TypeScript support: install Node.js and npm and add --ts-completer when calling install.py.
  • Rust support: add --rust-completer when calling install.py.
  • Java support: install JDK 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 20.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 default-jdk npm
  • Compile YCM
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all

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 (don't worry, it's easy).

Install YouCompleteMe with Vundle.

Remember: YCM is a plugin with a compiled component. If you update YCM using Vundle and the ycm_core library APIs have changed (happens rarely), YCM will notify you to recompile it. You should then rerun the install process.

Install development tools, 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 and add --cs-completer when calling install.py.
  • Go support: install Go and add --go-completer when calling install.py.
  • JavaScript and TypeScript support: install Node.js and npm and add --ts-completer when calling install.py.
  • Rust support: add --rust-completer when calling install.py.
  • Java support: install JDK 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

Quick start, installing all completers

cd YouCompleteMe
python3 install.py --all

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 are available.

Add the following line to your vimrc 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.

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. 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. Add CMake executable to the PATH environment variable.
  • Build Tools for Visual Studio 2019. 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.
  • Go support: install Go and add --go-completer when calling install.py.
  • JavaScript and TypeScript support: install Node.js and npm and add --ts-completer when calling install.py.
  • Rust support: add --rust-completer when calling install.py.
  • Java support: install JDK 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.

FreeBSD/OpenBSD

Quick start, installing all completers

  • Install YCM plugin via Vundle
  • Install CMake
pkg install cmake
  • Install xbuild, go, node and npm
  • Compile YCM
cd ~/.vim/bundle/YouCompleteMe
python3 install.py --all

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.

NOTE: OpenBSD / FreeBSD are not officially supported platforms by YCM.

Make sure you have a supported Vim version with Python 3 support, and a supported compiler and CMake, perhaps:

pkg install 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.

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

If the python executable is not present, or the default python is not the one that should be compiled against, specify the python interpreter explicitly:

python3 install.py --clangd-completer

The following additional language support options are available:

  • C# support: install Mono and add --cs-completer when calling ./install.py.
  • Go support: install Go and add --go-completer when calling ./install.py.
  • JavaScript and TypeScript support: install Node.js and npm and add --ts-completer when calling install.py.
  • Rust support: add --rust-completer when calling ./install.py.
  • Java support: install JDK 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.

Full Installation Guide

The full installation guide 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.)
  • 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)
  • Reference finding (GoToReferences)
  • Renaming symbols (RefactorRename <new name>)
  • Code formatting (Format)

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)
  • Management of OmniSharp-Roslyn server instance
  • Renaming symbols (RefactorRename <new name>)
  • 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 <new name>)

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)
  • View documentation comments for identifiers (GetDoc)
  • Type information for identifiers (GetType)
  • Code formatting (Format)
  • Management of gopls server instance

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 (FixIt)
  • Renaming symbols (RefactorRename <new name>)
  • Code formatting (Format)
  • Organize imports (OrganizeImports)
  • Management of TSServer server instance

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)
  • Type information for identifiers (GetType)
  • Renaming symbols (RefactorRename <new name>)
  • Code formatting (Format)
  • Management of rust-analyzer server instance

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 <new name>)
  • Code formatting (Format)
  • Organize imports (OrganizeImports)
  • Detection of java projects
  • Execute custom server command (ExecuteCommand <args>)
  • Management of jdt.ls server instance

User Guide

General Usage

If the offered completions are too broad, keep typing characters; YCM will continue refining the offered completions based on your input.

Filtering is "smart-case" 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:

matchesfoofôofOofÔ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 backwards. Note that if you're using console Vim (that is, not gvim or MacVim) then it's likely that the Shift-TAB binding will not work because the console will not pass it to Vim. You can remap the keys; see the Options section below.

Knowing a little bit about how YCM works internally will prevent confusion. YCM has several completion engines: an identifier-based completer that collects all of the identifiers in the current file and other files you visit (and your tags files) and searches them when you type (identifiers are put into per-filetype groups).

There are also several semantic engines in YCM. There 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 that has the vast majority of YCM logic and functionality. The server is started and stopped automatically as you start and stop Vim.

Completion String Ranking

The subsequence filter removes any completions that do not match the input, but then the sorting system kicks in. It's actually very complicated and uses lots of factors, but suffice it to say that "word boundary" (WB) subsequence character matches are "worth" more than non-WB matches. In effect, this means given an input of "gua", the completion "getUserAccount" would be ranked higher in the list than the "Fooguxa" completion (both of which are subsequence matches). A word-boundary character are all capital characters, characters preceded by an underscore and the first letter character in the completion string.

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. There is no key binding to clear the popup.

For more details on this feature and a few demos, check out the PR that proposed it.

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 <Plug>(YCMToggleSignatureHelp) for this.

For example, to hide/show the signature help popup by pressing Ctrl+l in insert mode: imap <silent> <C-l> <Plug>(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.

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.

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.17 (Intel, armv7-a, aarch64) - built on ubuntu 18.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 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-compelter --system-libclang

Please note that if using custom clangd or libclang it must match the version that YCM requires. Currently YCM requires clang 13.0.0.

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 which can be used to provide compile flags to clang:

Option 1: Use a compilation database

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. 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.
  • If using GNU make, check out compiledb or Bear.
  • 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.

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 which implements a trivial function which, given the file name as 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 <language> 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. 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 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

Ensure that you have enabled the Java completer. See the installation guide for details.

Create a project file (gradle or maven) file in the root directory of your Java project, by following the instructions below.

(Optional) Configure the LSP server. The jdt.ls configuration options can be found in their codebase.

If you previously used Eclim or Syntastic for Java, disable them for Java.

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, maven projects and gradle projects.

NOTE: Our recommendation is to use either maven or gradle projects.

Diagnostic display - Syntastic

The native support for Java includes YCM's native realtime 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 = []

Diagnostic display - Eclim

The native support for Java includes YCM's native realtime 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.

Eclipse Projects

Eclipse style projects require two files: .project and .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 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:

  <classpathentry kind="lib" path="/path/to/external/jar" />
  <classpathentry kind="lib" path="/path/to/external/java/source" />

It may also be necessary to change the directory in which your source files are located (paths are relative to the .project file itself):

  <classpathentry kind="src" output="target/classes" path="path/to/src/" />

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 in the root of the project. Once again a simple pom.xml can be found in ycmd source.

The format of pom.xml 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. Again, there is a trivial example in ycmd's tests.

The format of build.gradle 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.

Some users have experienced issues with their jdt.ls when using the Groovy language for their build.gradle. As such, try using 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 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.

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 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:

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.

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 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:

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.

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 insert 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.

Configuring through Vim options

You may find 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.

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 for details). The install script takes care of installing the Rust source code, so no configuration is necessary.

rust-analyzer supports a myriad of options. These are configured using LSP configuration, and are documented here.

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 handful of undocumented options for which the source code is the only reference.

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 setup YCM with Tern are available on the wiki.

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 and npm and call the install.py script with the --ts-completer flag.

TSServer relies on the jsconfig.json file for JavaScript and the tsconfig.json file 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
    }
}

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 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 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': 'rust',
  \     'cmdline': [ 'ra_lsp_server' ],
  \     'filetypes': [ 'rust' ],
  \     'project_root_files': [ 'Cargo.toml' ]
  \   },
  \   {
  \     'name': 'godot',
  \     'filetypes': [ 'gdscript' ],
  \     'port': 6008,
  \     'project_root_files': [ 'project.godot' ]
  \    }
  \ ]

Each dictionary contains the following keys:

  • name (string, mandatory): When configuring a LSP server the value of the name key will be used as the kwargs[ 'language' ]. Can be anything you like.
  • filetypes (list of string, mandatory): List of Vim filetypes this server should be used for.
  • project_root_files (list of string, optional): List of filenames to search for when trying to determine the project root.
  • cmdline (list of string, optional): If supplied, the server is started with this command line (each list element is a command line word). Typically, the server should be started with STDIO communication. If not supplied, port must be supplied.
  • port (number, optional): If supplied, ycmd will connect to the server at localhost:<port> using TCP (remote servers are not supported).
  • capabilities (dict, optional): If supplied, this is a dictionary that is merged with the LSP client capabilities reported to the language server. This can be used to enable or disable certain features, such as the support for configuration sections (workspace/configuration).

See the 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.

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 complete 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 <path-to-your-project> -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.

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.

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 <F5> :YcmForceCompileAndDiagnostics<CR> in your vimrc). Calling this command will force YCM to immediately recompile your file and display any new diagnostics it encounters. Do note that recompilation with this command may take a while and during this time the Vim GUI will be blocked.

YCM will display a short diagnostic message when you move your cursor to the line with the error. You can get a detailed diagnostic message with the <leader>d key mapping (can be changed in the options) YCM provides when your cursor is on the line with the diagnostic.

You can also see the full diagnostic message for all the diagnostics in the current file in Vim's locationlist, which can be opened with the :lopen and :lclose commands (make sure you have set let g:ycm_always_populate_location_list = 1 in your vimrc). A good way to toggle the display of the locationlist with a single key mapping is provided by another (very small) Vim plugin called ListToggle (which also makes it possible to change the height of the locationlist window), also written by yours truly.

Diagnostic Highlighting Groups

You can change the styling for the highlighting groups YCM uses. For the signs in the Vim gutter, the relevant groups are:

  • YcmErrorSign, which falls back to group SyntasticErrorSign and then error if they exist
  • YcmWarningSign, which falls back to group SyntasticWarningSign and then todo if they exist

You can also style the line that has the warning/error with these groups:

  • YcmErrorLine, which falls back to group SyntasticErrorLine if it exists
  • YcmWarningLine, which falls back to group SyntasticWarningLine if it exists

Note that the line highlighting groups only work when 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

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

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 <something> <Plug>(YCMFindSymbolInWorkspace)
  • nmap <something> <Plug>(YCMFindSymbolInDocument)

e.g.

  • nmap <leader>yfw <Plug>(YCMFindSymbolInWorkspace)
  • nmap <leader>yfd <Plug>(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 <Esc> 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.

While the popup is open, the following keys are intercepted:

  • <C-j>, <Down>, <C-n>, <Tab> - select the next item
  • <C-k>, <Up>, <C-p>, <S-Tab> - select the previous item
  • <PageUp>, <kPageUp> - jump up one screenful of items
  • <PageDown>, <kPageDown> - jump down one screenful of items
  • <Home>, <kHome> - jump to first item
  • <End>, <kEnd> - jump to last item
  • <CR> - jump to the selected item
  • <C-c> cancel/dismiss the popup

The search is also cancelled if you leave the prompt buffer window at any time, so you can use window commands <C-w>... for example.

Closing the popup

NOTE: Pressing <Esc> does not close the popup - you must use Ctrl-c for that, or use a window command (e.g. <Ctrl-w>j) or the mouse to leave the prompt buffer window.

Commands

The :YcmRestartServer command

If the ycmd completion server suddenly stops for some reason, you can restart it with this command.

The :YcmForceCompileAndDiagnostics command

Calling this command will force YCM to immediately recompile your file and display any new diagnostics it encounters. Do note that recompilation with this command may take a while and during this time the Vim GUI will be blocked.

You may want to map this command to a key; try putting nnoremap <F5> :YcmForceCompileAndDiagnostics<CR> in your vimrc.

The :YcmDiags command

Calling this command will fill Vim's locationlist with errors or warnings if any were detected in your file and then open it. If a given error or warning can be fixed by a call to :YcmCompleter FixIt, then (FixIt available) is appended to the error or warning text. See the FixIt completer subcommand for more information.

NOTE: The 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.

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, 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 <TAB> 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.

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 <leader>jd :YcmCompleter GoTo<CR> maps the <leader>jd sequence to the longer subcommand invocation.

GoTo Commands

These commands are useful for jumping around and exploring code. When moving the cursor, the subcommands add entries to Vim's jumplist so you can use CTRL-O to jump back to where you 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 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 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 long to compile but you know that you haven't made any changes since the last parse that would lead to incorrect jumps. When you're just browsing around your codebase, this command can spare you quite a bit of latency.

Supported in filetypes: c, cpp, objc, objcpp, cuda

The GoToSymbol <symbol query> 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 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

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 which 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:

    std::string s;

Invoking this command on s returns std::string => std::basic_string<char>

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 long 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.

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 on the current line. 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), the options are presented and one can be selected.

Completers which provide diagnostics may also provide trivial modifications to the source in order to correct the diagnostic. Examples include syntax errors such as missing trailing semi-colons, spurious characters, or other errors which the semantic engine can deterministically suggest corrections.

If no fix-it is available for the current line, or there is no diagnostic on the current line, this command has no effect on the current buffer. If any modifications are made, the number of changes made to the buffer is echo'd and the user may use the editor's undo command to revert.

When a diagnostic is available, and g:ycm_echo_current_diagnostic is set to 1, then the text (FixIt) is appended to the echo'd diagnostic when the completer is able to add this indication. The text (FixIt available) is also appended to the diagnostic text in the output of the :YcmDiags command for any diagnostics with available fix-its (where the completer can provide this indication).

NOTE: Causes re-parsing of the current translation unit.

Supported in filetypes: c, cpp, objc, objcpp, cuda, cs, go, java, javascript, rust, typescript

The RefactorRename <new name> subcommand

In supported file types, this command attempts to perform a semantic rename of the identifier under the cursor. This includes renaming declarations, definitions and usages of the identifier, or any other language-appropriate action. The specific behavior is defined by the semantic engine in use.

Similar to FixIt, this command applies automatic modifications to your source files. Rename operations may involve changes to multiple files, which may or may not be open in Vim buffers at the time. YouCompleteMe handles all of this for you. The behavior is described in the following section.

Supported in filetypes: c, cpp, objc, objcpp, cuda, java, javascript, python, typescript, rust, cs

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 <enter> combination to open the selected file in a new split. It is possible to customize how the quickfix window is opened by using the YcmQuickFixOpened autocommand.

The buffers are not saved automatically. That is, you must save the modified buffers manually after reviewing the changes from the quickfix list. Changes can be undone using Vim's powerful undo features (see :help undo). Note that Vim's undo is per-buffer, so to undo all changes, the undo commands must be applied in each modified buffer separately.

NOTE: While applying modifications, Vim may find files which are already open and have a swap file. The command is aborted if you select Abort or Quit in any such prompts. This leaves the Refactor operation partially complete and must be manually corrected using Vim's undo features. The quickfix list is not populated in this case. Inspect :buffers or equivalent (see :help buffers) to see the buffers that were opened by the command.

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 resolves 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 <args> 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 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:

  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:

  call youcompleteme#GetWarningCount()

The youcompleteme#GetCommandResponse( ... ) function

Run a completer subcommand and return the result as a string. This can be useful for example to display the GetGoc 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 <silent> <leader>D :call <SID>Hover()<CR>

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=<filetype> 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:


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 responses 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:

function! s:CustomizeYcmLocationWindow()
  " Move the window to the top of the screen.
  wincmd K
  " Set the window height to 5.
  5wincmd _
  " Switch back to 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 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 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

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 are 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 up front
  • 0 - Never resolve any candidates up front.
  • > 0 - Resolve up to this many candidates up front. If the number of candidates is greater than this value, no candidates are resolved.

In the later 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 are 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 <C-Space> shortcut.

If you want to just turn off the identifier completer but keep the semantic triggers, you should set g:ycm_min_num_of_chars_for_completion to a high number like 99.

Default: 1

let g:ycm_auto_trigger = 1

The g:ycm_filetype_whitelist option

This option controls for which Vim filetypes (see :h filetype) should YCM be turned on. The option value should be a Vim dictionary with keys being filetype strings (like python, cpp, etc.) and values being unimportant (the dictionary is used like a hash set, meaning that only the keys matter).

The * key is special and matches all filetypes. By default, the whitelist contains only this * key.

YCM also has a g:ycm_filetype_blacklist option that lists filetypes for which YCM shouldn't be turned on. YCM will work only in filetypes that both the whitelist and the blacklist allow (the blacklist "allows" a filetype by not having it as a key).

For example, let's assume you want YCM to work in files with the cpp filetype. The filetype should then be present in the whitelist either directly (cpp key in the whitelist) or indirectly through the special * key. It should not be present in the blacklist.

Filetypes that are blocked by the either of the lists will be completely ignored by YCM, meaning that neither the identifier-based completion engine nor the semantic engine will operate in them.

You can get the filetype of the current file in Vim with :set ft?.

Default: {'*': 1}

let g:ycm_filetype_whitelist = {'*': 1}

** 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, YCM will echo the text of the diagnostic present on the current line when you move your cursor to that line. If a FixIt is available for the current diagnostic, then (FixIt) is appended.

This option is part of the Syntastic compatibility layer; if the option is not set, YCM will fall back to the value of the g:syntastic_echo_current_error option before using this option's default.

Default: 1

let g:ycm_echo_current_diagnostic = 1

The g:ycm_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 <plug>(YCMHover) mapping, which can be used to manually trigger or hide the popup (it works like a toggle). For example:

nmap <leader>D <plug>(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.

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

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. 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.

Default: {}

The following example will do, for java filetype only:

  • Remove all error level diagnostics, and,
  • Also remove anything that contains ta<something>co
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. The format from "plain" ctags is NOT supported. Ctags needs to be called with the --fields=+l option (that's a lowercase L, not a one) because YCM needs the language:<lang> field in the tags output.

See the FAQ for pointers if YCM does not appear to read your tag files.

This option is off by default because it makes Vim slower if your tags are on a network directory.

Default: 0

let g:ycm_collect_identifiers_from_tags_files = 0

The g:ycm_seed_identifiers_with_syntax option

When this option is set to 1, YCM's identifier completer will seed its identifier database with the keywords of the programming language you're writing.

Since the keywords are extracted from the Vim syntax file for the filetype, all keywords may not be collected, depending on how the syntax file was written. Usually at least 95% of the keywords are successfully extracted.

Default: 0

let g:ycm_seed_identifiers_with_syntax = 0

The g:ycm_extra_conf_vim_data option

If you're using semantic completion for C-family files, this option might come handy; it's a way of sending data from Vim to your 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 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. 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 will keep the logfiles around after shutting down (they are deleted on shutdown by default).

To see where the logfiles are, call :YcmDebugInfo.

Default: 0

let g:ycm_keep_logfiles = 0

The g:ycm_log_level option

The logging level that YCM and the ycmd completion server 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 <Enter> to this list.

Default: ['<TAB>', '<Down>']

let g:ycm_key_list_select_completion = ['<TAB>', '<Down>']

The g:ycm_key_list_previous_completion option

This option controls the key mappings used to select the previous completion string. Invoking any of them repeatedly cycles backwards through the completion list.

Note that one of the defaults is <S-TAB> which means Shift-TAB. That mapping will probably only work in GUI Vim (Gvim or MacVim) and not in plain console Vim because the terminal usually does not forward modifier key combinations to Vim.

Default: ['<S-TAB>', '<Up>']

let g:ycm_key_list_previous_completion = ['<S-TAB>', '<Up>']

The g:ycm_key_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 <TAB> character, or when you want to expand a snippet from UltiSnips and navigate through it.

Default: ['<C-y>']

let g:ycm_key_list_stop_completion = ['<C-y>']

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 ., -> and :: in insert mode (if semantic completion support has been compiled in). This key mapping can be used to trigger semantic completion anywhere. Useful for searching for top-level functions and classes.

Console Vim (not Gvim or MacVim) passes <Nul> to Vim when the user types <C-Space> so YCM will make sure that <Nul> is used in the map command when you're editing in console Vim, and <C-Space> in GUI Vim. This means that you can just press <C-Space> in both console and GUI Vim and YCM will do the right thing.

Setting this option to an empty string will make sure no mapping is created.

Default: <C-Space>

let g:ycm_key_invoke_completion = '<C-Space>'

The g:ycm_key_detailed_diagnostics option

This option controls the key mapping used to show the full diagnostic text when the user's cursor is on the line with the diagnostic. It basically calls :YcmShowDetailedDiagnostic.

Setting this option to an empty string will make sure no mapping is created.

Default: <leader>d

let g:ycm_key_detailed_diagnostics = '<leader>d'

The g:ycm_global_ycm_extra_conf option

Normally, YCM searches for a .ycm_extra_conf.py file for compilation flags (see the User Guide for more details on how this works). This option specifies a fallback path to a config file which is used if no .ycm_extra_conf.py is found.

You can place such a global file anywhere in your filesystem.

Default: ''

let g:ycm_global_ycm_extra_conf = ''

The g:ycm_confirm_extra_conf option

When this option is set to 1 YCM will ask once per .ycm_extra_conf.py file if it is safe to be loaded. This is to prevent execution of malicious code from a .ycm_extra_conf.py file you didn't write.

To selectively get YCM to ask/not ask about loading certain .ycm_extra_conf.py files, see the g:ycm_extra_conf_globlist option.

Default: 1

let g:ycm_confirm_extra_conf = 1

The g:ycm_extra_conf_globlist option

This option is a list that may contain several globbing patterns. If a pattern starts with a ! all .ycm_extra_conf.py files matching that pattern will be blacklisted, that is they won't be loaded and no confirmation dialog will be shown. If a pattern does not start with a ! all files matching that pattern will be whitelisted. Note that this option is not used when confirmation is disabled using g:ycm_confirm_extra_conf and that items earlier in the list will take precedence over the later ones.

Rules:

  • * matches everything
  • ? matches any single character
  • [seq] matches any character in seq
  • [!seq] matches any char not in seq

Example:

let g:ycm_extra_conf_globlist = ['~/dev/*','!~/*']
  • The first rule will match everything contained in the ~/dev directory so .ycm_extra_conf.py files from there will be loaded.
  • The second rule will match everything in the home directory so a .ycm_extra_conf.py file from there won't be loaded.
  • As the first rule takes precedence everything in the home directory excluding the ~/dev directory will be blacklisted.

NOTE: The glob pattern is first expanded with Python's os.path.expanduser() and then resolved with os.path.abspath() before being matched against the filename.

Default: []

let g:ycm_extra_conf_globlist = []

The g:ycm_filepath_completion_use_working_dir option

By default, YCM's filepath completion will interpret relative paths like ../ as being relative to the folder of the file of the currently active buffer. Setting this option will force YCM to always interpret relative paths as being relative to Vim's current working directory.

Default: 0

let g:ycm_filepath_completion_use_working_dir = 0

The g:ycm_semantic_triggers option

This option controls the character-based triggers for the various semantic completion engines. The option holds a dictionary of key-values, where the keys are Vim's filetype strings delimited by commas and values are lists of strings, where the strings are the triggers.

Setting key-value pairs on the dictionary adds semantic triggers to the internal default set (listed below). You cannot remove the default triggers, only add new ones.

A "trigger" is a sequence of one or more characters that trigger semantic completion when typed. For instance, C++ (cpp filetype) has . listed as a trigger. So when the user types foo., the semantic engine will trigger and serve foo's list of member functions and variables. Since C++ also has -> listed as a trigger, the same thing would happen when the user typed foo->.

It's also possible to use a regular expression as a trigger. You have to prefix your trigger with re! to signify it's a regex trigger. For instance, re!\w+\. would only trigger after the \w+\. regex matches.

NOTE: The regex syntax is NOT Vim's, it's Python's.

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 lagginess if the omnifunc is slow.

Default: 1

let g:ycm_cache_omnifunc = 1

The g:ycm_use_ultisnips_completer option

By default, YCM will query the UltiSnips plugin for possible completions of snippet triggers. This option can turn that behavior off.

Default: 1

let g:ycm_use_ultisnips_completer = 1

The g:ycm_goto_buffer_command option

Defines where GoTo* commands result should be opened. Can take one of the following values: 'same-buffer', '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 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 repo.

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. This option is reserved, meaning that while signature help support remains experimental, its values and meaning may change and it may be removed in a future version.

Default: 0

" Disable signature help
let g:ycm_disable_signature_help = 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.

Default: 1

let g:ycm_update_diagnostics_in_insert_mode = 1

FAQ

The FAQ section has been moved to the wiki.

Contributor Code of Conduct

Please note that this project is released with a Contributor Code of Conduct. 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 or use the ycm-users mailing list.

If you have bug reports or feature suggestions, please use the issue tracker. Before you do, please carefully read 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 https://ycm-core.github.io/YouCompleteMe/.

The author's homepage is https://val.markovic.io.

Please do NOT go to #vim on freenode for support. Please contact the YouCompleteMe maintainers directly using the contact details.

License

This software is licensed under the GPL v3 license. © 2015-2018 YouCompleteMe contributors

Sponsorship

If you like YCM so much that you're wiling 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):

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 family with Trustees of Greyhound Rescue Wales.

Author: ycm-core
Source Code: https://github.com/ycm-core/YouCompleteMe
License: GPL-3.0 License

#python #vim 

Vincent Lab

Vincent Lab

1605176204

Why I Think You Should Learn Vim as a Developer

In this video, I’ll be showing you why I think it’s good to know Vim as a Developer.

#vim #vim editor #text editor #what is vim #speed,2x dev #vim for node.js

Skye  Torp

Skye Torp

1625317980

Emacs, Doom, Vim, Lisp & Games - with Henrik Lissner, Emacs Doom Creator

An interview with Henrik Lissner, the creator of Emacs Doom.

#emacs #doom #vim #lisp & games

Grape: An Opinionated Framework for Creating REST-like APIs in Ruby.

What is Grape?

Grape is a REST-like API framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs. It has built-in support for common conventions, including multiple formats, subdomain/prefix restriction, content negotiation, versioning and much more.

Stable Release

You're reading the documentation for the next release of Grape, which should be 1.7.0. Please read UPGRADING when upgrading from a previous version. The current stable release is 1.6.2.

Project Resources

Grape for Enterprise

Available as part of the Tidelift Subscription.

The maintainers of Grape are working with Tidelift to deliver commercial support and maintenance. Save time, reduce risk, and improve code health, while paying the maintainers of Grape. Click here for more details.

Installation

Ruby 2.4 or newer is required.

Grape is available as a gem, to install it run:

bundle add grape

Basic Usage

Grape APIs are Rack applications that are created by subclassing Grape::API. Below is a simple example showing some of the more common features of Grape in the context of recreating parts of the Twitter API.

module Twitter
  class API < Grape::API
    version 'v1', using: :header, vendor: 'twitter'
    format :json
    prefix :api

    helpers do
      def current_user
        @current_user ||= User.authorize!(env)
      end

      def authenticate!
        error!('401 Unauthorized', 401) unless current_user
      end
    end

    resource :statuses do
      desc 'Return a public timeline.'
      get :public_timeline do
        Status.limit(20)
      end

      desc 'Return a personal timeline.'
      get :home_timeline do
        authenticate!
        current_user.statuses.limit(20)
      end

      desc 'Return a status.'
      params do
        requires :id, type: Integer, desc: 'Status ID.'
      end
      route_param :id do
        get do
          Status.find(params[:id])
        end
      end

      desc 'Create a status.'
      params do
        requires :status, type: String, desc: 'Your status.'
      end
      post do
        authenticate!
        Status.create!({
          user: current_user,
          text: params[:status]
        })
      end

      desc 'Update a status.'
      params do
        requires :id, type: String, desc: 'Status ID.'
        requires :status, type: String, desc: 'Your status.'
      end
      put ':id' do
        authenticate!
        current_user.statuses.find(params[:id]).update({
          user: current_user,
          text: params[:status]
        })
      end

      desc 'Delete a status.'
      params do
        requires :id, type: String, desc: 'Status ID.'
      end
      delete ':id' do
        authenticate!
        current_user.statuses.find(params[:id]).destroy
      end
    end
  end
end

Mounting

All

By default Grape will compile the routes on the first route, it is possible to pre-load routes using the compile! method.

Twitter::API.compile!

This can be added to your config.ru (if using rackup), application.rb (if using rails), or any file that loads your server.

Rack

The above sample creates a Rack application that can be run from a rackup config.ru file with rackup:

run Twitter::API

(With pre-loading you can use)

Twitter::API.compile!
run Twitter::API

And would respond to the following routes:

GET /api/statuses/public_timeline
GET /api/statuses/home_timeline
GET /api/statuses/:id
POST /api/statuses
PUT /api/statuses/:id
DELETE /api/statuses/:id

Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.

ActiveRecord without Rails

If you want to use ActiveRecord within Grape, you will need to make sure that ActiveRecord's connection pool is handled correctly.

Rails 4

The easiest way to achieve that is by using ActiveRecord's ConnectionManagement middleware in your config.ru before mounting Grape, e.g.:

use ActiveRecord::ConnectionAdapters::ConnectionManagement

Rails 5+

Use otr-activerecord as follows:

use OTR::ActiveRecord::ConnectionManagement

Alongside Sinatra (or other frameworks)

If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using Rack::Cascade:

# Example config.ru

require 'sinatra'
require 'grape'

class API < Grape::API
  get :hello do
    { hello: 'world' }
  end
end

class Web < Sinatra::Base
  get '/' do
    'Hello world.'
  end
end

use Rack::Session::Cookie
run Rack::Cascade.new [Web, API]

Note that order of loading apps using Rack::Cascade matters. The grape application must be last if you want to raise custom 404 errors from grape (such as error!('Not Found',404)). If the grape application is not last and returns 404 or 405 response, cascade utilizes that as a signal to try the next app. This may lead to undesirable behavior showing the wrong 404 page from the wrong app.

Rails

Place API files into app/api. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory for Twitter::API should be app/api/twitter/api.rb.

Modify config/routes:

mount Twitter::API => '/'

Rails < 5.2

Modify application.rb:

config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

See below for additional code that enables reloading of API changes in development.

Rails 6.0

For Rails versions greater than 6.0.0.beta2, Zeitwerk autoloader is the default for CRuby. By default Zeitwerk inflects api as Api instead of API. To make our example work, you need to uncomment the lines at the bottom of config/initializers/inflections.rb, and add API as an acronym:

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'API'
end

Modules

You can mount multiple API implementations inside another one. These don't have to be different versions, but may be components of the same API.

class Twitter::API < Grape::API
  mount Twitter::APIv1
  mount Twitter::APIv2
end

You can also mount on a path, which is similar to using prefix inside the mounted API itself.

class Twitter::API < Grape::API
  mount Twitter::APIv1 => '/v1'
end

Keep in mind such declarations as before/after/rescue_from must be placed before mount in a case where they should be inherited.

class Twitter::API < Grape::API
  before do
    header 'X-Base-Header', 'will be defined for all APIs that are mounted below'
  end

  mount Twitter::Users
  mount Twitter::Search
end

Remounting

You can mount the same endpoints in two different locations.

class Voting::API < Grape::API
  namespace 'votes' do
    get do
      # Your logic
    end

    post do
      # Your logic
    end
  end
end

class Post::API < Grape::API
  mount Voting::API
end

class Comment::API < Grape::API
  mount Voting::API
end

Assuming that the post and comment endpoints are mounted in /posts and /comments, you should now be able to do get /posts/votes, post /posts/votes, get /comments/votes and post /comments/votes.

Mount Configuration

You can configure remountable endpoints to change how they behave according to where they are mounted.

class Voting::API < Grape::API
  namespace 'votes' do
    desc "Vote for your #{configuration[:votable]}"
    get do
      # Your logic
    end
  end
end

class Post::API < Grape::API
  mount Voting::API, with: { votable: 'posts' }
end

class Comment::API < Grape::API
  mount Voting::API, with: { votable: 'comments' }
end

Note that if you're passing a hash as the first parameter to mount, you will need to explicitly put () around parameters:

# good
mount({ ::Some::Api => '/some/api' }, with: { condition: true })

# bad
mount ::Some::Api => '/some/api', with: { condition: true }

You can access configuration on the class (to use as dynamic attributes), inside blocks (like namespace)

If you want logic happening given on an configuration, you can use the helper given.

class ConditionalEndpoint::API < Grape::API
  given configuration[:some_setting] do
    get 'mount_this_endpoint_conditionally' do
      configuration[:configurable_response]
    end
  end
end

If you want a block of logic running every time an endpoint is mounted (within which you can access the configuration Hash)

class ConditionalEndpoint::API < Grape::API
  mounted do
    YourLogger.info "This API was mounted at: #{Time.now}"

    get configuration[:endpoint_name] do
      configuration[:configurable_response]
    end
  end
end

More complex results can be achieved by using mounted as an expression within which the configuration is already evaluated as a Hash.

class ExpressionEndpointAPI < Grape::API
  get(mounted { configuration[:route_name] || 'default_name' }) do
    # some logic
  end
end
class BasicAPI < Grape::API
  desc 'Statuses index' do
    params: mounted { configuration[:entity] || API::Entities::Status }.documentation
  end
  params do
    requires :all, using: mounted { configuration[:entity] || API::Entities::Status }.documentation
  end
  get '/statuses' do
    statuses = Status.all
    type = current_user.admin? ? :full : :default
    present statuses, with: mounted { configuration[:entity] || API::Entities::Status }, type: type
  end
end

class V1 < Grape::API
  version 'v1'
  mount BasicAPI, with: { entity: mounted { configuration[:entity] || API::Enitities::Status } }
end

class V2 < Grape::API
  version 'v2'
  mount BasicAPI, with: { entity: mounted { configuration[:entity] || API::Enitities::V2::Status } }
end

Versioning

There are four strategies in which clients can reach your API's endpoints: :path, :header, :accept_version_header and :param. The default strategy is :path.

Path

version 'v1', using: :path

Using this versioning strategy, clients should pass the desired version in the URL.

curl http://localhost:9292/v1/statuses/public_timeline

Header

version 'v1', using: :header, vendor: 'twitter'

Currently, Grape only supports versioned media types in the following format:

vnd.vendor-and-or-resource-v1234+format

Basically all tokens between the final - and the + will be interpreted as the version.

Using this versioning strategy, clients should pass the desired version in the HTTP Accept head.

curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline

By default, the first matching version is used when no Accept header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the :strict option. When this option is set to true, a 406 Not Acceptable error is returned when no correct Accept header is supplied.

When an invalid Accept header is supplied, a 406 Not Acceptable error is returned if the :cascade option is set to false. Otherwise a 404 Not Found error is returned by Rack if no other route matches.

Accept-Version Header

version 'v1', using: :accept_version_header

Using this versioning strategy, clients should pass the desired version in the HTTP Accept-Version header.

curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline

By default, the first matching version is used when no Accept-Version header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the :strict option. When this option is set to true, a 406 Not Acceptable error is returned when no correct Accept header is supplied and the :cascade option is set to false. Otherwise a 404 Not Found error is returned by Rack if no other route matches.

Param

version 'v1', using: :param

Using this versioning strategy, clients should pass the desired version as a request parameter, either in the URL query string or in the request body.

curl http://localhost:9292/statuses/public_timeline?apiver=v1

The default name for the query parameter is 'apiver' but can be specified using the :parameter option.

version 'v1', using: :param, parameter: 'v'
curl http://localhost:9292/statuses/public_timeline?v=v1

Describing Methods

You can add a description to API methods and namespaces. The description would be used by grape-swagger to generate swagger compliant documentation.

Note: Description block is only for documentation and won't affects API behavior.

desc 'Returns your public timeline.' do
  summary 'summary'
  detail 'more details'
  params  API::Entities::Status.documentation
  success API::Entities::Entity
  failure [[401, 'Unauthorized', 'Entities::Error']]
  named 'My named route'
  headers XAuthToken: {
            description: 'Validates your identity',
            required: true
          },
          XOptionalHeader: {
            description: 'Not really needed',
            required: false
          }
  hidden false
  deprecated false
  is_array true
  nickname 'nickname'
  produces ['application/json']
  consumes ['application/json']
  tags ['tag1', 'tag2']
end
get :public_timeline do
  Status.limit(20)
end
  • detail: A more enhanced description
  • params: Define parameters directly from an Entity
  • success: (former entity) The Entity to be used to present by default this route
  • failure: (former http_codes) A definition of the used failure HTTP Codes and Entities
  • named: A helper to give a route a name and find it with this name in the documentation Hash
  • headers: A definition of the used Headers
  • Other options can be found in grape-swagger

Configuration

Use Grape.configure to set up global settings at load time. Currently the configurable settings are:

  • param_builder: Sets the Parameter Builder, defaults to Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder.

To change a setting value make sure that at some point during load time the following code runs

Grape.configure do |config|
  config.setting = value
end

For example, for the param_builder, the following code could run in an initializer:

Grape.configure do |config|
  config.param_builder = Grape::Extensions::Hashie::Mash::ParamBuilder
end

You can also configure a single API:

API.configure do |config|
  config[key] = value
end

This will be available inside the API with configuration, as if it were mount configuration.

Parameters

Request parameters are available through the params hash object. This includes GET, POST and PUT parameters, along with any named parameters you specify in your route strings.

get :public_timeline do
  Status.order(params[:sort_by])
end

Parameters are automatically populated from the request body on POST and PUT for form input, JSON and XML content-types.

The request:

curl -d '{"text": "140 characters"}' 'http://localhost:9292/statuses' -H Content-Type:application/json -v

The Grape endpoint:

post '/statuses' do
  Status.create!(text: params[:text])
end

Multipart POSTs and PUTs are supported as well.

The request:

curl --form image_file='@image.jpg;type=image/jpg' http://localhost:9292/upload

The Grape endpoint:

post 'upload' do
  # file in params[:image_file]
end

In the case of conflict between either of:

  • route string parameters
  • GET, POST and PUT parameters
  • the contents of the request body on POST and PUT

Route string parameters will have precedence.

Params Class

By default parameters are available as ActiveSupport::HashWithIndifferentAccess. This can be changed to, for example, Ruby Hash or Hashie::Mash for the entire API.

class API < Grape::API
  include Grape::Extensions::Hashie::Mash::ParamBuilder

  params do
    optional :color, type: String
  end
  get do
    params.color # instead of params[:color]
  end

The class can also be overridden on individual parameter blocks using build_with as follows.

params do
  build_with Grape::Extensions::Hash::ParamBuilder
  optional :color, type: String
end

Or globally with the Configuration Grape.configure.param_builder.

In the example above, params["color"] will return nil since params is a plain Hash.

Available parameter builders are Grape::Extensions::Hash::ParamBuilder, Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder and Grape::Extensions::Hashie::Mash::ParamBuilder.

Declared

Grape allows you to access only the parameters that have been declared by your params block. It will:

  • Filter out the params that have been passed, but are not allowed.
  • Include any optional params that are declared but not passed.
  • Perform any parameter renaming on the resulting hash.

Consider the following API endpoint:

format :json

post 'users/signup' do
  { 'declared_params' => declared(params) }
end

If you do not specify any parameters, declared will return an empty hash.

Request

curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": "last name"}}'

Response

{
  "declared_params": {}
}

Once we add parameters requirements, grape will start returning only the declared parameters.

format :json

params do
  optional :user, type: Hash do
    optional :first_name, type: String
    optional :last_name, type: String
  end
end

post 'users/signup' do
  { 'declared_params' => declared(params) }
end

Request

curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": "last name", "random": "never shown"}}'

Response

{
  "declared_params": {
    "user": {
      "first_name": "first name",
      "last_name": "last name"
    }
  }
}

Missing params that are declared as type Hash or Array will be included.

format :json

params do
  optional :user, type: Hash do
    optional :first_name, type: String
    optional :last_name, type: String
  end
  optional :widgets, type: Array
end

post 'users/signup' do
  { 'declared_params' => declared(params) }
end

Request

curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{}'

Response

{
  "declared_params": {
    "user": {
      "first_name": null,
      "last_name": null
    },
    "widgets": []
  }
}

The returned hash is an ActiveSupport::HashWithIndifferentAccess.

The #declared method is not available to before filters, as those are evaluated prior to parameter coercion.

Include Parent Namespaces

By default declared(params) includes parameters that were defined in all parent namespaces. If you want to return only parameters from your current namespace, you can set include_parent_namespaces option to false.

format :json

namespace :parent do
  params do
    requires :parent_name, type: String
  end

  namespace ':parent_name' do
    params do
      requires :child_name, type: String
    end
    get ':child_name' do
      {
        'without_parent_namespaces' => declared(params, include_parent_namespaces: false),
        'with_parent_namespaces' => declared(params, include_parent_namespaces: true),
      }
    end
  end
end

Request

curl -X GET -H "Content-Type: application/json" localhost:9292/parent/foo/bar

Response

{
  "without_parent_namespaces": {
    "child_name": "bar"
  },
  "with_parent_namespaces": {
    "parent_name": "foo",
    "child_name": "bar"
  },
}

Include Missing

By default declared(params) includes parameters that have nil values. If you want to return only the parameters that are not nil, you can use the include_missing option. By default, include_missing is set to true. Consider the following API:

format :json

params do
  requires :user, type: Hash do
    requires :first_name, type: String
    optional :last_name, type: String
  end
end

post 'users/signup' do
  { 'declared_params' => declared(params, include_missing: false) }
end

Request

curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "random": "never shown"}}'

Response with include_missing:false

{
  "declared_params": {
    "user": {
      "first_name": "first name"
    }
  }
}

Response with include_missing:true

{
  "declared_params": {
    "user": {
      "first_name": "first name",
      "last_name": null
    }
  }
}

It also works on nested hashes:

format :json

params do
  requires :user, type: Hash do
    requires :first_name, type: String
    optional :last_name, type: String
    requires :address, type: Hash do
      requires :city, type: String
      optional :region, type: String
    end
  end
end

post 'users/signup' do
  { 'declared_params' => declared(params, include_missing: false) }
end

Request

curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "random": "never shown", "address": { "city": "SF"}}}'

Response with include_missing:false

{
  "declared_params": {
    "user": {
      "first_name": "first name",
      "address": {
        "city": "SF"
      }
    }
  }
}

Response with include_missing:true

{
  "declared_params": {
    "user": {
      "first_name": "first name",
      "last_name": null,
      "address": {
        "city": "Zurich",
        "region": null
      }
    }
  }
}

Note that an attribute with a nil value is not considered missing and will also be returned when include_missing is set to false:

Request

curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": null, "address": { "city": "SF"}}}'

Response with include_missing:false

{
  "declared_params": {
    "user": {
      "first_name": "first name",
      "last_name": null,
      "address": { "city": "SF"}
    }
  }
}

Parameter Validation and Coercion

You can define validations and coercion options for your parameters using a params block.

params do
  requires :id, type: Integer
  optional :text, type: String, regexp: /\A[a-z]+\z/
  group :media, type: Hash do
    requires :url
  end
  optional :audio, type: Hash do
    requires :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3
  end
  mutually_exclusive :media, :audio
end
put ':id' do
  # params[:id] is an Integer
end

When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.

Optional parameters can have a default value.

params do
  optional :color, type: String, default: 'blue'
  optional :random_number, type: Integer, default: -> { Random.rand(1..100) }
  optional :non_random_number, type: Integer, default:  Random.rand(1..100)
end

Default values are eagerly evaluated. Above :non_random_number will evaluate to the same number for each call to the endpoint of this params block. To have the default evaluate lazily with each request use a lambda, like :random_number above.

Note that default values will be passed through to any validation options specified. The following example will always fail if :color is not explicitly provided.

params do
  optional :color, type: String, default: 'blue', values: ['red', 'green']
end

The correct implementation is to ensure the default value passes all validations.

params do
  optional :color, type: String, default: 'blue', values: ['blue', 'red', 'green']
end

Supported Parameter Types

The following are all valid types, supported out of the box by Grape:

  • Integer
  • Float
  • BigDecimal
  • Numeric
  • Date
  • DateTime
  • Time
  • Boolean
  • String
  • Symbol
  • Rack::Multipart::UploadedFile (alias File)
  • JSON

Integer/Fixnum and Coercions

Please be aware that the behavior differs between Ruby 2.4 and earlier versions. In Ruby 2.4, values consisting of numbers are converted to Integer, but in earlier versions it will be treated as Fixnum.

params do
  requires :integers, type: Hash do
    requires :int, coerce: Integer
  end
end
get '/int' do
  params[:integers][:int].class
end

...

get '/int' integers: { int: '45' }
  #=> Integer in ruby 2.4
  #=> Fixnum in earlier ruby versions

Custom Types and Coercions

Aside from the default set of supported types listed above, any class can be used as a type as long as an explicit coercion method is supplied. If the type implements a class-level parse method, Grape will use it automatically. This method must take one string argument and return an instance of the correct type, or return an instance of Grape::Types::InvalidValue which optionally accepts a message to be returned in the response.

class Color
  attr_reader :value
  def initialize(color)
    @value = color
  end

  def self.parse(value)
    return new(value) if %w[blue red green]).include?(value)

    Grape::Types::InvalidValue.new('Unsupported color')
  end
end

params do
  requires :color, type: Color, default: Color.new('blue')
  requires :more_colors, type: Array[Color] # Collections work
  optional :unique_colors, type: Set[Color] # Duplicates discarded
end

get '/stuff' do
  # params[:color] is already a Color.
  params[:color].value
end

Alternatively, a custom coercion method may be supplied for any type of parameter using coerce_with. Any class or object may be given that implements a parse or call method, in that order of precedence. The method must accept a single string parameter, and the return value must match the given type.

params do
  requires :passwd, type: String, coerce_with: Base64.method(:decode64)
  requires :loud_color, type: Color, coerce_with: ->(c) { Color.parse(c.downcase) }

  requires :obj, type: Hash, coerce_with: JSON do
    requires :words, type: Array[String], coerce_with: ->(val) { val.split(/\s+/) }
    optional :time, type: Time, coerce_with: Chronic
  end
end

Note that, a nil value will call the custom coercion method, while a missing parameter will not.

Example of use of coerce_with with a lambda (a class with a parse method could also have been used) It will parse a string and return an Array of Integers, matching the Array[Integer] type.

params do
  requires :values, type: Array[Integer], coerce_with: ->(val) { val.split(/\s+/).map(&:to_i) }
end

Grape will assert that coerced values match the given type, and will reject the request if they do not. To override this behaviour, custom types may implement a parsed? method that should accept a single argument and return true if the value passes type validation.

class SecureUri
  def self.parse(value)
    URI.parse value
  end

  def self.parsed?(value)
    value.is_a? URI::HTTPS
  end
end

params do
  requires :secure_uri, type: SecureUri
end

Multipart File Parameters

Grape makes use of Rack::Request's built-in support for multipart file parameters. Such parameters can be declared with type: File:

params do
  requires :avatar, type: File
end
post '/' do
  params[:avatar][:filename] # => 'avatar.png'
  params[:avatar][:type] # => 'image/png'
  params[:avatar][:tempfile] # => #<File>
end

First-Class JSON Types

Grape supports complex parameters given as JSON-formatted strings using the special type: JSON declaration. JSON objects and arrays of objects are accepted equally, with nested validation rules applied to all objects in either case:

params do
  requires :json, type: JSON do
    requires :int, type: Integer, values: [1, 2, 3]
  end
end
get '/' do
  params[:json].inspect
end

client.get('/', json: '{"int":1}') # => "{:int=>1}"
client.get('/', json: '[{"int":"1"}]') # => "[{:int=>1}]"

client.get('/', json: '{"int":4}') # => HTTP 400
client.get('/', json: '[{"int":4}]') # => HTTP 400

Additionally type: Array[JSON] may be used, which explicitly marks the parameter as an array of objects. If a single object is supplied it will be wrapped.

params do
  requires :json, type: Array[JSON] do
    requires :int, type: Integer
  end
end
get '/' do
  params[:json].each { |obj| ... } # always works
end

For stricter control over the type of JSON structure which may be supplied, use type: Array, coerce_with: JSON or type: Hash, coerce_with: JSON.

Multiple Allowed Types

Variant-type parameters can be declared using the types option rather than type:

params do
  requires :status_code, types: [Integer, String, Array[Integer, String]]
end
get '/' do
  params[:status_code].inspect
end

client.get('/', status_code: 'OK_GOOD') # => "OK_GOOD"
client.get('/', status_code: 300) # => 300
client.get('/', status_code: %w(404 NOT FOUND)) # => [404, "NOT", "FOUND"]

As a special case, variant-member-type collections may also be declared, by passing a Set or Array with more than one member to type:

params do
  requires :status_codes, type: Array[Integer,String]
end
get '/' do
  params[:status_codes].inspect
end

client.get('/', status_codes: %w(1 two)) # => [1, "two"]

Validation of Nested Parameters

Parameters can be nested using group or by calling requires or optional with a block. In the above example, this means params[:media][:url] is required along with params[:id], and params[:audio][:format] is required only if params[:audio] is present. With a block, group, requires and optional accept an additional option type which can be either Array or Hash, and defaults to Array. Depending on the value, the nested parameters will be treated either as values of a hash or as values of hashes in an array.

params do
  optional :preferences, type: Array do
    requires :key
    requires :value
  end

  requires :name, type: Hash do
    requires :first_name
    requires :last_name
  end
end

Dependent Parameters

Suppose some of your parameters are only relevant if another parameter is given; Grape allows you to express this relationship through the given method in your parameters block, like so:

params do
  optional :shelf_id, type: Integer
  given :shelf_id do
    requires :bin_id, type: Integer
  end
end

In the example above Grape will use blank? to check whether the shelf_id param is present.

given also takes a Proc with custom code. Below, the param description is required only if the value of category is equal foo:

params do
  optional :category
  given category: ->(val) { val == 'foo' } do
    requires :description
  end
end

You can rename parameters:

params do
  optional :category, as: :type
  given type: ->(val) { val == 'foo' } do
    requires :description
  end
end

Note: param in given should be the renamed one. In the example, it should be type, not category.

Group Options

Parameters options can be grouped. It can be useful if you want to extract common validation or types for several parameters. The example below presents a typical case when parameters share common options.

params do
  requires :first_name, type: String, regexp: /w+/, desc: 'First name'
  requires :middle_name, type: String, regexp: /w+/, desc: 'Middle name'
  requires :last_name, type: String, regexp: /w+/, desc: 'Last name'
end

Grape allows you to present the same logic through the with method in your parameters block, like so:

params do
  with(type: String, regexp: /w+/) do
    requires :first_name, desc: 'First name'
    requires :middle_name, desc: 'Middle name'
    requires :last_name, desc: 'Last name'
  end
end

Renaming

You can rename parameters using as, which can be useful when refactoring existing APIs:

resource :users do
  params do
    requires :email_address, as: :email
    requires :password
  end
  post do
    User.create!(declared(params)) # User takes email and password
  end
end

The value passed to as will be the key when calling declared(params).

Built-in Validators

allow_blank

Parameters can be defined as allow_blank, ensuring that they contain a value. By default, requires only validates that a parameter was sent in the request, regardless its value. With allow_blank: false, empty values or whitespace only values are invalid.

allow_blank can be combined with both requires and optional. If the parameter is required, it has to contain a value. If it's optional, it's possible to not send it in the request, but if it's being sent, it has to have some value, and not an empty string/only whitespaces.

params do
  requires :username, allow_blank: false
  optional :first_name, allow_blank: false
end

values

Parameters can be restricted to a specific set of values with the :values option.

params do
  requires :status, type: Symbol, values: [:not_started, :processing, :done]
  optional :numbers, type: Array[Integer], default: 1, values: [1, 2, 3, 5, 8]
end

Supplying a range to the :values option ensures that the parameter is (or parameters are) included in that range (using Range#include?).

params do
  requires :latitude, type: Float, values: -90.0..+90.0
  requires :longitude, type: Float, values: -180.0..+180.0
  optional :letters, type: Array[String], values: 'a'..'z'
end

Note that both range endpoints have to be a #kind_of? your :type option (if you don't supply the :type option, it will be guessed to be equal to the class of the range's first endpoint). So the following is invalid:

params do
  requires :invalid1, type: Float, values: 0..10 # 0.kind_of?(Float) => false
  optional :invalid2, values: 0..10.0 # 10.0.kind_of?(0.class) => false
end

The :values option can also be supplied with a Proc, evaluated lazily with each request. If the Proc has arity zero (i.e. it takes no arguments) it is expected to return either a list or a range which will then be used to validate the parameter.

For example, given a status model you may want to restrict by hashtags that you have previously defined in the HashTag model.

params do
  requires :hashtag, type: String, values: -> { Hashtag.all.map(&:tag) }
end

Alternatively, a Proc with arity one (i.e. taking one argument) can be used to explicitly validate each parameter value. In that case, the Proc is expected to return a truthy value if the parameter value is valid. The parameter will be considered invalid if the Proc returns a falsy value or if it raises a StandardError.

params do
  requires :number, type: Integer, values: ->(v) { v.even? && v < 25 }
end

While Procs are convenient for single cases, consider using Custom Validators in cases where a validation is used more than once.

Note that allow_blank validator applies while using :values. In the following example the absence of :allow_blank does not prevent :state from receiving blank values because :allow_blank defaults to true.

params do
  requires :state, type: Symbol, values: [:active, :inactive]
end

except_values

Parameters can be restricted from having a specific set of values with the :except_values option.

The except_values validator behaves similarly to the values validator in that it accepts either an Array, a Range, or a Proc. Unlike the values validator, however, except_values only accepts Procs with arity zero.

params do
  requires :browser, except_values: [ 'ie6', 'ie7', 'ie8' ]
  requires :port, except_values: { value: 0..1024, message: 'is not allowed' }
  requires :hashtag, except_values: -> { Hashtag.FORBIDDEN_LIST }
end

same_as

A same_as option can be given to ensure that values of parameters match.

params do
  requires :password
  requires :password_confirmation, same_as: :password
end

regexp

Parameters can be restricted to match a specific regular expression with the :regexp option. If the value does not match the regular expression an error will be returned. Note that this is true for both requires and optional parameters.

params do
  requires :email, regexp: /.+@.+/
end

The validator will pass if the parameter was sent without value. To ensure that the parameter contains a value, use allow_blank: false.

params do
  requires :email, allow_blank: false, regexp: /.+@.+/
end

mutually_exclusive

Parameters can be defined as mutually_exclusive, ensuring that they aren't present at the same time in a request.

params do
  optional :beer
  optional :wine
  mutually_exclusive :beer, :wine
end

Multiple sets can be defined:

params do
  optional :beer
  optional :wine
  mutually_exclusive :beer, :wine
  optional :scotch
  optional :aquavit
  mutually_exclusive :scotch, :aquavit
end

Warning: Never define mutually exclusive sets with any required params. Two mutually exclusive required params will mean params are never valid, thus making the endpoint useless. One required param mutually exclusive with an optional param will mean the latter is never valid.

exactly_one_of

Parameters can be defined as 'exactly_one_of', ensuring that exactly one parameter gets selected.

params do
  optional :beer
  optional :wine
  exactly_one_of :beer, :wine
end

Note that using :default with mutually_exclusive will cause multiple parameters to always have a default value and raise a Grape::Exceptions::Validation mutually exclusive exception.

at_least_one_of

Parameters can be defined as 'at_least_one_of', ensuring that at least one parameter gets selected.

params do
  optional :beer
  optional :wine
  optional :juice
  at_least_one_of :beer, :wine, :juice
end

all_or_none_of

Parameters can be defined as 'all_or_none_of', ensuring that all or none of parameters gets selected.

params do
  optional :beer
  optional :wine
  optional :juice
  all_or_none_of :beer, :wine, :juice
end

Nested mutually_exclusive, exactly_one_of, at_least_one_of, all_or_none_of

All of these methods can be used at any nested level.

params do
  requires :food, type: Hash do
    optional :meat
    optional :fish
    optional :rice
    at_least_one_of :meat, :fish, :rice
  end
  group :drink, type: Hash do
    optional :beer
    optional :wine
    optional :juice
    exactly_one_of :beer, :wine, :juice
  end
  optional :dessert, type: Hash do
    optional :cake
    optional :icecream
    mutually_exclusive :cake, :icecream
  end
  optional :recipe, type: Hash do
    optional :oil
    optional :meat
    all_or_none_of :oil, :meat
  end
end

Namespace Validation and Coercion

Namespaces allow parameter definitions and apply to every method within the namespace.

namespace :statuses do
  params do
    requires :user_id, type: Integer, desc: 'A user ID.'
  end
  namespace ':user_id' do
    desc "Retrieve a user's status."
    params do
      requires :status_id, type: Integer, desc: 'A status ID.'
    end
    get ':status_id' do
      User.find(params[:user_id]).statuses.find(params[:status_id])
    end
  end
end

The namespace method has a number of aliases, including: group, resource, resources, and segment. Use whichever reads the best for your API.

You can conveniently define a route parameter as a namespace using route_param.

namespace :statuses do
  route_param :id do
    desc 'Returns all replies for a status.'
    get 'replies' do
      Status.find(params[:id]).replies
    end
    desc 'Returns a status.'
    get do
      Status.find(params[:id])
    end
  end
end

You can also define a route parameter type by passing to route_param's options.

namespace :arithmetic do
  route_param :n, type: Integer do
    desc 'Returns in power'
    get 'power' do
      params[:n] ** params[:n]
    end
  end
end

Custom Validators

class AlphaNumeric < Grape::Validations::Validators::Base
  def validate_param!(attr_name, params)
    unless params[attr_name] =~ /\A[[:alnum:]]+\z/
      raise Grape::Exceptions::Validation.new params: [@scope.full_name(attr_name)], message: 'must consist of alpha-numeric characters'
    end
  end
end
params do
  requires :text, alpha_numeric: true
end

You can also create custom classes that take parameters.

class Length < Grape::Validations::Validators::Base
  def validate_param!(attr_name, params)
    unless params[attr_name].length <= @option
      raise Grape::Exceptions::Validation.new params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long"
    end
  end
end
params do
  requires :text, length: 140
end

You can also create custom validation that use request to validate the attribute. For example if you want to have parameters that are available to only admins, you can do the following.

class Admin < Grape::Validations::Validators::Base
  def validate(request)
    # return if the param we are checking was not in request
    # @attrs is a list containing the attribute we are currently validating
    # in our sample case this method once will get called with
    # @attrs being [:admin_field] and once with @attrs being [:admin_false_field]
    return unless request.params.key?(@attrs.first)
    # check if admin flag is set to true
    return unless @option
    # check if user is admin or not
    # as an example get a token from request and check if it's admin or not
    raise Grape::Exceptions::Validation.new params: @attrs, message: 'Can not set admin-only field.' unless request.headers['X-Access-Token'] == 'admin'
  end
end

And use it in your endpoint definition as:

params do
  optional :admin_field, type: String, admin: true
  optional :non_admin_field, type: String
  optional :admin_false_field, type: String, admin: false
end

Every validation will have its own instance of the validator, which means that the validator can have a state.

Validation Errors

Validation and coercion errors are collected and an exception of type Grape::Exceptions::ValidationErrors is raised. If the exception goes uncaught it will respond with a status of 400 and an error message. The validation errors are grouped by parameter name and can be accessed via Grape::Exceptions::ValidationErrors#errors.

The default response from a Grape::Exceptions::ValidationErrors is a humanly readable string, such as "beer, wine are mutually exclusive", in the following example.

params do
  optional :beer
  optional :wine
  optional :juice
  exactly_one_of :beer, :wine, :juice
end

You can rescue a Grape::Exceptions::ValidationErrors and respond with a custom response or turn the response into well-formatted JSON for a JSON API that separates individual parameters and the corresponding error messages. The following rescue_from example produces [{"params":["beer","wine"],"messages":["are mutually exclusive"]}].

format :json
subject.rescue_from Grape::Exceptions::ValidationErrors do |e|
  error! e, 400
end

Grape::Exceptions::ValidationErrors#full_messages returns the validation messages as an array. Grape::Exceptions::ValidationErrors#message joins the messages to one string.

For responding with an array of validation messages, you can use Grape::Exceptions::ValidationErrors#full_messages.

format :json
subject.rescue_from Grape::Exceptions::ValidationErrors do |e|
  error!({ messages: e.full_messages }, 400)
end

Grape returns all validation and coercion errors found by default. To skip all subsequent validation checks when a specific param is found invalid, use fail_fast: true.

The following example will not check if :wine is present unless it finds :beer.

params do
  required :beer, fail_fast: true
  required :wine
end

The result of empty params would be a single Grape::Exceptions::ValidationErrors error.

Similarly, no regular expression test will be performed if :blah is blank in the following example.

params do
  required :blah, allow_blank: false, regexp: /blah/, fail_fast: true
end

I18n

Grape supports I18n for parameter-related error messages, but will fallback to English if translations for the default locale have not been provided. See en.yml for message keys.

In case your app enforces available locales only and :en is not included in your available locales, Grape cannot fall back to English and will return the translation key for the error message. To avoid this behaviour, either provide a translation for your default locale or add :en to your available locales.

Custom Validation messages

Grape supports custom validation messages for parameter-related and coerce-related error messages.

presence, allow_blank, values, regexp

params do
  requires :name, values: { value: 1..10, message: 'not in range from 1 to 10' }, allow_blank: { value: false, message: 'cannot be blank' }, regexp: { value: /^[a-z]+$/, message: 'format is invalid' }, message: 'is required'
end

same_as

params do
  requires :password
  requires :password_confirmation, same_as: { value: :password, message: 'not match' }
end

all_or_none_of

params do
  optional :beer
  optional :wine
  optional :juice
  all_or_none_of :beer, :wine, :juice, message: "all params are required or none is required"
end

mutually_exclusive

params do
  optional :beer
  optional :wine
  optional :juice
  mutually_exclusive :beer, :wine, :juice, message: "are mutually exclusive cannot pass both params"
end

exactly_one_of

params do
  optional :beer
  optional :wine
  optional :juice
  exactly_one_of :beer, :wine, :juice, message: { exactly_one: "are missing, exactly one parameter is required", mutual_exclusion: "are mutually exclusive, exactly one parameter is required" }
end

at_least_one_of

params do
  optional :beer
  optional :wine
  optional :juice
  at_least_one_of :beer, :wine, :juice, message: "are missing, please specify at least one param"
end

Coerce

params do
  requires :int, type: { value: Integer, message: "type cast is invalid" }
end

With Lambdas

params do
  requires :name, values: { value: -> { (1..10).to_a }, message: 'not in range from 1 to 10' }
end

Pass symbols for i18n translations

You can pass a symbol if you want i18n translations for your custom validation messages.

params do
  requires :name, message: :name_required
end
# en.yml

en:
  grape:
    errors:
      format: ! '%{attributes} %{message}'
      messages:
        name_required: 'must be present'

Overriding Attribute Names

You can also override attribute names.

# en.yml

en:
  grape:
    errors:
      format: ! '%{attributes} %{message}'
      messages:
        name_required: 'must be present'
      attributes:
        name: 'Oops! Name'

Will produce 'Oops! Name must be present'

With Default

You cannot set a custom message option for Default as it requires interpolation %{option1}: %{value1} is incompatible with %{option2}: %{value2}. You can change the default error message for Default by changing the incompatible_option_values message key inside en.yml

params do
  requires :name, values: { value: -> { (1..10).to_a }, message: 'not in range from 1 to 10' }, default: 5
end

Headers

Request

Request headers are available through the headers helper or from env in their original form.

get do
  error!('Unauthorized', 401) unless headers['Secret-Password'] == 'swordfish'
end
get do
  error!('Unauthorized', 401) unless env['HTTP_SECRET_PASSWORD'] == 'swordfish'
end

Header Case Handling

The above example may have been requested as follows:

curl -H "secret_PassWord: swordfish" ...

The header name will have been normalized for you.

  • In the header helper names will be coerced into a capitalized kebab case.
  • In the env collection they appear in all uppercase, in snake case, and prefixed with 'HTTP_'.

The header name will have been normalized per HTTP standards defined in RFC2616 Section 4.2 regardless of what is being sent by a client.

Response

You can set a response header with header inside an API.

header 'X-Robots-Tag', 'noindex'

When raising error!, pass additional headers as arguments. Additional headers will be merged with headers set before error! call.

error! 'Unauthorized', 401, 'X-Error-Detail' => 'Invalid token.'

Routes

To define routes you can use the route method or the shorthands for the HTTP verbs. To define a route that accepts any route set to :any. Parts of the path that are denoted with a colon will be interpreted as route parameters.

route :get, 'status' do
end

# is the same as

get 'status' do
end

# is the same as

get :status do
end

# is NOT the same as

get ':status' do # this makes params[:status] available
end

# This will make both params[:status_id] and params[:id] available

get 'statuses/:status_id/reviews/:id' do
end

To declare a namespace that prefixes all routes within, use the namespace method. group, resource, resources and segment are aliases to this method. Any endpoints within will share their parent context as well as any configuration done in the namespace context.

The route_param method is a convenient method for defining a parameter route segment. If you define a type, it will add a validation for this parameter.

route_param :id, type: Integer do
  get 'status' do
  end
end

# is the same as

namespace ':id' do
  params do
    requires :id, type: Integer
  end

  get 'status' do
  end
end

Optionally, you can define requirements for your named route parameters using regular expressions on namespace or endpoint. The route will match only if all requirements are met.

get ':id', requirements: { id: /[0-9]*/ } do
  Status.find(params[:id])
end

namespace :outer, requirements: { id: /[0-9]*/ } do
  get :id do
  end

  get ':id/edit' do
  end
end

Helpers

You can define helper methods that your endpoints can use with the helpers macro by either giving a block or an array of modules.

module StatusHelpers
  def user_info(user)
    "#{user} has statused #{user.statuses} status(s)"
  end
end

module HttpCodesHelpers
  def unauthorized
    401
  end
end

class API < Grape::API
  # define helpers with a block
  helpers do
    def current_user
      User.find(params[:user_id])
    end
  end

  # or mix in an array of modules
  helpers StatusHelpers, HttpCodesHelpers

  before do
    error!('Access Denied', unauthorized) unless current_user
  end

  get 'info' do
    # helpers available in your endpoint and filters
    user_info(current_user)
  end
end

You can define reusable params using helpers.

class API < Grape::API
  helpers do
    params :pagination do
      optional :page, type: Integer
      optional :per_page, type: Integer
    end
  end

  desc 'Get collection'
  params do
    use :pagination # aliases: includes, use_scope
  end
  get do
    Collection.page(params[:page]).per(params[:per_page])
  end
end

You can also define reusable params using shared helpers.

module SharedParams
  extend Grape::API::Helpers

  params :period do
    optional :start_date
    optional :end_date
  end

  params :pagination do
    optional :page, type: Integer
    optional :per_page, type: Integer
  end
end

class API < Grape::API
  helpers SharedParams

  desc 'Get collection.'
  params do
    use :period, :pagination
  end

  get do
    Collection
      .from(params[:start_date])
      .to(params[:end_date])
      .page(params[:page])
      .per(params[:per_page])
  end
end

Helpers support blocks that can help set default values. The following API can return a collection sorted by id or created_at in asc or desc order.

module SharedParams
  extend Grape::API::Helpers

  params :order do |options|
    optional :order_by, type: Symbol, values: options[:order_by], default: options[:default_order_by]
    optional :order, type: Symbol, values: %i(asc desc), default: options[:default_order]
  end
end

class API < Grape::API
  helpers SharedParams

  desc 'Get a sorted collection.'
  params do
    use :order, order_by: %i(id created_at), default_order_by: :created_at, default_order: :asc
  end

  get do
    Collection.send(params[:order], params[:order_by])
  end
end

Path Helpers

If you need methods for generating paths inside your endpoints, please see the grape-route-helpers gem.

Parameter Documentation

You can attach additional documentation to params using a documentation hash.

params do
  optional :first_name, type: String, documentation: { example: 'Jim' }
  requires :last_name, type: String, documentation: { example: 'Smith' }
end

If documentation isn't needed (for instance, it is an internal API), documentation can be disabled.

class API < Grape::API
  do_not_document!

  # endpoints...
end

In this case, Grape won't create objects related to documentation which are retained in RAM forever.

Cookies

You can set, get and delete your cookies very simply using cookies method.

class API < Grape::API
  get 'status_count' do
    cookies[:status_count] ||= 0
    cookies[:status_count] += 1
    { status_count: cookies[:status_count] }
  end

  delete 'status_count' do
    { status_count: cookies.delete(:status_count) }
  end
end

Use a hash-based syntax to set more than one value.

cookies[:status_count] = {
  value: 0,
  expires: Time.tomorrow,
  domain: '.twitter.com',
  path: '/'
}

cookies[:status_count][:value] +=1

Delete a cookie with delete.

cookies.delete :status_count

Specify an optional path.

cookies.delete :status_count, path: '/'

HTTP Status Code

By default Grape returns a 201 for POST-Requests, 204 for DELETE-Requests that don't return any content, and 200 status code for all other Requests. You can use status to query and set the actual HTTP Status Code

post do
  status 202

  if status == 200
     # do some thing
  end
end

You can also use one of status codes symbols that are provided by Rack utils

post do
  status :no_content
end

Redirecting

You can redirect to a new url temporarily (302) or permanently (301).

redirect '/statuses'
redirect '/statuses', permanent: true

Recognizing Path

You can recognize the endpoint matched with given path.

This API returns an instance of Grape::Endpoint.

class API < Grape::API
  get '/statuses' do
  end
end

API.recognize_path '/statuses'

Allowed Methods

When you add a GET route for a resource, a route for the HEAD method will also be added automatically. You can disable this behavior with do_not_route_head!.

class API < Grape::API
  do_not_route_head!

  get '/example' do
    # only responds to GET
  end
end

When you add a route for a resource, a route for the OPTIONS method will also be added. The response to an OPTIONS request will include an "Allow" header listing the supported methods. If the resource has before and after callbacks they will be executed, but no other callbacks will run.

class API < Grape::API
  get '/rt_count' do
    { rt_count: current_user.rt_count }
  end

  params do
    requires :value, type: Integer, desc: 'Value to add to the rt count.'
  end
  put '/rt_count' do
    current_user.rt_count += params[:value].to_i
    { rt_count: current_user.rt_count }
  end
end
curl -v -X OPTIONS http://localhost:3000/rt_count

> OPTIONS /rt_count HTTP/1.1
>
< HTTP/1.1 204 No Content
< Allow: OPTIONS, GET, PUT

You can disable this behavior with do_not_route_options!.

If a request for a resource is made with an unsupported HTTP method, an HTTP 405 (Method Not Allowed) response will be returned. If the resource has before callbacks they will be executed, but no other callbacks will run.

curl -X DELETE -v http://localhost:3000/rt_count/

> DELETE /rt_count/ HTTP/1.1
> Host: localhost:3000
>
< HTTP/1.1 405 Method Not Allowed
< Allow: OPTIONS, GET, PUT

Raising Exceptions

You can abort the execution of an API method by raising errors with error!.

error! 'Access Denied', 401

Anything that responds to #to_s can be given as a first argument to error!.

error! :not_found, 404

You can also return JSON formatted objects by raising error! and passing a hash instead of a message.

error!({ error: 'unexpected error', detail: 'missing widget' }, 500)

You can set additional headers for the response. They will be merged with headers set before error! call.

error!('Something went wrong', 500, 'X-Error-Detail' => 'Invalid token.')

You can present documented errors with a Grape entity using the the grape-entity gem.

module API
  class Error < Grape::Entity
    expose :code
    expose :message
  end
end

The following example specifies the entity to use in the http_codes definition.

desc 'My Route' do
 failure [[408, 'Unauthorized', API::Error]]
end
error!({ message: 'Unauthorized' }, 408)

The following example specifies the presented entity explicitly in the error message.

desc 'My Route' do
 failure [[408, 'Unauthorized']]
end
error!({ message: 'Unauthorized', with: API::Error }, 408)

Default Error HTTP Status Code

By default Grape returns a 500 status code from error!. You can change this with default_error_status.

class API < Grape::API
  default_error_status 400
  get '/example' do
    error! 'This should have http status code 400'
  end
end

Handling 404

For Grape to handle all the 404s for your API, it can be useful to use a catch-all. In its simplest form, it can be like:

route :any, '*path' do
  error! # or something else
end

It is very crucial to define this endpoint at the very end of your API, as it literally accepts every request.

Exception Handling

Grape can be told to rescue all StandardError exceptions and return them in the API format.

class Twitter::API < Grape::API
  rescue_from :all
end

This mimics default rescue behaviour when an exception type is not provided. Any other exception should be rescued explicitly, see below.

Grape can also rescue from all exceptions and still use the built-in exception handing. This will give the same behavior as rescue_from :all with the addition that Grape will use the exception handling defined by all Exception classes that inherit Grape::Exceptions::Base.

The intent of this setting is to provide a simple way to cover the most common exceptions and return any unexpected exceptions in the API format.

class Twitter::API < Grape::API
  rescue_from :grape_exceptions
end

You can also rescue specific exceptions.

class Twitter::API < Grape::API
  rescue_from ArgumentError, UserDefinedError
end

In this case UserDefinedError must be inherited from StandardError.

Notice that you could combine these two approaches (rescuing custom errors takes precedence). For example, it's useful for handling all exceptions except Grape validation errors.

class Twitter::API < Grape::API
  rescue_from Grape::Exceptions::ValidationErrors do |e|
    error!(e, 400)
  end

  rescue_from :all
end

The error format will match the request format. See "Content-Types" below.

Custom error formatters for existing and additional types can be defined with a proc.

class Twitter::API < Grape::API
  error_formatter :txt, ->(message, backtrace, options, env, original_exception) {
    "error: #{message} from #{backtrace}"
  }
end

You can also use a module or class.

module CustomFormatter
  def self.call(message, backtrace, options, env, original_exception)
    { message: message, backtrace: backtrace }
  end
end

class Twitter::API < Grape::API
  error_formatter :custom, CustomFormatter
end

You can rescue all exceptions with a code block. The error! wrapper automatically sets the default error code and content-type.

class Twitter::API < Grape::API
  rescue_from :all do |e|
    error!("rescued from #{e.class.name}")
  end
end

Optionally, you can set the format, status code and headers.

class Twitter::API < Grape::API
  format :json
  rescue_from :all do |e|
    error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
  end
end

You can also rescue all exceptions with a code block and handle the Rack response at the lowest level.

class Twitter::API < Grape::API
  rescue_from :all do |e|
    Rack::Response.new([ e.message ], 500, { 'Content-type' => 'text/error' })
  end
end

Or rescue specific exceptions.

class Twitter::API < Grape::API
  rescue_from ArgumentError do |e|
    error!("ArgumentError: #{e.message}")
  end

  rescue_from NoMethodError do |e|
    error!("NoMethodError: #{e.message}")
  end
end

By default, rescue_from will rescue the exceptions listed and all their subclasses.

Assume you have the following exception classes defined.

module APIErrors
  class ParentError < StandardError; end
  class ChildError < ParentError; end
end

Then the following rescue_from clause will rescue exceptions of type APIErrors::ParentError and its subclasses (in this case APIErrors::ChildError).

rescue_from APIErrors::ParentError do |e|
    error!({
      error: "#{e.class} error",
      message: e.message
    }, e.status)
end

To only rescue the base exception class, set rescue_subclasses: false. The code below will rescue exceptions of type RuntimeError but not its subclasses.

rescue_from RuntimeError, rescue_subclasses: false do |e|
    error!({
      status: e.status,
      message: e.message,
      errors: e.errors
    }, e.status)
end

Helpers are also available inside rescue_from.

class Twitter::API < Grape::API
  format :json
  helpers do
    def server_error!
      error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
    end
  end

  rescue_from :all do |e|
    server_error!
  end
end

The rescue_from handler must return a Rack::Response object, call error!, or raise an exception (either the original exception or another custom one). The exception raised in rescue_from will be handled outside Grape. For example, if you mount Grape in Rails, the exception will be handle by Rails Action Controller.

Alternately, use the with option in rescue_from to specify a method or a proc.

class Twitter::API < Grape::API
  format :json
  helpers do
    def server_error!
      error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
    end
  end

  rescue_from :all,          with: :server_error!
  rescue_from ArgumentError, with: -> { Rack::Response.new('rescued with a method', 400) }
end

Inside the rescue_from block, the environment of the original controller method(.self receiver) is accessible through the #context method.

class Twitter::API < Grape::API
  rescue_from :all do |e|
    user_id = context.params[:user_id]
    error!("error for #{user_id}")
  end
end

Rescuing exceptions inside namespaces

You could put rescue_from clauses inside a namespace and they will take precedence over ones defined in the root scope:

class Twitter::API < Grape::API
  rescue_from ArgumentError do |e|
    error!("outer")
  end

  namespace :statuses do
    rescue_from ArgumentError do |e|
      error!("inner")
    end
    get do
      raise ArgumentError.new
    end
  end
end

Here 'inner' will be result of handling occurred ArgumentError.

Unrescuable Exceptions

Grape::Exceptions::InvalidVersionHeader, which is raised when the version in the request header doesn't match the currently evaluated version for the endpoint, will never be rescued from a rescue_from block (even a rescue_from :all) This is because Grape relies on Rack to catch that error and try the next versioned-route for cases where there exist identical Grape endpoints with different versions.

Exceptions that should be rescued explicitly

Any exception that is not subclass of StandardError should be rescued explicitly. Usually it is not a case for an application logic as such errors point to problems in Ruby runtime. This is following standard recommendations for exceptions handling.

Rails 3.x

When mounted inside containers, such as Rails 3.x, errors such as "404 Not Found" or "406 Not Acceptable" will likely be handled and rendered by Rails handlers. For instance, accessing a nonexistent route "/api/foo" raises a 404, which inside rails will ultimately be translated to an ActionController::RoutingError, which most likely will get rendered to a HTML error page.

Most APIs will enjoy preventing downstream handlers from handling errors. You may set the :cascade option to false for the entire API or separately on specific version definitions, which will remove the X-Cascade: true header from API responses.

cascade false
version 'v1', using: :header, vendor: 'twitter', cascade: false

Logging

Grape::API provides a logger method which by default will return an instance of the Logger class from Ruby's standard library.

To log messages from within an endpoint, you need to define a helper to make the logger available in the endpoint context.

class API < Grape::API
  helpers do
    def logger
      API.logger
    end
  end
  post '/statuses' do
    logger.info "#{current_user} has statused"
  end
end

To change the logger level.

class API < Grape::API
  self.logger.level = Logger::INFO
end

You can also set your own logger.

class MyLogger
  def warning(message)
    puts "this is a warning: #{message}"
  end
end

class API < Grape::API
  logger MyLogger.new
  helpers do
    def logger
      API.logger
    end
  end
  get '/statuses' do
    logger.warning "#{current_user} has statused"
  end
end

For similar to Rails request logging try the grape_logging or grape-middleware-logger gems.

API Formats

Your API can declare which content-types to support by using content_type. If you do not specify any, Grape will support XML, JSON, BINARY, and TXT content-types. The default format is :txt; you can change this with default_format. Essentially, the two APIs below are equivalent.

class Twitter::API < Grape::API
  # no content_type declarations, so Grape uses the defaults
end

class Twitter::API < Grape::API
  # the following declarations are equivalent to the defaults

  content_type :xml, 'application/xml'
  content_type :json, 'application/json'
  content_type :binary, 'application/octet-stream'
  content_type :txt, 'text/plain'

  default_format :txt
end

If you declare any content_type whatsoever, the Grape defaults will be overridden. For example, the following API will only support the :xml and :rss content-types, but not :txt, :json, or :binary. Importantly, this means the :txt default format is not supported! So, make sure to set a new default_format.

class Twitter::API < Grape::API
  content_type :xml, 'application/xml'
  content_type :rss, 'application/xml+rss'

  default_format :xml
end

Serialization takes place automatically. For example, you do not have to call to_json in each JSON API endpoint implementation. The response format (and thus the automatic serialization) is determined in the following order:

  • Use the file extension, if specified. If the file is .json, choose the JSON format.
  • Use the value of the format parameter in the query string, if specified.
  • Use the format set by the format option, if specified.
  • Attempt to find an acceptable format from the Accept header.
  • Use the default format, if specified by the default_format option.
  • Default to :txt.

For example, consider the following API.

class MultipleFormatAPI < Grape::API
  content_type :xml, 'application/xml'
  content_type :json, 'application/json'

  default_format :json

  get :hello do
    { hello: 'world' }
  end
end
  • GET /hello (with an Accept: */* header) does not have an extension or a format parameter, so it will respond with JSON (the default format).
  • GET /hello.xml has a recognized extension, so it will respond with XML.
  • GET /hello?format=xml has a recognized format parameter, so it will respond with XML.
  • GET /hello.xml?format=json has a recognized extension (which takes precedence over the format parameter), so it will respond with XML.
  • GET /hello.xls (with an Accept: */* header) has an extension, but that extension is not recognized, so it will respond with JSON (the default format).
  • GET /hello.xls with an Accept: application/xml header has an unrecognized extension, but the Accept header corresponds to a recognized format, so it will respond with XML.
  • GET /hello.xls with an Accept: text/plain header has an unrecognized extension and an unrecognized Accept header, so it will respond with JSON (the default format).

You can override this process explicitly by specifying env['api.format'] in the API itself. For example, the following API will let you upload arbitrary files and return their contents as an attachment with the correct MIME type.

class Twitter::API < Grape::API
  post 'attachment' do
    filename = params[:file][:filename]
    content_type MIME::Types.type_for(filename)[0].to_s
    env['api.format'] = :binary # there's no formatter for :binary, data will be returned "as is"
    header 'Content-Disposition', "attachment; filename*=UTF-8''#{CGI.escape(filename)}"
    params[:file][:tempfile].read
  end
end

You can have your API only respond to a single format with format. If you use this, the API will not respond to file extensions other than specified in format. For example, consider the following API.

class SingleFormatAPI < Grape::API
  format :json

  get :hello do
    { hello: 'world' }
  end
end
  • GET /hello will respond with JSON.
  • GET /hello.json will respond with JSON.
  • GET /hello.xml, GET /hello.foobar, or any other extension will respond with an HTTP 404 error code.
  • GET /hello?format=xml will respond with an HTTP 406 error code, because the XML format specified by the request parameter is not supported.
  • GET /hello with an Accept: application/xml header will still respond with JSON, since it could not negotiate a recognized content-type from the headers and JSON is the effective default.

The formats apply to parsing, too. The following API will only respond to the JSON content-type and will not parse any other input than application/json, application/x-www-form-urlencoded, multipart/form-data, multipart/related and multipart/mixed. All other requests will fail with an HTTP 406 error code.

class Twitter::API < Grape::API
  format :json
end

When the content-type is omitted, Grape will return a 406 error code unless default_format is specified. The following API will try to parse any data without a content-type using a JSON parser.

class Twitter::API < Grape::API
  format :json
  default_format :json
end

If you combine format with rescue_from :all, errors will be rendered using the same format. If you do not want this behavior, set the default error formatter with default_error_formatter.

class Twitter::API < Grape::API
  format :json
  content_type :txt, 'text/plain'
  default_error_formatter :txt
end

Custom formatters for existing and additional types can be defined with a proc.

class Twitter::API < Grape::API
  content_type :xls, 'application/vnd.ms-excel'
  formatter :xls, ->(object, env) { object.to_xls }
end

You can also use a module or class.

module XlsFormatter
  def self.call(object, env)
    object.to_xls
  end
end

class Twitter::API < Grape::API
  content_type :xls, 'application/vnd.ms-excel'
  formatter :xls, XlsFormatter
end

Built-in formatters are the following.

  • :json: use object's to_json when available, otherwise call MultiJson.dump
  • :xml: use object's to_xml when available, usually via MultiXml, otherwise call to_s
  • :txt: use object's to_txt when available, otherwise to_s
  • :serializable_hash: use object's serializable_hash when available, otherwise fallback to :json
  • :binary: data will be returned "as is"

If a body is present in a request to an API, with a Content-Type header value that is of an unsupported type a "415 Unsupported Media Type" error code will be returned by Grape.

Response statuses that indicate no content as defined by Rack here will bypass serialization and the body entity - though there should be none - will not be modified.

JSONP

Grape supports JSONP via Rack::JSONP, part of the rack-contrib gem. Add rack-contrib to your Gemfile.

require 'rack/contrib'

class API < Grape::API
  use Rack::JSONP
  format :json
  get '/' do
    'Hello World'
  end
end

CORS

Grape supports CORS via Rack::CORS, part of the rack-cors gem. Add rack-cors to your Gemfile, then use the middleware in your config.ru file.

require 'rack/cors'

use Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :get
  end
end

run Twitter::API

Content-type

Content-type is set by the formatter. You can override the content-type of the response at runtime by setting the Content-Type header.

class API < Grape::API
  get '/home_timeline_js' do
    content_type 'application/javascript'
    "var statuses = ...;"
  end
end

API Data Formats

Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters section above. It also supports custom data formats. You must declare additional content-types via content_type and optionally supply a parser via parser unless a parser is already available within Grape to enable a custom format. Such a parser can be a function or a class.

With a parser, parsed data is available "as-is" in env['api.request.body']. Without a parser, data is available "as-is" and in env['api.request.input'].

The following example is a trivial parser that will assign any input with the "text/custom" content-type to :value. The parameter will be available via params[:value] inside the API call.

module CustomParser
  def self.call(object, env)
    { value: object.to_s }
  end
end
content_type :txt, 'text/plain'
content_type :custom, 'text/custom'
parser :custom, CustomParser

put 'value' do
  params[:value]
end

You can invoke the above API as follows.

curl -X PUT -d 'data' 'http://localhost:9292/value' -H Content-Type:text/custom -v

You can disable parsing for a content-type with nil. For example, parser :json, nil will disable JSON parsing altogether. The request data is then available as-is in env['api.request.body'].

JSON and XML Processors

Grape uses JSON and ActiveSupport::XmlMini for JSON and XML parsing by default. It also detects and supports multi_json and multi_xml. Adding those gems to your Gemfile and requiring them will enable them and allow you to swap the JSON and XML back-ends.

RESTful Model Representations

Grape supports a range of ways to present your data with some help from a generic present method, which accepts two arguments: the object to be presented and the options associated with it. The options hash may include :with, which defines the entity to expose.

Grape Entities

Add the grape-entity gem to your Gemfile. Please refer to the grape-entity documentation for more details.

The following example exposes statuses.

module API
  module Entities
    class Status < Grape::Entity
      expose :user_name
      expose :text, documentation: { type: 'string', desc: 'Status update text.' }
      expose :ip, if: { type: :full }
      expose :user_type, :user_id, if: ->(status, options) { status.user.public? }
      expose :digest do |status, options|
        Digest::MD5.hexdigest(status.txt)
      end
      expose :replies, using: API::Status, as: :replies
    end
  end

  class Statuses < Grape::API
    version 'v1'

    desc 'Statuses index' do
      params: API::Entities::Status.documentation
    end
    get '/statuses' do
      statuses = Status.all
      type = current_user.admin? ? :full : :default
      present statuses, with: API::Entities::Status, type: type
    end
  end
end

You can use entity documentation directly in the params block with using: Entity.documentation.

module API
  class Statuses < Grape::API
    version 'v1'

    desc 'Create a status'
    params do
      requires :all, except: [:ip], using: API::Entities::Status.documentation.except(:id)
    end
    post '/status' do
      Status.create! params
    end
  end
end

You can present with multiple entities using an optional Symbol argument.

  get '/statuses' do
    statuses = Status.all.page(1).per(20)
    present :total_page, 10
    present :per_page, 20
    present :statuses, statuses, with: API::Entities::Status
  end

The response will be

  {
    total_page: 10,
    per_page: 20,
    statuses: []
  }

In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.

class Status
  def entity
    Entity.new(self)
  end

  class Entity < Grape::Entity
    expose :text, :user_id
  end
end

If you organize your entities this way, Grape will automatically detect the Entity class and use it to present your models. In this example, if you added present Status.new to your endpoint, Grape will automatically detect that there is a Status::Entity class and use that as the representative entity. This can still be overridden by using the :with option or an explicit represents call.

You can present hash with Grape::Presenters::Presenter to keep things consistent.

get '/users' do
  present { id: 10, name: :dgz }, with: Grape::Presenters::Presenter
end

The response will be

{
  id:   10,
  name: 'dgz'
}

It has the same result with

get '/users' do
  present :id, 10
  present :name, :dgz
end

Hypermedia and Roar

You can use Roar to render HAL or Collection+JSON with the help of grape-roar, which defines a custom JSON formatter and enables presenting entities with Grape's present keyword.

Rabl

You can use Rabl templates with the help of the grape-rabl gem, which defines a custom Grape Rabl formatter.

Active Model Serializers

You can use Active Model Serializers serializers with the help of the grape-active_model_serializers gem, which defines a custom Grape AMS formatter.

Sending Raw or No Data

In general, use the binary format to send raw data.

class API < Grape::API
  get '/file' do
    content_type 'application/octet-stream'
    File.binread 'file.bin'
  end
end

You can set the response body explicitly with body.

class API < Grape::API
  get '/' do
    content_type 'text/plain'
    body 'Hello World'
    # return value ignored
  end
end

Use body false to return 204 No Content without any data or content-type.

You can also set the response to a file with sendfile. This works with the Rack::Sendfile middleware to optimally send the file through your web server software.

class API < Grape::API
  get '/' do
    sendfile '/path/to/file'
  end
end

To stream a file in chunks use stream

class API < Grape::API
  get '/' do
    stream '/path/to/file'
  end
end

If you want to stream non-file data use the stream method and a Stream object. This is an object that responds to each and yields for each chunk to send to the client. Each chunk will be sent as it is yielded instead of waiting for all of the content to be available.

class MyStream
  def each
    yield 'part 1'
    yield 'part 2'
    yield 'part 3'
  end
end

class API < Grape::API
  get '/' do
    stream MyStream.new
  end
end

Authentication

Basic and Digest Auth

Grape has built-in Basic and Digest authentication (the given block is executed in the context of the current Endpoint). Authentication applies to the current namespace and any children, but not parents.

http_basic do |username, password|
  # verify user's password here
  # IMPORTANT: make sure you use a comparison method which isn't prone to a timing attack
end

Digest auth supports clear-text passwords and password hashes.

http_digest({ realm: 'Test Api', opaque: 'app secret' }) do |username|
  # lookup the user's password here
end
http_digest(realm: { realm: 'Test Api', opaque: 'app secret', passwords_hashed: true }) do |username|
  # lookup the user's password hash here
end

Register custom middleware for authentication

Grape can use custom Middleware for authentication. How to implement these Middleware have a look at Rack::Auth::Basic or similar implementations.

For registering a Middleware you need the following options:

  • label - the name for your authenticator to use it later
  • MiddlewareClass - the MiddlewareClass to use for authentication
  • option_lookup_proc - A Proc with one Argument to lookup the options at runtime (return value is an Array as Parameter for the Middleware).

Example:


Grape::Middleware::Auth::Strategies.add(:my_auth, AuthMiddleware, ->(options) { [options[:realm]] } )


auth :my_auth, { realm: 'Test Api'} do |credentials|
  # lookup the user's password here
  { 'user1' => 'password1' }[username]
end

Use Doorkeeper, warden-oauth2 or rack-oauth2 for OAuth2 support.

You can access the controller params, headers, and helpers through the context with the #context method inside any auth middleware inherited from Grape::Middleware::Auth::Base.

Describing and Inspecting an API

Grape routes can be reflected at runtime. This can notably be useful for generating documentation.

Grape exposes arrays of API versions and compiled routes. Each route contains a route_prefix, route_version, route_namespace, route_method, route_path and route_params. You can add custom route settings to the route metadata with route_setting.

class TwitterAPI < Grape::API
  version 'v1'
  desc 'Includes custom settings.'
  route_setting :custom, key: 'value'
  get do

  end
end

Examine the routes at runtime.

TwitterAPI::versions # yields [ 'v1', 'v2' ]
TwitterAPI::routes # yields an array of Grape::Route objects
TwitterAPI::routes[0].version # => 'v1'
TwitterAPI::routes[0].description # => 'Includes custom settings.'
TwitterAPI::routes[0].settings[:custom] # => { key: 'value' }

Note that Route#route_xyz methods have been deprecated since 0.15.0.

Please use Route#xyz instead.

Note that difference of Route#options and Route#settings.

The options can be referred from your route, it should be set by specifing key and value on verb methods such as get, post and put. The settings can also be referred from your route, but it should be set by specifing key and value on route_setting.

Current Route and Endpoint

It's possible to retrieve the information about the current route from within an API call with route.

class MyAPI < Grape::API
  desc 'Returns a description of a parameter.'
  params do
    requires :id, type: Integer, desc: 'Identity.'
  end
  get 'params/:id' do
    route.route_params[params[:id]] # yields the parameter description
  end
end

The current endpoint responding to the request is self within the API block or env['api.endpoint'] elsewhere. The endpoint has some interesting properties, such as source which gives you access to the original code block of the API implementation. This can be particularly useful for building a logger middleware.

class ApiLogger < Grape::Middleware::Base
  def before
    file = env['api.endpoint'].source.source_location[0]
    line = env['api.endpoint'].source.source_location[1]
    logger.debug "[api] #{file}:#{line}"
  end
end

Before, After and Finally

Blocks can be executed before or after every API call, using before, after, before_validation and after_validation. If the API fails the after call will not be triggered, if you need code to execute for sure use the finally.

Before and after callbacks execute in the following order:

  1. before
  2. before_validation
  3. validations
  4. after_validation (upon successful validation)
  5. the API call (upon successful validation)
  6. after (upon successful validation and API call)
  7. finally (always)

Steps 4, 5 and 6 only happen if validation succeeds.

If a request for a resource is made with an unsupported HTTP method (returning HTTP 405) only before callbacks will be executed. The remaining callbacks will be bypassed.

If a request for a resource is made that triggers the built-in OPTIONS handler, only before and after callbacks will be executed. The remaining callbacks will be bypassed.

For example, using a simple before block to set a header.

before do
  header 'X-Robots-Tag', 'noindex'
end

You can ensure a block of code runs after every request (including failures) with finally:

finally do
  # this code will run after every request (successful or failed)
end

Namespaces

Callbacks apply to each API call within and below the current namespace:

class MyAPI < Grape::API
  get '/' do
    "root - #{@blah}"
  end

  namespace :foo do
    before do
      @blah = 'blah'
    end

    get '/' do
      "root - foo - #{@blah}"
    end

    namespace :bar do
      get '/' do
        "root - foo - bar - #{@blah}"
      end
    end
  end
end

The behavior is then:

GET /           # 'root - '
GET /foo        # 'root - foo - blah'
GET /foo/bar    # 'root - foo - bar - blah'

Params on a namespace (or whichever alias you are using) will also be available when using before_validation or after_validation:

class MyAPI < Grape::API
  params do
    requires :blah, type: Integer
  end
  resource ':blah' do
    after_validation do
      # if we reach this point validations will have passed
      @blah = declared(params, include_missing: false)[:blah]
    end

    get '/' do
      @blah.class
    end
  end
end

The behavior is then:

GET /123        # 'Integer'
GET /foo        # 400 error - 'blah is invalid'

Versioning

When a callback is defined within a version block, it's only called for the routes defined in that block.

class Test < Grape::API
  resource :foo do
    version 'v1', :using => :path do
      before do
        @output ||= 'v1-'
      end
      get '/' do
        @output += 'hello'
      end
    end

    version 'v2', :using => :path do
      before do
        @output ||= 'v2-'
      end
      get '/' do
        @output += 'hello'
      end
    end
  end
end

The behavior is then:

GET /foo/v1       # 'v1-hello'
GET /foo/v2       # 'v2-hello'

Altering Responses

Using present in any callback allows you to add data to a response:

class MyAPI < Grape::API
  format :json

  after_validation do
    present :name, params[:name] if params[:name]
  end

  get '/greeting' do
    present :greeting, 'Hello!'
  end
end

The behavior is then:

GET /greeting              # {"greeting":"Hello!"}
GET /greeting?name=Alan    # {"name":"Alan","greeting":"Hello!"}

Instead of altering a response, you can also terminate and rewrite it from any callback using error!, including after. This will cause all subsequent steps in the process to not be called. This includes the actual api call and any callbacks

Anchoring

Grape by default anchors all request paths, which means that the request URL should match from start to end to match, otherwise a 404 Not Found is returned. However, this is sometimes not what you want, because it is not always known upfront what can be expected from the call. This is because Rack-mount by default anchors requests to match from the start to the end, or not at all. Rails solves this problem by using a anchor: false option in your routes. In Grape this option can be used as well when a method is defined.

For instance when your API needs to get part of an URL, for instance:

class TwitterAPI < Grape::API
  namespace :statuses do
    get '/(*:status)', anchor: false do

    end
  end
end

This will match all paths starting with '/statuses/'. There is one caveat though: the params[:status] parameter only holds the first part of the request url. Luckily this can be circumvented by using the described above syntax for path specification and using the PATH_INFO Rack environment variable, using env['PATH_INFO']. This will hold everything that comes after the '/statuses/' part.

Using Custom Middleware

Grape Middleware

You can make a custom middleware by using Grape::Middleware::Base. It's inherited from some grape official middlewares in fact.

For example, you can write a middleware to log application exception.

class LoggingError < Grape::Middleware::Base
  def after
    return unless @app_response && @app_response[0] == 500
    env['rack.logger'].error("Raised error on #{env['PATH_INFO']}")
  end
end

Your middleware can overwrite application response as follows, except error case.

class Overwriter < Grape::Middleware::Base
  def after
    [200, { 'Content-Type' => 'text/plain' }, ['Overwritten.']]
  end
end

You can add your custom middleware with use, that push the middleware onto the stack, and you can also control where the middleware is inserted using insert, insert_before and insert_after.

class CustomOverwriter < Grape::Middleware::Base
  def after
    [200, { 'Content-Type' => 'text/plain' }, [@options[:message]]]
  end
end


class API < Grape::API
  use Overwriter
  insert_before Overwriter, CustomOverwriter, message: 'Overwritten again.'
  insert 0, CustomOverwriter, message: 'Overwrites all other middleware.'

  get '/' do
  end
end

You can access the controller params, headers, and helpers through the context with the #context method inside any middleware inherited from Grape::Middleware::Base.

Rails Middleware

Note that when you're using Grape mounted on Rails you don't have to use Rails middleware because it's already included into your middleware stack. You only have to implement the helpers to access the specific env variable.

If you are using a custom application that is inherited from Rails::Application and need to insert a new middleware among the ones initiated via Rails, you will need to register it manually in your custom application class.

class Company::Application < Rails::Application
  config.middleware.insert_before(Rack::Attack, Middleware::ApiLogger)
end

Remote IP

By default you can access remote IP with request.ip. This is the remote IP address implemented by Rack. Sometimes it is desirable to get the remote IP Rails-style with ActionDispatch::RemoteIp.

Add gem 'actionpack' to your Gemfile and require 'action_dispatch/middleware/remote_ip.rb'. Use the middleware in your API and expose a client_ip helper. See this documentation for additional options.

class API < Grape::API
  use ActionDispatch::RemoteIp

  helpers do
    def client_ip
      env['action_dispatch.remote_ip'].to_s
    end
  end

  get :remote_ip do
    { ip: client_ip }
  end
end

Writing Tests

Writing Tests with Rack

Use rack-test and define your API as app.

RSpec

You can test a Grape API with RSpec by making HTTP requests and examining the response.



describe Twitter::API do
  include Rack::Test::Methods

  def app
    Twitter::API
  end

  context 'GET /api/statuses/public_timeline' do
    it 'returns an empty array of statuses' do
      get '/api/statuses/public_timeline'
      expect(last_response.status).to eq(200)
      expect(JSON.parse(last_response.body)).to eq []
    end
  end
  context 'GET /api/statuses/:id' do
    it 'returns a status by id' do
      status = Status.create!
      get "/api/statuses/#{status.id}"
      expect(last_response.body).to eq status.to_json
    end
  end
end

There's no standard way of sending arrays of objects via an HTTP GET, so POST JSON data and specify the correct content-type.

describe Twitter::API do
  context 'POST /api/statuses' do
    it 'creates many statuses' do
      statuses = [{ text: '...' }, { text: '...'}]
      post '/api/statuses', statuses.to_json, 'CONTENT_TYPE' => 'application/json'
      expect(last_response.body).to eq 201
    end
  end
end

Airborne

You can test with other RSpec-based frameworks, including Airborne, which uses rack-test to make requests.

require 'airborne'

Airborne.configure do |config|
  config.rack_app = Twitter::API
end

describe Twitter::API do
  context 'GET /api/statuses/:id' do
    it 'returns a status by id' do
      status = Status.create!
      get "/api/statuses/#{status.id}"
      expect_json(status.as_json)
    end
  end
end

MiniTest

require 'test_helper'

class Twitter::APITest < MiniTest::Test
  include Rack::Test::Methods

  def app
    Twitter::API
  end

  def test_get_api_statuses_public_timeline_returns_an_empty_array_of_statuses
    get '/api/statuses/public_timeline'
    assert last_response.ok?
    assert_equal [], JSON.parse(last_response.body)
  end

  def test_get_api_statuses_id_returns_a_status_by_id
    status = Status.create!
    get "/api/statuses/#{status.id}"
    assert_equal status.to_json, last_response.body
  end
end

Writing Tests with Rails

RSpec

describe Twitter::API do
  context 'GET /api/statuses/public_timeline' do
    it 'returns an empty array of statuses' do
      get '/api/statuses/public_timeline'
      expect(response.status).to eq(200)
      expect(JSON.parse(response.body)).to eq []
    end
  end
  context 'GET /api/statuses/:id' do
    it 'returns a status by id' do
      status = Status.create!
      get "/api/statuses/#{status.id}"
      expect(response.body).to eq status.to_json
    end
  end
end

In Rails, HTTP request tests would go into the spec/requests group. You may want your API code to go into app/api - you can match that layout under spec by adding the following in spec/rails_helper.rb.

RSpec.configure do |config|
  config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/
end

MiniTest

class Twitter::APITest < ActiveSupport::TestCase
  include Rack::Test::Methods

  def app
    Rails.application
  end

  test 'GET /api/statuses/public_timeline returns an empty array of statuses' do
    get '/api/statuses/public_timeline'
    assert last_response.ok?
    assert_equal [], JSON.parse(last_response.body)
  end

  test 'GET /api/statuses/:id returns a status by id' do
    status = Status.create!
    get "/api/statuses/#{status.id}"
    assert_equal status.to_json, last_response.body
  end
end

Stubbing Helpers

Because helpers are mixed in based on the context when an endpoint is defined, it can be difficult to stub or mock them for testing. The Grape::Endpoint.before_each method can help by allowing you to define behavior on the endpoint that will run before every request.

describe 'an endpoint that needs helpers stubbed' do
  before do
    Grape::Endpoint.before_each do |endpoint|
      allow(endpoint).to receive(:helper_name).and_return('desired_value')
    end
  end

  after do
    Grape::Endpoint.before_each nil
  end

  it 'stubs the helper' do

  end
end

Reloading API Changes in Development

Reloading in Rack Applications

Use grape-reload.

Reloading in Rails Applications

Add API paths to config/application.rb.

# Auto-load API and its subdirectories
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

Create config/initializers/reload_api.rb.

if Rails.env.development?
  ActiveSupport::Dependencies.explicitly_unloadable_constants << 'Twitter::API'

  api_files = Dir[Rails.root.join('app', 'api', '**', '*.rb')]
  api_reloader = ActiveSupport::FileUpdateChecker.new(api_files) do
    Rails.application.reload_routes!
  end
  ActionDispatch::Callbacks.to_prepare do
    api_reloader.execute_if_updated
  end
end

For Rails >= 5.1.4, change this:

ActionDispatch::Callbacks.to_prepare do
  api_reloader.execute_if_updated
end

to this:

ActiveSupport::Reloader.to_prepare do
  api_reloader.execute_if_updated
end

See StackOverflow #3282655 for more information.

Performance Monitoring

Active Support Instrumentation

Grape has built-in support for ActiveSupport::Notifications which provides simple hook points to instrument key parts of your application.

The following are currently supported:

endpoint_run.grape

The main execution of an endpoint, includes filters and rendering.

  • endpoint - The endpoint instance

endpoint_render.grape

The execution of the main content block of the endpoint.

  • endpoint - The endpoint instance

endpoint_run_filters.grape

  • endpoint - The endpoint instance
  • filters - The filters being executed
  • type - The type of filters (before, before_validation, after_validation, after)

endpoint_run_validators.grape

The execution of validators.

  • endpoint - The endpoint instance
  • validators - The validators being executed
  • request - The request being validated

format_response.grape

Serialization or template rendering.

  • env - The request environment
  • formatter - The formatter object (e.g., Grape::Formatter::Json)

See the ActiveSupport::Notifications documentation for information on how to subscribe to these events.

Monitoring Products

Grape integrates with following third-party tools:

Contributing to Grape

Grape is work of hundreds of contributors. You're encouraged to submit pull requests, propose features and discuss issues.

See CONTRIBUTING.

Security

See SECURITY for details.

License

MIT License. See LICENSE for details.

Copyright

Copyright (c) 2010-2020 Michael Bleigh, Intridea Inc. and Contributors.


Author: ruby-grape
Source code: https://github.com/ruby-grape/grape
License: MIT license

#ruby   #ruby-on-rails