Skip to content
Snippets Groups Projects
Commit 401b3338 authored by tuhe's avatar tuhe
Browse files

Refactor citation + tags and update README.md

parent 2995d500
No related branches found
No related tags found
No related merge requests found
......@@ -180,7 +180,7 @@ if __name__ == "__main__":
print("and that is a fact!") #!o=b
```
This example will produce two files `cs101_output/o_tag_a.txt`, `cs101_output/o_tag_b.txt`:
```python
```terminal
Here are the first 4 square numbers
1 is a square
4 is a square
......@@ -188,14 +188,15 @@ Here are the first 4 square numbers
16 is a square
```
and
```python
```terminal
Area of square of width 2 and height 4 is:
8
and that is a fact!
```
## The #i!-tag
The #!i-tag allows you to create interactive python shell-snippets that can be imported using the minted `pycon` environment ('\inputminted{python}{input.shell}').
The #!i-tag allows you to create interactive python shell-snippets that can be imported using
the minted `pycon` environment (`\inputminted{python}{input.shell}`).
As an example, consider the instructor file
```python
for animal in ["Dog", "cat", "wolf"]: #!i=a
......@@ -233,6 +234,26 @@ Let's consider the following example of a simple document with a couple of refer
![LaTeX sample](https://gitlab.compute.dtu.dk/tuhe/snipper/-/raw/main/docs/index.png)
The code for this document is:
```latex
\documentclass{article}
\usepackage{url,graphics,rotating,hyperref}
\usepackage{cleveref}
\usepackage{showlabels}
\begin{document}
\section{First section}\label{sec1}
Math is hard \cite{bertsekasII,rosolia2018data,herlau}, see also \cref{eq1} and \cref{fig1}.
\begin{equation}
2+2 = 4 \label{eq1}
\end{equation}
\begin{figure}\centering
\includegraphics[width=.8\linewidth]{br}\caption{A figure}\label{fig1}
\end{figure}
\bibliographystyle{alpha}
\bibliography{library}
\end{document}
```
To use the references in code we first have to load the `references.bib` file and the `index.aux`-file and then:
- Snipper allows you to directly insert this information using `\cite` and `\ref`
- You can also define custom citation command which allows you to reference common sources like
......@@ -254,28 +275,41 @@ def myfun():
print("See \ref{sec1}") # Also works.
return 42
```
We can manually compile this example by first loading the aux-files and the bibliographies as follows:
```python
```
Next, we load the python file containing the reference code and fix all references based on the aux and bibliography data.
Note the last parts of the file contains the special commands `\nref` (references to lecture notes) and `\aref2` (assignment 2) which I want to define.
This can be done by changing the call to snipper as follows (`examples/process_cs101_references.py`)
```python
from snipper.snip_dir import snip_dir
from snipper.load_citations import get_aux, get_bibtex
def main():
bibfile = get_bibtex('latex/library.bib')
auxfile = get_aux('latex/index.aux')
references = dict(bibtex=bibfile,
aux=auxfile,
commands=[dict(command='\\aref2', output="(Assignment 2, %s)", aux=auxfile),
dict(command='\\nref', output="\cite[%s]{herlau}", aux=auxfile),
])
snip_dir("./cs101_instructor", "./cs101_students", output_dir="./cs101_output", references=references)
if __name__ == "__main__":
main()
```
The middle command is a convenience feature: It allows us to specify a special citation command `\nref{..}` which always compiles to `\cite[\ref{...}]{herlau}`. This is useful if e.g. `herlau` is the bibtex key for your lecture notes. The result is as follows:
And this then produce the output:
```python
def myfun(): #!s
"""
To solve this exercise, look at \ref{eq1} in \ref{sec1}.
You can also look at \cite{bertsekasII} and \cite{herlau}
More specifically, look at \cite[Equation 117]{bertsekasII} and \cite[\ref{fig1}]{herlau}
We can also write a special tag to reduce repetition: \nref{fig1} and \nref{sec1}.
References:
[Ber07] Dimitri P. Bertsekas. Dynamic Programming and Optimal Control, Vol. II. Athena Scientific, 3rd edition, 2007. ISBN 1886529302.
[Her21] Tue Herlau. Sequential decision making. (See 02465_Notes.pdf), 2021.
"""
return 42 #!s
def myfun():
"""
Simple aux references eq. (1) in Section 1.
Simple bibtex citations: (Ber07) and (Her21, Somewhere around the middle)
Example of custom command (reference notes)
> (Her21, Figure 1)
Other example of custom command (reference assignment)
> (Assignment 2, Section 1)
"""
print("See Section 1") # Also works.
return 42
```
Note this example uses the low-level api. Normally you would just pass the bibtex and aux-file to the main censor-file command.
## Additional features:
- You can name tags using `#!s=bar` to get a `foo_bar.py` snippet. This is useful when you need to cut multiple sessions. This also works for the other tags.
\ No newline at end of file
Since the aux/bibtex databases are just dictionaries it is easy to join them together from different sources.
I have written reference tags to lecture and exercise material as well as my notes and it makes reference management very easy.
\ No newline at end of file
......@@ -94,16 +94,17 @@ As an example, Consider the instructor file
{{ cs101_instructor.o_tag_py }}
```
This example will produce two files `cs101_output/o_tag_a.txt`, `cs101_output/o_tag_b.txt`:
```python
```terminal
{{ cs101_output.o_tag_a_txt }}
```
and
```python
```terminal
{{ cs101_output.o_tag_b_txt }}
```
## The #i!-tag
The #!i-tag allows you to create interactive python shell-snippets that can be imported using the minted `pycon` environment ('\inputminted{python}{input.shell}').
The #!i-tag allows you to create interactive python shell-snippets that can be imported using
the minted `pycon` environment (`\inputminted{python}{input.shell}`).
As an example, consider the instructor file
```python
{{ cs101_instructor.i_tag_py }}
......@@ -126,6 +127,11 @@ Let's consider the following example of a simple document with a couple of refer
![LaTeX sample]({{resources}}/docs/index.png)
The code for this document is:
```latex
{{index_tex}}
```
To use the references in code we first have to load the `references.bib` file and the `index.aux`-file and then:
- Snipper allows you to directly insert this information using `\cite` and `\ref`
- You can also define custom citation command which allows you to reference common sources like
......@@ -137,21 +143,14 @@ Let's look at all of these in turn. The file we will consider in the instructor-
```python
{{ cs101_instructor.references_py }}
```
We can manually compile this example by first loading the aux-files and the bibliographies as follows:
```python
{{ load_references_a_py }}
```
Next, we load the python file containing the reference code and fix all references based on the aux and bibliography data.
Note the last parts of the file contains the special commands `\nref` (references to lecture notes) and `\aref2` (assignment 2) which I want to define.
This can be done by changing the call to snipper as follows (`examples/process_cs101_references.py`)
```python
{{ load_references_b_py }}
{{ process_cs101_references_py }}
```
The middle command is a convenience feature: It allows us to specify a special citation command `\nref{..}` which always compiles to `\cite[\ref{...}]{herlau}`. This is useful if e.g. `herlau` is the bibtex key for your lecture notes. The result is as follows:
And this then produce the output:
```python
{{ citations_py }}
{{ cs101_students.references_py }}
```
Note this example uses the low-level api. Normally you would just pass the bibtex and aux-file to the main censor-file command.
## Additional features:
- You can name tags using `#!s=bar` to get a `foo_bar.py` snippet. This is useful when you need to cut multiple sessions. This also works for the other tags.
Since the aux/bibtex databases are just dictionaries it is easy to join them together from different sources.
I have written reference tags to lecture and exercise material as well as my notes and it makes reference management very easy.
......@@ -31,6 +31,10 @@ if __name__ == "__main__":
def dir_import(dir):
dat = {}
for f in glob.glob(dir+"/*.*"):
ex = f.split(".")[-1]
if ex not in ['py', 'txt', 'shell', 'tex', 'txt']:
continue
name = os.path.basename(f).replace(".", '_')
with open(f, 'r') as f:
s = [s for s in f.read().rstrip().splitlines() if s.strip() != '']
......@@ -39,12 +43,11 @@ if __name__ == "__main__":
for d in dirs:
data[d] = dir_import("../examples/"+d)
# for f in glob.glob("../examples/"+d+"/*.*"):
# name = os.path.basename(f).replace(".",'_')
# with open(f, 'r') as f:
# data[d][name] = f.read()
data = {**data, **dir_import('../examples')}
data = {**data, **dir_import('../examples/latex')}
data['resources'] = 'https://gitlab.compute.dtu.dk/tuhe/snipper/-/raw/main'
convert.pdf2png(np + "/index.pdf", "./index.png", scale_to=800)
......
......@@ -41,9 +41,9 @@ def fix_bibtex(lines, bibtex):
s = s[:i] + rtxt + s[j+1:]
i = i + len(rtxt)
if len(all_refs) > 0:
if not s.startswith(COMMENT):
s = f"{COMMENT}\n{COMMENT}\n" + s
if len(all_refs) > 0:
i = s.find(COMMENT, s.find(COMMENT)+1)
all_refs = [" " + r.strip() for r in all_refs]
s = s[:i] + "References:\n" + "\n".join(all_refs) +"\n"+ s[i:]
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment