~mwshinn/+junk/notes

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
           System for Lab Notes and Literate Programming v2
                            Opened: 8/5/12

@@@
\tableofcontents
@@@

* Introduction

When working on simulations and computer-based modeling/experiments,
it is necessary to organize data, keep track of information, and
document ideas.  However, no quality system exists for this type of
work.

The script contained herein describes a system that allows one to keep
a lab notebook.  It uses a format that is attractive and readable as a
plain text file, yet also looks good typeset with LaTeX as a pdf.  

This text format is dynamic.  It continues to evolve to fit the needs
at hand.  While it will try to maintain backwards compatibility, this
is not always possible.  Additions and deletions will be documented in
this file.

UPDATE (10/7/12): I realized recently how useful it would be to have a
system that I can use for lab reports as well.  I have updated the
document/code accordingly.

** Emacs mode

I have written an emacs mode ("notes-mode") to make working with notes
files easier in emacs.  It can be installed by moving the file
"notes-mode.el" into the ".emacs.d/site-lisp" directory, and adding
the following lines to your ".emacs" file:

> (add-to-list 'load-path "~/.emacs.d/site-lisp")
> (let ((default-directory "~/.emacs.d/site-lisp/"))
>      (normal-top-level-add-subdirs-to-load-path))
> (require 'notes-mode)

Alternatively, you can place it in any directory in emacs' load path
and just add the following to your ".emacs" file:

> (require 'notes-mode)

This mode is based on org-mode.  Most of the features of org-mode
don't make a lot of sense with notes-mode, so for now, they may be
ignored.  I may try later to only import the features of org-mode that
are needed.

* Format

** General structure

Each document consists of a title, header information (properties),
the document content, and optionally the "Closed" property at the end
of the document.  Additionally, each document may have its own
director, which should be named by appending ".d" to the end of the
file name.  All file names fields throught your document will be
relative to this directory.

The title is always the first line of the document.  The next several
lines consist of header information in the format "Key: value".  The
following are accepted key/value combinations and what they can be
used for:

- "Opened" - The only mandatory key.  This is the date you started the
  document.  This can be any string, though I don't see why it would
  be useful to use anything other than a date.
- "Type" - Can be "Note" (default), "Report", or "Draft".  See the
  section below on document types for more information.
- "Closed" - The date when the note was finished.  Can be any string.
  If any edits are made past this date, it is recommended to use the
  "UPDATE" syntax described below.  This is the only option that can
  be placed at the end of the document.
- "By" - The author(s) of the document.  Can be any string.  Defaults
  to "Maxwell Shinn" because that's the name of this program's only
  user.
- "Spacing" - Can be "Single" (default), "1.5", or "Double".  Will
  single, 1.5, or double space the document.
- "Bibliography" - Can be set to either "auto" or a file name that
  exists in the note's ".d" directory.  If "auto", a bibtex file will
  be created by downloading the citations for all of your inline
  references (see the ``Links'' section).  If it is set to a file
  name, that file name will be included so that "\ref{}"-style
  citations may be included.
- "Debug" - Can be set to "False" (default) or "True".  "True"
  disables all internet-dependent features and significantly speeds up
  compilation time.

If "Type" is set to "Note" (or not included), one additional option
becomes available:

- "Project" - If you have many note files, this consists of the
  category or project to which it belongs.  

If "Type" is set to "Report", a few more options are available:

- "Course" - Only valid if "Type" is set to "Report".  The name of the
  course for which this report was written.  This can be any string.
  If you are not a student, I don't know why this would be valuable.
- "Instructor" - Allows you to suck up to your TA by putting their
  name on your document.  Can be any string.  Again, probably not
  useful if you're not a student.
- "Due" - A due date for the report.  Can be any string.

** Types of text

There are several types of text you can insert.  They should all be
inserted with at least one blank line (pressing enter twice) between
them.  Otherwise, they may run together or cause an error.  More than
one blank line between paragraphs will create extra whitespace in the
document.

*** Body text

Any text without other designators will be considered paragraph text.
Paragraph text can include inline expressions.

*** Headers

Headers may be specified by including one, two, or three asterisks in
front of a single line of text.  One asterisk indicates a top-level
header, two a subheader, and three a subsubheader.  (This syntax is
inspired from org-mode.)  They should be separated from paragraphs and
from each other by at least a single empty line (pressing enter
twice).

*** Math

There are two types of ways to enter mathematical expressions: inline
math, and equation blocks.  Both are entered using the simplified
LaTeX math format described below.  Inline expressions are described
below as well.

Equation blocks must begin with "$$$" on a line by itself, and ended
with "$$$" on a line by itself.  Multiple equations can be entered,
each on a new line.  There should be no blank lines within the body of
the block.  If including multiple equations within an equation block,
it is possible to align them by using standard LaTeX "&" syntax, where
"&" is inserted at the desired point of alignment.  Two columns of
aligned equations are also possible by putting "&" at each alignment
point and "&" in the middle of the equations.

Equation blocks may also have a label, described below.

*** Code blocks

Code blocks start and end with a line containing only the text "===".
Optionally, they may start with the line "===>" and end with the line
"<===", as this will get them to properly highlight on some text
editors, though either will be accepted by the parser.  Anything
contained within a code block will be extracted when the tool
"extract-code" is run.  See below for more information on this, as
well as how to specify the language.

Code blocks may also have a label, described below.

*** Raw LaTeX and raw LaTeX headers

Because the parser makes many modifications to the source text, in
order to ensure that a complex command is processed directly by the
LaTeX interpreter, start and end it with a line containing only
the text "@@@".

Similarly, it is possible to insert LaTeX code unmodified into the
header.  To do this, start and end a segment of LaTeX code with a line
containing only the text "!!!".  Note that wherever this appears in
the document, it will be inserted into the same spot in the header.
If multiple such statments occur, they are inserted in the order in
which they appear.  Normally, no more than one of these is found at
the top of the document.

*** Updates

After a document has been closed (or has undergone a long state of
inactivity), if there is new content related to a particular region
within an old note, there is special syntax to indicate, ``this was
not known at the time of writing, but may be useful for future
reference.''  Updates are not intended to contain new information, but
rather to point to it.

To insert one, at the beginning of a new paragraph, insert the text
"UPDATE ([date]):", where "[date]" is the date that the update was
added.  Then, begin the paragraph /on the same line/ and continue as
normal.  A blank line afterwards delimits the end of the update.

*** Important

Important paragraphs are paragraphs that are supposed to stand out.
They are useful, for instance, for jotting down relevant ideas without
interfering with the flow of the note.  Any paragraph can be turned
into an important one by adding the text "-> " to the first line.
Then, start the paragraph after this marker and continue as normal.
(Generally these look best in the text file if subsequent lines after
the first are indented by three spaces, though the parser will accept
either style.)

Also note that it is rendered differently if the document type is
"Note" compared to if it is "Report".  See the differences in document
type below for more info.

*** Preformatted

Sometimes it is useful to insert a few lines of preformatted text.
This differs from code blocks in that it is not extracted, and that it
does not perform syntax highlighting in the compiled file.  Any line
that starts with "> " will be considered a preformatted line.  Several
preformatted lines can follow each other without a blank line in
between, but there must be a blank line between preformatted blocks
and paragraphs.

*** Image

Images may be inserted by inserting a line containing only the name of
the image file (or relative path to the image) enclosed in angle
brackets; for instance, "<image.png>".  Supported image types include
anything that is supported by either LaTeX or pdflatex, including png,
jpeg, eps, pdf, and others.  Image paths should be relative to the
note's ".d" directory.

Images are autoscaled to fit the page width.  If the image is of low
resolution, it will only expand to be as wide as its resolution
allows.  Unfortunately, this also means that images that are shaped
approximately like the page will be scaled to fill the whole page.  An
easy hacky way to get around this is to shrink the resolution or add
more whitespace on the sides.

Images may also have a label, described below.  If they do have a
label, they should also have a caption.  If both are included, the
image is given a figure number (e.g. "Figure 3"), and can be referred
to by a link, described below.

-> An image with a caption but no label will not display the caption.
   An image with a label but no caption can be linked to, but it will
   show up as "Figure ??".  Using a title within the link (described
   below) will allow you to name the link something else and still
   have it link properly.

*** Table

Tables are inserted using basic org-mode notation.  Tables should be
entered in the following format:

> | First cell ! | Second cell | ... | Last cell |
> |--------------+-------------+-----+-----------|
> | Stuff        | More stuff  |     | More?     |
> |              | 34          | asd | $x$       |

More formally, the cells on a particular line should be delimited by
"|".  The first and last characters on any given line must be a "|".
All lines consisting only of dashes and pluses will be turned into a
horizontal separator.  An exclamation point in the first line will
indicate a horizontal separator should be placed at that location.  An
exclamation point separated by something other than spaces from a
neighboring "|" will cause an error.

Tables may also have labels and captions, just like images.  See the
images section for some peculiarities about this.

** Inline expressions

Inline expressions may be placed anywhere within a paragraph,
important section, caption, or update.  Some may also be placed within
tables or math blocks.

*** Text formatting commands

Bold, italic, underlined, highlighted, and crossed-out text can be
inserted by surrounding some text in asterisks ("*"), forward slashes
("/"), underscores ("_"), vertical bars ("|"), or tildes ("~"),
respectively.  These characters must be placed at word boundaries,
with either a space, a newline, or punctuation at each end; for
instance "mou_set_rap" will not have the intended underlining.  This
must be accomplished with manual LaTeX commands.  These work anywhere
text can be found.

*** Inline math

Inline math is very similar to that on LaTeX.  Enclosing Simplified
LaTeX math expressions in dollar signs will cause them to be typeset
as a mathematical expression.  See the Simplified LaTeX section below
for more information on it.

*** Inline preformatted

Anything enclosed in double quotes is interpreted as preformatted
text.  Note that the UTF-8 left and right double quote varieties will
not work for this purpose, only the raw ascii double quotes.  Anything
found within double quotes will be interpreted as preformatted text.
This is an easy way to include symbols that would otherwise compile
into other symbols, for instance LaTeX commands or dollar signs.

-> The quotes themselves will remain in the compiled document, but the
   content inside them will be preformatted.  There is currently no
   way to do preformatted text inline without them.

*** Links

Links allow one to link to numerous different things.  They include a
destination, and optionally a title.  Those with a title are in the
format "[[location][title]]" and those that do not are in the format "[[location]]".
Below is a list of different possible link types:

- *Linking to figures/tables* - To link to a figure or table, use its
  label as the location.  Figures without labels cannot be linked to.
  If a title is not provided, it will default to "Figure X" or "Table
  X", where "X" is the figure/table number.
- *Citation links* - To link to a citation, let the location be
  "doi:123456789", "isbn:123456789", or "pmid:123456789", where
  "123456789" is the DOI, ISBN, or PubMed ID.  The link title will be
  "(author, year)", and the link location will be to an online
  identifier of the source.  If the header contains the key
  "Bibliography" set to "auto", these will be included in a generated
  bibliography as well.  If in debug mode, the DOI/ISBN/PMID will be
  displayed in parentheses instaed.
- *Label link* - To link to a location in the document specified by a
  label, let the location be the name of the label.  The name of the
  label will also be the title if another title is not speficied.
- *Web link* - If the location is a URL (designated by "http" or
  "https" at the beginning) it will link to the designated web page.
  This web page will also be the title if another is not provided.
- *Files* - If the location points to a file (relative to the note's
  directory), the link will link to this file.  The file name will be
  used as the title unless another is specified.
- *Notes file* - If the location is the name of a notes file in the
  same directory as the present note, the link will link to this file.
  The file name will be used as the title if another is not provided.

*** Comments

Comments may be inserted by beginning a fragment with "/*" and ending
it with "*/".  They can also optionally be inserted by adding a "#" at
the beginning of the line followed by a space, though this is
depreciated.  These can be included anywhere within a line, or
spanning multiple lines.  The text enclosed within them will never be
displayed.

** UTF8 characters

UTF-8 characters can be entered directly into the document, either in
a math or non-math environment.

It may be necessary to speficy the correct LaTeX command to be used
with the chararcter.  This can be done by finding the portion of the
code labeled "Substitutions" and adding it in.  However, most common
ones are already there.

** Simplified LaTeX math

*** Matrices

*** Exponents and subscripts

*** Quotes

** Links, labels, and captions

** Extracting code

** Document types

** Special quirks

*** Quotation marks

Since ascii quotation marks will insert inline preformatted text,
quotation marks can be inserted with "``" at the beginning and "''" at
the end, as in LaTeX documents.

* Implementation

The following Perl code is a working implementation of this format.

** Initialization

<<latexify-notes.pl>>
===>
#!/usr/bin/perl -w
use Regexp::Grammars;
use Storable; # For caching

if ($#ARGV != 0) {
    die "\nUsage: ./latexify-notes.pl [FILE]\nFILE is the formatted file to be converted to latex format";
}
<===

** Global variables


The "@tokens" variable stores the list of tokens as they are detected
by the regex.  They are stored here in a simple list, where
"___TOKENn___" corresponds to tokens[n].

===>
@tokens = ();
<===

"content" is the text that is read from the file.  It will be
processed in-place, i.e. after processing, content will contain the
output string.  All operations performed in this script are for the
purpose of manipulating the "content" variable.

===>
#$content = do{ local $/; <DATA>};
$filename = $ARGV[0];
local $/ = undef;
open(FILE, $filename);
$content = <FILE>;
close(FILE);
<===


The first line of the document is separated and stored in "title".

===>
($title, $content) = split("\n", $content, 2);
$content = "\n" . $content . "\n";
do { no Regexp::Grammars; $title =~ s/^\s*//; $title =~ s/\s*$//};
<===

The "%properties" hash stores properties as they are accumulated in
parsing the document.  These can be set within the document in "Key:
Value" format.  Note that both "key" and "value" must be alphanumerics
only.  All properties besides "By", "Opened", "Closed", "Type", and
"Project" are currently ignored in the standard note-taking mode.
When "Type" is set to "Report", the properties "Course" and
"Instructor" are also recognized.

===>
%properties = ('By' => "Maxwell Shinn", 
               'Type' => "Note", 
               'Spacing' => "Single",
               'Debug' => "False");
<===

The ID is just the filename without the ".n", and the extension
encompasses everything after the first period.

===>
$id = "";
$suffix = "";
$ext = "";
do { 
    no Regexp::Grammars; 
    if ($filename =~ m/^.*?([^\/\\]+)\.([nr])$/) {
        $id = $1;
        $suffix = $2;
        if ($suffix eq "r") { $properties{'Type'} = "Report"; }
        if ($id =~ m/\./) { $ext = (split("\\.", $id, 2))[1]; }
    }
    else {
        die "Invalid file name.";
    }
};
<===

Here, we create the machinery necessary for backreferences to labels.
The variable "%labeltexts" is a hash that describes all of the labels
in the document.  The text to display is indexed by the label name.
For instance, a label called "dispequation" would be called "Equation
1" in the document, so the text would be "Equation".  Thus, we would
have "('dispequation' => 'Equation ')" as the expected value of this
hash.  Similarly, "%labeltypes" includes the short LaTeX name that
describes the type indexed by the same label as "%labeltexts".
Equations are "eq", figures are "fig", and tables are "tab".

===>
%labeltexts = ();
%labeltypes = ();
<===

Additionally, it is possible to automatically create a bibliography by
specifying "auto" as the source for the bibliography.  This variable
holds the full text for the ".bib" file, generated as each call to a
DOI is created.

===>
$bibtex_entries = "";
<===

** Substitutions

These define a list of simple substitutions.  The keys are replaced
with the values in "%replacements".  In "%replacements_math", they
text is enclosed in an ensuremath command when it is replaced.

===>
%replacements_math = (
    "α"   => "\\alpha",
    "β"   => "\\beta",
    "γ"   => "\\gamma",
    "δ"   => "\\delta",
    "ε"   => "\\epsilon",
    "ζ"   => "\\zeta",
    "η"   => "\\eta",
    "θ"   => "\\theta",
    "ι"   => "\\iota",
    "κ"   => "\\kappa",
    "λ"   => "\\lambda",
    "μ"   => "\\mu",
    "ν"   => "\\nu",
    "ξ"   => "\\xi",
    "ο"   => "\\omicron",
    "π"   => "\\pi",
    "ρ"   => "\\rho",
    "σ"   => "\\sigma",
    "ς"   => "\\varsigma",
    "τ"   => "\\tau",
    "υ"   => "\\upsilon",
    "φ"   => "\\varphi",
    "χ"   => "\\chi",
    "ψ"   => "\\psi",
    "ω"   => "\\omega",
    "Γ"   => "\\Gamma",
    "Δ"   => "\\Delta",
    "Θ"   => "\\Theta",
    "Λ"   => "\\Lambda",
    "Ξ"   => "\\Xi",
    "Π"   => "\\Pi",
    "Σ"   => "\\Sigma",
    "Υ"   => "\\Upsilon",
    "Φ"   => "\\Phi",
    "Ψ"   => "\\Psi",
    "Ω"   => "\\Omega",
    "∫∫∫" => "\\iiint",
    "(?<!∫)∫∫(?!∫)"  => "\\iint",
    "(?<!∫)∫(?!∫)"   => "\\int",
    "∂"   => "\\partial",
    "∇"   => "\\nabla",
    "×"   => "\\times",
    "÷"   => "\\div",
    "·"   => "\\cdot",
    "±"   => "\\pm",
    "→"   => "\\rightarrow",
    "←"   => "\\leftarrow",
    "⤳"   => "\\rightsquigarrow",
    "⇒"   => "\\Rightarrow",
    "⇐"   => "\\Leftarrow",
    "≠"   => "\\neq",
    "≤"   => "\\leq",
    "≥"   => "\\geq",
    "≈"   => "\\approx",
    "⊃"  => "\\supset",
    "⊂"  => "\\subset",
    "⊇"  => "\\supseteq",
    "⊆"  => "\\subseteq",
    "∖"  => "\\setminus",
    "⇔"  => "\\Leftrightarrow",
    "≡"  => "\\equiv",
    "ℵ"   => "\\aleph",
    "¬"   => "\\lnot",
    "∧"  => "\\land",
    "∨"  => "\\lor",
    "(?<! )∀"  => "\\forall \\,",
    " ∀"  => "\\hspace{.2cm}\\forall \\,",
    "∃"  => "\\exists",
    "∄"   => "\\nexists",
    "ℓ"   => "\\ell",
    "∞"   => "\\infty",
    "∈"  => "\\in",
    "∋"  => "\\ni",
    "ℝ"  => "\\mathbb{R}",
    "ℕ"  => "\\mathbb{N}",
    "ℂ"  => "\\mathbb{C}",
    "ℤ"  => "\\mathbb{Z}",
    "ℚ"  => "\\mathbb{Q}",
    "𝔽"  => "\\mathbb{F}",
    "ø"  => "\\emptyset",
    "∅"  => "\\emptyset",
    "∘"  => "\\circ",
    "∑"  => "\\sum",
    "∏"  => "\\prod",
    "§"  => "\\S",
    "∪_" => "\\bigcup_",
    "∪(?!\_)"  => "\\cup",
    "∩_" => "\\bigcap_",
    "∩(?!\_)"  => "\\cap",
    "‹"  => "\\langle",
    "›"  => "\\rangle",
    "→"   => "\\rightarrow",
    "↑"  => "\\uparrow",
    "‣"   => "\\rightarrow", # TEMPORARY!
    "⇒"   => "\\Rightarrow",
    "≠"   => "\\neq",
    "≟"   => "\\overset{?}{=}",
    "≤"   => "\\leq",
    "≥"   => "\\geq",
    "≈"   => "\\approx",
    "♯"  => "{\\sharp}", 
    "♭"  => "{\\flat}",
    "♮"  => "{\\natural}"
);
# I haven't done anything with this yet... future feature?
# %replacements_math_only = (
#     "(?<!\\\\)sin(?![A-Za-z0-9])" => "\\$1"
# );

@rmfuns = ("sin", "cos", "tan", "arcsin", "arccos", "arctan", "asin",
           "acos", "atan", "sec", "csc", "cot", "ln", "log", "max",
           "min", "sup", "inf", "ker", "coker", "rng", "corng", "var",
           "rank", "rk", "exp", "erf", "det", "tr", "lim", "Cov",
           "Var");

%replacements = (
    "\\.\\.\\." => "\\ldots ",
    "…"         => "\\ldots ",
    "ä"         => '\"{a}',
    "á"         => "\\'{a}",
    "é"         => "\\'{e}",
    "í"         => "\\'{i}",
    "ó"         => "\\'{o}",
    "ú"         => "\\'{u}",
    "ö"         => '\"{o}',
    "ü"         => '\"{u}',
    "✓"         => '', # For checking off checked problems
    "✗"         => '', # For checking off checked problems
    "LaTeX"     => "{\\LaTeX}",
    "St\\."       => "St.\\@",
    "Mr\\."       => "Mr.\\@",
    "Mrs\\."      => "Mrs.\\@",
    "Ms\\."       => "Ms.\\@",
    "Dr\\."       => "Dr.\\@",
    "Apt\\."      => "Apt.\\@",
    "Prof\\."     => "Prof.\\@",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆑𝆑(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{ff}",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆑(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{f}",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆐𝆑(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{mf}",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆐𝆏(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{mp}",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆏(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{p}",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆏𝆏(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{pp}",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆑𝆏(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{fp}",
    "(?<![𝆑𝆏𝆍𝆎𝆐])𝆍𝆑𝆎(?![𝆑𝆏𝆍𝆎𝆐])"  => "\\dynmark{sfz}"
);

<===

** Grammar

This section defines the grammar/syntax used for the notes file
format.  It also outlines the format of the resulting parse tree,
which is used in the processing section.

===>
qr{
    <grammar: notes>
    <token: Paragraph>          <.bls> <lines> <.ble>
    <token: bls>               (?<=\n\n)
    <token: ble>               (?=\n\n)
    <token: partbls>           (?<=\n)
    <token: partble>           (?=\n)
    <token: line>              [^\n]+
    <token: lines>             (<[line]> \n)* <[line]>

    <token: BigMath>            <.bls> <optionallabel>? \$\$\$ \n <lines> \n \$\$\$ <.ble>
    <token: InlineMath>         <.math> <mathtext> <.math>
    <token: math>              (?<!\\)(?<!\$)\$
    <token: mathtext>          [^\$]+

    <token: Matrix2>            mat\[(<[matrixrow2]>,\s*\n*)* <[matrixrow2]>\]
    <token: matrixrow2>         \[(<[matrixcell2]>,\s*\n*)* <[matrixcell2]>\]
    <token: matrixcell2>        [^\s\]]+

    <token: Matrix>            mat\[(<[matrixrow]>;\s*\n*)* <[matrixrow]>\]
    <token: matrixrow>         (<[matrixcell]>[,\s]\s*)* <[matrixcell]>
    <token: matrixcell>        [^\s,;\]]+

    <token: Quote>             \" <quotetext> \"
    <token: quotetext>         [^"]+

    <token: Feedback>          <-\{ <feedbacktext> \}
    <token: feedbacktext>      [^\}]+

    <token: RawLatex>          <.bls> \@\@\@ \n <lines> \n \@\@\@ <.ble>
    <token: RawLatexHeader>    <.bls> \!\!\! \n <lines> \n \!\!\! <.ble>

    <token: Comment>           <.partbls> (<.begincomment> <[line]> \n)* <.begincomment> <[line]> <.partble> | /\* .*? \*/
    <token: begincomment>      \#\s
    
    <token: Preformatted>      <.bls> (<.beginpreformatted> <[line]> \n)* <.beginpreformatted> <[line]> <.ble>
    <token: beginpreformatted> >\s

    <token: Important>         <.bls> <.beginimportant> <lines> <.ble>
    <token: beginimportant>    \->\s

    <token: Update>            <.bls> UPDATE \s \(<date=([0-9/]+)>\): <lines> <.ble>

    <token: Image>             <.bls> <optionallabel>? <.beginimage> <line> <.endimage> <optionaldesc>? <.ble>
    <token: beginimage>        (?<!\<) < (?!\<)
    <token: endimage>          (?<!\>) > (?!\>)

    <token: Section>           <.bls> <.beginsection> <line> <.partble>
    <token: beginsection>      \*\s

    <token: Subsection>        <.bls> <.beginsubsection> <line> <.partble>
    <token: beginsubsection>   \*\*\s

    <token: Subsubsection>     <.bls> <.beginsubsubsection> <line> <.partble>
    <token: beginsubsubsection> \*\*\*\s

    <token: Bullets>           <.bls> (<[bulletpoint]> <[bulletline]> \n)* <[bulletpoint]> <[bulletline]> <.ble>
    <token: bulletline>        <line> <[trailinglines]>*
    <token: trailinglines>     \n [ ]+ [^\- 0-9][^ ][^\n]+ | \n [ ]+ [a-z0-9]+[^\.][^\n]+
    <token: bulletpoint>       <bulletwhitespace> <bulletpointmark> \s
    <token: bulletpointmark>   [\-] | [0-9]{1,3}\.
    <token: bulletwhitespace>  [ \t]*

    <token: Table>             <.bls> <optionallabel>? (<[tableline]> \n)* <[tableline]> <optionaldesc>? <.ble>
    <token: tableline>         [+|] [^\n]+ [+|]

    <token: Property>          <.partbls> [ \t]* <name=([A-Z][A-Za-z]+)> : [ \t]* <val=line> <.partble>

    <token: Link>              <.beginlink> <linkprefix>? <linktext> <linktitle>? <.endlink>
    <token: beginlink>         \[\[
    <token: endlink>           \]\]
    <token: linkprefix>        http:// | ftp:// | doi: | pmid: | isbn: | ref:
    <token: linktext>          [^\]]+
    <token: linktitle>         <.linktitledelim> <linktext>
    <token: linktitledelim>    \]\[

    <token: Code>              <.bls> <optionallabel>? <.delimitcode> \n <codelines> \n <.delimitcode> <.ble>
    <token: codeline>          [^\n]*
    <token: codelines>         (<[codeline]> \n)*? <[codeline]>
    <token: delimitcode>       [\<]?===[\>]?

    <token: Label>             \<\< <linklabeltext> \>\>
    <token: optionallabel>     <Label> \n
    <token: linklabeltext>     [^\>]+

    <token: Vspace>            <.bls> (\n*) <.partble>

    <token: Description>       \{ <descriptiontext>  \}
    <token: optionaldesc>      \n <Description>
    <token: descriptiontext>   [^\}]+


}xms;
<===

** Utility functions

These functions contain code that is reusable in multiple of the processing functions.

-> One thing to note about the design is that the "\ensuremath"
   function is necessary, even in math environments, and should not be
   removed.  It ensures that things will remain grouped together.  In
   theory, plain curly brackets could replace it in math environments.
   For instance, it makes sure "$2^\alpha\beta$" shows up properly.

===>
sub math_formatting {
    my $text = shift;
    do {
        no Regexp::Grammars;
        $text =~ s/(?<!_)_(-?[A-Za-z0-9\.]+)(?!\_)/\_{$1}/g; # Easy subscript/superscript words
        $text =~ s/\^(-?[A-Za-z0-9\.]+)(?!\^)/\^{$1}/g; 
        $text =~ s/([A-Za-z0-9\\\{\}]+)/\\sqrt{$1}/g; # Square roots # FIXME the {} in there is a hack to get \sqrt{\pi} to work with \ensuremath
        $text =~ s/√\(([^\)]+)\)/\\sqrt{$1}/g; 
        $text =~ s/\<\</\\ll/g; # Much greater than/less than
        $text =~ s/\>\>/\\gg/g;
        $text =~ s/d([A-Za-z0-9\\\{\}_]*)\/d([A-Za-z0-9\\\{\}_]+)/\\frac{d$1}{d$2}/g; # Easy derivatives
        $text =~ s/\\ensuremath\{\\partial\}([A-Za-z0-9\\\{\}_]*)\/\\ensuremath\{\\partial\}([A-Za-z0-9\\\{\}_]+)/\\frac{\\partial $1}{\\partial $2}/g; # Easy derivatives
        $text =~ s/d^\{([0-9])\}[ ]*([A-Za-z0-9\\\{\}_]*)\/d([A-Za-z0-9\\\{\}_]+)^\{\\1\}/\\frac{d^$1 $2}{d$3^$1}/g; # FIXME double derivatives
        $text =~ s/%/\\%/g; # Percent signs
        $text =~ s/ { / \\{ /g; # Guess for set brackets
        $text =~ s/ } / \\} /g; 
        $text =~ s/ }\n/ \\}\n/g; 
        $text =~ s/\(([0-9A-Za-z]+)\/([0-9A-Za-z]+)\)/\\frac{$1}{$2}/g; # Easy short fractions
        $text =~ s/\|\|(.*?)\|\|/\\norm\*{$1}/g; # Norm signs
        # Commented because it causes errors in stats hw2.n # $text =~ s/\|(.*?)\|/\\abs\*{$1}/g; # Absolute value signs
        $text =~ s/\(/ \\left\( /g; #Math parentheses
        $text =~ s/\)/ \\right\) /g;
        $text =~ s/\*([^\* \n]+)\*/\\bm{$1}/gs; # Bold (matrix) text
        $text =~ s/~/{\\sim}/g; #Tilde.  In here instead of replacements_math because it conflicts with strikeouts.

        $funnames = join("|", @rmfuns); # Change sin -> \sin, ln -> \ln, etc.
        $text =~ s/(?<![\\A-Za-z0-9\"])($funnames)(?![A-Za-z0-9\"])/\\$1/g;

        # Moved this to the end to not interfere with putting "max" in quotes
        $text =~ s/\"([^\"]+)\"/\\text{$1}/gs; # Quotes make inline text automatically

    };
    return $text;
}

sub utf8_substitute {
    my $text = shift;
    my $inmathenv = shift; # Are we in the math environment already?
    do {
        no Regexp::Grammars;
        use Data::Dumper::Simple;
        @keys = keys %replacements_math;
        foreach (@keys) {
            $from = $_;
            $to = $replacements_math{$_};
            if ($inmathenv == 1) {
                $text =~ s/$from/\\ensuremath{$to}/sg;
            }
            else {
                $text =~ s/$from/\\ensuremath{$to}/sg;
            }
        }
        @keys = keys %replacements;
        foreach (@keys) {
            $from = $_;
            $to = $replacements{$_};
            $text =~ s/$from/$to/sg;
        }
        # Combining marks
        # Note: This includes a hack to get around the fact that greek letters that
        # were already replaced by \ensuremath{\letter} cannot be detected.
        $text =~ s/(\\[A-Za-z]+\}?|.)̃/\\ensuremath{\\tilde{$1}}/g;
        $text =~ s/(\\[A-Za-z]+\}?|.)̂/\\ensuremath{\\hat{$1}}/g;
        $text =~ s/(\\[A-Za-z]+\}?|.)/\\ensuremath{\\vec{$1}}/g;
        $text =~ s/(\\[A-Za-z]+\}?|.)̄/\\ensuremath{\\bar{$1}}/g; # Note, also called a macron
        $text =~ s/(\\[A-Za-z]+\}?|.)̉/\\ensuremath{\\overset{?}{$1}}/g;
        $text =~ s/(\\[A-Za-z]+\}?|.)̇/\\ensuremath{\\dot{$1}}/g;
        $text =~ s/(\\[A-Za-z]+\}?|.)/\\ensuremath{\\circled{$1}}/g;
    };

    return $text;
}

