Skip to content

Cursor is lost when placed on if, then or else if keywords #3387

Closed

Description

@nojaf

When formatting with a cursor (CodeFormatter.FormatDocumentAsync(isSignature, source, config, cursor)), the returned FormatResult.Cursor is None whenever the caret sits on an if, then, else or else if keyword. An editor doing format-on-type/format-on-save would lose the caret position in those spots.

This is long-standing behaviour, not a recent regression.

Repro

let source =
    """
let f x =
    if x = 1 then
        "one"
    else if x = 2 then
        "two"
    else
        "many"
"""

CodeFormatter.FormatDocumentAsync(false, source, FormatConfig.Default, CodeFormatter.MakePosition(3, 4))
|> Async.RunSynchronously
|> fun r -> r.Cursor   // None, expected Some

Sweeping the caret across every column of the two conditional lines, and logging which node Trivia.findNodeWhereRangeFitsIn picks:

Line 3, if x = 1 then

columns resolves to FormatResult.Cursor
0-3 (indent) BindingNode Some (2,0)
4-6 (if ) SingleTextNode None
7-12 (x = 1 ) SingleTextNode Some
13-17 (then) SingleTextNode None

Line 5, else if x = 2 then

columns resolves to FormatResult.Cursor
4, 6, 8 (else + trailing space) elseNode (object expression in ElseIfNode) None
9, 10 (if) ifNode (object expression in ElseIfNode) None
12 (x) SingleTextNode Some (3,12)

Overall 8 of 18 columns on the if line and 13 of 23 on the else if line lose the cursor.

Cause 1 — genControlExpressionStartCore never records a cursor

src/Fantomas.Core/CodePrinter.fs:2159

let enterStart =
    match startKeyword with
    | Choice1Of2 n -> enterNode n
    | Choice2Of2 n -> enterNode n.Node

let genStart =
    match startKeyword with
    | Choice1Of2 node -> !-node.Text
    | Choice2Of2 ifKw ->
        match ifKw with
        | IfKeywordNode.SingleWord node -> !-node.Text
        | IfKeywordNode.ElseIf _ -> !-"else if"

let leaveStart =
    match startKeyword with
    | Choice1Of2 n -> leaveNode n
    | Choice2Of2 n -> leaveNode n.Node

This hand-rolls genNode, which is enterNode + recordCursorNode + leaveNode, but leaves out recordCursorNode. Since recordCursorNode is the only thing that reads Node.TryGetCursor and sets FormattedCursor, the cursor Trivia.insertCursor stored on the if/then SingleTextNode is never read back.

That accounts for every None on the plain if line, including then (the endKeyword, generated the same way).

Cause 2 — else if additionally never stores the cursor

ElseIfNode keeps the else and if keywords as two object expressions exposed through Children, so findNodeWhereRangeFitsIn correctly descends into them. But neither is a SingleTextNode, and Trivia.insertCursor (src/Fantomas.Core/Trivia.fs:511) only calls AddCursor for that one type:

match nodeWithCursor with
| Some((:? SingleTextNode) as node) -> node.AddCursor cursor
| _ -> addToTree tree [| TriviaNode(TriviaContent.Cursor, cursorRange) |]

So the caret falls into the Cursor-trivia fallback instead, and that trivia does not make it to output for these nodes.

Compounding it, ElseIfNode's own implementation discards cursors outright (src/Fantomas.Core/SyntaxOak.fs:1629):

member _.AddCursor _ = ()
member _.TryGetCursor = None

The inner elseNode/ifNode object expressions do implement AddCursor/TryGetCursor against elseCursor/ifCursor, but nothing ever generates those nodes through genNode, so those values are never read either.

Possible directions

  1. Thread recordCursorNode through genControlExpressionStartCore for the start and end keywords. This alone fixes if and then for every conditional. It only ever sets FormattedCursor and emits no text, so it cannot change formatted output.
  2. For else if, decide where the caret should be anchored — the else, the if, or the ElseIfNode as a whole — and then either relax the SingleTextNode restriction in insertCursor or give ElseIfNode a real AddCursor/TryGetCursor.

Happy to take either of these on; opening this mainly so the analysis is not lost.

Notes

  • src/Fantomas.Core.Tests/CursorTests.fs is the natural home for regression tests.
  • Verified against d6507185a; Trivia.fs and genControlExpressionStartCore are unchanged there, so this is not caused by any recent work.

Activity

  1. added 2 commits that reference this issue on Sep 30, 2026
    eb1d617
    7577ce6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions