This repository was archived by the owner on Dec 23, 2023. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordScript.applescript
More file actions
Latest commit
1389 lines (1023 loc) · 50 KB
/
Copy pathWordScript.applescript
File metadata and controls
1389 lines (1023 loc) · 50 KB
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- WordScript for BibDesk
---
-- MIT License
-- Copyright (c) 2020 David Wingate
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
---
-- Acknowledgements
-- The basic functionality of this software was inspired by three existing projects:
-- - BibFuse by Colin A. Smith (http://bibfuse.sourceforge.net)
-- - BibDeskToWord by Conan C. Albrecht
-- - NatBib Reference Sheet by Sébastien Merkel (http://merkel.texture.rocks/Latex/natbib.php)
-- Many thanks to the authors of these projects for sharing their hard work.
---
-- check that Word and BibDesk are ready
tellapplication"System Events"
set {countWord, countBibDesk} to {0, 0}
if (exists of process "Microsoft Word") istruethen
setcountWordto (countof documents inapplication"Microsoft Word")
end if
if (exists of process "BibDesk") istruethen
setcountBibDeskto (countof documents inapplication"BibDesk")
end if
end tell
if {countWord, countBibDesk} contains0then
activate
try
display dialog"Documents must be open in both Microsoft Word and BibDesk" buttons {"Cancel", "Open Now"} default button "Open Now"
if button returned ofresultcontains"Open Now"then
tellapplication"BibDesk"
launch
end tell
delay3
end if
on error
return
end try
end if
-- check for selection in Word to trigger quick format
tellapplication"Microsoft Word"
if content oftext object offirstparagraphof selection contains"ADDIN"then
select text object offirstparagraphof selection -- select recently edited reference
end if
setselectionStartto (selection start of selection)
setselectionEndto (selection endof selection)
end tell
if selectionStart is not selectionEnd then
readBibliographySettings()
setbibliographySettingstoresult
if bibliographySettings is {} then
defaultSettings()
setbibliographySettingstoresult
writeBibliographySettings(bibliographySettings)
setbibliographySettingstoresult
if bibliographySettings is {} then
return
end if
end if
formatReferences(bibliographySettings)
return
end if
-- open WordScript Menu
activate
with timeout of0seconds
choose from list {"Format References", "Unformat References", "Fill Empty References", "Tools", "Document Settings"} with title "WordScript"with prompt "You should save your work first!" default items"Format References" cancel button name {"Exit"} OK button name {"Choose"}
setmenuChoicetoresult
end timeout
if menuChoice isfalsethen
return
end if
if menuChoice contains"Format References"then
readBibliographySettings()
setbibliographySettingstoresult
if bibliographySettings is {} then
defaultSettings()
setbibliographySettingstoresult
writeBibliographySettings(bibliographySettings)
setbibliographySettingstoresult
if bibliographySettings is {} then
return
end if
end if
formatReferences(bibliographySettings)
else if menuChoice contains"Unformat References"then
unformatReferences()
else if menuChoice contains"Fill Empty References"then
fillEmptyReferences()
else if menuChoice contains"Document Settings"then
readBibliographySettings()
setbibliographySettingstoresult
if bibliographySettings is {} then
defaultSettings()
setbibliographySettingstoresult
writeBibliographySettings(bibliographySettings)
setbibliographySettingstoresult
if bibliographySettings is {} then
return
end if
end if
settingsMenu(bibliographySettings)
ifresultis not bibliographySettings then
setbibliographySettingstoresult
writeBibliographySettings(bibliographySettings)
setbibliographySettingstoresult
if bibliographySettings is {} then
return
end if
try
tellapplication"Microsoft Word"
activate
display dialog"Settings have been changed, do you wish to format the references now?"
end tell
formatReferences(bibliographySettings)
on error
return
end try
else
return
end if
else if menuChoice contains"Tools"then
try
display dialog"References must be unformatted, do you wish to unformat now?"
unformatReferences()
on error
return
end try
toolsMenu()
try
activate
display dialog"Operation complete, do you wish to format the references now?"
readBibliographySettings()
setbibliographySettingstoresult
formatReferences(bibliographySettings)
on error
return
end try
end if
---
ondefaultSettings()
setbibDeskDocumentNameto""
setbibliographyTemplatePathto""
setcitepTemplatePathto""
setcitetTemplatePathto""
setparenthesisOpento"("
setparenthesisCloseto")"
setbibliographySortByto"Cite Key"-- BibDesk field (leave blank for order of appearance)
setbibliographyStyleto"Bibliography"-- leave blank to use formatting of template file
setitalicLatinto {"et al.", "ibid.", "cf.", "inter alia", "circa"}
setitalicPublicationTypesto {"film", "broadcast"}
setsuperscriptReferencesto"No"
setnumberedReferencesto"No"-- overrides templates and sorting
setnumberSeperatorto","
return {bibDeskDocumentName, bibliographyTemplatePath, citepTemplatePath, citetTemplatePath, parenthesisOpen, parenthesisClose, bibliographySortBy, bibliographyStyle, italicLatin, italicPublicationTypes, superscriptReferences, numberedReferences, numberSeperator}
end defaultSettings
---
onreadBibliographySettings()
-- global setup
tellapplication"Microsoft Word"
setwordDocumentto active document
setselectionRangeto create range wordDocument start (selection start of selection) end (selection endof selection)
set status bar to"Reading bibliography..."
end tell
-- look for a formatted bibliography
setAppleScript's text item delimitersto""
tellapplication"Microsoft Word"
setfieldCountto (countof fields in wordDocument)
repeatuntil fieldCount is0
setcurrentFieldto (field fieldCount of wordDocument)
setfieldCodeto content of field code of currentField
if field type of currentField is field addin andword2of fieldCode contains"bibliography"then
setbibliographySettingstocharacters21thru-2of fieldCode asstring
exit repeat
end if
setfieldCountto fieldCount -1
end repeat
if fieldCount is0then-- look for an unformatted bibliography
setfindObjectto find object of selection -- set up the find system in Word
set match wildcards of findObject totrue
set wrap of findObject to find continue
set content of findObject to"\\\\bibliography*\\}"
select (create range wordDocument start 0end0)
try-- count the number of instances found
setfindCountto0
repeatwhile (execute find findObject)
setfindCountto findCount +1
end repeat
on error-- this can break if advanced find and replace has been used in Word
display dialog"Something is wrong with the find system in Microsoft Word, please quit Microsoft Word then re-open" buttons {"OK"} cancel button {"OK"} default button {"OK"}
return
end try
ifthe findCount is not0then-- extract raw bibiography settings
setbibliographySettingstocharacters15thru-2of (content of selection asstring) asstring
else if findCount is0then-- no bibliography found
return {}
end if
end if
end tell
try-- extract bibliography settings as a list
setAppleScript's text item delimitersto {"<bibDeskDocumentName=", "><bibliographyTemplatePath=", "><citepTemplatePath=", "><citetTemplatePath=", "><parenthesisOpen=", "><parenthesisClose=", "><bibliographySortBy=", "><bibliographyStyle=", "><italicLatin=", "><italicPublicationTypes=", "><superscriptReferences=", "><numberedReferences=", "><numberSeperator=", ">"}
set {bibliographyCommand, bibDeskDocumentName, bibliographyTemplatePath, citepTemplatePath, citetTemplatePath, parenthesisOpen, parenthesisClose, bibliographySortBy, bibliographyStyle, italicLatin, italicPublicationTypes, superscriptReferences, numberedReferences, numberSeperator} totextitemsof bibliographySettings
on error-- if anything is amiss, recreate the bibliography field
tellapplication"Microsoft Word"
display dialog"There is something wrong with the bibliography data, please delete the bibliography and try again" buttons {"OK"} default button {"OK"}
end tell
return
end try
setAppleScript's text item delimitersto","-- recover lists from settings
setitalicLatintotextitemsof italicLatin
setitalicPublicationTypestotextitemsof italicPublicationTypes
setAppleScript's text item delimitersto""
try-- check to make sure that the template files exist
tellapplication"Finder"
get (existsof (POSIX file (bibliographyTemplatePath asstring) asalias))
get (existsof (POSIX file (citepTemplatePath asstring) asalias))
get (existsof (POSIX file (citetTemplatePath asstring) asalias))
end tell
on error-- if not, recreate the bibliography field
tellapplication"Microsoft Word"
display dialog"Template files not found, please delete the bibliography and try again" buttons {"OK"} default button {"OK"}
end tell
return
end try
-- restore Word to its original position
tellapplication"Microsoft Word"
try
select selectionRange
on error-- produces error if cursor was at the end of the document
select (create range wordDocument start (selection endof selection) end (selection endof selection))
end try
set status bar to"Finished reading bibliography"
end tell
return {bibDeskDocumentName, bibliographyTemplatePath, citepTemplatePath, citetTemplatePath, parenthesisOpen, parenthesisClose, bibliographySortBy, bibliographyStyle, italicLatin, italicPublicationTypes, superscriptReferences, numberedReferences, numberSeperator}
end readBibliographySettings
---
onwriteBibliographySettings(bibliographySettings)
-- global setup
tellapplication"Microsoft Word"
setwordDocumentto active document
setselectionRangeto create range wordDocument start (selection start of selection) end (selection endof selection)
set status bar to"Writing bibliography..."
end tell
tellapplication"BibDesk"
setbibDeskDocumenttofront document
end tell
-- parse bibliography settings
setAppleScript's text item delimitersto""
set {bibDeskDocumentName, bibliographyTemplatePath, citepTemplatePath, citetTemplatePath, parenthesisOpen, parenthesisClose, bibliographySortBy, bibliographyStyle, italicLatin, italicPublicationTypes, superscriptReferences, numberedReferences, numberSeperator} to bibliographySettings
-- parse custom lists from the bibliography settings
setAppleScript's text item delimitersto","
setitalicLatintotextitemsof italicLatin
setitalicPublicationTypestotextitemsof italicPublicationTypes
setAppleScript's text item delimitersto""
-- look for formatted bibliography
tellapplication"Microsoft Word"
setfieldCountto (countof fields in wordDocument)
if fieldCount is not0then
repeatuntil fieldCount is0
if content of field code of field fieldCount of wordDocument contains"ADDIN bibliography"then
setbibliographyFieldto field fieldCount of wordDocument
set show codes of bibliographyField totrue
exit repeat
end if
setfieldCountto fieldCount -1
end repeat
end if
end tell
-- if none found, create the bibliography field
if fieldCount is0then
try
tellapplication"Microsoft Word"
display dialog"No bibliography found, do you wish to create one now?"
setbibliographyFieldto make new field atendoftext object of wordDocument withproperties {field type:field quote, show codes:true, field text:"*"}
end tell
on error-- return the bibliography settings empty
return {}
end try
if bibDeskDocumentName is""then-- if default settings were used, set the BibDesk library
tellapplication"BibDesk"
setbibDeskDocumentNametonameof bibDeskDocument
end tell
end if
if bibliographyTemplatePath is""then-- if default settings were used, set the template paths
tellapplication"Microsoft Word"
setbibliographyTemplatePathtoPOSIX pathof (choose filewith prompt "Please choose WordScript Template Bibliography"of type {"public.rtf", "com.microsoft.word.doc"})
end tell
end if
setAppleScript's text item delimitersto"/"-- guess the other template paths
setassumedTemplatePathto (textitems1through-2of bibliographyTemplatePath) asstring
setAppleScript's text item delimitersto""
tellapplication"Finder"
try
setcitepTemplatePathtoPOSIX pathof (POSIX file (assumedTemplatePath &"/"&"WordScript Template Author-Year (citep).txt"asstring) asalias)
setcitetTemplatePathtoPOSIX pathof (POSIX file (assumedTemplatePath &"/"&"WordScript Template Year Only (citet).txt"asstring) asalias)
end try
end tell
if citepTemplatePath is""then-- otherwise choose manually
tellapplication"Microsoft Word"
setcitepTemplatePathtoPOSIX pathof (choose filewith prompt "Please choose WordScript Template Author-Year (citep)"of type {"public.plain-text"})
end tell
end if
if citetTemplatePath is""then
tellapplication"Microsoft Word"
setcitetTemplatePathtoPOSIX pathof (choose filewith prompt "Please choose WordScript Template Year Only (citet)"of type {"public.plain-text"})
end tell
end if
end if
-- write the bibiography field in Word
tellapplication"Microsoft Word"
setAppleScript's textitem delimiters to","
set content of field code of bibliographyField to" ADDIN bibliography{"&"<bibDeskDocumentName="& bibDeskDocumentName &"><bibliographyTemplatePath="& bibliographyTemplatePath &"><citepTemplatePath="& citepTemplatePath &"><citetTemplatePath="& citetTemplatePath &"><parenthesisOpen="& parenthesisOpen &"><parenthesisClose="& parenthesisClose &"><bibliographySortBy="& bibliographySortBy &"><bibliographyStyle="& bibliographyStyle &"><italicLatin="& italicLatin &"><italicPublicationTypes="& italicPublicationTypes &"><superscriptReferences="& superscriptReferences &"><numberedReferences="& numberedReferences &"><numberSeperator="& numberSeperator &">}"
setAppleScript's textitem delimiters to""
try-- restore the cursor to its original position
select selectionRange
on error-- produces error if cursor was at the end of the document
select (create range wordDocument start (selection endof selection) end (selection endof selection))
end try
end tell
-- restore Word to its original position
tellapplication"Microsoft Word"
try
select selectionRange
on error-- produces error if cursor was at the end of the document
select (create range wordDocument start (selection endof selection) end (selection endof selection))
end try
set status bar to"Finished writing bibliography"
end tell
return {bibDeskDocumentName, bibliographyTemplatePath, citepTemplatePath, citetTemplatePath, parenthesisOpen, parenthesisClose, bibliographySortBy, bibliographyStyle, italicLatin, italicPublicationTypes, superscriptReferences, numberedReferences, numberSeperator}
end writeBibliographySettings
---
onformatReferences(bibliographySettings)
-- global setup
tellapplication"Microsoft Word"
setwordDocumentto active document
setselectionRangeto create range wordDocument start (selection start of selection) end (selection endof selection)
set status bar to"Formatting references..."
end tell
tellapplication"BibDesk"
setbibDeskDocumenttofront document
end tell
-- parse bibliography settings
setAppleScript's text item delimitersto""
set {bibDeskDocumentName, bibliographyTemplatePath, citepTemplatePath, citetTemplatePath, parenthesisOpen, parenthesisClose, bibliographySortBy, bibliographyStyle, italicLatin, italicPublicationTypes, superscriptReferences, numberedReferences, numberSeperator} to bibliographySettings
-- parse custom lists from the bibliography settings
setAppleScript's text item delimitersto","
setitalicLatintotextitemsof italicLatin
setitalicPublicationTypestotextitemsof italicPublicationTypes
setAppleScript's text item delimitersto""
-- read the plain text template data (should this move to 'format author-year references'?)
setcitepTemplatetoread citepTemplatePath
setcitetTemplatetoread citetTemplatePath
-- intitialise document lists
setciteKeyListto {}
setpublicationListto {}
setibidCiteKeyListto {}
setitalicReferencesto {}
-- begin formatting the references
tellapplication"Microsoft Word"
activate
-- establish the format range
if (selection start of selection) is equal to (selection endof selection) then
if content of selection is"]"then-- just edited page number
setformatRangetowordsof sentences of selection
else
setformatRangeto wordDocument -- format entire document
select (create range wordDocument start 0end0)
end if
else
setformatRangeto selectionRange -- format selection only
end if
-- set up the find system in Word
setfindObjectto find object of selection
set match wildcards of findObject totrue
set wrap of findObject to find continue
-- convert unformatted cite commands to ADDIN fields
repeatwithciteCommandin {"citep", "citet", "citealp", "citealt", "bibliography"}
set content of findObject to"\\\\"& citeCommand &"*\\}"
select formatRange
try
repeatwhile (execute find findObject)
setciteCommandto content of selection
set content of selection to""
make new field at (text object of selection) withproperties {field type:field quote, show codes:true, field text:"*"}
setcurrentFieldtofirst field of (create range wordDocument start ((selection start of selection) -1) end (selection endof selection))
set content of field code of currentField to" ADDIN "&characters2thru-1of citeCommand
end repeat
on error-- this can break if advanced find and replace has been used in Word
display dialog"Something is wrong with the find system in Microsoft Word, please quit Microsoft Word then re-open" buttons {"OK"} default button {"OK"}
return
end try
end repeat
repeatwithfieldNumberfrom1tocountof fields of formatRange -- convert ADDIN fields to formatted references
setcurrentFieldto field fieldNumber of formatRange
setfieldCodeto content of field code of currentField
if field type of currentField is field addin and {"citep", "citet", "citealp", "citealt"} containsword2of fieldCode then-- extract cite key and prefix/suffix
select currentField
setAppleScript's text item delimitersto {"{", "}"} -- parse cite key
setciteKeytotextitem2of fieldCode
setAppleScript's text item delimitersto {"[", "]"} -- parse prefix/suffix
setreferencePrefixto""
setreferenceSuffixto""
if (countoftextitemsof fieldCode) is5then-- two pairs of square brackets
setreferencePrefixtotextitem2of fieldCode
setreferenceSuffixtotextitem4of fieldCode
else if (countoftextitemsof fieldCode) is3then-- one pair of square brackets
setreferenceSuffixtotextitem2of fieldCode
end if
tellapplication"BibDesk"-- match cite keys to publications
setmultiplePublicationsto {} -- intitialise the multiple reference lists
setmultipleCiteKeysto {}
setAppleScript's text item delimitersto","-- multiple cite keys must be seperated by commas in BibDesk
repeatwitheachIntegerfrom1tocountoftextitemsof citeKey -- loop through every cite key and match to a publication
setcurrentCiteKeytoitem eachInteger oftextitemsof citeKey
setcurrentPublicationto (publications in bibDeskDocument whose cite key is currentCiteKey)
if (countof currentPublication) is0then-- no match found
tellapplication"Microsoft Word"
set show codes of currentField totrue
select field code of currentField
select (create range wordDocument start ((selection start ofselection) -1) end (selectionendofselection) +1)
display dialog"No BibDesk reference matches this cite key: "& currentCiteKey buttons {"OK"} default button {"OK"}
return
end tell
end if
if ibidCiteKeyList is not {} andlastitemof ibidCiteKeyList is currentCiteKey then-- check for ibid. references
setibidReferencetotrue
else
setibidReferencetofalse
end if
setibidCiteKeyListto ibidCiteKeyList & currentCiteKey
if citeKeyList does not contain currentCiteKey then-- list all cite keys
setciteKeyListto citeKeyList & currentCiteKey
end if
repeatwitheachIntegerfrom1tothecountof citeKeyList -- get number for numbered references
ifitem eachInteger of citeKeyList is currentCiteKey then
setciteKeyNumberto eachInteger
end if
end repeat
setmultiplePublicationsto multiplePublications & currentPublication -- list multiple publications in current field
-- list of all publications
if publicationList does not contain currentPublication thensetpublicationListto publicationList & currentPublication
-- list references to be made italic such as films
if italicPublicationTypes contains type of (publications in bibDeskDocument whose cite key is citeKey) then
setitalicReferenceTitleto title of (publications in bibDeskDocument whose cite key is citeKey)
if italicReferences does not contain italicReferenceTitle then
setitalicReferencesto italicReferences & italicReferenceTitle
end if
end if
setmultipleCiteKeysto multipleCiteKeys & citeKeyNumber
setciteKeyNumberTextto multipleCiteKeys
endrepeat
endtell
if (numberedReferences asboolean) isfalsethen
-- format author-year references
if fieldCode contains"citep"then
if ibidReference istruethen
settemplatedTextto"ibid."
else
tellapplication"BibDesk"
settemplatedTextto (templated text document bibDeskDocumentName using text citepTemplate for multiplePublications)
end tell
end if
setformattedReferenceto parenthesisOpen & referencePrefix & templatedText & referenceSuffix & parenthesisClose
else if fieldCode contains"citet"then
if ibidReference istruethen
settemplatedTextto"ibid."
else
tellapplication"BibDesk"
settemplatedTextto (templated text document bibDeskDocumentName using text citetTemplate for multiplePublications)
end tell
end if
setformattedReferenceto parenthesisOpen & referencePrefix & templatedText & referenceSuffix & parenthesisClose
else if fieldCode contains"citealp"then
if ibidReference istruethen
settemplatedTextto"ibid."
else
tellapplication"BibDesk"
settemplatedTextto (templated text document bibDeskDocumentName using text citepTemplate for multiplePublications)
end tell
end if
setformattedReferenceto referencePrefix & templatedText & referenceSuffix
else if fieldCode contains"citealt"then
if ibidReference istruethen
settemplatedTextto"ibid."
else
tellapplication"BibDesk"
settemplatedTextto (templated text document bibDeskDocumentName using text citetTemplate for multiplePublications)
end tell
end if
setformattedReferenceto referencePrefix & templatedText & referenceSuffix
end if
set content ofresult range of currentField to formattedReference
else if (numberedReferences asboolean) istruethen
-- format numbered references
setformattedReferenceto""
setAppleScript's text item delimitersto numberSeperator
set content ofresult range of currentField to parenthesisOpen & citeKeyNumberText & parenthesisClose
end if
-- set superscript for current field
if superscriptReferences isfalsethen
setsuperscriptof font object ofresult range of currentField tofalse
else if superscriptReferences istruethen
setsuperscriptof font object ofresult range of currentField totrue
end if
set show codes of currentField tofalse
-- set italics for current field
setitalicCombinedto italicLatin & italicReferences
repeatwitheachItalicin italicCombined
if formattedReference contains eachItalic then
setAppleScript's text item delimitersto","
repeatwithitalicFindin italicCombined
setfindObjectto find object of selection
set content of findObject to italicFind
set content of replacement of findObject to italicFind
setitalicof font object of replacement of findObject totrue
execute find findObject replace replace all
end repeat
setAppleScript's text item delimitersto""
end if
end repeat
end if
end repeat
-- format bibliography
setfieldCounttocountof fields of formatRange
repeatuntil fieldCount is0
setcurrentFieldto field fieldCount of formatRange
setfieldCodeto content of field code of currentField
if field type of currentField is field addin andword2of fieldCode contains"bibliography"then
setbibliographyFieldto currentField
select bibliographyField
-- compile the bibliography text and export to a temp file
tellapplication"System Events"
settempDirectorytopath to temporary itemsfrom user domain
setbibliographyTemplateFiletoPOSIX file bibliographyTemplatePath asstring
setbibliographyTemplateFileNametonameoffile bibliographyTemplatePath
settempfileto (tempDirectory asstring) & bibliographyTemplateFileName
end tell
tellapplication"BibDesk"
if bibliographySortBy is not""and (numberedReferences asboolean) isfalsethen
sort publicationList by bibliographySortBy
setpublicationListtoresult
end if
export bibDeskDocument using template file (bibliographyTemplateFile asstring) tofile tempfile for publicationList
end tell
-- insert exported text into the bibliography field
set show codes of bibliographyField tofalse
set content ofresult range of bibliographyField to"*"
insert fileat (create range wordDocument start (start of content ofresult range of bibliographyField) end (start of content ofresult range of bibliographyField)) filename tempfile
tellapplication"System Events"to delete file tempfile
-- set Word style of bibliography and force font object
set style ofresult range of bibliographyField to bibliographyStyle
setnameof font object ofresult range of bibliographyField tonameof font object ofWord style bibliographyStyle of wordDocument
-- remove superfluous characters
delete (create range wordDocument start ((endof content ofresult range of bibliographyField) -2) end (endof content ofresult range of bibliographyField))
exit repeat
end if
setfieldCountto fieldCount -1
end repeat
endtell
-- restore Word to its original position
tellapplication"Microsoft Word"
try
select selectionRange
on error-- produces error if cursor was at the end of the document
select (create range wordDocument start (selection endof selection) end (selection endof selection))
end try
set status bar to"Finished formatting references"
end tell
return bibliographySettings
end formatReferences
---
onunformatReferences()
-- global setup
tellapplication"Microsoft Word"
setwordDocumentto active document
setselectionRangeto create range wordDocument start (selection start of selection) end (selection endof selection)
set status bar to"Unformatting references..."
end tell
setAppleScript's text item delimitersto""
-- unformat references
tellapplication"Microsoft Word"
activate
if (selection start of selection) is equal to (selection endof selection) then
setformatRangeto wordDocument
try
display dialog"Are you sure? This will unformat the entire document!" buttons {"Cancel", "OK"} default button "OK"
on error
return
end try
else
setformatRangeto selectionRange
end if
setfieldListto fields of formatRange
if (countof fieldList) is0then
display dialog"There are no formatted references in this selection" buttons {"OK"} default button "OK"
return
end if
repeatwithcurrentFieldinreverseof fieldList
setfieldCodeto content of field code of currentField
if field type of currentField is field addin and {"cite", "citep", "citet", "citealp", "citealt", "bibliography"} containsword2of fieldCode then
if fieldCode contains"bibliography"thenset style ofresult range of currentField to"Normal"
setfieldCodetocharacters8thru-1of fieldCode asstring
select currentField
insert text"\\"& fieldCode atendoftext object of selection
delete currentField
end if
endrepeat
endtell
-- restore Word to its original position
tellapplication"Microsoft Word"
try
select selectionRange
on error-- produces error if cursor was at the end of the document
select (create range wordDocument start (selection endof selection) end (selection endof selection))
end try
set status bar to"Finished unformatting references"
end tell
end unformatReferences
---
onfillEmptyReferences()
-- find empty references contained by {}
setAppleScript's text item delimitersto""
tellapplication"Microsoft Word"
setwordDocumentto active document
setselectionRangeto (create range wordDocument start (selection start of selection) end (selection endof selection))
set status bar to"Filling empty references..."
-- start from the beginning of the document
select (create range wordDocument start 0end0)
-- set up the find system in Word
setfindObjectto find object of selection
set match wildcards of findObject totrue
-- prevent wrapping to enable skip option
set wrap of findObject to find stop
-- find empty references and contents but not cite commands
set content of findObject to"[!\\]]\\{*\\}"
settheCounterto0
repeatwhile (execute find findObject)
set status bar to"Searching for empty references... ("& theCounter &")"
setemptyReferenceTextto content of (create range wordDocument start (selection start of selection) +1end (selection endof selection))
setemptyReferenceContextto"\""&characters1through-2of (content of sentences of selection asstring) &"\""
try
set {citepList, citetList, citealpList, citeSkip} to {"(Author, YEAR)", "(YEAR)", "(Custom...)", "Skip this instance"}
choose from list {citepList, citetList, citealpList, citeSkip} with title "Fill Empty References {}"with prompt "Please select reference[s] in BibDesk for:
"& emptyReferenceContext &"
" default items citepList
settheResulttoresult
if theResult does not contain citeSkip then
if theResult contains citepList then
tellapplication"BibDesk"tosettemplatedTextto templated textfront document using text"<$publications><$#=1?>\\citep[][]{<$citeKey/><?$#?>,<$citeKey/></$#?></$publications>}"for selection offront document
else if theResult contains citetList then
tellapplication"BibDesk"tosettemplatedTextto templated textfront document using text"<$publications><$#=1?>\\citet[][]{<$citeKey/><?$#?>,<$citeKey/></$#?></$publications>}"for selection offront document
else if theResult contains citealpList then
setemptyReferenceContextto emptyReferenceContext &"
(Use 'citealp' for Author, YEAR, and 'citealt' for YEAR)"
tellapplication"BibDesk"tosettemplatedTextto templated textfront document using text"<$publications><$#=1?>\\citealp[][]{<$citeKey/>}<?$#?>\\citealp[; ][]{<$citeKey/>}</$#?></$publications>"for selection offront document
else if theResult isfalsethen
exit repeat
end if
display dialog"Please confirm the cite command for:
"& emptyReferenceContext with title "Fill Empty References {}" default answer templatedText default button "OK"
settemplatedTexttotext returned ofresult
set content of (create range wordDocument start (selection start of selection) +1end (selection endof selection)) to (templatedText asstring)
settheCounterto theCounter +1
end if
on error
-- prevent "no empty references" dialog
settheCounterto-1
-- exit repeat instead of return to avoid breaking the find system in Word
exit repeat
end try
-- continue search from end of filled reference onwards
select (create range wordDocument start (selection endof selection) end (selection endof selection))
end repeat
try
select selectionRange
end try
end tell
if theCounter is0then
tellapplication"Microsoft Word"
display dialog"No empty references filled" buttons {"OK"} default button "OK"
end tell
else if theCounter is greater than0then
try
tellapplication"Microsoft Word"
display dialog"Empty references filled, format references now?" buttons {"No", "Yes"} cancel button "No" default button "Yes"
if button returned ofresultcontains"Yes"then menuChoiceFormat()
endtell
endtry
end if
tellapplication"Microsoft Word"
set status bar to"Finished filling empty references"
end tell
return
end fillEmptyReferences
---
ontoolsMenu()
-- global setup
tellapplication"Microsoft Word"
setwordDocumentto active document
setselectionRangeto create range active document start (selection start of selection) end (selection endof selection)
end tell
-- open tools menu
repeat
tellapplication"Microsoft Word"
activate
choose from list {"Convert from \\cite to \\citep", "Covert from \\citep to \\cite", "Convert p./pp. to :", "Convert : to p./pp.", "Add Leading Space", "Remove Leading Space"} with title "WordScript Tools"with prompt "You should save your work first!" default items"Convert from \\cite to \\citep" cancel button name {"Exit"} OK button name {"Choose"}
setmenuChoicetoresult
end tell
if menuChoice isfalsethen
exit repeat
end if
if menuChoice contains"Export to Static Group"then
-- rewrite from scratch
else if menuChoice contains"Convert from \\cite to \\citep"then
setAppleScript's text item delimitersto""
tellapplication"Microsoft Word"
activate
setfindObjectto find object oftext object of wordDocument
set match wildcards of findObject tofalse
repeatwithciteCommandin {"\\cite{", "\\cite["}
set content of findObject to citeCommand
if citeCommand asstringis"\\cite{"then