sub text_substitute {
    my $text = shift;
    do {
        no Regexp::Grammars;
        $text =~ s/\*\*([^ ].*?)\*\*/\*$1\*/gs; # Emphasized text - backward compatibility
        $text =~ s/(?<=\s)\*([^ \n][^\*]*[^ \n])\*/\\textbf{$1}/gs; # Bold text
        $text =~ s/(?<=\s)\/([^ \n][^\/]*[^ \n])\//\\textit{$1}/gs; # Italic text
        $text =~ s/(?<=\W)\|([^ \n\|][^\|]*[^ \n\|])\|(?=\W)/\\hl{$1}/gs; # Highlighted text
        if ($properties{'Type'} eq "Draft") {
            $text =~ s/(?<=\W)~([^ \n~][^~]*[^ \n~])~(?=\W)/\\deleted{$1}/gs; # Strikeout text
        }
        else {
            $text =~ s/(?<=\W)~([^ \n~][^~]*[^ \n~])~(?=\W)/\\sout{$1}/gs; # Strikeout text
        }
        $text =~ s/(?<=\s)_([^ _\n][^_]*[^ _\n])_([ \n,!.:;)"'])/\\underline{$1}$2/gs; # Underline text
        $text =~ s/\%/\\\%/g; # Replace percent signs with real percent signs

    };
    return $text;
}

sub escape_latex {
    my $text = shift;
    do {
        no Regexp::Grammars;
        $text =~ s/\\/\\textbackslash /gs;
        $text =~ s/{/\\{/gs;
        $text =~ s/}/\\}/gs;
        $text =~ s/%/\\%/gs;
        $text =~ s/\_/\\\_/gs;
        $text =~ s/\#/\\\#/gs;
        $text =~ s/\^/\\\^/gs;
        $text =~ s/~/\\~/gs;
        $text =~ s/\$/\\\$/gs;
        $text =~ s/\&/\\\&/gs;
    };
    return $text;
}

sub create_absolute_link {
    my $text = shift;
    return "$filename.d/$text";
}
<===

** Citations


The following functions manage citations.  They are used to retrieve
and format the citations appropriately.  

===>
# Implement PMID with https://www.ncbi.nlm.nih.gov/books/NBK25498/#chapter3.EPost__ESummaryEFetch
# Implement ISBN with http://xisbn.worldcat.org/webservices/xid/isbn/1401307787?method=getMetadata&format=xml&fl=*
sub get_citation_from_doi {
    my $url = shift;
    my $output = "";
    # Resolve the DOI and write it to a text file
    $command = "curl -LH \"Accept: application/x-research-info-systems\" 'http://dx.doi.org/$url'";
    $bibcommand = "curl -LH \"Accept: text/bibliography; style=bibtex\" 'http://dx.doi.org/$url'";
    if ($properties{'Debug'} ne "True") {
        $output = command_or_cache($command);
        if (exists $properties{'Bibliography'} && $properties{'Bibliography'} eq "auto") {
            $bibtex_entries .= command_or_cache($bibcommand) . "\n";
        }
    }
    else {
        $output = `false`;
    }
    if ($? == 0) { # Fetch successful, exit status 0
        do {
            no Regexp::Grammars;
            my ($authorlast) = $output =~ /AU\s*-\s*([^,]+),/;
            my ($year) = $output =~ /PY\s*-\s*([0-9]{4})/;
            return "($authorlast,~$year)";
        }
    }
    else {
        return $url;
    }
}
# TODO get Bibtex entry for ISBNs
sub get_citation_from_isbn {
    my $isbn = shift;
    my $output = "";
    $command = "curl -L 'http://xisbn.worldcat.org/webservices/xid/isbn/$isbn?method=getMetadata&format=xml&fl=*'";
    if ($properties{'Debug'} ne "True") {
        $output = command_or_cache($command);
        # Put bibliography stuff in here when you write it
    }
    else {
        $output = `false`;
    }
    if ($? == 0) { # Fetch successful, exit status 0
        do {
            no Regexp::Grammars;
            my $author = $1 if ($output =~ /author="([^"]+)"/);
            my $year = $1 if ($output =~ /year="([^"]+)"/);
            if ($author eq "") {
                return "($year)";
            }
            return "($author,~$year)";
        }
    }
    else {
        return "(ISBN~$isbn)";
    }
}
# TODO Make a bibtex entry from this info
sub get_citation_from_pmid {
    my $pmid = shift;
    my $output = "";
    if ($properties{'Debug'} ne "True") {
        # First get the special ID their API needs
        my $url = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?db=pubmed&id=$pmid";
        my $command = "curl -L '$url'";
        my $web = "";
        my $key = "";
        $output = command_or_cache($command);
        if ($? != 0) { # Make sure fetch was successful
            return "(PMID~$pmid)";
        }
        do {
            no Regexp::Grammars;
            $web = $1 if ($output =~ /<WebEnv>(\S+)<\/WebEnv>/);
            $key = $1 if ($output =~ /<QueryKey>(\d+)<\/QueryKey>/);
        };
        # Now actually look it up
        $url = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&query_key=$key&WebEnv=$web&rettype=xml";
        $command = "curl -L '$url'";
        $output = command_or_cache($command);
        my $author = "";
        my $year = "";
        do {
            no Regexp::Grammars;
            $author = $1 if ($output =~ /<LastName>([^<]+)<\/LastName>/);
            $year = $1 if ($output =~ /<DateCreated>\s*<Year>([0-9]+)<\/Year>/);
        };
        return "($author,~$year)";
    }
    else {
        return "(PMID~$pmid)";
    }
}
<===

