Titles, result text and details (card, inspector, Lore Entries) get red wavy lines under misspelled words; right-click gives suggestions, Add to dictionary (saved with the spread) and Ignore (this session). Uses the Godot-Hunspell add-on's SpellChecker when it is installed; off on Android and when the add-on is missing. English (en_US) dictionary included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
47 lines
1.8 KiB
GDScript
47 lines
1.8 KiB
GDScript
class_name SpellWords
|
||
extends RefCounted
|
||
## Finds the words a spellchecker should look at in a field's text. Skips the
|
||
## parts that aren't prose: BBCode tags ([b], [color=#fff]), {placeholders},
|
||
## @values, [[Spread::Card]] links, numbers, dice ("2d6") and web addresses.
|
||
|
||
static var _word_re: RegEx
|
||
static var _skip_re: RegEx
|
||
|
||
|
||
static func _setup() -> void:
|
||
if _word_re != null:
|
||
return
|
||
# Letters, with inner apostrophes ("don't", "fortune-teller's" splits at -).
|
||
_word_re = RegEx.create_from_string("[\\p{L}]+(?:['’][\\p{L}]+)*")
|
||
# Spans to blank out first, so words inside them are never checked.
|
||
_skip_re = RegEx.create_from_string("\\[\\[[^\\]]*\\]\\]|\\[[^\\]\\n]*\\]|\\{[^}\\n]*\\}|@[\\w.]+|https?://\\S+|\\b\\d+d\\d+\\b|\\w*\\d\\w*")
|
||
|
||
|
||
## Vector2i(start, end) for each word to check, in text order (end exclusive).
|
||
static func ranges(text: String) -> Array[Vector2i]:
|
||
_setup()
|
||
var masked := text
|
||
for m in _skip_re.search_all(text):
|
||
var blank := " ".repeat(m.get_end() - m.get_start())
|
||
masked = masked.substr(0, m.get_start()) + blank + masked.substr(m.get_end())
|
||
var out: Array[Vector2i] = []
|
||
for m in _word_re.search_all(masked):
|
||
var word := m.get_string()
|
||
# Single letters and ALL-CAPS short forms (HP, NPC) are left alone.
|
||
if word.length() < 2 or (word.length() <= 4 and word == word.to_upper()):
|
||
continue
|
||
out.append(Vector2i(m.get_start(), m.get_end()))
|
||
return out
|
||
|
||
|
||
## The word range holding character `at`, or Vector2i(-1, -1).
|
||
static func range_at(text: String, at: int) -> Vector2i:
|
||
for r in ranges(text):
|
||
if at >= r.x and at <= r.y:
|
||
return r
|
||
return Vector2i(-1, -1)
|
||
|
||
|
||
## `text` with range `r` replaced by `word`.
|
||
static func replace(text: String, r: Vector2i, word: String) -> String:
|
||
return text.substr(0, r.x) + word + text.substr(r.y)
|