-
Notifications
You must be signed in to change notification settings - Fork 219
Auto Indentation and Pairing
A simple plugin that auto-closes, deletes and skips over matching delimiters in JLine. AutopairWidgets has been ported to JLine/java from zsh-autopair.
LineReader reader = LineReaderBuilder.builder()
.terminal(terminal)
.completer(completer)
.parser(parser)
.build();
// Create autopair widgets
AutopairWidgets autopairWidgets = new AutopairWidgets(reader);
// Enable autopair
autopairWidgets.enable();
AutopairWidgets
does 5 things for you:
-
It inserts matching pairs (by default, that means brackets, quotes and spaces):
e.g.
echo |
=> " =>echo "|"
-
It skips over matched pairs:
e.g.
cat ./*.{py,rb|}
=> } =>cat ./*.{py,rb}|
-
It auto-deletes pairs on backspace:
e.g.
git commit -m "|"
=> backspace =>git commit -m |
-
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) -
Spaces between brackets are expanded and contracted.
e.g.
echo [|]
=> space =>echo [ | ]
=> backspace =>echo [|]
Note: In above examples cursor position is marked as |.
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);
This plugin provides autopair-toggle
widget that toggles between enabled/disabled autopair.
Command line auto indentation has been implemented in DefaultParser
and LineReaderImpl
classes.
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();
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
.