This function is used by the previous three to cache URLs.  It checks
to see if a URL has been previously retrieved, and if so, returns the
contents from the cache.  If not, it downloads the URL, and then saves
it to the cache and returns it.  This should not be used if content is
not expected to be static.

===>
$urlcachefilename = '/home/max/Tmp/test.note.urlcache';
%urlcache = ();
if (-e $urlcachefilename) {
    %urlcache = %{retrieve($urlcachefilename)};
}
sub command_or_cache {
    my $command = shift;
    #use Data::Dumper::Simple;
    #print Dumper $urlcache;
    #print $command;
    #print $urlcache{$command};
    if (exists $urlcache{$command}) {
        return $urlcache{$command};
    }
    else {
        $output = `$command`;
        $urlcache{$command} = $output;
        return $output;
    }
}
<===

** Processing rule types

These functions are called whenever a match is found from the grammar.
The parse tree is their only argument.  They process the parse tree
and return valid LaTeX that represents the information from the parse
tree.

===>
sub proc_preformatted {
    my $tree = shift;
    my $line = join("\n", @{$tree->{Preformatted}->{line}});
    $verbtext = "verbatim";
    return "\\begin{$verbtext}\n$line\n\\end{$verbtext}";
}
sub proc_rawlatex {
    my $tree = shift;
    my $line = join("\n", @{$tree->{RawLatex}->{lines}->{line}});
    return $line;
}
$custom_header = "";
sub proc_rawlatexheader {
    my $tree = shift;
    my $line = join("\n", @{$tree->{RawLatexHeader}->{lines}->{line}});
    $custom_header .= "$line\n";
    return "";
}
sub proc_image {
    my $tree = shift;
    my $imgfile = create_absolute_link(${$tree}{Image}{line});
    my $text = "\\begin{center}\n";
    my $label = "";
    $text .= "\\includegraphicsscaled{$imgfile}\n";
    $text .= "\\end{center}\n";

    if (exists $tree->{Image}->{optionallabel}) {
        $label = $tree->{Image}->{optionallabel}->{Label}->{linklabeltext};
        $text = "\\hypertarget{" . $label . "}{}\n" . $text;
        $labeltexts{$label} = 'Figure';
        $labeltypes{$label} = 'fig';
    }

    if (exists $tree->{Image}->{optionaldesc}) {
        my $desc = $tree->{Image}->{optionaldesc}->{Description}->{descriptiontext};
        $desc = utf8_substitute($desc, 0);
	    if ($label ne "") { $label = "\n\\label{fig:$label}"; }
        my $prefigure = "\\begin{figure}[h!]\n";
        my $postfigure = "\n\\caption{$desc}$label\n\\end{figure}";
	    $text = $prefigure . $text . $postfigure;
    }

    return $text;
}
sub proc_inlinemath {
    my $tree = shift;
    my $text = ${$tree}{InlineMath}{mathtext};
    $text = utf8_substitute($text, 1);
    $text = math_formatting($text);
    return '$' . $text . '$';
}
sub proc_quotes {
    my $tree = shift;
    my $text = ${$tree}{Quote}{quotetext};
    $text = escape_latex($text);
    $text = utf8_substitute($text, 0);
    return "\\texttt{\"\\textbf{" . $text . "}\"}";
}
sub proc_feedback {
    my $tree = shift;
    my $text = ${$tree}{Feedback}{feedbacktext};
    $text = escape_latex($text);
    $text = utf8_substitute($text, 0);
    if ($properties{'Type'} eq "Draft") {
        return "\\todo[fancyline]{$text}";
    }
    return "\\pdfcomment{$text}";
}
sub proc_property {
    my $tree = shift;
    my $name = ${$tree}{Property}{name};
    my $val = ${$tree}{Property}{val};
    $properties{$name} = $val;
    return "\n";
}
sub proc_comment {
    return "";
}
sub proc_vspace {
    my $tree = shift;
    my $line = $tree->{Vspace};
    do {
        no Regexp::Grammars;
        $line =~ s/~\\\\\n/\n/g;
    };
    return "~\\\\\n$line";
}
sub proc_label {
    my $tree = shift;
    my $labelname = ${$tree}{Label}{linklabeltext};
    return "\\hypertarget{" . $labelname . "}{}";
}
sub proc_matrix {
    # use Data::Dumper::Simple;
    my $tree = shift;
    # print Dumper $tree;
    my @rows = @{$tree->{Matrix}->{matrixrow}};
    # Check for an augmented matrix
    my $endmatrix = "";
    my @firstrow = @{$tree->{Matrix}->{matrixrow}[0]->{matrixcell}};
    if ($firstrow[scalar(@firstrow)-2] eq "|") {
        # $latexmatrix = "\\ensuremath{\\left[\\begin{array}{" . "c"x(scalar(@firstrow)-2) . "|c} ";
        # $endmatrix = "\\end{array}\\right]}";
        $latexmatrix = "\\ensuremath{\\begin{bmatrix}[" . "c"x(scalar(@firstrow)-2) . "|c] ";
        $endmatrix = "\\end{bmatrix}}";
    }
    else {
        $latexmatrix = "\\ensuremath{\\begin{bmatrix} ";
        $endmatrix = "\\end{bmatrix}}";
    }
    for (my $i=0; $i<scalar(@rows); $i++) {
        my @cells = @{$tree->{Matrix}->{matrixrow}[$i]->{matrixcell}};
        for (my $j=0; $j<scalar(@cells)-1; $j++) {
            # Skip augmented matrix bars
            if ($j==scalar(@cells)-2 && $cells[$j] eq "|") {
                next;
            }
            my $cellval = $cells[$j];
            $cellval = utf8_substitute($cellval, 1);
            $cellval = text_substitute($cellval);
            $cellval = math_formatting($cellval);
            $latexmatrix .= $cellval . " & ";
        }
        my $cellval = $cells[scalar(@cells)-1];
        $cellval = utf8_substitute($cellval, 1);
        $cellval = text_substitute($cellval);
        $cellval = math_formatting($cellval);
        $latexmatrix .= $cellval . " \\\\";
    }
    $latexmatrix .= $endmatrix;
    return $latexmatrix;
}
sub proc_bigmath {
    my $tree = shift;
    my $line = join(" \\\\\n", @{$tree->{BigMath}->{lines}->{line}});
    my $firstline = ${$tree->{BigMath}->{lines}->{line}}[0];
    my $text = "";
    my $label = "";
    if (exists $tree->{BigMath}->{optionallabel}) {
        $label = $tree->{BigMath}->{optionallabel}->{Label}->{linklabeltext};
    }

    # Do some things to pretty it up
	$line =~ s/\\sum/\\displaystyle \\sum/g; # Pretty summations

    # Check to see if it has alignment informaiton or not

    # I don't know what I want to use the "\" at the end of the line syntax for
    # if($firstline =~ m/\\$/x) {
    #     do {no Regexp::Grammars; $line =~ s/\\ \\\\/\\\\/; };
    #     $text .= "\\begin{equation*}\\begin{split}\n";
    #     $text .= $line;
    #     $text .= "\n\\end{split}\\end{equation*}";
    # }
    if ($firstline =~ m/&/x) {
        do {no Regexp::Grammars; $line =~ s/\\ \\\\\n/ /g; }; # Allows \ syntax at end of line to continue
        $text .= "\\begin{align*}\n";
        $text .= $line;
        $text .= "\n\\end{align*}";
    }
    elsif ($label ne "") {
        $text .= "\\begin{equation}\n";
        $text .= "\\label{eq:" . $label . "}\n";
        $text .= $line;
        $text .= "\n\\end{equation}";
    }
    else {
        do {no Regexp::Grammars; $line =~ s/\\ \\\\\n/ /g; };
        $text .= "\\begin{gather*}\n";
        $text .= $line;
        $text .= "\n\\end{gather*}";
    }

    if ($label ne "") {
        $text = "\\hypertarget{" . $label . "}{}\n" . $text;
        $labeltexts{$label} = 'Equation';
        $labeltypes{$label} = 'eq';
    }
    $text = utf8_substitute($text, 1);
    $text = math_formatting($text);
    return $text;
}
sub proc_important {
    my $tree = shift;
    my $start = "\\begin{center}\n\\fbox{\n\\begin{minipage}{.8\\textwidth}\n";
    my $end = "\n\\end{minipage}\n}\n\\end{center}";
    my $startr = "\\begin{center}\\begin{minipage}{.8\\textwidth} \\bf\n";
    my $endr = "\n\\end{minipage}\n\\end{center}\\vspace{.2cm}";
    my $line .= join("\n", @{$tree->{Important}->{lines}->{line}});

    $line = utf8_substitute($line, 0);
    $line = text_substitute($line);
    if ($properties{'Type'} eq "Report") {
        return $startr . $line . $endr;
    }
    else {
        return $start . $line . $end;
    }
}


