Skip to content

harper-ls: textDocument/codeAction reads the request range as Unicode scalar offsets instead of UTF-16 #4992

Open

Description

@ninjackster

Describe the bug

textDocument/codeAction reads the request range as Unicode scalar offsets, but harper-ls reports diagnostics and edits in UTF-16 code units. On a line with astral characters (emoji) before the flagged word, sending the diagnostic's own range back returns no code actions, so the client gets no fixes for that lint.

harper-ls does not advertise positionEncoding, so UTF-16 is the encoding in use (the LSP 3.17 default). Diagnostics and TextEdit ranges already follow it. Only the incoming request range does not.

It only shows once the drift is at least as long as the overlap with the flagged span. With one emoji before a three-letter word, the two readings still overlap and the fix comes back. With four emoji, they don't.

To Reproduce

Text: 🎉🎉🎉🎉 Look at teh launch. Each 🎉 (U+1F389) is 2 UTF-16 code units and 1 scalar.

  1. Open it as a plaintext document.
  2. harper-ls publishes a The diagnostic at UTF-16 17..20, which is teh (correct).
  3. Send textDocument/codeAction with that same range, 17..20. The response has 0 actions.
  4. Send it with the scalar offsets for the same span, 13..16. The response has 9 actions, and their edits start at UTF-16 17 (correct).

Output from the script below against harper-ls 3.2.0:

text: 🎉🎉🎉🎉 Look at teh launch.
diagnostic 'The': UTF-16 17..20 -> 'teh'
codeAction with UTF-16 range from the diagnostic 17..20: 0 actions, fixes=[], edit starts=[]
codeAction with same span as Unicode scalar offsets 13..16: 9 actions, fixes=['Replace with: “the”', 'Replace with: “the”'], edit starts=[17]
repro.py (Python 3, no dependencies): python3 repro.py /path/to/harper-ls
# Minimal repro: harper-ls reads textDocument/codeAction ranges as Unicode scalar offsets, not UTF-16.
# Usage: python3 repro.py /path/to/harper-ls
import json, subprocess, sys

ls = subprocess.Popen([sys.argv[1], "--stdio"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
next_id = 0

def send(msg):
    body = json.dumps(msg).encode()
    ls.stdin.write(b"Content-Length: %d\r\n\r\n" % len(body) + body)
    ls.stdin.flush()

def read():
    length = 0
    while (line := ls.stdout.readline().strip()):
        if line.lower().startswith(b"content-length:"):
            length = int(line.split(b":")[1])
    return json.loads(ls.stdout.read(length))

def wait_for(pred):
    while True:
        msg = read()
        if msg.get("method") == "workspace/configuration":  # answer config pulls with defaults
            send({"jsonrpc": "2.0", "id": msg["id"], "result": [{"harper-ls": {}}] * len(msg["params"]["items"])})
        elif "id" in msg and "method" in msg:
            send({"jsonrpc": "2.0", "id": msg["id"], "result": None})
        elif pred(msg):
            return msg

def request(method, params):
    global next_id
    next_id += 1
    send({"jsonrpc": "2.0", "id": next_id, "method": method, "params": params})
    return wait_for(lambda m: m.get("id") == next_id)["result"]

def rng(start, end):
    return {"start": {"line": 0, "character": start}, "end": {"line": 0, "character": end}}

uri = "file:///repro.txt"
text = "🎉🎉🎉🎉 Look at teh launch."  # each 🎉 (U+1F389) is 2 UTF-16 code units but 1 Unicode scalar
request("initialize", {"processId": None, "rootUri": None, "capabilities": {"workspace": {"configuration": True}}})
send({"jsonrpc": "2.0", "method": "initialized", "params": {}})
send({"jsonrpc": "2.0", "method": "textDocument/didOpen",
      "params": {"textDocument": {"uri": uri, "languageId": "plaintext", "version": 1, "text": text}}})
diag = next(d for d in wait_for(lambda m: m.get("method") == "textDocument/publishDiagnostics")["params"]["diagnostics"] if d["code"] == "The")

s, e = diag["range"]["start"]["character"], diag["range"]["end"]["character"]
print("text:", text)
print(f"diagnostic {diag['code']!r}: UTF-16 {s}..{e} -> {text.encode('utf-16-le')[s*2:e*2].decode('utf-16-le')!r}")
for label, r in [("UTF-16 range from the diagnostic", rng(s, e)), ("same span as Unicode scalar offsets", rng(len(text.encode("utf-16-le")[:s*2].decode("utf-16-le")), len(text.encode("utf-16-le")[:e*2].decode("utf-16-le"))))]:
    actions = request("textDocument/codeAction", {"textDocument": {"uri": uri}, "range": r, "context": {"diagnostics": [diag]}})
    fixes = [a["title"] for a in actions or [] if "edit" in a]
    edit_starts = sorted({c["range"]["start"]["character"] for a in actions or [] if "edit" in a for c in a["edit"]["changes"][uri]})
    print(f"codeAction with {label} {r['start']['character']}..{r['end']['character']}: {len(actions or [])} actions, fixes={fixes[:2]}, edit starts={edit_starts}")
send({"jsonrpc": "2.0", "method": "exit"})

Expected behavior

The code-action request range uses the same UTF-16 positions as the diagnostics, so step 3 returns the 9 actions that step 4 does.

Platform

harper-ls 3.2.0 over stdio (the harper-ls-aarch64-apple-darwin release asset, and the Homebrew build), macOS 27.2.1 on Apple silicon. I found it while writing an LSP client for a macOS writing app. Any client that sends UTF-16 positions should see it.

Additional context

Related but closed: #609 (underlines off by one after an emoji) and #2098 (the Obsidian plugin's offsets with emoji). Those covered the diagnostic side, which is correct now.

My workaround in the client is to send the union of the UTF-16 and scalar readings of the range, then keep only the actions whose HarperIgnoreLint message matches the diagnostic. That keeps working once this is fixed.

Activity

  1. added
    bug
    harper-ls
    on Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugharper-ls

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions