Skip to main content

Module highlight

Module highlight 

Source
Expand description

Match highlighting: which characters of a hit the user typed.

After a search, Searcher::highlight (or Searcher::highlight_text for Searcher::search_text queries) re-runs the alignment of the query with one hit’s term and walks it back. It returns the parts of the caller’s original term string that the alignment matched, as sorted, disjoint, half-open ranges in code points, UTF-8 bytes and UTF-16 units. Only call it for the hits you show: the search itself does no highlighting work.

A term character is highlighted when it is aligned with an equal query character or is one of a transposed pair; substituted characters and characters the user skipped are not. The full rules (normalisation, partially matched characters such as ß, tie-breaking, prefix mode) are in docs/design/highlighting.md.

use keyhammer::cost::CostModel;
use keyhammer::highlight::HighlightMode;
use keyhammer::search::{SearchConfig, Searcher};
use keyhammer::text::Normalizer;
use keyhammer::trie::Trie;

let items = [("Coração", 10), ("Corrida", 5)];
let trie = Trie::build_normalized(&items, &Normalizer::new()).unwrap();
let cm = CostModel::qwerty();
let mut s = Searcher::new();
let q = "coracap"; // "p" for "o", a neighbouring key
let out = s.search_text(&trie, &cm, q, &SearchConfig::default()).unwrap();
let hit = &out.hits[0];
// The string the caller inserted for this term.
let source = items[trie.input_index(hit.id) as usize].0;
let h = s.highlight_text(&trie, &cm, q, hit, source, HighlightMode::Whole).unwrap();
assert_eq!(h.cost, hit.cost);
// "Coraçã" is highlighted, the final "o" was mistyped.
assert_eq!(h.ranges.len(), 1);
assert_eq!(h.ranges[0].chars, 0..6);
assert_eq!(h.ranges[0].utf8, 0..8); // ç and ã are two bytes each
assert_eq!(h.ranges[0].utf16, 0..6);
assert_eq!(&source[h.ranges[0].utf8.clone()], "Coraçã");

Structs§

Highlight
The highlighting of one hit.
MatchRange
One span of the caller’s term string, in three units.

Enums§

HighlightError
Why a hit could not be highlighted.
HighlightMode
Which search produced the hit.