sub proc_update {
    my $tree = shift;
    my $text = "\\begin{description}\n";
    $text .= "\\item[Update ({$tree->{Update}->{date}})] \n";
    $text .= join("\n", @{$tree->{Update}->{lines}->{line}});
    $text .= "\n\\end{description}";
    $text = utf8_substitute($text, 0);
    $text = text_substitute($text);
    return $text;
}
sub proc_section {
    my $tree = shift;
    my $text = ${$tree}{Section}{line};
    $text = utf8_substitute($text, 0);
    $text = text_substitute($text);
    if ($properties{'Type'} eq "Report") {
        return "\\subsection{" . $text . "}";
    }
    return "\\section{" . $text . "}";
}
sub proc_subsection {
    my $tree = shift;
    my $text = ${$tree}{Subsection}{line};
    $text = utf8_substitute($text, 0);
    $text = text_substitute($text);
    if ($properties{'Type'} eq "Report") {
        return "\\subsubsection{" . $text . "}";
    }
    return "\\subsection{" . $text . "}";
}
sub proc_subsubsection {
    my $tree = shift;
    my $text = ${$tree}{Subsubsection}{line};
    $text = utf8_substitute($text, 0);
    $text = text_substitute($text);
    if ($properties{'Type'} eq "Report") {
        return "\\paragraph{" . $text . "}";
    }
    return "\\subsubsection{" . $text . "}";
}
sub proc_table {
    my $tree = shift;
    use Data::Dumper;
    my @lines = @{$tree->{Table}->{tableline}};
    my $tfmt = $lines[0];
    my $label = "";
    no Regexp::Grammars;
    $tfmt =~ s/\|$//;
    $tfmt =~ s/[^|!]//g;
    $tfmt =~ s/\|/l /g; # These will be left aligned
    $tfmt =~ s/\!/| /g; # Vertical bar

    my $text = "\\begin{tabular}{$tfmt}\n";
    for (my $i=0; $i<scalar(@lines); $i++) {
        my $curline = $lines[$i];
        if ($curline =~ /^\|[+-]+\|\s*$/) { # Detect an hline
            $text .= "\\hline\n";
        }
        else {
            if ($i==0) {
                $curline =~ s/![ ]*\|/\|/g;
            }
            $curline =~ s/^\|//;
            $curline =~ s/^(.+)\|\s*$/$1 \\\\ /;
            $curline =~ tr/\|/\&/;
            $text .= $curline . "\n";
        }
    }
    $text .= "\\end{tabular}";
    $text = utf8_substitute($text, 0);
    $text = text_substitute($text);
    use Regexp::Grammars;

    if (exists $tree->{Table}->{optionallabel}) {
        $label = $tree->{Table}->{optionallabel}->{Label}->{linklabeltext};
        $text = $text . "\\hypertarget{" . $label . "}{}\n";
        $labeltexts{$label} = 'Table';
        $labeltypes{$label} = 'tab';
    }
    # Whether to use "h" or "h!" as position information depending on document type
    my $postype = "h!";
    if ($properties{'Type'} eq "Report") {
        $postype = "";
    }
    if (exists $tree->{Table}->{optionaldesc}) {
        my $desc = $tree->{Table}->{optionaldesc}->{Description}->{descriptiontext};
        $desc = utf8_substitute($desc, 0);
	    if ($label ne "") { $label = "\\label{tab:$label}"; }
        my $prefigure = "\\begin{center}\n\\begin{table}[$postype]\n\\caption{$desc}$label\n";
        my $postfigure = "\n\\end{table}\n\\end{center}";
	    $text = $prefigure . $text . $postfigure;
    }
    return $text;
}
sub proc_bullets {
    my $tree = shift;
    my $currentlevel = 0;
    my $returnstring = "";
    # Each time we read a new item, if it has more whitespace than the
    # previous one, we'll push a new item onto the levelstack.  The
    # type will either be "enumerate" or "itemize".  Since Perl
    # doesn't have good tuple support, we'll store the spacing
    # associated with that level in spacingstack.
    my @levelstack = ();
    my @spacingstack = ();
    use Data::Dumper;
    my @lines = @{$tree->{Bullets}->{bulletline}};
    my @spaces = @{$tree->{Bullets}->{bulletpoint}};
    no Regexp::Grammars;
    for (my $i=0; $i<scalar(@lines); $i++) {
        my $wslen = length($spaces[$i]->{bulletwhitespace});
        if ($wslen > $currentlevel) {
            my $env = "";
            if ($spaces[$i]->{bulletpointmark} =~ /[0-9]/) {
                $env = "enumerate";
            } else {
                $env = "itemize"; 
            }
            push(@levelstack, $env);
            $returnstring .= "\\begin{$env}\n";
            push(@spacingstack, $currentlevel);
            $currentlevel = $wslen;
        }
        while ($wslen < $currentlevel) {
            my $env = pop(@levelstack);
            $returnstring .= "\\end{$env}\n";
            $currentlevel = pop(@spacingstack);
        }
        $line = $lines[$i]->{line};
        $line .= join(" ", @{$lines[$i]->{trailinglines}});
        $line = utf8_substitute($line, 0);
        $line = text_substitute(" $line "); # Some things at the start of a line won't substitute properly without that space in there
        $returnstring .= " "x$wslen . "\\item " . $line . "\n";
    }
    my $env = "";
    while ($currentlevel > 0) {
        my $env = pop(@levelstack);
        $returnstring .= "\\end{$env}\n";
        $currentlevel = pop(@spacingstack);
    }
    if ($spaces[0]->{bulletpointmark} =~ /[0-9]/) {
        $env = "enumerate";
    } else {
        $env = "itemize"; 
    }
    use Regexp::Grammars;
    return "\\begin{$env}\n$returnstring\\end{$env}";
}
sub proc_link {
    my $tree = shift;
    $linkloc = $tree->{Link}->{linktext};
    if (exists $tree->{Link}->{linktitle}->{linktext}) {
        $linktitle = $tree->{Link}->{linktitle}->{linktext};
    }
    else {
        $linktitle = $linkloc;
    }
    if (exists $tree->{Link}->{linkprefix}) {
        if ($tree->{Link}->{linkprefix} eq "http://") {
            return "\\href{$linkloc}{$linktitle}";
        }
        elsif ($tree->{Link}->{linkprefix} eq "doi:") {
            if ($linktitle eq $linkloc) {
                $linktitle = get_citation_from_doi($linkloc);
            }
            return "\\href{http://dx.doi.org/$linkloc}{$linktitle}";
            # TODO make link text related to doi source with command: curl -D - -L -H "Accept: text/turtle" "http://dx.doi.org/10.1126/science.1157784"
        }
        elsif ($tree->{Link}->{linkprefix} eq "isbn:") {
            if ($linktitle eq $linkloc) {
                $linktitle = get_citation_from_isbn($linkloc);
            }
            return "\\href{http://www.worldcat.org/isbn/$linkloc}{$linktitle}";
            # TODO make link text related to doi source with command: curl -D - -L -H "Accept: text/turtle" "http://dx.doi.org/10.1126/science.1157784"
        }
        elsif ($tree->{Link}->{linkprefix} eq "pmid:") {
            if ($linktitle eq $linkloc) {
                $linktitle = get_citation_from_pmid($linkloc);
            }
            return "\\href{http://www.ncbi.nlm.nih.gov/pubmed/$linkloc}{$linktitle}";
        }
        elsif ($tree->{Link}->{linkprefix} eq "ref:") {
            return "\\hyperlink{$linkloc}{$linktitle}";
        }
    }
    use Data::Dumper::Simple;
    if (exists $labeltexts{$linkloc}) {
        $labeltype = $labeltypes{$linkloc};
        $labeltext = $labeltexts{$linkloc};
        if ($linktitle eq $linkloc) {
            $linktitle = "$labeltext \\ref{$labeltype:$linkloc}";
        }
        return "\\hyperlink{$linkloc}{$linktitle}";
    }
    if (do {no Regexp::Grammars; $linkloc =~ m/.*\.n/;}) {
        return "\\href{run:$linkloc.pdf}{$linktitle}";
    }
    return "\\href{run:$id.$suffix.d/$linkloc}{$linktitle}";
}
%linenos = ();
$labellast = $id;
sub proc_code {
    my $tree = shift;
    my $num_lines = @{$tree->{Code}->{codelines}->{codeline}};
    my $line = join("\n", @{$tree->{Code}->{codelines}->{codeline}});

    # Figure out the programming language by the extension
    %langs = (
        "c" => "C",
        "h" => "C",
        "cpp" => "C++",
        "hpp" => "C++",
        "php" => "PHP",
        "py" => "Python",
        "pl" => "Perl",
        "m" => "Octave",
        "gnuplot" => "Gnuplot",
        "sh" => "sh",
        "erl" => "erlang",
        "el" => "Lisp"
    );
    
    my $text = "";
    my $labelext = "";
    my $lstoptions = "";
    my $label = $labellast;
    # Find the label, if it exists, and use it to detect the language
    # this segment is in.  See extract-code.pl for logic.
    if (exists $tree->{Code}->{optionallabel}) {
        $label = $tree->{Code}->{optionallabel}->{Label}->{linklabeltext};
        $text = "\\hypertarget{" . $label . "}{}\n" . $text;
        $labellast = $label;
    }
    do {
        no Regexp::Grammars;
        if ($label =~ m/\.([A-Za-z0-9]+)$/) {
            $labelext = $1;
        }
    };

    # Determine listings options
    if (exists $langs{$labelext}) {
        $lstoptions .= "language=$langs{$labelext},";
    }
    elsif (exists $langs{$ext}) {
        $lstoptions .= "language=$langs{$ext},";
    }
    # Numbering
    if (exists $linenos{$label}) {
        $lstoptions .= "firstnumber=$linenos{$label},";
        $linenos{$label} += $num_lines;
    }
    else {
        $lstoptions .= "firstnumber=1,";
        $linenos{$label} = $num_lines+1;
    }
    $from = $linenos{$label} - $num_lines;
    $to = $linenos{$label}-1;
    $lstoptions .= "title={\\tiny \\hfill $label, $from--$to},backgroundcolor=\\color\{lightgray\},frame=single,framerule=0pt,";


    if ($labelext eq "") {
        $verbtext = "verbatim";
        $text .= "\\begin{$verbtext}";
        $text .= $line;
        $text .= "\n\\end{$verbtext}";
    }
    else {
        $lstlistingtext = "lstlisting";
        $text .= "\\begin{$lstlistingtext}[$lstoptions]\n";
        $text .= $line;
        $text .= "\n\\end{$lstlistingtext}";
    }

    return $text;
}

<===

The "@rules" variable holds all of the information necessary to detect
and parse each token and aspect of the notes file syntax.  "regex"
contains a regular expression that will detect a particular feature
and generate its parse tree, and "proc" contains the name of the
function that can process the parse tree (from the section above).

-> The order of the elements in "@rules" matters!  Those that are
first in the list are processed first.  Hence, it is important to put
the rules that need verbatim text first, since no other tokens should
be detected within these.

===>
$inlinemath   = qr{ <extends: notes> <InlineMath> }xms;
$quotes       = qr{ <extends: notes> <Quote> }xms;
$feedback     = qr{ <extends: notes> <Feedback> }xms;
$matrix       = qr{ <extends: notes> <Matrix> }xms;
$bigmath      = qr{ <extends: notes> <BigMath> }xms;
$rawlatex     = qr{ <extends: notes> <RawLatex> }xms;
$rawlatexhead = qr{ <extends: notes> <RawLatexHeader> }xms;
$comment      = qr{ <extends: notes> <Comment> }xms;
$preformatted = qr{ <extends: notes> <Preformatted> }xms;
$important    = qr{ <extends: notes> <Important> }xms;
$update       = qr{ <extends: notes> <Update> }xms;
$image        = qr{ <extends: notes> <Image> }xms;
$section      = qr{ <extends: notes> <Section> }xms;
$subsection   = qr{ <extends: notes> <Subsection> }xms;
$subsubsection= qr{ <extends: notes> <Subsubsection> }xms;
$bullets      = qr{ <extends: notes> <Bullets> }xms;
$table        = qr{ <extends: notes> <Table> }xms;
$property     = qr{ <extends: notes> <Property> }xms;
$label        = qr{ <extends: notes> <Label> }xms;
$link         = qr{ <extends: notes> <Link> }xms;
$code         = qr{ <extends: notes> <Code> }xms;
$vspace       = qr{ <extends: notes> <Vspace> }xms;

