@riebeckite/plugin-citations 0.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +79 -0
- package/README_ja.md +79 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +745 -0
- package/dist/src/bibliography.d.ts +2 -0
- package/dist/src/remark.d.ts +7 -0
- package/dist/src/state.d.ts +7 -0
- package/dist/src/types.d.ts +46 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright Rerurate_514
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# @riebeckite/plugin-citations
|
|
2
|
+
|
|
3
|
+
[日本語版](./README_ja.md)
|
|
4
|
+
|
|
5
|
+
Official Riebeckite plugin for BibTeX / BibLaTeX based citations in Markdown and Obsidian notes.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { citations } from "@riebeckite/plugin-citations";
|
|
9
|
+
|
|
10
|
+
export default {
|
|
11
|
+
plugins: [
|
|
12
|
+
citations({ bibliography: "references.bib" }),
|
|
13
|
+
],
|
|
14
|
+
};
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Supported citation syntax
|
|
18
|
+
|
|
19
|
+
The plugin implements a stable Pandoc-inspired subset:
|
|
20
|
+
|
|
21
|
+
- `[@smith2024]`
|
|
22
|
+
- `[@smith2024; @doe2025]` — multiple keys must be separated by `;`
|
|
23
|
+
- `@smith2024 argues that ...`
|
|
24
|
+
- `[-@smith2024]` — suppress-author input
|
|
25
|
+
- `[@smith2024, p. 42]` and `[see @doe2025]` — prefix and suffix are kept, rendering as `[1, p. 42]` and `[see 2]`
|
|
26
|
+
|
|
27
|
+
Repeated citations reuse the first number assigned to that key. Under numeric labels, `[-@smith2024]` renders the same label as `[@smith2024]`.
|
|
28
|
+
|
|
29
|
+
Inline `@key` must be preceded by the start of the text, whitespace, or `(`. Text attached directly to `@key` on the left — for example `本文@smith2024` — is not recognized; write `[@smith2024]` instead.
|
|
30
|
+
|
|
31
|
+
Riebeckite parses `:name` as a directive before this plugin runs. When that split breaks a citation key, the plugin reassembles it, so `[@colon:2024]` and `@colon:2024 argues` both work. Keys may contain letters, digits, `-`, `_`, `:`, and `.`.
|
|
32
|
+
|
|
33
|
+
Not transformed: inline code, fenced code blocks, HTML, frontmatter, normal Markdown links (at any nesting depth), and Obsidian WikiLinks.
|
|
34
|
+
|
|
35
|
+
## Bibliography files
|
|
36
|
+
|
|
37
|
+
- `citations({ bibliography })` paths are relative to the content root.
|
|
38
|
+
- Frontmatter `bibliography` is resolved relative to the page first, then to the content root. Both `/` and `\` separators are accepted and `../` is normalized inside the string; every candidate still goes through the content source, so nothing outside the configured content root can be read.
|
|
39
|
+
- The bibliography file is read at build time only. It is never copied into the output and absolute paths never appear in generated files.
|
|
40
|
+
|
|
41
|
+
## Supported bibliography subset
|
|
42
|
+
|
|
43
|
+
Curated entry types are `article`, `book`, `inproceedings`, and `misc`. Other entry types are still parsed and rendered with generic fields, and reported as `citation-unsupported-entry-type`.
|
|
44
|
+
|
|
45
|
+
`@comment`, `@preamble`, and `@string` entries are accepted and skipped. Malformed entries report `citation-malformed-bibliography` and parsing resumes at the next `@`, so one broken entry does not discard the rest of the file.
|
|
46
|
+
|
|
47
|
+
Supported syntax: multiline fields, quoted and braced values, nested braces, commas inside values, escaped characters, trailing commas, whitespace and CRLF.
|
|
48
|
+
|
|
49
|
+
Reported through `citation-unsupported-bibliography-syntax` instead of failing silently:
|
|
50
|
+
|
|
51
|
+
- `@string` macro references are rendered literally; they are not expanded.
|
|
52
|
+
- `#` string concatenation keeps only the first part.
|
|
53
|
+
|
|
54
|
+
## References section
|
|
55
|
+
|
|
56
|
+
Pages with citations receive a `References` heading and an ordered list at the end of the Markdown body. Each entry carries an `id` of the form `ref-<sanitized key>`, where characters outside `[A-Za-z0-9_-]` are replaced by `-` and collisions get a deterministic numeric suffix. Citation labels link to that anchor.
|
|
57
|
+
|
|
58
|
+
Use `referencesHeading` for localized headings:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
citations({ bibliography: "references.bib", referencesHeading: "参考文献" })
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Diagnostics
|
|
65
|
+
|
|
66
|
+
Reported through Riebeckite diagnostics:
|
|
67
|
+
|
|
68
|
+
- `citation-unknown-key`
|
|
69
|
+
- `citation-missing-bibliography`
|
|
70
|
+
- `citation-malformed-bibliography`
|
|
71
|
+
- `citation-duplicate-key`
|
|
72
|
+
- `citation-unsupported-entry-type`
|
|
73
|
+
- `citation-unsupported-bibliography-syntax`
|
|
74
|
+
|
|
75
|
+
Citation numbering, reference ordering, generated HTML, and diagnostics are deterministic: identical input produces identical output.
|
|
76
|
+
|
|
77
|
+
## License
|
|
78
|
+
|
|
79
|
+
Apache-2.0
|
package/README_ja.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# @riebeckite/plugin-citations
|
|
2
|
+
|
|
3
|
+
[English](./README.md)
|
|
4
|
+
|
|
5
|
+
Markdown / Obsidian ノートで BibTeX / BibLaTeX の文献情報を使って引用を表示する、Riebeckite 公式プラグインです。
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { citations } from "@riebeckite/plugin-citations";
|
|
9
|
+
|
|
10
|
+
export default {
|
|
11
|
+
plugins: [
|
|
12
|
+
citations({ bibliography: "references.bib" }),
|
|
13
|
+
],
|
|
14
|
+
};
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## 対応する引用の記法
|
|
18
|
+
|
|
19
|
+
Pandoc を参考にした、安定した一部の記法を扱います。
|
|
20
|
+
|
|
21
|
+
- `[@smith2024]`
|
|
22
|
+
- `[@smith2024; @doe2025]` — 複数のキーは `;` で区切る
|
|
23
|
+
- `@smith2024 argues that ...`
|
|
24
|
+
- `[-@smith2024]` — 著者名を出さない形の入力
|
|
25
|
+
- `[@smith2024, p. 42]` と `[see @doe2025]` — prefix / suffix を保持し、`[1, p. 42]` と `[see 2]` として表示する
|
|
26
|
+
|
|
27
|
+
同じ文献を何度も引用した場合は、最初に割り当てた番号を再利用します。番号形式の表示では `[-@smith2024]` と `[@smith2024]` のラベルは同じになります。
|
|
28
|
+
|
|
29
|
+
本文中の `@key` は、テキストの先頭、空白、`(` のいずれかの直後に書きます。`本文@smith2024` のように `@key` の左が文字でつながっている形は認識されないため、`[@smith2024]` を使ってください。
|
|
30
|
+
|
|
31
|
+
Riebeckite はこのプラグインより先に `:name` を directive として解釈します。directive 化によって引用キーが分断された場合はプラグインが組み直すため、`[@colon:2024]` と `@colon:2024 argues` の両方が動きます。キーに使えるのは英字、数字、`-`、`_`、`:`、`.` です。
|
|
32
|
+
|
|
33
|
+
変換しない対象: inline code、fenced code block、HTML、frontmatter、任意の階層にある通常の Markdown リンク、Obsidian の WikiLink。
|
|
34
|
+
|
|
35
|
+
## 文献ファイルの読み込み
|
|
36
|
+
|
|
37
|
+
- `citations({ bibliography })` のパスはコンテンツルートからの相対パスです。
|
|
38
|
+
- frontmatter の `bibliography` は、まずページからの相対パス、次にコンテンツルートからの相対パスとして解決します。`/` と `\` の両区切りを受け付け、`../` は文字列内で正規化します。候補はいずれも content source を通るため、設定されたコンテンツルートの外は読み込めません。
|
|
39
|
+
- 文献ファイルはビルド時に読み込むだけで、出力にはコピーされず、絶対パスも生成物に現れません。
|
|
40
|
+
|
|
41
|
+
## 対応する BibTeX の範囲
|
|
42
|
+
|
|
43
|
+
重点的に扱う文献種別は `article`、`book`、`inproceedings`、`misc` です。その他の種別も汎用フィールドとして読み込んで表示し、`citation-unsupported-entry-type` として報告します。
|
|
44
|
+
|
|
45
|
+
`@comment`、`@preamble`、`@string` は受け付けて読み飛ばします。壊れたエントリは `citation-malformed-bibliography` を出し、次の `@` から再開するため、1件の不正でファイル残りが消えることはありません。
|
|
46
|
+
|
|
47
|
+
対応する構文: 複数行フィールド、引用符と波括弧の値、ネストした波括弧、値の中のカンマ、エスケープ文字、末尾カンマ、空白、CRLF。
|
|
48
|
+
|
|
49
|
+
次は沈黙せず `citation-unsupported-bibliography-syntax` として報告します。
|
|
50
|
+
|
|
51
|
+
- `@string` のマクロ参照は展開せずそのまま文字列として表示する
|
|
52
|
+
- `#` による文字列連結は先頭の部分しか保持しない
|
|
53
|
+
|
|
54
|
+
## 参考文献リスト
|
|
55
|
+
|
|
56
|
+
引用があるページでは、Markdown 本文の末尾に `References` 見出しと番号付きリストを追加します。各項目には `ref-<正規化したキー>` 形式の `id` を付与します。`[A-Za-z0-9_-]` 以外の文字は `-` に置き換え、衝突した場合は決定的な連番を付けます。引用ラベルはこのアンカーへリンクします。
|
|
57
|
+
|
|
58
|
+
日本語サイトでは見出しを変えられます。
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
citations({ bibliography: "references.bib", referencesHeading: "参考文献" })
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## diagnostics
|
|
65
|
+
|
|
66
|
+
以下を Riebeckite の diagnostics に出力します。
|
|
67
|
+
|
|
68
|
+
- `citation-unknown-key`
|
|
69
|
+
- `citation-missing-bibliography`
|
|
70
|
+
- `citation-malformed-bibliography`
|
|
71
|
+
- `citation-duplicate-key`
|
|
72
|
+
- `citation-unsupported-entry-type`
|
|
73
|
+
- `citation-unsupported-bibliography-syntax`
|
|
74
|
+
|
|
75
|
+
引用番号、参考文献の並び、生成される HTML、diagnostics の順序は決定的で、同じ入力からは同じ出力になります。
|
|
76
|
+
|
|
77
|
+
## ライセンス
|
|
78
|
+
|
|
79
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CitationsOptions } from "./src/types.js";
|
|
2
|
+
export { parseBibliography } from "./src/bibliography.js";
|
|
3
|
+
export { remarkCitations } from "./src/remark.js";
|
|
4
|
+
export type { BibliographyEntry, CitationOccurrence, CitationReference, CitationSyntax, CitationsOptions, ResolvedCitation, } from "./src/types.js";
|
|
5
|
+
export declare function citations(options?: CitationsOptions): import("@riebeckite/core").RiebeckitePlugin<CitationsOptions>;
|
|
6
|
+
export declare const citationsPlugin: typeof citations;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
1
|
+
// index.ts
|
|
2
|
+
import {
|
|
3
|
+
definePlugin,
|
|
4
|
+
readContentSourceEntry
|
|
5
|
+
} from "@riebeckite/core";
|
|
6
|
+
|
|
7
|
+
// src/remark.ts
|
|
8
|
+
import { visit } from "unist-util-visit";
|
|
9
|
+
|
|
10
|
+
// src/bibliography.ts
|
|
11
|
+
var SUPPORTED_TYPES = /* @__PURE__ */ new Set(["article", "book", "inproceedings", "misc"]);
|
|
12
|
+
var NON_ENTRY_TYPES = /* @__PURE__ */ new Set(["comment", "preamble", "string"]);
|
|
13
|
+
var BUILTIN_MACROS = /* @__PURE__ */ new Set([
|
|
14
|
+
"jan",
|
|
15
|
+
"feb",
|
|
16
|
+
"mar",
|
|
17
|
+
"apr",
|
|
18
|
+
"may",
|
|
19
|
+
"jun",
|
|
20
|
+
"jul",
|
|
21
|
+
"aug",
|
|
22
|
+
"sep",
|
|
23
|
+
"oct",
|
|
24
|
+
"nov",
|
|
25
|
+
"dec"
|
|
26
|
+
]);
|
|
27
|
+
function parseBibliography(source, filePath = "bibliography") {
|
|
28
|
+
const text = source.replace(/\r\n?/g, "\n");
|
|
29
|
+
const entries = /* @__PURE__ */ new Map();
|
|
30
|
+
const diagnostics = [];
|
|
31
|
+
let index = 0;
|
|
32
|
+
while (index < text.length) {
|
|
33
|
+
const at = text.indexOf("@", index);
|
|
34
|
+
if (at < 0) break;
|
|
35
|
+
const parsed = parseEntry(text, at, filePath);
|
|
36
|
+
if (parsed.kind === "ignored") {
|
|
37
|
+
index = at + 1;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (parsed.kind === "malformed") {
|
|
41
|
+
diagnostics.push({
|
|
42
|
+
code: "citation-malformed-bibliography",
|
|
43
|
+
severity: "error",
|
|
44
|
+
message: `Malformed bibliography entry in ${filePath}: ${parsed.reason}`,
|
|
45
|
+
filePath
|
|
46
|
+
});
|
|
47
|
+
index = at + 1;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
index = parsed.nextIndex;
|
|
51
|
+
if (parsed.kind === "skipped") continue;
|
|
52
|
+
const { entry } = parsed;
|
|
53
|
+
if (entries.has(entry.key)) {
|
|
54
|
+
diagnostics.push({
|
|
55
|
+
code: "citation-duplicate-key",
|
|
56
|
+
severity: "warning",
|
|
57
|
+
message: `Duplicate bibliography key: ${entry.key}`,
|
|
58
|
+
filePath,
|
|
59
|
+
target: entry.key
|
|
60
|
+
});
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (!SUPPORTED_TYPES.has(entry.type)) {
|
|
64
|
+
diagnostics.push({
|
|
65
|
+
code: "citation-unsupported-entry-type",
|
|
66
|
+
severity: "warning",
|
|
67
|
+
message: `Bibliography entry type "${entry.type}" is not fully supported; "${entry.key}" is rendered with generic fields.`,
|
|
68
|
+
filePath,
|
|
69
|
+
target: entry.key
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
diagnostics.push(...parsed.diagnostics);
|
|
73
|
+
entries.set(entry.key, entry);
|
|
74
|
+
}
|
|
75
|
+
return { entries, diagnostics };
|
|
76
|
+
}
|
|
77
|
+
function parseEntry(text, start, filePath) {
|
|
78
|
+
const typeMatch = /^@([A-Za-z]+)\s*[{(]/.exec(text.slice(start));
|
|
79
|
+
if (!typeMatch) return { kind: "ignored" };
|
|
80
|
+
const type = typeMatch[1].toLowerCase();
|
|
81
|
+
const bodyStart = start + typeMatch[0].length;
|
|
82
|
+
const close = findEntryClose(text, bodyStart - 1);
|
|
83
|
+
if (close < 0) return { kind: "malformed", reason: "unterminated entry" };
|
|
84
|
+
const body = text.slice(bodyStart, close).trim();
|
|
85
|
+
if (NON_ENTRY_TYPES.has(type)) {
|
|
86
|
+
return { kind: "skipped", nextIndex: close + 1 };
|
|
87
|
+
}
|
|
88
|
+
const comma = findTopLevelComma(body);
|
|
89
|
+
if (comma < 0) {
|
|
90
|
+
return { kind: "malformed", reason: `entry "${type}" has no citation key` };
|
|
91
|
+
}
|
|
92
|
+
const key = body.slice(0, comma).trim();
|
|
93
|
+
if (!key) return { kind: "malformed", reason: "empty citation key" };
|
|
94
|
+
const fields = parseFields(body.slice(comma + 1), key, filePath);
|
|
95
|
+
return {
|
|
96
|
+
kind: "entry",
|
|
97
|
+
entry: { key, type, fields: fields.fields },
|
|
98
|
+
nextIndex: close + 1,
|
|
99
|
+
diagnostics: fields.diagnostics
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function findEntryClose(text, openIndex) {
|
|
103
|
+
const open = text[openIndex];
|
|
104
|
+
let depth = 0;
|
|
105
|
+
let braceDepth = 0;
|
|
106
|
+
let quoted = false;
|
|
107
|
+
for (let index = openIndex; index < text.length; index += 1) {
|
|
108
|
+
const char = text[index];
|
|
109
|
+
if (char === '"' && text[index - 1] !== "\\") {
|
|
110
|
+
quoted = !quoted;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (quoted) continue;
|
|
114
|
+
if (open === "{") {
|
|
115
|
+
if (char === "{") depth += 1;
|
|
116
|
+
else if (char === "}") {
|
|
117
|
+
depth -= 1;
|
|
118
|
+
if (depth === 0) return index;
|
|
119
|
+
}
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (char === "{") {
|
|
123
|
+
braceDepth += 1;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (char === "}") {
|
|
127
|
+
braceDepth -= 1;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (braceDepth > 0) continue;
|
|
131
|
+
if (char === "(") depth += 1;
|
|
132
|
+
else if (char === ")") {
|
|
133
|
+
depth -= 1;
|
|
134
|
+
if (depth === 0) return index;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return -1;
|
|
138
|
+
}
|
|
139
|
+
function findTopLevelComma(input) {
|
|
140
|
+
let braceDepth = 0;
|
|
141
|
+
let quoted = false;
|
|
142
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
143
|
+
const char = input[index];
|
|
144
|
+
if (char === '"' && input[index - 1] !== "\\") {
|
|
145
|
+
quoted = !quoted;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (quoted) continue;
|
|
149
|
+
if (char === "{") braceDepth += 1;
|
|
150
|
+
else if (char === "}") braceDepth -= 1;
|
|
151
|
+
else if (char === "," && braceDepth <= 0) return index;
|
|
152
|
+
}
|
|
153
|
+
return -1;
|
|
154
|
+
}
|
|
155
|
+
function parseFields(input, target, filePath) {
|
|
156
|
+
const fields = {};
|
|
157
|
+
const diagnostics = [];
|
|
158
|
+
let index = 0;
|
|
159
|
+
while (index < input.length) {
|
|
160
|
+
const matcher = /\s*([A-Za-z][A-Za-z0-9_-]*)\s*=\s*/y;
|
|
161
|
+
matcher.lastIndex = index;
|
|
162
|
+
const field = matcher.exec(input);
|
|
163
|
+
if (!field) {
|
|
164
|
+
const rest = input.slice(index).replace(/[\s,]+/g, "");
|
|
165
|
+
if (rest) {
|
|
166
|
+
diagnostics.push(
|
|
167
|
+
unsupportedSyntax(
|
|
168
|
+
`Unexpected text "${rest}" where a field was expected`,
|
|
169
|
+
target,
|
|
170
|
+
filePath
|
|
171
|
+
)
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
const name = field[1].toLowerCase();
|
|
177
|
+
const value = readValue(input, matcher.lastIndex);
|
|
178
|
+
fields[name] = cleanValue(value.value);
|
|
179
|
+
if (value.unclosed) {
|
|
180
|
+
diagnostics.push({
|
|
181
|
+
code: "citation-malformed-bibliography",
|
|
182
|
+
severity: "error",
|
|
183
|
+
message: `Unclosed ${value.opener === "{" ? "braced" : "quoted"} value for field "${name}" in "${filePath}".`,
|
|
184
|
+
filePath,
|
|
185
|
+
target
|
|
186
|
+
});
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
let nextIndex = value.nextIndex;
|
|
190
|
+
if (isConcatenation(input, nextIndex)) {
|
|
191
|
+
diagnostics.push(
|
|
192
|
+
unsupportedSyntax(
|
|
193
|
+
`String concatenation in field "${name}" is not supported`,
|
|
194
|
+
target,
|
|
195
|
+
filePath
|
|
196
|
+
)
|
|
197
|
+
);
|
|
198
|
+
nextIndex = scanToTopLevelComma(input, nextIndex);
|
|
199
|
+
} else if (isUnresolvedMacro(value)) {
|
|
200
|
+
diagnostics.push(
|
|
201
|
+
unsupportedSyntax(
|
|
202
|
+
`BibTeX macro "${value.value}" in field "${name}" is not expanded and is rendered literally`,
|
|
203
|
+
target,
|
|
204
|
+
filePath
|
|
205
|
+
)
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
index = nextIndex;
|
|
209
|
+
while (input[index] && /[\s,]/.test(input[index])) index += 1;
|
|
210
|
+
}
|
|
211
|
+
return { fields, diagnostics };
|
|
212
|
+
}
|
|
213
|
+
function readValue(input, start) {
|
|
214
|
+
const opener = input[start];
|
|
215
|
+
if (opener === "{" || opener === '"') {
|
|
216
|
+
const closer = opener === "{" ? "}" : '"';
|
|
217
|
+
let depth = opener === "{" ? 1 : 0;
|
|
218
|
+
for (let index = start + 1; index < input.length; index += 1) {
|
|
219
|
+
const char = input[index];
|
|
220
|
+
if (opener === "{" && char === "{") depth += 1;
|
|
221
|
+
if (char === closer && input[index - 1] !== "\\") {
|
|
222
|
+
if (opener === '"' || depth === 1) {
|
|
223
|
+
return {
|
|
224
|
+
value: input.slice(start + 1, index),
|
|
225
|
+
nextIndex: index + 1,
|
|
226
|
+
delimited: true
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
depth -= 1;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
value: input.slice(start + 1),
|
|
234
|
+
nextIndex: input.length,
|
|
235
|
+
delimited: true,
|
|
236
|
+
unclosed: true,
|
|
237
|
+
opener
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
let end = start;
|
|
241
|
+
while (end < input.length && input[end] !== "," && input[end] !== "#") {
|
|
242
|
+
end += 1;
|
|
243
|
+
}
|
|
244
|
+
return {
|
|
245
|
+
value: input.slice(start, end).trim(),
|
|
246
|
+
nextIndex: end,
|
|
247
|
+
delimited: false
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function isConcatenation(input, from) {
|
|
251
|
+
return input.slice(from).trimStart().startsWith("#");
|
|
252
|
+
}
|
|
253
|
+
function scanToTopLevelComma(input, from) {
|
|
254
|
+
let braceDepth = 0;
|
|
255
|
+
let quoted = false;
|
|
256
|
+
for (let index = from; index < input.length; index += 1) {
|
|
257
|
+
const char = input[index];
|
|
258
|
+
if (char === '"' && input[index - 1] !== "\\") {
|
|
259
|
+
quoted = !quoted;
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (quoted) continue;
|
|
263
|
+
if (char === "{") braceDepth += 1;
|
|
264
|
+
else if (char === "}") braceDepth -= 1;
|
|
265
|
+
else if (char === "," && braceDepth <= 0) return index;
|
|
266
|
+
}
|
|
267
|
+
return input.length;
|
|
268
|
+
}
|
|
269
|
+
function isUnresolvedMacro(value) {
|
|
270
|
+
if (value.delimited) return false;
|
|
271
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(value.value)) return false;
|
|
272
|
+
return !BUILTIN_MACROS.has(value.value.toLowerCase());
|
|
273
|
+
}
|
|
274
|
+
function unsupportedSyntax(message, target, filePath) {
|
|
275
|
+
return {
|
|
276
|
+
code: "citation-unsupported-bibliography-syntax",
|
|
277
|
+
severity: "warning",
|
|
278
|
+
message: `${message} in "${filePath}".`,
|
|
279
|
+
filePath,
|
|
280
|
+
target
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
function cleanValue(value) {
|
|
284
|
+
return value.replace(/[{}]/g, "").replace(/\\([&%$#_{}])/g, "$1").trim();
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// src/remark.ts
|
|
288
|
+
var BLOCKING_ANCESTORS = /* @__PURE__ */ new Set([
|
|
289
|
+
"link",
|
|
290
|
+
"linkReference",
|
|
291
|
+
"definition",
|
|
292
|
+
"inlineCode",
|
|
293
|
+
"code",
|
|
294
|
+
"html",
|
|
295
|
+
"yaml",
|
|
296
|
+
"toml"
|
|
297
|
+
]);
|
|
298
|
+
function remarkCitations(options) {
|
|
299
|
+
return async (tree, file) => {
|
|
300
|
+
const blocked = /* @__PURE__ */ new WeakSet();
|
|
301
|
+
prepareTree(tree, blocked);
|
|
302
|
+
const paths = bibliographyPathGroups(options, readFrontmatter(file));
|
|
303
|
+
const bibliography = await loadBibliographies(paths, options);
|
|
304
|
+
const context = createRenderContext(options, bibliography.entries);
|
|
305
|
+
visit(
|
|
306
|
+
tree,
|
|
307
|
+
"text",
|
|
308
|
+
(node, index, parent) => {
|
|
309
|
+
if (index === void 0 || !parent.children) return;
|
|
310
|
+
if (blocked.has(node)) return;
|
|
311
|
+
const replacement = transformTextNode(node, context);
|
|
312
|
+
if (replacement.length === 1 && replacement[0] === node) return;
|
|
313
|
+
parent.children.splice(index, 1, ...replacement);
|
|
314
|
+
return index + replacement.length;
|
|
315
|
+
}
|
|
316
|
+
);
|
|
317
|
+
if (context.orderedKeys.length > 0) {
|
|
318
|
+
tree.children.push(createReferencesHeading(options.referencesHeading));
|
|
319
|
+
tree.children.push(createReferencesList(context));
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function readFrontmatter(file) {
|
|
324
|
+
const matter = file.data?.matter;
|
|
325
|
+
return typeof matter === "object" && matter !== null ? matter : void 0;
|
|
326
|
+
}
|
|
327
|
+
function prepareTree(root, blocked) {
|
|
328
|
+
prepareNode(root, blocked, false);
|
|
329
|
+
}
|
|
330
|
+
function prepareNode(node, blocked, insideBlocked) {
|
|
331
|
+
const children = node.children;
|
|
332
|
+
if (!children) return;
|
|
333
|
+
const isBlocked = insideBlocked || node.type !== void 0 && BLOCKING_ANCESTORS.has(node.type);
|
|
334
|
+
if (!isBlocked) repairSplitCitations(children);
|
|
335
|
+
for (const child of children) {
|
|
336
|
+
if (!child || typeof child !== "object") continue;
|
|
337
|
+
const candidate = child;
|
|
338
|
+
if (candidate.type === "text") {
|
|
339
|
+
if (isBlocked) blocked.add(candidate);
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
prepareNode(candidate, blocked, isBlocked);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
function repairSplitCitations(children) {
|
|
346
|
+
for (let index = 1; index < children.length; index += 1) {
|
|
347
|
+
const node = children[index];
|
|
348
|
+
if (node?.type !== "textDirective") continue;
|
|
349
|
+
const previous = children[index - 1];
|
|
350
|
+
if (previous?.type !== "text" || typeof previous.value !== "string") {
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
if (Array.isArray(node.children) && node.children.length > 0) continue;
|
|
354
|
+
if (node.attributes && Object.keys(node.attributes).length > 0) continue;
|
|
355
|
+
const junction = previous.value.length;
|
|
356
|
+
const following = children[index + 1];
|
|
357
|
+
const followingValue = following?.type === "text" && typeof following.value === "string" ? following.value : "";
|
|
358
|
+
const merged = `${previous.value}:${node.name ?? ""}${followingValue}`;
|
|
359
|
+
if (!spansCitation(merged, junction)) continue;
|
|
360
|
+
previous.value = merged;
|
|
361
|
+
if (followingValue) children.splice(index + 1, 1);
|
|
362
|
+
children.splice(index, 1);
|
|
363
|
+
index -= 1;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
function spansCitation(value, junction) {
|
|
367
|
+
return findCitations(value).some(
|
|
368
|
+
(match) => match.start < junction && match.end > junction
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
function bibliographyPathGroups(options, frontmatter) {
|
|
372
|
+
if (frontmatter?.bibliography !== void 0) {
|
|
373
|
+
return pathList(frontmatter.bibliography).map(
|
|
374
|
+
(path) => pageRelativeCandidates(path, options.sourceSlug)
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
return pathList(options.bibliography).map((path) => [path]);
|
|
378
|
+
}
|
|
379
|
+
function pathList(value) {
|
|
380
|
+
if (typeof value === "string") return [value];
|
|
381
|
+
if (Array.isArray(value)) {
|
|
382
|
+
return value.filter((item) => typeof item === "string");
|
|
383
|
+
}
|
|
384
|
+
return [];
|
|
385
|
+
}
|
|
386
|
+
function pageRelativeCandidates(path, sourceSlug) {
|
|
387
|
+
const normalized = normalizeLogicalPath(path);
|
|
388
|
+
if (!sourceSlug || isAbsoluteLikePath(normalized)) return [normalized];
|
|
389
|
+
const directory = normalizeLogicalPath(sourceSlug).split("/").slice(0, -1).join("/");
|
|
390
|
+
if (!directory) return [normalized];
|
|
391
|
+
const relative = normalizeLogicalPath(`${directory}/${normalized}`);
|
|
392
|
+
return relative === normalized ? [normalized] : [relative, normalized];
|
|
393
|
+
}
|
|
394
|
+
function isAbsoluteLikePath(path) {
|
|
395
|
+
return path.startsWith("/") || /^[A-Za-z]:\//.test(path);
|
|
396
|
+
}
|
|
397
|
+
function normalizeLogicalPath(path) {
|
|
398
|
+
const parts = [];
|
|
399
|
+
for (const segment of path.replace(/\\/g, "/").split("/")) {
|
|
400
|
+
if (!segment || segment === ".") continue;
|
|
401
|
+
if (segment === "..") {
|
|
402
|
+
if (parts.length > 0 && parts.at(-1) !== "..") parts.pop();
|
|
403
|
+
else parts.push(segment);
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
parts.push(segment);
|
|
407
|
+
}
|
|
408
|
+
const prefix = path.startsWith("/") ? "/" : "";
|
|
409
|
+
return `${prefix}${parts.join("/")}`;
|
|
410
|
+
}
|
|
411
|
+
async function loadBibliographies(pathGroups, options) {
|
|
412
|
+
const entries = /* @__PURE__ */ new Map();
|
|
413
|
+
const diagnostics = [];
|
|
414
|
+
for (const candidates of pathGroups) {
|
|
415
|
+
const resolved = await loadFirstAvailable(candidates, options);
|
|
416
|
+
if (!resolved) {
|
|
417
|
+
diagnostics.push({
|
|
418
|
+
code: "citation-missing-bibliography",
|
|
419
|
+
severity: "error",
|
|
420
|
+
message: `Bibliography file was not found: ${candidates[0] ?? ""}`,
|
|
421
|
+
filePath: candidates[0]
|
|
422
|
+
});
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
diagnostics.push(...resolved.parsed.diagnostics);
|
|
426
|
+
for (const [key, entry] of resolved.parsed.entries) {
|
|
427
|
+
if (entries.has(key)) {
|
|
428
|
+
diagnostics.push({
|
|
429
|
+
code: "citation-duplicate-key",
|
|
430
|
+
severity: "warning",
|
|
431
|
+
message: `Duplicate bibliography key: ${key}`,
|
|
432
|
+
filePath: resolved.path,
|
|
433
|
+
target: key
|
|
434
|
+
});
|
|
435
|
+
} else {
|
|
436
|
+
entries.set(key, entry);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
pushUniqueDiagnostics(options.diagnostics, diagnostics, options.sourceSlug);
|
|
441
|
+
return { entries, diagnostics };
|
|
442
|
+
}
|
|
443
|
+
async function loadFirstAvailable(candidates, options) {
|
|
444
|
+
for (const path of candidates) {
|
|
445
|
+
const resolved = await cachedBibliography(path, options);
|
|
446
|
+
if (resolved.found) return { path, parsed: resolved.parsed };
|
|
447
|
+
}
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
async function cachedBibliography(path, options) {
|
|
451
|
+
const cached = options.cache.get(path);
|
|
452
|
+
if (cached) return cached;
|
|
453
|
+
const promise = (async () => {
|
|
454
|
+
const source = await options.loadBibliography(path);
|
|
455
|
+
if (source === null) {
|
|
456
|
+
return {
|
|
457
|
+
found: false,
|
|
458
|
+
parsed: { entries: /* @__PURE__ */ new Map(), diagnostics: [] }
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
return { found: true, parsed: parseBibliography(source, path) };
|
|
462
|
+
})();
|
|
463
|
+
options.cache.set(path, promise);
|
|
464
|
+
return promise;
|
|
465
|
+
}
|
|
466
|
+
function createRenderContext(options, entries) {
|
|
467
|
+
return {
|
|
468
|
+
entries,
|
|
469
|
+
numbers: /* @__PURE__ */ new Map(),
|
|
470
|
+
orderedKeys: [],
|
|
471
|
+
referenceIds: /* @__PURE__ */ new Map(),
|
|
472
|
+
usedReferenceIds: /* @__PURE__ */ new Set(),
|
|
473
|
+
occurrences: [],
|
|
474
|
+
options
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
function transformTextNode(node, context) {
|
|
478
|
+
const segments = [];
|
|
479
|
+
let cursor = 0;
|
|
480
|
+
for (const match of findCitations(node.value)) {
|
|
481
|
+
if (match.start > cursor)
|
|
482
|
+
segments.push({
|
|
483
|
+
type: "text",
|
|
484
|
+
value: node.value.slice(cursor, match.start)
|
|
485
|
+
});
|
|
486
|
+
segments.push(renderCitation(match.references, match.bracketed, context));
|
|
487
|
+
cursor = match.end;
|
|
488
|
+
}
|
|
489
|
+
if (segments.length === 0) return [node];
|
|
490
|
+
if (cursor < node.value.length)
|
|
491
|
+
segments.push({ type: "text", value: node.value.slice(cursor) });
|
|
492
|
+
return segments;
|
|
493
|
+
}
|
|
494
|
+
function findCitations(value) {
|
|
495
|
+
const matches = [];
|
|
496
|
+
const ignoredRanges = findWikiLinkRanges(value);
|
|
497
|
+
const bracketPattern = /\[([^\]]*@[-A-Za-z0-9_:.]+[^\]]*)\]/g;
|
|
498
|
+
for (const match of value.matchAll(bracketPattern)) {
|
|
499
|
+
if (value[match.index - 1] === "[" || value[match.index + match[0].length] === "]") {
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
if (rangeOverlaps(ignoredRanges, match.index, match.index + match[0].length))
|
|
503
|
+
continue;
|
|
504
|
+
const references = parseBracketCitation(match[1]);
|
|
505
|
+
if (references.length === 0) continue;
|
|
506
|
+
matches.push({
|
|
507
|
+
start: match.index,
|
|
508
|
+
end: match.index + match[0].length,
|
|
509
|
+
references,
|
|
510
|
+
bracketed: true
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
const inlinePattern = /(^|[\s(])@([-A-Za-z0-9_:.]+)(?=\b)/g;
|
|
514
|
+
for (const match of value.matchAll(inlinePattern)) {
|
|
515
|
+
const start = match.index + match[1].length;
|
|
516
|
+
if (rangeOverlaps(ignoredRanges, start, start + match[2].length + 1))
|
|
517
|
+
continue;
|
|
518
|
+
if (overlaps(matches, start, start + match[2].length + 1)) continue;
|
|
519
|
+
matches.push({
|
|
520
|
+
start,
|
|
521
|
+
end: start + match[2].length + 1,
|
|
522
|
+
bracketed: false,
|
|
523
|
+
references: [{ key: match[2], suppressAuthor: false }]
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
return matches.toSorted((a, b) => a.start - b.start);
|
|
527
|
+
}
|
|
528
|
+
function findWikiLinkRanges(value) {
|
|
529
|
+
const ranges = [];
|
|
530
|
+
const pattern = /\[\[[\s\S]*?\]\]/g;
|
|
531
|
+
for (const match of value.matchAll(pattern)) {
|
|
532
|
+
ranges.push({ start: match.index, end: match.index + match[0].length });
|
|
533
|
+
}
|
|
534
|
+
return ranges;
|
|
535
|
+
}
|
|
536
|
+
function rangeOverlaps(ranges, start, end) {
|
|
537
|
+
return ranges.some((range) => start < range.end && end > range.start);
|
|
538
|
+
}
|
|
539
|
+
function parseBracketCitation(input) {
|
|
540
|
+
return input.split(";").map((part) => parseCitationPart(part.trim())).filter((part) => Boolean(part));
|
|
541
|
+
}
|
|
542
|
+
function parseCitationPart(part) {
|
|
543
|
+
const match = /^(?<prefix>.*?)\s*(?<suppress>-?)@(?<key>[-A-Za-z0-9_:.]+)(?<suffix>.*)$/.exec(
|
|
544
|
+
part
|
|
545
|
+
);
|
|
546
|
+
if (!match?.groups) return null;
|
|
547
|
+
return {
|
|
548
|
+
key: match.groups.key,
|
|
549
|
+
prefix: match.groups.prefix.trim() || void 0,
|
|
550
|
+
suffix: match.groups.suffix.trim() || void 0,
|
|
551
|
+
suppressAuthor: match.groups.suppress === "-"
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
function overlaps(matches, start, end) {
|
|
555
|
+
return matches.some((match) => start < match.end && end > match.start);
|
|
556
|
+
}
|
|
557
|
+
function renderCitation(references, bracketed, context) {
|
|
558
|
+
const renderedReferences = references.map(
|
|
559
|
+
(reference) => renderCitationReference(reference, context)
|
|
560
|
+
);
|
|
561
|
+
const separator = renderedReferences.some((item) => item.hasAffix) ? "; " : ", ";
|
|
562
|
+
const text = renderedReferences.map((item) => item.text).join(separator);
|
|
563
|
+
const label = bracketed ? `[${text}]` : text;
|
|
564
|
+
const occurrenceId = `citation-${context.options.sourceSlug ?? "page"}-${context.occurrences.length + 1}`.replace(
|
|
565
|
+
/[^A-Za-z0-9_-]/g,
|
|
566
|
+
"-"
|
|
567
|
+
);
|
|
568
|
+
context.occurrences.push({
|
|
569
|
+
id: occurrenceId,
|
|
570
|
+
pageSlug: context.options.sourceSlug,
|
|
571
|
+
references,
|
|
572
|
+
label,
|
|
573
|
+
syntax: bracketed ? references.some((item) => item.suppressAuthor) ? "suppress-author" : "bracket" : "inline"
|
|
574
|
+
});
|
|
575
|
+
return {
|
|
576
|
+
type: "link",
|
|
577
|
+
url: `#${referenceId(references[0]?.key ?? "unknown", context)}`,
|
|
578
|
+
title: null,
|
|
579
|
+
children: [{ type: "text", value: label }]
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
function renderCitationReference(reference, context) {
|
|
583
|
+
const number = numberForReference(reference, context).toString();
|
|
584
|
+
return {
|
|
585
|
+
text: citationReferenceText(reference.prefix, number, reference.suffix),
|
|
586
|
+
hasAffix: Boolean(reference.prefix || reference.suffix)
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function citationReferenceText(prefix, number, suffix) {
|
|
590
|
+
const withPrefix = prefix ? `${prefix} ${number}` : number;
|
|
591
|
+
if (!suffix) return withPrefix;
|
|
592
|
+
return /^[,.;:)]/.test(suffix) ? `${withPrefix}${suffix}` : `${withPrefix} ${suffix}`;
|
|
593
|
+
}
|
|
594
|
+
function numberForReference(reference, context) {
|
|
595
|
+
const existing = context.numbers.get(reference.key);
|
|
596
|
+
if (existing) return existing;
|
|
597
|
+
const number = context.orderedKeys.length + 1;
|
|
598
|
+
context.numbers.set(reference.key, number);
|
|
599
|
+
context.orderedKeys.push(reference.key);
|
|
600
|
+
referenceId(reference.key, context);
|
|
601
|
+
if (!context.entries.has(reference.key)) {
|
|
602
|
+
pushUniqueDiagnostics(
|
|
603
|
+
context.options.diagnostics,
|
|
604
|
+
[
|
|
605
|
+
{
|
|
606
|
+
code: "citation-unknown-key",
|
|
607
|
+
severity: "warning",
|
|
608
|
+
message: `Unknown citation key: ${reference.key}`,
|
|
609
|
+
slug: context.options.sourceSlug,
|
|
610
|
+
target: reference.key
|
|
611
|
+
}
|
|
612
|
+
],
|
|
613
|
+
context.options.sourceSlug
|
|
614
|
+
);
|
|
615
|
+
}
|
|
616
|
+
return number;
|
|
617
|
+
}
|
|
618
|
+
function referenceId(key, context) {
|
|
619
|
+
const existing = context.referenceIds.get(key);
|
|
620
|
+
if (existing) return existing;
|
|
621
|
+
const sanitized = key.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
622
|
+
const base = `ref-${sanitized || "key"}`;
|
|
623
|
+
let id = base;
|
|
624
|
+
let counter = 2;
|
|
625
|
+
while (context.usedReferenceIds.has(id)) {
|
|
626
|
+
id = `${base}-${counter}`;
|
|
627
|
+
counter += 1;
|
|
628
|
+
}
|
|
629
|
+
context.referenceIds.set(key, id);
|
|
630
|
+
context.usedReferenceIds.add(id);
|
|
631
|
+
return id;
|
|
632
|
+
}
|
|
633
|
+
function createReferencesHeading(text = "References") {
|
|
634
|
+
return {
|
|
635
|
+
type: "heading",
|
|
636
|
+
depth: 2,
|
|
637
|
+
children: [{ type: "text", value: text }]
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
function createReferencesList(context) {
|
|
641
|
+
return {
|
|
642
|
+
type: "list",
|
|
643
|
+
ordered: true,
|
|
644
|
+
start: 1,
|
|
645
|
+
spread: false,
|
|
646
|
+
children: context.orderedKeys.map(
|
|
647
|
+
(key) => ({
|
|
648
|
+
type: "listItem",
|
|
649
|
+
spread: false,
|
|
650
|
+
data: { hProperties: { id: referenceId(key, context) } },
|
|
651
|
+
children: [
|
|
652
|
+
{
|
|
653
|
+
type: "paragraph",
|
|
654
|
+
children: [
|
|
655
|
+
{
|
|
656
|
+
type: "text",
|
|
657
|
+
value: renderBibliographyEntry(context.entries.get(key), key)
|
|
658
|
+
}
|
|
659
|
+
]
|
|
660
|
+
}
|
|
661
|
+
]
|
|
662
|
+
})
|
|
663
|
+
)
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
function renderBibliographyEntry(entry, key) {
|
|
667
|
+
if (!entry) return key;
|
|
668
|
+
const author = entry.fields.author ?? entry.fields.editor;
|
|
669
|
+
const year = entry.fields.year ?? entry.fields.date;
|
|
670
|
+
const title = entry.fields.title;
|
|
671
|
+
const container = entry.fields.journal ?? entry.fields.booktitle ?? entry.fields.publisher;
|
|
672
|
+
return [author, year ? `(${year})` : void 0, title, container].filter(Boolean).join(". ");
|
|
673
|
+
}
|
|
674
|
+
function pushUniqueDiagnostics(target, diagnostics, slug) {
|
|
675
|
+
for (const diagnostic of diagnostics) {
|
|
676
|
+
const next = diagnostic.slug ? diagnostic : { ...diagnostic, slug };
|
|
677
|
+
const signature = diagnosticSignature(next);
|
|
678
|
+
if (target.some((item) => diagnosticSignature(item) === signature))
|
|
679
|
+
continue;
|
|
680
|
+
target.push(next);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
function diagnosticSignature(diagnostic) {
|
|
684
|
+
return `${diagnostic.code}:${diagnostic.slug ?? ""}:${diagnostic.filePath ?? ""}:${diagnostic.target ?? ""}:${diagnostic.message}`;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// src/state.ts
|
|
688
|
+
function createCitationState() {
|
|
689
|
+
return { bibliographies: /* @__PURE__ */ new Map(), diagnostics: [] };
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// index.ts
|
|
693
|
+
var PLUGIN_NAME = "citations";
|
|
694
|
+
function citations(options = {}) {
|
|
695
|
+
const state = createCitationState();
|
|
696
|
+
return definePlugin({
|
|
697
|
+
name: PLUGIN_NAME,
|
|
698
|
+
options,
|
|
699
|
+
validateOptions: validateCitationsOptions,
|
|
700
|
+
extendMarkdownPipeline: (pipeline, context) => {
|
|
701
|
+
pipeline.use(remarkCitations, {
|
|
702
|
+
...options,
|
|
703
|
+
sourceSlug: context.sourceSlug,
|
|
704
|
+
contentSource: context.contentSource,
|
|
705
|
+
diagnostics: state.diagnostics,
|
|
706
|
+
loadBibliography: async (path) => {
|
|
707
|
+
if (!context.contentSource) return null;
|
|
708
|
+
const content = await readContentSourceEntry(
|
|
709
|
+
context.contentSource,
|
|
710
|
+
path
|
|
711
|
+
);
|
|
712
|
+
if (content === null) return null;
|
|
713
|
+
return typeof content === "string" ? content : new TextDecoder().decode(content);
|
|
714
|
+
},
|
|
715
|
+
cache: state.bibliographies
|
|
716
|
+
});
|
|
717
|
+
},
|
|
718
|
+
addDiagnostics: () => state.diagnostics
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
var citationsPlugin = citations;
|
|
722
|
+
function validateCitationsOptions(options) {
|
|
723
|
+
if (!options) return [];
|
|
724
|
+
const issues = [];
|
|
725
|
+
if (options.bibliography !== void 0) {
|
|
726
|
+
const value = options.bibliography;
|
|
727
|
+
const valid = typeof value === "string" || Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
728
|
+
if (!valid) {
|
|
729
|
+
issues.push({
|
|
730
|
+
path: "bibliography",
|
|
731
|
+
message: "Expected a bibliography path or an array of paths."
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
if (options.referencesHeading !== void 0 && typeof options.referencesHeading !== "string") {
|
|
736
|
+
issues.push({ path: "referencesHeading", message: "Expected a string." });
|
|
737
|
+
}
|
|
738
|
+
return issues;
|
|
739
|
+
}
|
|
740
|
+
export {
|
|
741
|
+
citations,
|
|
742
|
+
citationsPlugin,
|
|
743
|
+
parseBibliography,
|
|
744
|
+
remarkCitations
|
|
745
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Root } from "mdast";
|
|
2
|
+
import type { RemarkCitationsOptions } from "./types.js";
|
|
3
|
+
type MarkdownFile = {
|
|
4
|
+
data?: Record<string, unknown>;
|
|
5
|
+
};
|
|
6
|
+
export declare function remarkCitations(options: RemarkCitationsOptions): (tree: Root, file: MarkdownFile) => Promise<void>;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Diagnostic } from "@riebeckite/core";
|
|
2
|
+
import type { BibliographyCache } from "./types.js";
|
|
3
|
+
export type CitationState = {
|
|
4
|
+
readonly bibliographies: BibliographyCache;
|
|
5
|
+
readonly diagnostics: Diagnostic[];
|
|
6
|
+
};
|
|
7
|
+
export declare function createCitationState(): CitationState;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ContentSource, Diagnostic } from "@riebeckite/core";
|
|
2
|
+
export type CitationsOptions = {
|
|
3
|
+
/** Vault-relative BibTeX/BibLaTeX file path or paths. */
|
|
4
|
+
bibliography?: string | readonly string[];
|
|
5
|
+
/** Heading inserted above generated references. Defaults to "References". */
|
|
6
|
+
referencesHeading?: string;
|
|
7
|
+
};
|
|
8
|
+
export type BibliographyEntry = {
|
|
9
|
+
readonly key: string;
|
|
10
|
+
readonly type: "article" | "book" | "inproceedings" | "misc" | string;
|
|
11
|
+
readonly fields: Readonly<Record<string, string>>;
|
|
12
|
+
};
|
|
13
|
+
export type CitationSyntax = "bracket" | "inline" | "suppress-author";
|
|
14
|
+
export type CitationReference = {
|
|
15
|
+
readonly key: string;
|
|
16
|
+
readonly prefix?: string;
|
|
17
|
+
readonly suffix?: string;
|
|
18
|
+
readonly suppressAuthor: boolean;
|
|
19
|
+
};
|
|
20
|
+
export type CitationOccurrence = {
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly pageSlug?: string;
|
|
23
|
+
readonly references: readonly CitationReference[];
|
|
24
|
+
readonly label: string;
|
|
25
|
+
readonly syntax: CitationSyntax;
|
|
26
|
+
};
|
|
27
|
+
export type ResolvedCitation = CitationReference & {
|
|
28
|
+
readonly entry?: BibliographyEntry;
|
|
29
|
+
readonly number?: number;
|
|
30
|
+
};
|
|
31
|
+
export type ParsedBibliography = {
|
|
32
|
+
readonly entries: ReadonlyMap<string, BibliographyEntry>;
|
|
33
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
34
|
+
};
|
|
35
|
+
export type CachedBibliography = {
|
|
36
|
+
readonly found: boolean;
|
|
37
|
+
readonly parsed: ParsedBibliography;
|
|
38
|
+
};
|
|
39
|
+
export type BibliographyCache = Map<string, Promise<CachedBibliography>>;
|
|
40
|
+
export type RemarkCitationsOptions = CitationsOptions & {
|
|
41
|
+
readonly sourceSlug?: string;
|
|
42
|
+
readonly contentSource?: ContentSource;
|
|
43
|
+
readonly diagnostics: Diagnostic[];
|
|
44
|
+
readonly cache: BibliographyCache;
|
|
45
|
+
readonly loadBibliography: (path: string) => Promise<string | null>;
|
|
46
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@riebeckite/plugin-citations",
|
|
3
|
+
"version": "0.0.14",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"dependencies": {
|
|
8
|
+
"@types/mdast": "^4.0.4",
|
|
9
|
+
"unist-util-visit": "^5.1.0",
|
|
10
|
+
"@riebeckite/core": "0.0.14"
|
|
11
|
+
},
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"README.md",
|
|
18
|
+
"README_ja.md",
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"import": "./dist/index.js",
|
|
25
|
+
"source": "./index.ts",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/Rerurate514/riebeckite.git",
|
|
32
|
+
"directory": "packages/plugins/citations"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/Rerurate514/riebeckite#readme",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/Rerurate514/riebeckite/issues"
|
|
37
|
+
},
|
|
38
|
+
"description": "BibTeX and BibLaTeX citation rendering for Riebeckite Markdown content.",
|
|
39
|
+
"keywords": [
|
|
40
|
+
"riebeckite",
|
|
41
|
+
"plugin",
|
|
42
|
+
"citations",
|
|
43
|
+
"bibtex",
|
|
44
|
+
"markdown"
|
|
45
|
+
],
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": "^20.19.0 || >=22.12.0"
|
|
48
|
+
},
|
|
49
|
+
"sideEffects": false,
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "node ../../../scripts/build_package.mjs",
|
|
52
|
+
"test": "node --import tsx --test \"test/*.test.ts\""
|
|
53
|
+
}
|
|
54
|
+
}
|