Skip to main content

cellix_doc/
synctex.rs

1//! SyncTeX: how a PDF's pages map back to the source lines that made them, and forward again.
2//! The engine writes the map when asked, and this reads it.
3
4use std::collections::HashMap;
5use std::io::Read;
6use std::path::{Path, PathBuf};
7
8use flate2::read::GzDecoder;
9
10/// SyncTeX counts in scaled points. A PDF point is this many.
11const SCALED_POINTS: f32 = 65781.76;
12
13#[derive(Clone, Copy, Debug, PartialEq)]
14struct Mark {
15    file: u32,
16    line: usize,
17    /// In PDF points, from the page's top left.
18    x: f32,
19    y: f32,
20}
21
22/// The marks of one PDF.
23#[derive(Clone, Debug, Default, PartialEq)]
24pub struct Map {
25    files: HashMap<u32, PathBuf>,
26    pages: Vec<Vec<Mark>>,
27}
28
29/// Reads `tag,line:x,y` after a record's letter.
30fn mark(record: &str) -> Option<Mark> {
31    let (place, position) = record.split_once(':')?;
32    let (file, line) = place.split_once(',')?;
33    let position = position.split(':').next()?;
34    let (x, y) = position.split_once(',')?;
35    Some(Mark {
36        file: file.parse().ok()?,
37        line: line.parse().ok()?,
38        x: x.parse::<f32>().ok()? / SCALED_POINTS,
39        y: y.parse::<f32>().ok()? / SCALED_POINTS,
40    })
41}
42
43/// A path as one place on disk: canonical when it exists, and otherwise without the `.` and
44/// `..` steps an engine writes, as in `/w/./ch1/intro.tex`.
45fn same_place(path: &Path) -> PathBuf {
46    if let Ok(real) = std::fs::canonicalize(path) {
47        return real;
48    }
49    let mut out = PathBuf::new();
50    for part in path.components() {
51        match part {
52            std::path::Component::CurDir => {}
53            std::path::Component::ParentDir => {
54                out.pop();
55            }
56            other => out.push(other),
57        }
58    }
59    out
60}
61
62impl Map {
63    /// Reads the map beside a PDF, if the engine wrote one.
64    pub fn beside(pdf: &Path) -> Option<Self> {
65        let bytes = std::fs::read(pdf.with_extension("synctex.gz")).ok()?;
66        let mut text = String::new();
67        GzDecoder::new(&bytes[..]).read_to_string(&mut text).ok()?;
68        Some(Self::parse(&text, pdf.parent().unwrap_or(Path::new(""))))
69    }
70
71    pub fn parse(text: &str, folder: &Path) -> Self {
72        let mut map = Self::default();
73        let mut page: Option<usize> = None;
74        for line in text.lines() {
75            if let Some(input) = line.strip_prefix("Input:") {
76                if let Some((tag, path)) = input.split_once(':')
77                    && let Ok(tag) = tag.parse()
78                    && !path.is_empty()
79                {
80                    map.files.insert(tag, folder.join(path));
81                }
82                continue;
83            }
84            let mut chars = line.chars();
85            match chars.next() {
86                Some('{') => {
87                    page = chars.as_str().parse::<usize>().ok().map(|p| p - 1);
88                    if let Some(index) = page
89                        && map.pages.len() <= index
90                    {
91                        map.pages.resize(index + 1, Vec::new());
92                    }
93                }
94                Some('}') => page = None,
95                // Text and its neighbours, not the boxes that hold a whole page.
96                Some('h' | 'x' | 'k' | 'g' | '$') => {
97                    if let (Some(index), Some(found)) = (page, mark(chars.as_str())) {
98                        map.pages[index].push(found);
99                    }
100                }
101                _ => {}
102            }
103        }
104        map
105    }
106
107    /// The source line nearest a place on a page, with points from its top left.
108    pub fn to_source(&self, page: usize, x: f32, y: f32) -> Option<(PathBuf, usize)> {
109        let near = |m: &&Mark| (m.y - y).abs() * 4.0 + (m.x - x).abs();
110        let found = self
111            .pages
112            .get(page)?
113            .iter()
114            .min_by(|a, b| near(a).total_cmp(&near(b)))?;
115        Some((self.files.get(&found.file)?.clone(), found.line))
116    }
117
118    /// Where a source line landed, as a page and points from its top.
119    pub fn to_pdf(&self, file: &Path, line: usize) -> Option<(usize, f32)> {
120        // By the whole path, since chapters often share a name: `ch1/intro.tex`, `ch2/intro.tex`.
121        let wanted = same_place(file);
122        let tag = *self
123            .files
124            .iter()
125            .find(|(_, path)| same_place(path) == wanted)?
126            .0;
127        let mut best: Option<(usize, usize, f32)> = None;
128        for (page, marks) in self.pages.iter().enumerate() {
129            for found in marks.iter().filter(|m| m.file == tag) {
130                let distance = found.line.abs_diff(line);
131                if best.is_none_or(|b| distance < b.0) {
132                    best = Some((distance, page, found.y));
133                }
134            }
135        }
136        best.map(|(_, page, y)| (page, y))
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    const SAMPLE: &str = "SyncTeX Version:1
145Input:1:/w/main.tex
146Input:2:
147Input:3:/w/two.tex
148Content:
149!372
150{1
151[1,38:4736287,46220575:26673152,41484288,0
152h1,6:8799519,8865055:0,0,0
153k1,10:12701574,11617567:3902055
154x1,12:9000000,20000000
155}1
156!100
157{2
158h3,4:9000000,9000000:0,0,0
159}2
160";
161
162    #[test]
163    fn a_click_finds_its_line() {
164        let map = Map::parse(SAMPLE, Path::new("/w"));
165        let (x, y) = (9000000.0 / SCALED_POINTS, 20000000.0 / SCALED_POINTS);
166        let (file, line) = map.to_source(0, x, y).unwrap();
167        assert_eq!(file, Path::new("/w/main.tex"));
168        assert_eq!(line, 12);
169        assert_eq!(
170            map.to_source(1, 0.0, 0.0).unwrap().0,
171            Path::new("/w/two.tex")
172        );
173    }
174
175    #[test]
176    fn a_line_finds_its_page() {
177        let map = Map::parse(SAMPLE, Path::new("/w"));
178        let (page, y) = map.to_pdf(Path::new("/w/two.tex"), 5).unwrap();
179        assert_eq!(page, 1);
180        assert!((y - 9000000.0 / SCALED_POINTS).abs() < 0.01);
181        assert_eq!(map.to_pdf(Path::new("/w/main.tex"), 11).unwrap().0, 0);
182    }
183
184    #[test]
185    fn chapters_with_one_name_find_their_own_pages() {
186        let dir = tempfile::tempdir().unwrap();
187        for chapter in ["ch1", "ch2"] {
188            std::fs::create_dir(dir.path().join(chapter)).unwrap();
189            std::fs::write(dir.path().join(chapter).join("intro.tex"), "x\n").unwrap();
190        }
191        let w = dir.path().display();
192        // pdflatex writes the paths as it opened them, `./` and all.
193        let text = format!(
194            "SyncTeX Version:1\nInput:1:{w}/./ch1/intro.tex\nInput:2:{w}/./ch2/intro.tex\nContent:\n{{1\nh1,3:9000000,9000000:0,0,0\n}}1\n{{2\nh2,3:9000000,20000000:0,0,0\n}}2\n"
195        );
196        let map = Map::parse(&text, dir.path());
197        let page = |chapter: &str| map.to_pdf(&dir.path().join(chapter).join("intro.tex"), 3);
198        assert_eq!(page("ch1").unwrap().0, 0);
199        assert_eq!(page("ch2").unwrap().0, 1);
200        assert_eq!(map.to_pdf(&dir.path().join("intro.tex"), 3), None);
201    }
202}