@rules = (
    {regex => $code, proc => 'proc_code'}, # Must go first to avoid quotation mark conflicts
    {regex => $preformatted, proc => 'proc_preformatted'}, # Go second to make sure all symbols are captured
    {regex => $rawlatexhead, proc => 'proc_rawlatexheader'}, # Remove all header portions
    {regex => $rawlatex, proc => 'proc_rawlatex'}, # Do this next to make sure latex is preserved
    {regex => $image, proc => 'proc_image'},
    {regex => $property, proc => 'proc_property'},
    {regex => $matrix, proc => 'proc_matrix'},
    {regex => $bigmath, proc => 'proc_bigmath'},
    {regex => $inlinemath, proc => 'proc_inlinemath'},
    {regex => $quotes, proc => 'proc_quotes'},
    {regex => $feedback, proc => 'proc_feedback'},
    {regex => $comment, proc => 'proc_comment'},
    {regex => $important, proc => 'proc_important'},
    {regex => $update, proc => 'proc_update'},
    {regex => $section, proc => 'proc_section'},
    {regex => $subsection, proc => 'proc_subsection'},
    {regex => $subsubsection, proc => 'proc_subsubsection'},
    {regex => $table, proc => 'proc_table'},
    {regex => $link, proc => 'proc_link'}, # Must go after table, figure, and bigmath to make sure references work
    {regex => $bullets, proc => 'proc_bullets'}, #Must go after link to make sure links in bullets are handled
    {regex => $label, proc => 'proc_label'},
    {regex => $vspace, proc => 'proc_vspace'});
<===

** Prepare the content

Here, we process each type of token/section, listed above.

Iterate through each of the rules defined in @rules.  Look for the
regex, and for each instance it is found, pass a reference of the
Regexp::Grammars parse tree to the appropriate proc function.

===>
$tokenid = 0;
for(my $i=0; $i<scalar(@rules); $i++) {
    while (1) {
        if ($content =~ s/$rules[$i]{regex}/___TOKEN${tokenid}___/) {
            # We need to pass the result list by reference to the
            # function specified in @rules
            $text = &{$rules[$i]{proc}}(\%/);
            # Add the processed text to the @tokens array
            push(@tokens, $text);
            $tokenid++;
        }
        else {last;}
    }
}
<===

Replace all of the tokens in the string with the appropriate token
from @tokens.  Note that there is a bug in Regexp::Grammars, so we have
to disable it while doing substitutions.

===>
no Regexp::Grammars; 

# Replace the special characters
$content = utf8_substitute($content, 0);
$content = text_substitute($content);

# Replace all the ___TOKENxxx___ symbols with the actual tokens
while ($content =~ s/___TOKEN([0-9]+)___/$tokens[$1]/g) {}
<===

** Header and Footer

"header" and "footer" define the top and bottom of the output LaTeX
document.  This is for initialization such as the begindocument line.

===>
if ($properties{'Type'} eq "Report" || $properties{'Type'} eq "Draft") {
    $fontsize = "12pt";
}
else {
    $fontsize = "10pt";
}

$header = "\\documentclass[" . $fontsize . "]{article}
\\usepackage[pdftex]{graphicx}
\\usepackage{epstopdf}
\\epstopdfsetup{outdir=/tmp/}
\\usepackage[colorlinks=true,filecolor=blue]{hyperref}\n";

if (exists $properties{'Project'}) { $subject = "ID: $id, Project: $properties{'Project'}"; }
else { $subject = "ID: $id"; }
$header .= "\\hypersetup
{
    pdftitle={$title},
    pdfauthor={Max Shinn},
    pdfcreator={TeX},
    pdfsubject={$subject},
}\n";

<===

This will ensure that if there are things still marked "TODO" in the
document, a watermark will be inserted as a reminder to actually go do
those things.

===>
do {
    no Regexp::Grammars;
    if ($content =~ m/TODO /) {
        $header .= "\\usepackage{draftwatermark}\n";
    }
};

$header .= "\\usepackage{underscore}
\\usepackage{grffile}
%\\usepackage{ulem}
\\usepackage{gensymb}
\\usepackage{amsmath}
\\usepackage{amssymb}
\\renewcommand*\\rmdefault{ppl}\\normalfont\\upshape % Palatino font

\\usepackage{mathtools}
\\usepackage{bm} % For typesetting matrices
\\setcounter{MaxMatrixCols}{30} % Longer matrices

%\\setcounter{errorcontextlines}{999} % More context for errors

