|
| 1 | +// SiYuan - Refactor your thinking |
| 2 | +// Copyright (c) 2020-present, b3log.org |
| 3 | +// |
| 4 | +// This program is free software: you can redistribute it and/or modify |
| 5 | +// it under the terms of the GNU Affero General Public License as published by |
| 6 | +// the Free Software Foundation, either version 3 of the License, or |
| 7 | +// (at your option) any later version. |
| 8 | +// |
| 9 | +// This program is distributed in the hope that it will be useful, |
| 10 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +// GNU Affero General Public License for more details. |
| 13 | +// |
| 14 | +// You should have received a copy of the GNU Affero General Public License |
| 15 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + |
| 17 | +package search |
| 18 | + |
| 19 | +import ( |
| 20 | + "regexp" |
| 21 | + "sort" |
| 22 | + "strings" |
| 23 | +) |
| 24 | + |
| 25 | +// hanSimpToTrads 是 hanTradToSimp 的反向索引:简体字 -> 折叠到该简体的全部繁体字。 |
| 26 | +var hanSimpToTrads = map[rune][]rune{} |
| 27 | + |
| 28 | +func init() { |
| 29 | + for t, s := range hanTradToSimp { |
| 30 | + hanSimpToTrads[s] = append(hanSimpToTrads[s], t) |
| 31 | + } |
| 32 | + for _, ts := range hanSimpToTrads { |
| 33 | + sort.Slice(ts, func(i, j int) bool { return ts[i] < ts[j] }) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// hanCharClass 返回与 r 繁简等价的所有字符(含 r 自身对应的简体),用于构造高亮正则。 |
| 38 | +func hanCharClass(r rune) (ret []rune) { |
| 39 | + canon := r |
| 40 | + if s, ok := hanTradToSimp[r]; ok { |
| 41 | + canon = s |
| 42 | + } |
| 43 | + ret = append(ret, canon) |
| 44 | + ret = append(ret, hanSimpToTrads[canon]...) |
| 45 | + return |
| 46 | +} |
| 47 | + |
| 48 | +// hanInsensitiveRegexp 将关键字逐字符展开为繁简等价字符类,例如 "诗经" -> "[诗詩][经經]"。 |
| 49 | +// 仅用于搜索结果高亮;等价关系与 go-sqlite3 中 siyuan 分词器 han_insensitive 的映射表 |
| 50 | +// 来自同一份 OpenCC TSCharacters 数据,必须保持一致。 |
| 51 | +func hanInsensitiveRegexp(k string) string { |
| 52 | + var b strings.Builder |
| 53 | + for _, r := range k { |
| 54 | + class := hanCharClass(r) |
| 55 | + if 1 == len(class) { |
| 56 | + b.WriteString(regexp.QuoteMeta(string(r))) |
| 57 | + continue |
| 58 | + } |
| 59 | + b.WriteString("[") |
| 60 | + for _, c := range class { |
| 61 | + b.WriteString(regexp.QuoteMeta(string(c))) |
| 62 | + } |
| 63 | + b.WriteString("]") |
| 64 | + } |
| 65 | + return b.String() |
| 66 | +} |
0 commit comments