External Formatting


Vim's internal formatting features work great in many cases, but sometimes it can be helpful to send a buffer's content to an external program to perform the formatting, then replace the buffer contents with the result.

For example, suppose we have the following JSON file in a buffer and want to sort the keys.

Initial Conditions
{ 
··"bananas":·12,
··"strawberries":·15,
··"apples":·34,
··"oranges":·24,
··"grapes":·33
}
COMMANDTop1:1
:%!jq -S . %

We will demonstrate how to achieve this using a command-line mode command that calls jq, a popular command-line JSON processor. Obviously jq needs to be installed on a system for this to work.

The command to execute is:

:%!jq -S . %

Let's break this down to review what is happening: To start, this follows the pattern:

:[range]!{cmd} {args}

where

:%

specifies the range as the entire file. Next,

!{cmd}

indicates that an external command is to be called with the specified range and arguments. In this case the external command to be called is:

jq -S . %

The details of this command are (mostly) outside the scope of Vim itself, but can be found by executing

jq --help

which indicates that the jq command is called with the format:

jq [options] <jq filter> [file]

where:

[options] = -S  (sort object keys)
<jq filter> = . (pass all lines back to stdout)
[file] = %      (Vim inserts the current filename)

Now, when we execute this command we get the following result:

After External Formatting
{ 
··"apples":·34,
··"bananas":·12,
··"grapes":·33,
··"oranges":·24,
··"strawberries":·15
}
NORMALTop1:1
7 lines filtered

which contains our sorted JSON object.