-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathZoteroLinkCitation.bas
823 lines (661 loc) · 26.8 KB
/
ZoteroLinkCitation.bas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
Attribute VB_Name = "ZoteroLinkCitation"
' An MS Word macro that links author-date or number style citations to their bibliography entry.
' https://github.com/altairwei/ZoteroLinkCitation
Option Explicit
Type Citation
BibPattern As String
Start As Long
End As Long
End Type
'-------------------------------------------------------------------
' VBA JSON Parser
' https://medium.com/swlh/excel-vba-parse-json-easily-c2213f4d8e7a
'-------------------------------------------------------------------
Private p&, token, dic
Private Function ParseJSON(json$, Optional key$ = "obj") As Object
p = 1
token = Tokenize(json)
Set dic = CreateObject("Scripting.Dictionary")
If token(p) = "{" Then ParseObj key Else ParseArr key
Set ParseJSON = dic
End Function
Private Function ParseObj(key$)
Do: p = p + 1
Select Case token(p)
Case "]"
Case "[": ParseArr key
Case "{"
If token(p + 1) = "}" Then
p = p + 1
dic.Add key, "null"
Else
ParseObj key
End If
Case "}": key = ReducePath(key): Exit Do
Case ":": key = key & "." & token(p - 1)
Case ",": key = ReducePath(key)
Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
End Select
Loop
End Function
Private Function ParseArr(key$)
Dim e&
Do: p = p + 1
Select Case token(p)
Case "}"
Case "{": ParseObj key & ArrayID(e)
Case "[": ParseArr key
Case "]": Exit Do
Case ":": key = key & ArrayID(e)
Case ",": e = e + 1
Case Else: dic.Add key & ArrayID(e), token(p)
End Select
Loop
End Function
Private Function Tokenize(s$)
Const Pattern = """(([^""\\]|\\.)*)""|[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|\w+|[^\s""']+?"
Tokenize = RExtract(s, Pattern, True)
End Function
Private Function RExtract(s$, Pattern, Optional bGroup1Bias As Boolean, Optional bGlobal As Boolean = True)
Dim c&, m, n
Dim v()
With CreateObject("VBScript.RegExp")
.Global = bGlobal
.MultiLine = False
.IgnoreCase = True
.Pattern = Pattern
If .TEST(s) Then
Set m = .Execute(s)
ReDim v(1 To m.Count)
For Each n In m
c = c + 1
v(c) = n.value
If bGroup1Bias Then If Len(n.submatches(0)) Or n.value = """""" Then v(c) = n.submatches(0)
Next
End If
End With
RExtract = v
End Function
Private Function ArrayID$(e)
ArrayID = "(" & e & ")"
End Function
Private Function ReducePath$(key$)
If InStr(key, ".") Then ReducePath = Left(key, InStrRev(key, ".") - 1) Else ReducePath = key
End Function
Function GetFilteredValues(dic, match)
Dim c&, i&, v, w
v = dic.keys
ReDim w(1 To dic.Count)
For i = 0 To UBound(v)
If v(i) Like match Then
c = c + 1
w(c) = dic(v(i))
End If
Next
ReDim Preserve w(1 To c)
GetFilteredValues = w
End Function
Function GetFilteredTable(dic, cols)
Dim c&, i&, j&, v, w, z
v = dic.keys
z = GetFilteredValues(dic, cols(0))
ReDim w(1 To UBound(z), 1 To UBound(cols) + 1)
For j = 1 To UBound(cols) + 1
z = GetFilteredValues(dic, cols(j - 1))
For i = 1 To UBound(z)
w(i, j) = z(i)
Next
Next
GetFilteredTable = w
End Function
'-------------------------------------------------------------------
' ZoteroLinkCitation Utilities
'-------------------------------------------------------------------
Private Sub QuickSort(arr As Variant, inLow As Long, inHigh As Long)
Dim pivot As String
Dim tmpSwap As Variant
Dim low As Long
Dim high As Long
low = inLow
high = inHigh
pivot = arr((low + high) \ 2)
While (low <= high)
While (arr(low) < pivot And low < inHigh)
low = low + 1
Wend
While (pivot < arr(high) And high > inLow)
high = high - 1
Wend
If (low <= high) Then
tmpSwap = arr(low)
arr(low) = arr(high)
arr(high) = tmpSwap
low = low + 1
high = high - 1
End If
Wend
If (inLow < high) Then QuickSort arr, inLow, high
If (low < inHigh) Then QuickSort arr, low, inHigh
End Sub
Private Function ExtractZoteroPrefData() As String
Dim prop As Variant
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
For Each prop In ActiveDocument.CustomDocumentProperties
If Left(prop.Name, 11) = "ZOTERO_PREF" Then
dict(prop.Name) = prop.Value
End If
Next prop
Dim sortedKeys As Variant
sortedKeys = dict.Keys
Call QuickSort(sortedKeys, LBound(sortedKeys), UBound(sortedKeys))
Dim concatenatedValues As String
Dim key As Variant
For Each key In sortedKeys
concatenatedValues = concatenatedValues & dict(key)
Next key
ExtractZoteroPrefData = concatenatedValues
End Function
Private Function GetZoteroPrefs() As Object
Dim zoteroData As String
zoteroData = ExtractZoteroPrefData()
Dim xmlDoc As Object
Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
xmlDoc.Async = False
xmlDoc.LoadXML zoteroData
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
If xmlDoc.ParseError.ErrorCode <> 0 Then
MsgBox "XML Parse Error: " & xmlDoc.ParseError.Reason
Set GetZoteroPrefs = dict
Exit Function
End If
Dim dataElem As Object
Set dataElem = xmlDoc.SelectSingleNode("//data")
If Not dataElem Is Nothing Then
dict("data-version") = dataElem.getAttribute("data-version")
dict("zotero-version") = dataElem.getAttribute("zotero-version")
End If
Dim sessionElem As Object
Set sessionElem = xmlDoc.SelectSingleNode("//session")
If Not sessionElem Is Nothing Then
dict("session-id") = sessionElem.getAttribute("id")
End If
Dim styleElem As Object
Set styleElem = xmlDoc.SelectSingleNode("//style")
If Not styleElem Is Nothing Then
Dim segments() As String
segments = Split(styleElem.getAttribute("id"), "/")
dict("style-id") = segments(UBound(segments))
dict("hasBibliography") = styleElem.getAttribute("hasBibliography")
dict("bibliographyStyleHasBeenSet") = styleElem.getAttribute("bibliographyStyleHasBeenSet")
End If
Dim prefElem As Object
Set prefElem = xmlDoc.SelectSingleNode("//prefs/pref[@name='fieldType']")
If Not prefElem Is Nothing Then
dict("pref-fieldType") = prefElem.getAttribute("value")
End If
Set GetZoteroPrefs = dict
End Function
Private Function RemoveSpecifiedHtmlTags(inputString As String, tagsToRemove As Variant) As String
Dim regex As Object
Dim tag As Variant
Set regex = CreateObject("VBScript.RegExp")
For Each tag In tagsToRemove
With regex
.Global = True
.IgnoreCase = True
.Pattern = "</?" & tag & ".*?>"
inputString = .Replace(inputString, "")
End With
Next tag
RemoveSpecifiedHtmlTags = inputString
End Function
Private Function RemoveHtmlTags(inputString As String) As String
Dim tagsToRemove() As Variant
tagsToRemove = Array("i", "sub", "sup")
RemoveHtmlTags = RemoveSpecifiedHtmlTags(inputString, tagsToRemove)
End Function
Function SimpleHash(ByVal inputString As String) As String
Dim i As Long
Dim hashValue As Long
For i = 1 To Len(inputString)
hashValue = hashValue + (Asc(Mid(inputString, i, 1)) * i)
Next i
Dim modValue As Long
modValue = 100
hashValue = hashValue Mod modValue
If hashValue < 0 Then
hashValue = hashValue + modValue
End If
SimpleHash = Format$(hashValue, "000")
End Function
Private Function ConvertToBookmarkName(ByVal str As String) As String
Dim result As String
Dim i As Integer
' Replace illegal characters
result = Replace(str, " ", "_")
For i = 1 To Len(result)
' Check each character and replace if not alphanumeric or underscore
If Not (Mid(result, i, 1) Like "[A-Za-z0-9_]") Then
Mid(result, i, 1) = "_"
End If
Next i
' Avoid starting with a digit
If Left(result, 1) Like "[0-9]" Then
result = "_" & result
End If
' Limit the length to 40 characters
If Len(result) > 40 Then
result = Left(result, 36)
result = result & "_" & SimpleHash(str)
End If
ConvertToBookmarkName = result
End Function
Private Sub AssertArrayLengthsEqual(array1 As Variant, array2 As Variant)
If Not UBound(array1) - LBound(array1) = UBound(array2) - LBound(array2) Then
MsgBox "Assertion Failed: The lengths of the two arrays are not equal.", vbCritical, "Assertion Failed"
Err.Raise Number:=vbObjectError + 513, Description:="Array length assertion failed."
End If
End Sub
Private Function ParseCSLCitationJson(ByVal code As String) As Object
Dim jsonObj As Object
Set jsonObj = ParseJSON(Trim(Replace(code, "ADDIN ZOTERO_ITEM CSL_CITATION", "")), "CSL")
Set ParseCSLCitationJson = jsonObj
End Function
Function StyleExists(ByVal styleToTest As String, ByVal docToTest as Word.Document) As Boolean
Dim testStyle as Word.Style
On Error Resume Next
Set testStyle = docToTest.Styles(styleToTest)
StyleExists = Not testStyle Is Nothing
End Function
'-------------------------------------------------------------------
' Citation Style Handler
'-------------------------------------------------------------------
' Such as (Dweba et al., 2017; Hu et al., 2022; Moonjely et al., 2023)
Private Sub ExtractAuthorYearCitations(field As Field, ByRef citations() As Citation, _
Optional onlyYear As Boolean = False, Optional multiRefCommaSep As Boolean = True)
Dim targetRange As Range, charRange As Range
Set targetRange = field.Result
Set charRange = targetRange.Duplicate
charRange.Collapse wdCollapseStart
ReDim citations(0)
Dim rangeIndex As Long
rangeIndex = -1
Dim inCitation As Boolean, nComma As Integer, beginYear As Boolean
inCitation = False
nComma = 0
beginYear = False
Dim json As Object
Set json = ParseCSLCitationJson(field.Code)
Dim startChar As Long, endChar As Long
Dim i As Long
For i = 1 To targetRange.Characters.Count
charRange.Start = targetRange.Start + i - 1
charRange.End = targetRange.Start + i
' Start of full author-year citation
If charRange.Text = "(" And Not onlyYear Then
inCitation = True
startChar = charRange.Start + 1
' Start of year citation
ElseIf charRange.Text Like "[0-9]" Then
beginYear = True
If onlyYear And Not inCitation Then
inCitation = True
startChar = charRange.Start
EndIf
' Check multiple citations of same author
ElseIf multiRefCommaSep And charRange.Text = "," Then
nComma = nComma + 1
If nComma > 1 And beginYear Then
GoTo CreateCitationObject
End If
' End of citation
ElseIf charRange.Text = ";" Or charRange.Text = ")" Then
beginYear = False
If multiRefCommaSep Then nComma = 0
CreateCitationObject:
If inCitation Then
endChar = charRange.Start
rangeIndex = rangeIndex + 1
If rangeIndex > UBound(citations) Then
ReDim Preserve citations(0 To rangeIndex)
End If
citations(rangeIndex).Start = startChar
citations(rangeIndex).End = endChar
citations(rangeIndex).BibPattern = RemoveHtmlTags( _
json("CSL.citationItems(" & rangeIndex & ").itemData.title"))
inCitation = False
End If
' Skip space after delimiter
If (charRange.Text = ";" Or charRange.Text = ",") And Not onlyYear Then
i = i + 1
startChar = endChar + 2
inCitation = True
End If
End If
Next i
' Resize the array to fit the number of found ranges
ReDim Preserve citations(0 To rangeIndex)
End Sub
' Such as [1], [2], [3] etc.
Private Sub ExtractNumberInBrackets(field As Field, ByRef citations() As Citation, Optional bracket As String = "[]")
Dim targetRange As Range, charRange As Range
Set targetRange = field.Result
Set charRange = targetRange.Duplicate
charRange.Collapse wdCollapseStart
ReDim citations(0)
Dim rangeIndex As Long
rangeIndex = -1
Dim startBracket As String, endBracket As String
startBracket = Left(bracket, 1)
endBracket = Right(bracket, 1)
Dim inBrackets As Boolean
inBrackets = False
Dim json As Object
Set json = ParseCSLCitationJson(field.code)
Dim startChar As Long, endChar As Long
Dim i As Long
For i = 1 To targetRange.Characters.Count
charRange.Start = targetRange.Start + i - 1
charRange.End = targetRange.Start + i
If charRange.Text = startBracket Then
inBrackets = True
startChar = charRange.Start + 1 ' Start after the bracket
ElseIf charRange.Text = endBracket And inBrackets Then
If startChar < endChar Then
rangeIndex = rangeIndex + 1
If rangeIndex > UBound(citations) Then
ReDim Preserve citations(0 To rangeIndex)
End If
With citations(rangeIndex)
.Start = startChar
.End = endChar
.BibPattern = RemoveHtmlTags( _
json("CSL.citationItems(" & rangeIndex & ").itemData.title"))
End With
End If
inBrackets = False
ElseIf inBrackets And IsNumeric(charRange.Text) Then
endChar = charRange.End ' Update end if still in brackets and character is numeric
End If
Next i
' Resize the array to fit the number of found ranges
ReDim Preserve citations(0 To rangeIndex)
End Sub
' Such as [47,98,100–102]
Private Sub ExtractSerialNumberCitations(field As Field, ByRef citations() As Citation, Optional border = "")
Dim targetRange As Range, charRange As Range
Set targetRange = field.Result
Set charRange = targetRange.Duplicate
charRange.Collapse wdCollapseStart
ReDim citations(0)
Dim rangeIndex As Long, citOrder As Long
rangeIndex = -1
citOrder = -1
Dim startBorder As String, endBorder As String
startBorder = Left(border, 1)
endBorder = Right(border, 1)
Dim inCitation As Boolean
inCitation = False
Dim lastNum As Long
lastNum = 0
Dim json As Object
Set json = ParseCSLCitationJson(field.Code)
Dim startChar As Long, endChar As Long
Dim currentChar As String
Dim citationText As String
Dim i As Long, RL As Long
RL = targetRange.Characters.Count
' Add a pseudo-border to the citation text without borders
If Len(endBorder) = 0 Then
RL = RL + 1
endBorder = "]"
EndIf
For i = 1 To RL
charRange.Start = targetRange.Start + i - 1
charRange.End = targetRange.Start + i
If i <= targetRange.Characters.Count Then
currentChar = charRange.Text
Else
' Point to the psuedo-border
currentChar = endBorder
EndIf
If currentChar Like "[0-9]" And Not inCitation Then
inCitation = True
startChar = charRange.Start
citationText = currentChar
' ChrW(8211) means the character "en dash"
ElseIf currentChar = "," Or currentChar = endBorder Or currentChar = ChrW(8211) Then
If currentChar = ChrW(8211) Then
lastNum = CLng(citationText)
End If
If inCitation Then
endChar = charRange.Start
rangeIndex = rangeIndex + 1
If rangeIndex > UBound(citations) Then
ReDim Preserve citations(0 To rangeIndex)
End If
If (currentChar = "," Or currentChar = endBorder) And lastNum > 0 Then
citOrder = citOrder + CLng(citationText) - lastNum
Else
citOrder = citOrder + 1
End If
citations(rangeIndex).Start = startChar
citations(rangeIndex).End = endChar
citations(rangeIndex).BibPattern = RemoveHtmlTags( _
json("CSL.citationItems(" & citOrder & ").itemData.title"))
If Len(citations(rangeIndex).BibPattern) = 0 Then
Err.Raise vbObjectError + 1, "ExtractCitations", "Can not find citation CSL data"
EndIf
inCitation = False
End If
If currentChar = "," Or currentChar = endBorder Then
lastNum = 0
End If
ElseIf inCitation Then
citationText = citationText & currentChar
End If
Next i
ReDim Preserve citations(0 To rangeIndex)
End Sub
'-------------------------------------------------------------------
' Supported Citation Styles
'-------------------------------------------------------------------
Private Function isSupportedStyle(ByVal style As String) As Boolean
Dim predefinedList As String
predefinedList = "|" & _
"molecular-plant|ieee|apa|vancouver|american-chemical-society|" & _
"american-medical-association|nature|american-political-science-association|" & _
"american-sociological-association|chicago-author-date|" & _
"china-national-standard-gb-t-7714-2015-numeric|" & _
"china-national-standard-gb-t-7714-2015-author-date|" & _
"harvard-cite-them-right|elsevier-harvard|modern-language-association|"
style = "|" & style & "|"
isSupportedStyle = InStr(1, predefinedList, style, vbTextCompare) > 0
End Function
Private Sub ExtractCitations(field As Field, ByRef citations() As Citation, style As String)
Select Case style
Case "molecular-plant", "chicago-author-date", "modern-language-association"
Call ExtractAuthorYearCitations(field, citations, onlyYear:=False, multiRefCommaSep:=False)
Case "apa", "china-national-standard-gb-t-7714-2015-author-date", _
"american-political-science-association", "american-sociological-association", _
"harvard-cite-them-right"
Call ExtractAuthorYearCitations(field, citations, onlyYear:=True, multiRefCommaSep:=True)
Case "elsevier-harvard"
Call ExtractAuthorYearCitations(field, citations, onlyYear:=False, multiRefCommaSep:=True)
Case "ieee"
Call ExtractNumberInBrackets(field, citations, "[]")
Case "vancouver"
Call ExtractSerialNumberCitations(field, citations, "()")
Case "china-national-standard-gb-t-7714-2015-numeric"
Call ExtractSerialNumberCitations(field, citations, "[]")
Case "american-chemical-society", "american-medical-association", "nature"
Call ExtractSerialNumberCitations(field, citations, "")
Case Else
Err.Raise vbObjectError + 1, "ExtractCitations", "Citation style not recognized"
End Select
End Sub
'-------------------------------------------------------------------
' ZoteroLinkCitation Macro
'-------------------------------------------------------------------
Public Sub ZoteroLinkCitationWithinSelection()
If Selection.Fields.Count > 0 Then
Dim originalRng As Range
Set originalRng = Selection.Range
Application.ScreenUpdating = False
Dim targetFields As New Collection
Dim fld As Field
For Each fld In Selection.Fields
targetFields.Add fld
Next fld
Call ZoteroLinkCitation(targetFields, False, False)
' Restore the original selection
ActiveWindow.ScrollIntoView originalRng, True
originalRng.Select
Application.ScreenUpdating = True
End If
End Sub
Public Sub ZoteroLinkCitationAll()
Dim originalRng As Range
Set originalRng = Selection.Range
Dim debugging As Boolean
debugging = (MsgBox("Do you want run in debug mode?", vbYesNo + vbQuestion, "Debug?") = vbYes)
' Disable screen updating for performance
Application.ScreenUpdating = False
Call ZoteroLinkCitation(ActiveDocument.Fields, debugging)
' Restore the original selection
ActiveWindow.ScrollIntoView originalRng, True
originalRng.Select
' Re-enable screen updating
Application.ScreenUpdating = True
Exit Sub
End Sub
Private Sub ZoteroLinkCitation(targetFields, Optional debugging As Boolean = False, Optional notify As Boolean = True)
' Do not support Bookmark-type citations
Dim prefs As Object
Set prefs = GetZoteroPrefs()
If Not prefs("pref-fieldType") = "Field" Then
MsgBox "Only support 'Fields' type citations", vbCritical, "Error"
Exit Sub
End If
Dim styleId As String
styleId = prefs("style-id")
If Not isSupportedStyle(styleId) Then
MsgBox "The current citation style is not yet supported: " & styleId, vbCritical, "Error"
Exit Sub
End If
Dim userTextStyle As String
If notify Then
Dim resp As String
resp = InputBox(title := "Set an MS Word style for hyperlinks?", _
prompt := "If you want to set a certain style for hyperlinks," & _
" enter the name of that style below.")
If StyleExists(resp, ActiveDocument) Then userTextStyle = resp
End If
Dim i As Long
Dim bibField As Field
Set bibField = Nothing
' Find the Zotero bibliography field
For i = ActiveDocument.Fields.Count To 1 Step -1
If ActiveDocument.Fields(i).Type = wdFieldAddin Then
If InStr(ActiveDocument.Fields(i).Code, "ADDIN ZOTERO_BIBL") > 0 Then
Set bibField = ActiveDocument.Fields(i)
Exit For
EndIf
End If
Next i
If bibField Is Nothing Then
Err.Raise vbObjectError + 513, , "Can not find Zotero bibliography field."
End If
' Iterate through all fields in the document
Dim aField As Field, iCount As Integer
For Each aField In targetFields
' Check if the field is a Zotero citation
If aField.Type = wdFieldAddin Then
If InStr(aField.Code, "ADDIN ZOTERO_ITEM") > 0 Then
If debugging Then
' Focus to next field
Application.ScreenUpdating = True
ActiveWindow.ScrollIntoView aField.Result, True
aField.Result.Select
' Update the document
DoEvents
If MsgBox("Processed " & iCount & " citations, and found the next group:" & vbCrLf & vbCrLf & _
aField.Result.Text & vbCrLf & vbCrLf & "Do you want to continue?", _
vbYesNo + vbQuestion, "Continue?") = vbNo Then
Exit For
End If
Application.ScreenUpdating = False
End If
Dim cit As Citation, cits() As Citation
Call ExtractCitations(aField, cits, styleId)
' Locate all citations in the field
Dim tempBookmarkName As String
For i = 0 To UBound(cits)
cit = cits(i)
Dim rng As Range
Set rng = aField.Result.Document.Range(Start:=cit.Start, End:=cit.End)
tempBookmarkName = "ZoteroLinkCitationTempBookmark" & i
ActiveDocument.Bookmarks.Add Name:=tempBookmarkName, Range:=rng
Next i
' Link citations to bibliography
For i = 0 To UBound(cits)
cit = cits(i)
Dim title As String
title = cit.BibPattern
' Create a sanitized anchor name from the title
Dim titleAnchor As String
titleAnchor = ConvertToBookmarkName(title)
' Get the range of Zotero bibliography
Dim rngBibliography As Range
Set rngBibliography = bibField.Result
With rngBibliography.Find
.ClearFormatting
.Text = Left(title, 255)
.Forward = True
.Wrap = wdFindStop ' Stop when reaching the end of the range
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.Execute
End With
' Check if the text was found
If rngBibliography.Find.Found Then
' Create a new range object to represent the found paragraph
Dim rngFound As Range
Set rngFound = rngBibliography.Paragraphs(1).Range
' Ensure that the Range does not extend to the end of the bibliography field
rngFound.End = rngFound.End - 1
' Add a bookmark to the found range
ActiveDocument.Bookmarks.Add Range:=rngFound, Name:=titleAnchor
Else
If MsgBox("Not found in bibliography:" & vbCrLf & title & vbCrLf & vbCrLf & _
"Do you want to continue with the next Zotero citation?", _
vbYesNo + vbCritical, "Error") = vbNo Then
GoTo ExitTheMacro
Else
GoTo SkipToNextCitation
End If
End If
' Create hyperlink according to temporary bookmark
Dim hp As Hyperlink
Set hp = ActiveDocument.Hyperlinks.Add( _
Anchor:=ActiveDocument.Bookmarks("ZoteroLinkCitationTempBookmark" & i).Range, _
SubAddress:=titleAnchor, ScreenTip:="")
' Apply text style to the hyperlink
If userTextStyle <> "" Then
hp.Range.style = ActiveDocument.Styles(userTextStyle)
End If
iCount = iCount + 1
SkipToNextCitation:
ActiveDocument.Bookmarks("ZoteroLinkCitationTempBookmark" & i).Delete
Next i
End If
End If
Next aField
ExitTheMacro:
If notify Then MsgBox "Linked " & iCount & " Zotero citations.", vbInformation, "Finish"
End Sub