Skip to content

Auto Indentation and Pairing

mattirn edited this page Oct 29, 2020 · 6 revisions

AutopairWidgets

A simple plugin that auto-closes, deletes and skips over matching delimiters in JLine. AutopairWidgets has been ported to JLine/java from zsh-autopair.

Java

LineReader reader = LineReaderBuilder.builder()
                    .terminal(terminal)
                    .completer(completer)
                    .parser(parser)
                    .build();
// Create autopair widgets
AutopairWidgets autopairWidgets = new AutopairWidgets(reader);
// Enable autopair 
autopairWidgets.enable();

Functionality

AutopairWidgets does 5 things for you:

  1. It inserts matching pairs (by default, that means brackets, quotes and spaces):

    e.g. echo | => " => echo "|"

  2. It skips over matched pairs:

    e.g. cat ./*.{py,rb|} => } => cat ./*.{py,rb}|

  3. It auto-deletes pairs on backspace:

    e.g. git commit -m "|" => backspace => git commit -m |

  4. And does all of the above only when it makes sense to do so. e.g. when the pair is balanced and when the cursor isn't next to a boundary character:

    e.g. echo "|"" => backspace => echo |"" (doesn't aggressively eat up too many quotes)

  5. Spaces between brackets are expanded and contracted.

    e.g. echo [|] => space => echo [ | ] => backspace => echo [|]

Note: In above examples cursor position is marked as |.

Configuration

By default curly brackets {} are not paired by AutopairWidgets. Curly bracket pairing can be enabled by creating AutopairWidgets as

AutopairWidgets autopairWidgets = new AutopairWidgets(reader, true);

Key Bindings

This plugin provides autopair-toggle widget that toggles between enabled/disabled autopair.

Auto indentation

Command line auto indentation has been implemented in DefaultParser and LineReaderImpl classes.

Java

DefaultParser parser = new DefaultParser();
parser.setEofOnUnclosedBracket(Bracket.CURLY, Bracket.ROUND, Bracket.SQUARE);

LineReader reader = LineReaderBuilder.builder()
                    .terminal(terminal)
                    .completer(completer)
                    .parser(parser)
                    .variable(LineReader.SECONDARY_PROMPT_PATTERN, "%M%P > ") 
                    .variable(LineReader.INDENTATION, 2)   // indentation size
                    .option(Option.INSERT_BRACKET, true)   // insert closing bracket automatically
                    .build();

Functionality

Widget accept-line call Parser's method parser(...) that in case of unclosed brackets will throw EOFError exception that is caught by accept-line widget. EOFError exception contains necessary information to add indentation and the next closing bracket to the buffer.

Note that the last closing bracket must be entered manually even when option INSERT_BRACKET has been set true.

Clone this wiki locally