Skip to content

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

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

ADFA-4613: Surround with try/catch code action#1524
itsaky-adfa wants to merge 4 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 for selected lines or the current line.
  • Wraps code in a fixed try/catch block catching Exception and printing the stack trace.
  • Added line-range, indentation, blank-line, and invalid-input handling with five unit tests.
  • Registered the action in the Kotlin code actions menu and added localized UI text and tooltip metadata.
  • Kotlin unit tests pass. Manual on-device verification is recommended for editor action wiring.
  • Risk: the generated catch block is fixed and may not match all project error-handling conventions.

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

Layer / File(s) Summary
Compute try/catch text edits
lsp/kotlin/.../utils/SurroundWithTryCatch.kt, lsp/kotlin/.../utils/SurroundWithTryCatchTest.kt
Validates selected line ranges, preserves indentation, builds the wrapping TextEdit, and tests valid, blank, and invalid selections.
Register and execute the editor action
lsp/kotlin/.../KotlinCodeActionsMenu.kt, lsp/kotlin/.../actions/SurroundWithTryCatchAction.kt, idetooltips/.../TooltipTag.kt, resources/.../strings.xml
Registers the action, reads the selection, submits the edit through the language client, and adds its label and tooltip key.

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, elissa-appdevforall

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 names the new Surround with try/catch code action and matches the main change.
Description check ✅ Passed The description accurately explains the new Kotlin code action, helper, wiring, and tests.
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

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