Skip to content

ADFA-4613: Surround with try/catch code action#1524

Open
itsaky-adfa wants to merge 15 commits into
stagefrom
worktree/ADFA-4613
Open

ADFA-4613: Surround with try/catch code action#1524
itsaky-adfa wants to merge 15 commits into
stagefrom
worktree/ADFA-4613

Conversation

@itsaky-adfa

@itsaky-adfa itsaky-adfa commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds a Surround with try/catch code action to the Kotlin K2 LSP. On a selection in the editor's "Code actions" menu, it wraps the selected lines in:

try {
	<selected lines, indented one level deeper>
} catch (e: Exception) {
	e.printStackTrace()
}

Jira: ADFA-4613 (subtask of ADFA-3317, Integrate K2 compiler with LSP)

Approach

  • Selection-driven, not diagnostic-driven. Kotlin has no checked exceptions, and the K2 diagnostics provider emits nothing for unhandled exceptions, so there is no native diagnostic to trigger off (unlike the Java LSP's AddThrowsAction). The action operates on the current selection; with no selection it wraps the current line.
  • Pure edit helper. computeSurroundWithTryCatchEdit(text, startLine, endLine) computes a single whole-line replace TextEdit (columns ignored, matching CommentLineAction). It computes indentation itself, so the result is correct even if the follow-up formatter is unavailable.
  • Thin action. SurroundWithTryCatchAction : BaseKotlinCodeAction reads the editor selection, calls the helper, and routes the edit through languageClient.performCodeAction(...) with Command.CMD_FORMAT_CODE, mirroring AddImportAction. Registered in KotlinCodeActionsMenu.

Fixed catch (e: Exception) with an e.printStackTrace() body. Out of scope (deliberately): @Throws/exception-type inference, a diagnostic-triggered variant, PSI statement-snapping, and surround-with for other constructs.

Changes

  • lsp/kotlin/.../utils/SurroundWithTryCatch.kt - pure edit helper (new)
  • lsp/kotlin/.../actions/SurroundWithTryCatchAction.kt - the code action (new)
  • lsp/kotlin/.../KotlinCodeActionsMenu.kt - register the action
  • idetooltips/.../TooltipTag.kt - tooltip tag constant
  • resources/.../values/strings.xml - action_surround_with_try_catch string

Testing

  • Unit tests for the pure helper (SurroundWithTryCatchTest, 5 cases: single line, indented multi-line block, blank-line preservation, whitespace-only no-op, out-of-range guards), asserting exact newText and Range including computed indices. :lsp:kotlin:testV7DebugUnitTest -> 5/5 pass, no regressions.
  • The action wiring has no cheap unit test (needs a live editor); verified by module compile + existing suite. Manual on-device check recommended: select statements in a .kt file, run "Surround with try/catch" from the Code actions menu, confirm the block is wrapped and reindented.

@itsaky-adfa itsaky-adfa self-assigned this Jul 14, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@itsaky-adfa
itsaky-adfa requested a review from a team July 14, 2026 19:00
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough
  • Added a Kotlin K2 LSP “Surround with try/catch” code action that wraps the current selection (or current line when no selection is active) in:
    • try { ... } catch (e: Exception) { e.printStackTrace() }
  • Implemented a selection-driven edit helper (computeSurroundWithTryCatchEdit) that performs whole-line replacement, preserves indentation style (spaces vs tabs) and CRLF line endings, and keeps blank lines blank inside the try-body.
  • Added editor-selection span resolution (resolveSurroundLines) to trim the visually-unselected trailing line when the selection ends at column 0.
  • Registered the action in the Kotlin code actions menu, added the localized UI label (action_surround_with_try_catch), and wired tooltip metadata (TooltipTag.EDITOR_CODE_ACTIONS_KT_SURROUND_TRY_CATCH).
  • Expanded unit tests for single-/multi-line behavior, blank/whitespace-only handling, out-of-range guards, indentation style, CRLF preservation, and selection boundary cases (test coverage expanded beyond the initial scenarios).
  • Risks / best-practice notes:
    • The catch block is generated with a fixed signature (catch (e: Exception)) and body (e.printStackTrace()), which may not match all project-specific exception-handling conventions.
    • The action dispatches formatting via Command.CMD_FORMAT_CODE and requires a language client at post-exec time (logs a warning and no-ops if missing).

Walkthrough

Adds a Kotlin code action that wraps selected editor lines in a try/catch block, computes the corresponding TextEdit, registers the action in the Kotlin menu, and provides UI text and tooltip metadata.

Changes

Surround with try/catch and Kotlin action metadata

Layer / File(s) Summary
Action contracts and tooltip metadata
idetooltips/.../TooltipTag.kt, lsp/kotlin/.../actions/*, resources/.../strings.xml
Adds Kotlin-specific tooltip tags, wires them to existing actions, and adds the try/catch action label.
Compute try/catch text edits
lsp/kotlin/.../utils/SurroundWithTryCatch.kt, lsp/kotlin/.../utils/SurroundWithTryCatchTest.kt
Resolves whole-line selections, preserves indentation and newline style, builds the wrapping TextEdit, and tests valid, blank, invalid, CRLF, and indentation cases.
Register and execute the editor action
lsp/kotlin/.../KotlinCodeActionsMenu.kt, lsp/kotlin/.../actions/SurroundWithTryCatchAction.kt
Registers the action, reads the selection, computes the edit, and submits it through the language client.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant KotlinCodeActionsMenu
  participant SurroundWithTryCatchAction
  participant computeSurroundWithTryCatchEdit
  participant languageClient
  KotlinCodeActionsMenu->>SurroundWithTryCatchAction: expose action
  SurroundWithTryCatchAction->>computeSurroundWithTryCatchEdit: pass selected lines and editor text
  computeSurroundWithTryCatchEdit-->>SurroundWithTryCatchAction: return TextEdit
  SurroundWithTryCatchAction->>languageClient: performCodeAction with DocumentChange
Loading

Possibly related PRs

Suggested reviewers: dara-abijo-adfa, jatezzz

Poem

I’m a bunny with braces, hopping through code,
Wrapping risky lines on their Kotlin road.
Try on the left, catch on the right,
A neat little fix in one quick bite! 🐰

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding a Surround with try/catch code action.
Description check ✅ Passed The description matches the changeset and accurately describes the new Kotlin code action and its implementation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree/ADFA-4613

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SurroundWithTryCatch.kt (1)

28-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive the block indentation token from the surrounding code.

The implementation hardcodes \t for the added block depth. If the user's codebase uses spaces (e.g., baseIndent consists of spaces), this creates a mix of spaces and tabs (e.g., \te.printStackTrace()). While the follow-up formatter might clean this up, inferring the indent token ensures the raw text edit remains consistent in case the formatter is unavailable or fails.

♻️ Proposed refactor to dynamically infer indentation
 	val baseIndent =
 		selected.first(String::isNotBlank).takeWhile { it == ' ' || it == '\t' }
-	val body = selected.joinToString("\n") { if (it.isBlank()) it else "\t$it" }
+	val indentToken = if (baseIndent.startsWith(" ")) "    " else "\t"
+	val body = selected.joinToString("\n") { if (it.isBlank()) it else "$indentToken$it" }
 
 	val newText = buildString {
 		append(baseIndent).append("try {\n")
 		append(body).append('\n')
 		append(baseIndent).append("} catch (e: Exception) {\n")
-		append(baseIndent).append("\te.printStackTrace()\n")
+		append(baseIndent).append(indentToken).append("e.printStackTrace()\n")
 		append(baseIndent).append("}")
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SurroundWithTryCatch.kt`
around lines 28 - 38, Update the indentation logic in the newText builder to
derive the block indentation token from the surrounding code instead of
hardcoding tab characters. Use the indentation style represented by baseIndent
when indenting body lines and the catch statement, while preserving the existing
try/catch structure and relative nesting.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SurroundWithTryCatch.kt`:
- Around line 28-38: Update the indentation logic in the newText builder to
derive the block indentation token from the surrounding code instead of
hardcoding tab characters. Use the indentation style represented by baseIndent
when indenting body lines and the catch statement, while preserving the existing
try/catch structure and relative nesting.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 499f9ecd-3320-4fb2-845e-d5c61d16d8fa

📥 Commits

Reviewing files that changed from the base of the PR and between 875853d and 9ac90bf.

📒 Files selected for processing (6)
  • idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/KotlinCodeActionsMenu.kt
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/SurroundWithTryCatchAction.kt
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/utils/SurroundWithTryCatch.kt
  • lsp/kotlin/src/test/java/com/itsaky/androidide/lsp/kotlin/utils/SurroundWithTryCatchTest.kt
  • resources/src/main/res/values/strings.xml

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/ImplementMembersAction.kt`:
- Around line 33-34: Update ImplementMembersAction’s titleTextRes and tooltipTag
to the implement-members metadata that matches computeImplementMembersEdit and
its implementMembers action ID. Keep the action’s existing implementation
behavior unchanged rather than advertising override-superclass methods.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 16597bf3-5c70-4581-9982-3581eaa64f37

📥 Commits

Reviewing files that changed from the base of the PR and between f90b6b9 and e8872a7.

📒 Files selected for processing (6)
  • idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/ImplementMembersAction.kt
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/NullSafetyAction.kt
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/OrganizeImportsAction.kt
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/SurroundWithTryCatchAction.kt
  • resources/src/main/res/values/strings.xml
💤 Files with no reviewable changes (1)
  • resources/src/main/res/values/strings.xml
🚧 Files skipped from review as they are similar to previous changes (1)
  • lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/SurroundWithTryCatchAction.kt

Comment on lines +33 to +34
override var titleTextRes: Int = R.string.action_override_superclass_methods
override var tooltipTag: String = TooltipTag.EDITOR_CODE_ACTIONS_KT_OVERRIDE_SUPER

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep the metadata aligned with the implemented action.

ImplementMembersAction still calls computeImplementMembersEdit and uses the implementMembers ID, but these lines now advertise “Override superclass methods.” Restore implement-members metadata, or rename/rework the action consistently if override-superclass behavior is intended.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lsp/kotlin/src/main/java/com/itsaky/androidide/lsp/kotlin/actions/ImplementMembersAction.kt`
around lines 33 - 34, Update ImplementMembersAction’s titleTextRes and
tooltipTag to the implement-members metadata that matches
computeImplementMembersEdit and its implementMembers action ID. Keep the
action’s existing implementation behavior unchanged rather than advertising
override-superclass methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants