Backend Development 18 min read

Design and Development of an IntelliJ Plugin for Smart Code Completion and Formatting

This article describes the motivation, design, implementation, and deployment of an IntelliJ IDEA plugin that automatically inserts semicolons and braces, formats code, and uses a chain‑of‑responsibility pattern to decouple business logic, providing developers with a smoother coding experience.

JD Tech
JD Tech
JD Tech
Design and Development of an IntelliJ Plugin for Smart Code Completion and Formatting

Introduction As development experience grows, many habits and pain points accumulate. Adapting the IDE to team habits, improving efficiency, and unifying code style become urgent. Modifying the IDE can also eliminate security risks and increase robustness.

Background Large projects enforce strict code style, making manual formatting tedious. Developers repeatedly add semicolons ; or braces {} and move the cursor, which is boring and inefficient. A plugin that automatically completes and formats code can free developers from this repetitive work.

Plugin Features

Intelligent end‑of‑line completion and cursor jump

Automatic formatting of the current line

Block‑code exit handling

With the plugin, developers no longer need to type ; or {} manually or move the cursor; they can focus on business logic and press Ctrl+Enter to finish a line.

IntelliJ Platform Overview IntelliJ provides a platform for building IDEs such as IDEA, WebStorm, Android Studio, PhpStorm, and PyCharm. It offers a rich set of language tools, UI components, PSI (Program Structure Interface), VFS, editor basics, and a plugin mechanism.

IntelliJ Platform Modules

Base Platform – threading, messaging, project structure, libraries, SDKs

Action System – add menu/toolbar items via plugins

PSI – code syntax and semantic model, code completion, inspection

VFS – unified file API

GUI – dialogs, toolbars, notifications

Editor Basics – document access, caret handling, editor events

Plugin – extension points and extensions

Others – additional utilities

These modules enable four major plugin types: custom language support, framework integration, tool integration, and UI customization.

Plugin Development Preparation Use IntelliJ IDEA Community 9.0+ and its source code for reference.

Important Concepts

Plugin descriptor file : META-INF\plugin.xml defines id, version, actions, extensions, supported languages, etc.

Version compatibility : declare supported IntelliJ versions in plugin.xml and handle API changes via conditional code or reflection.

Plugin levels : Application, Project, Module – each determines the plugin instance scope.

Extension points and extensions : declare <extensionPoints> and <extension> to interact with other plugins or the platform.

Persistence : implement PersistentStateComponent to store plugin state.

Plugin services : defined in plugin.xml , instantiated once per level.

Dependencies : declare jar or plugin dependencies in <depends> .

Creating an Action Extend AnAction (or EditorAction ) and override actionPerformed . Register the action in plugin.xml under <actions> or programmatically.

public class SuperEnterAction extends EditorAction {
    public SuperEnterAction() {
        super(new Handler());
    }
    private static class Handler extends EditorWriteActionHandler {
        public Handler() { super(true); }
        @Override
        public boolean isEnabledForCaret(@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) {
            return getEnterHandler().isEnabled(editor, caret, dataContext);
        }
        @Override
        public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
            // custom logic
        }
    }
}

Register:

<actions>
    <action id="super_enter" class="com.jd.tools.SuperEnterAction" text="Smart Assistant" description="Intelligent code completion and formatting">
        <add-to-group group-id="EditorActions" anchor="first" />
        <keyboard-shortcut keymap="$default" first-keystroke="ctrl ENTER"/>
    </action>
</actions>

Business Logic Decoupling Instead of long if‑else chains, a Chain of Responsibility pattern is used. Each handler implements IEnterHandler with isEnabledForCase and execute methods.

public interface IEnterHandler {
    boolean isEnabledForCase(EnterEvent event);
    boolean execute(EnterEvent event);
}

Base handlers such as BaseAppendSemicolonHandler and BaseAppendBracketHandler provide common logic; specific handlers (e.g., OnReturnEnterHandler ) override isEnabledForCase .

public class OnReturnEnterHandler extends BaseAppendSemicolonHandler {
    private static final Pattern RETURN_PATTERN = Pattern.compile("\\s*return\\s*\\w*", Pattern.DOTALL);
    @Override
    public boolean isEnabledForCase(EnterEvent event) {
        return RETURN_PATTERN.matcher(event.getCurrentLine()).matches();
    }
}

The manager registers handlers in order:

private EnterManager enterManager = new EnterManager();
private void initHandlers() {
    enterManager.addHandler(new OnConditionEnterHandler());
    // ... other handlers ...
    enterManager.addHandler(new FinalEnterHandler());
}

When an Enter event occurs, the manager dispatches it to the chain.

EnterEvent enterEvent = new EnterEvent();
CharSequence documentText = DocUtils.computeDescriptionMatchingPrefix(editor.getDocument(), lineEndOffset);
enterEvent.setCurrentLine(documentText.toString().trim());
enterEvent.setEditor(editor);
boolean consumeEvent = enterManager.onEnter(enterEvent);

Tool Methods Key IntelliJ APIs used:

Insert text: Editor.getDocument().insertString(int offset, String str)

Move caret: Editor.getCaretModel().moveToOffset(int offset)

Execute editor action: EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER).execute(editor, caret, dataContext)

Format current line (see code snippet in original source)

Debugging When using DevKit, simply click the Debug button. For Gradle projects, run intellij/runIde or intellij/runIdea tasks; attach source code via IDEA_SDK to debug platform classes.

Publishing Two packaging modes: a single JAR for plugins without external dependencies, or a ZIP containing a lib folder for plugins with external JARs. Publishing can be done via DevKit (Build → Prepare Plugin Module for Deployment) or Gradle tasks such as buildPlugin , patchPluginXml , and publishPlugin .

Usage Effects After installation, pressing Ctrl+Enter completes statements, inserts missing semicolons or braces, and formats the line, as demonstrated by the animated GIFs in the original article.

References IntelliJ official documentation and source code.

Design PatternsJavacode completionIDEplugin developmentIntelliJ
JD Tech
Written by

JD Tech

Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.