Skip to content

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

Merged
itsaky-adfa merged 17 commits into
stagefrom
worktree/ADFA-4613
Jul 27, 2026
Merged

ADFA-4613: Surround with try/catch code action#1524
itsaky-adfa merged 17 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

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2ebef810-f9b3-48b5-8a8d-9b59a68b02c6

📥 Commits

Reviewing files that changed from the base of the PR and between e5087a8 and ed7aa25.

📒 Files selected for processing (2)
  • idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt
  • resources/src/main/res/values/strings.xml
💤 Files with no reviewable changes (1)
  • idetooltips/src/main/java/com/itsaky/androidide/idetooltips/TooltipTag.kt

📝 Walkthrough
  • Added a Kotlin K2 LSP “Surround with try/catch” code action for selected lines or the current line.
  • Preserves indentation, blank lines, and LF/CRLF line endings.
  • Registered the action with localized text and tooltip metadata.
  • Added comprehensive unit tests for selections, indentation, whitespace, line endings, and invalid ranges.
  • Risk: manual on-device verification is still recommended.

Walkthrough

Adds a Kotlin editor action that wraps selected whole lines in a try/catch, preserves indentation and line endings, registers the action in the Kotlin menu, submits the edit through the language client, and adds tooltip, label, and focused tests.

Changes

Kotlin try/catch code action

Layer / File(s) Summary
Action metadata and tooltip contracts
idetooltips/.../TooltipTag.kt, resources/.../strings.xml, lsp/kotlin/.../SurroundWithTryCatchAction.kt
Defines the tooltip tag, localized action label, and action metadata.
Selection and edit computation
lsp/kotlin/.../utils/SurroundWithTryCatch.kt, lsp/kotlin/.../SurroundWithTryCatchTest.kt
Resolves whole-line selections and generates validated try/catch edits with indentation, blank-line, CRLF, and range-index handling.
Menu and language-client integration
lsp/kotlin/.../KotlinCodeActionsMenu.kt, lsp/kotlin/.../SurroundWithTryCatchAction.kt
Adds the action to the Kotlin menu and submits its document change through the language client.

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

Sequence Diagram(s)

sequenceDiagram
  participant KotlinCodeActionsMenu
  participant SurroundWithTryCatchAction
  participant SurroundWithTryCatchUtils
  participant LanguageClient
  KotlinCodeActionsMenu->>SurroundWithTryCatchAction: expose try/catch action
  SurroundWithTryCatchAction->>SurroundWithTryCatchUtils: resolve selection and compute TextEdit
  SurroundWithTryCatchUtils-->>SurroundWithTryCatchAction: return TextEdit
  SurroundWithTryCatchAction->>LanguageClient: submit formatted DocumentChange
Loading

Suggested reviewers: hal-eisen-adfa, dara-abijo-adfa, jatezzz

Poem

A bunny chose lines with a hop and a snare,
Wrapped them in try/catch with neat padded care.
Tabs stayed as tabs, CRLFs danced bright,
The menu gained magic by editor light.
“Format it!” cried Rabbit, and edits took flight.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a Surround with try/catch code action.
Description check ✅ Passed The description is directly related to the changeset and accurately describes the new 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

The tooltip work in "fix: tooltips" belongs to ADFA-4867, which wires every
Kotlin code action to its own tag. Leaving it here made a try/catch PR the
only thing carrying tag fixes for three already-merged tickets.

Reverted from this branch:

- The editor.codeactions.kotlin.organizeimports, .overridesuper and
  .nullsafetyfix constants, plus the tooltipTag wiring on Implement members,
  Null-safety fixes and Organize imports.
- The Implement members label rename to "Override superclass methods", which
  also deleted the action_implement_members string. Per ADFA-4821 the Kotlin
  action covers properties and methods and stays "Implement members", so the
  string is restored. Deleting it would also have broken the build once
  ADFA-4867 landed, since that branch still references it.

Kept: editor.codeactions.kotlin.trycatch and its wiring on the new Surround
with try/catch action.

This leaves the branch diff as try/catch only.
@itsaky-adfa
itsaky-adfa merged commit cd39538 into stage Jul 27, 2026
4 checks passed
@itsaky-adfa
itsaky-adfa deleted the worktree/ADFA-4613 branch July 27, 2026 13:41
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