% Circled text, from http://www.faqoverflow.com/tex/7032.html
\\usepackage{tikz}
\\newcommand*\\circled[1]{\\tikz[baseline=(char.base)]{
            \\node[shape=circle,draw,inner sep=2pt] (char) {#1};}}


% Dynamic markings, from http://tex.stackexchange.com/questions/111788/how-to-typeset-music-dynamics-within-normal-text
\\newcommand{\\muskern}{\\kern-.15ex } % what MusiXTeX does
\\makeatletter
\\newcommand\\dynmark[1]{{\\normalfont\\bfseries\\itshape
  \\\@tfor\\next:=#1\\do{\\put\@muskern\\next}\\/}}
\\newcommand{\\put\@muskern}{\\let\\put\@muskern\\muskern}
\\makeatother

% Don't let images get too big
\\usepackage{calc}
\\newlength{\\imgwidth}
\\newcommand\\includegraphicsscaled[1]{%
    \\settowidth{\\imgwidth}{\\includegraphics{#1}}%
    \\setlength{\\imgwidth}{\\minof{\\imgwidth}{\\textwidth}}%
    \\includegraphics[width=\\imgwidth,keepaspectratio]{#1}%
}


% \\usepackage{enumitem} % Higher depth for bullet points
% \\setlistdepth{9}
% \\setlist[itemize,1]{label=\$\\bullet\$}
% \\setlist[itemize,2]{label=\$\\bullet\$}
% \\setlist[itemize,3]{label=\$\\bullet\$}
% \\setlist[itemize,4]{label=\$\\bullet\$}
% \\setlist[itemize,5]{label=\$\\bullet\$}
% \\setlist[itemize,6]{label=\$\\bullet\$}
% \\setlist[itemize,7]{label=\$\\bullet\$}
% \\setlist[itemize,8]{label=\$\\bullet\$}
% \\setlist[itemize,9]{label=\$\\bullet\$}
% \\renewlist{itemize}{itemize}{9}

\\DeclarePairedDelimiter\\abs{\\lvert}{\\rvert}
\\DeclarePairedDelimiter\\norm{\\lVert}{\\rVert}
";

if ($properties{'Type'} eq "Report") {
    $header .= "\n\\usepackage[margin=1in]{geometry}\n";
}

if ($properties{'Type'} eq "Draft") {
    $header .= "\n\\usepackage[margin=1in,right=3in,left=.7in]{geometry}\n";
    $header .= "\\setlength{\\marginparwidth}{2.5in}"

}

if ($properties{'Spacing'} eq "Double" || $properties{'Spacing'} eq "1.5") {
    $header .= "\n\\usepackage{setspace}\n\n";
}

if (exists $properties{'Bibliography'}) {
    $header .= "\n\\usepackage{natbib}\n\n";
}

$header .= "
\\usepackage{listings}
\\usepackage{color}
\\usepackage{soul} % For highlighting
\\usepackage{todonotes} % For feedback comments
\\usepackage{changes} % For colored strikeouts
\\colorlet{Changes\@Color}{red} % Change default strikeout color to red
\\usepackage{pdfcomment} % For feedback comments with report/note doctype
\\usepackage[font=small,labelfont=bf]{caption}
%\\captionsetup{belowskip=12pt,aboveskip=4pt} %table spacing for captions

% Experimenal support for notes files syntax highlighting using listings
% \lstdefinelanguage{rock}{morekeywords={UPDATE, ->, Opened:, Closed;, By:, Bibliography:,},
%    sensitive=false,
%    morecomment=[l]{>},
%    morecomment=[s]{/*}{*/},
%    morestring=[b]\",
%    morestring=[m]$,
%   }

\\definecolor{dkgreen}{rgb}{0,0.6,0}
\\definecolor{gray}{rgb}{0.5,0.5,0.5}
\\definecolor{mauve}{rgb}{0.58,0,0.82}
\\definecolor{lightgray}{gray}{0.97}

\\DeclareMathOperator{\\rank}{rank}
\\DeclareMathOperator{\\rk}{rk}
\\DeclareMathOperator{\\var}{var}
\\DeclareMathOperator{\\cov}{cov}
\\DeclareMathOperator{\\coker}{coker}
\\DeclareMathOperator{\\rng}{rng}
\\DeclareMathOperator{\\corng}{corng}
\\DeclareMathOperator{\\erf}{erf}
\\DeclareMathOperator{\\tr}{tr}
\\DeclareMathOperator{\\Cov}{Cov}
\\DeclareMathOperator{\\Var}{Var}

% Augmented matrices
\\makeatletter
\\renewcommand*\\env\@matrix[1][*\\c\@MaxMatrixCols c]{%
  \\hskip -\\arraycolsep
  \\let\\\@ifnextchar\\new\@ifnextchar
  \\array{#1}}
\\makeatother

\\lstset{
  basicstyle=\\footnotesize,
  firstnumber=last,
  numbers=left,                   % where to put the line-numbers
  numberstyle=\\tiny\\color{gray},% the style that is used for the line-numbers
  stepnumber=1,                   % the step between two line-numbers. If it's 1, each line 
                                  % will be numbered
  numbersep=5pt,                  % how far the line-numbers are from the code
  backgroundcolor=\\color{white}, % choose the background color. You must add \usepackage{color}
  showspaces=false,               % show spaces adding particular underscores
  showstringspaces=false,         % underline spaces within strings
  showtabs=false,                 % show tabs within strings adding particular underscores
  tabsize=2,                      % sets default tabsize to 2 spaces
  captionpos=b,                   % sets the caption-position to bottom
  breaklines=true,                % sets automatic line breaking
  breakatwhitespace=false,        % sets if automatic breaks should only happen at whitespace
  keywordstyle=\\color{blue},     % keyword style
  commentstyle=\\color{dkgreen},  % comment style
  stringstyle=\\color{mauve},     % string literal style
  morekeywords={*,...}            % if you want to add more keywords to the set
}
\\hypersetup{
%    colorlinks,%
    citecolor=black,%
    filecolor=black,%
    linkcolor=black,%
    urlcolor=black
}

\\setcounter{secnumdepth}{0} % No numbering of sections
";

# From proc_rawlatexheader
$header .= $custom_header;

$header .= "
\\begin{document}
";

if ($properties{'Spacing'} eq "Double") {
    $header .= "\n\\doublespacing\n";
}
elsif ($properties{'Spacing'} eq "1.5") {
    $header .= "\n\\onehalfspacing\n";
}
if (exists $properties{'Bibliography'}) {
    $header .= "\n\\bibliographystyle{cbe}\n\n";
}

$header .= "
\\begin{center}
\\section*{$title}
\\end{center}
";

if ($properties{'Type'} eq "Note") {
    $header .= "\n\\hfill {\\large \\textit{ID: $id}}\n";
    if (exists $properties{'Project'}) {
        $header .= "\\hfill {\\large \\textit{Project: $properties{'Project'}}} \\\\ \n";
    }
}
elsif ($properties{'Type'} eq "Report") {
    $header .= "\n \\begin{flushright} \n{\\large $properties{'By'}} \\\\ \n";
    if (exists $properties{'Course'}) {
        $header .= "{\\large $properties{'Course'}} \\\\ \n";
    }
    if (exists $properties{'Instructor'}) {
        $header .= "{\\large $properties{'Instructor'}} \\\\ \n";
    }
    if (exists $properties{'Due'}) {
        $header .= "\\hfill {\\large $properties{'Due'}} \\\\ \n";
    }
    elsif (exists $properties{'Closed'}) {
        $header .= "\\hfill {\\large $properties{'Closed'}} \\\\ \n";
    }
    else {
        $header .= "\\hfill {\\large $properties{'Opened'}} \\\\ \n";
    }
    $header .= "\\end{flushright}\n";
}

$footer = "";
<===

Include a signature.  "Maxwell Shinn" is the default name, but this
can be overridden by setting the "By" property.

===>
die "Note never opened.  Add 'Opened: [date]' to the document header." unless exists $properties{'Opened'};

if ($properties{'Type'} eq "Note") {
    $footer .= "\n\n\\hspace{1in}\n\n";
    if (exists $properties{'Closed'}) {
        $footer .= "\\hfill ---$properties{'By'},~~\\textit{$properties{'Opened'}--$properties{'Closed'}}\n\n";
    }
    else {
        $footer .= "\\hfill ---$properties{'By'},~~\\textit{$properties{'Opened'}}\n\n";
    }
}
<===

Optionally include a bibliography.

===>
if (exists $properties{'Bibliography'} && $properties{'Bibliography'} ne "auto") {
    $bib = create_absolute_link($properties{'Bibliography'});
    $footer .= "\n\\bibliography{$bib}\n\n";
}
elsif (exists $properties{'Bibliography'} && $properties{'Bibliography'} eq "auto") {
    # First clean the entries to remove underscores, and then write to a file.  We're still
    # using "no Regexp::Grammars" and thus don't have to specify it again.
    $bibtex_entries =~ tr/_/-/;
    $bibtex_entries =~ s/\},/\},\n/g;
    $bib = "$filename.bib";
    open HANDLE, ">",  $bib;
    print HANDLE $bibtex_entries;
    close HANDLE;
    $footer .= "\n\\nocite{*}\\bibliography{$bib}\n\n"
}
<===

Write out the cache

===>
store \%urlcache, $urlcachefilename;
<===

** Closing

Close the document and output the results

===>
$footer .= "\\end{document}\n";


print $header, "\n", $content, "\n", $footer
<===

* Extracting source code

The following will extract source code from any notes file and export
it to several individual files.

** Initialization

Basic header and some modules.

<<extract-code.pl>>
===>
#!/usr/bin/perl -w

use Regexp::Grammars;
use File::Basename;
<===

Load the file contents into the "$contents" variable.

===>
$filename = $ARGV[0];
local $/ = undef;
open(FILE, $filename);
$content = <FILE>;
close(FILE);
<===

Now find the filename, path, etc.

===>
$id = "";
do { 
    no Regexp::Grammars; 
    if ($filename =~ m/^.*?([^\/\\]+)\.([nr])$/) {
        $id = $1;
    }
    else {
        die "Invalid file name.";
    }
};
$path = (fileparse($filename))[1];
<===

The second optional command line parameter allows you to specify one
of the source files to be displayed as output.  Even if it is
displayed as output, it will still be written to the correct file.

===>
if (exists $ARGV[1]) {
    $onlyshow = $ARGV[1];
}
else {
    $onlyshow = "";
}
<===

** Grammar

I need to duplicate everything below because Perl is dumb and I can't
seem to get the scoping to work correctly within "Regexp::Grammars"
when I include it as an external file.

===>
qr{
    <grammar: notes>
    <token: Paragraph>          <.bls> <lines> <.ble>
    <token: bls>               (?<=\n\n)
    <token: ble>               (?=\n\n)
    <token: partbls>           (?<=\n)
    <token: partble>           (?=\n)
    <token: line>              [^\n]+
    <token: lines>             (<[line]> \n)* <[line]>
    <token: Code>              <.bls> <optionallabel>? <.delimitcode> \n <codelines> \n <.delimitcode> <.ble>
    <token: codeline>          [^\n]*
    <token: codelines>         (<[codeline]> \n)*? <[codeline]>
    <token: delimitcode>       [\<]?===[\>]?

    <token: Label>             \<\< <linklabeltext> \>\>
    <token: optionallabel>     <Label> \n
    <token: linklabeltext>     [^\>]+

}xms;

$code = qr{ <extends: notes> <Code> }xms;
<===

** Extracting the source code

Now we actually extract the source code.  Each label is used as the
name of the source code file.  The file is read sequentially.  If
there is a label, this label is the name of the file.  If there is not
a label, the most recent label is used (i.e. the label that was used
on the previous code block).  If the first one does not have a label,
the label is taken from the file name of the notes file.

===>
%sourcetexts = ();
$last = "";
while (1) {
    if ($content =~ s/$code//) {
        my $line = join("\n", @{$/{Code}->{codelines}->{codeline}}) . "\n";
        if (exists $/{Code}->{optionallabel}) {
            my $label = $/{Code}->{optionallabel}->{Label}->{linklabeltext};
            if (exists $sourcetexts{$label}) {
                $sourcetexts{$label} .= $line;
                $last = $label;
            }
            else {
                $sourcetexts{$label} = $line;
                $last = $label;
            }
        }
        elsif ($last ne "") {
            $sourcetexts{$last} .= $line;
        }
        else {
            $sourcetexts{$id} = $line;
            $last = $id;
        }
    }
    else {last;}
}
<===

Now actually print them all out to files.

===>
while(($k,$v)=each(%sourcetexts)) {
    open HANDLE, ">",  $path . "/" . $k;
    print HANDLE $v;
    close HANDLE;
    if ($onlyshow eq $k) {
        print $v;
    }
}
<===