tex.go (2292B)
1 package scan 2 3 import ( 4 "os" 5 "path/filepath" 6 "regexp" 7 "slices" 8 "strings" 9 ) 10 11 var ( 12 citeRe = regexp.MustCompile(`\\(?:no)?cite[a-zA-Z]*\*?(?:\[[^\]]*\]){0,2}\{([^}]*)\}`) 13 bibRe = regexp.MustCompile(`\\(?:bibliography|addbibresource)\{([^}]*)\}`) 14 inputRe = regexp.MustCompile(`\\(?:input|include|subfile)\{([^}]*)\}`) 15 todoRe = regexp.MustCompile(`\\todo(?:\[[^\]]*\])?\{([^}]*)\}|(?:TODO|FIXME|XXX)[:\s]+(.*)`) 16 ) 17 18 // TeX holds facts extracted from a LaTeX main file and its \input files. 19 type TeX struct { 20 Cites []string 21 Bibs []string 22 Todos []Todo 23 } 24 25 type Todo struct { 26 File string 27 Line int 28 Text string 29 } 30 31 // ParseTeX reads main (relative to src) and the files it inputs, one level 32 // of recursion per file, ignoring commented-out lines for cites and bibs. 33 func ParseTeX(src, main string) TeX { 34 var t TeX 35 seen := map[string]bool{} 36 var walk func(rel string, depth int) 37 walk = func(rel string, depth int) { 38 if seen[rel] || depth > 3 { 39 return 40 } 41 seen[rel] = true 42 b, err := os.ReadFile(filepath.Join(src, rel)) 43 if err != nil { 44 return 45 } 46 for i, line := range strings.Split(string(b), "\n") { 47 if m := todoRe.FindStringSubmatch(line); m != nil { 48 text := strings.TrimSpace(m[1] + m[2]) 49 if text != "" { 50 t.Todos = append(t.Todos, Todo{rel, i + 1, text}) 51 } 52 } 53 code := stripComment(line) 54 for _, m := range citeRe.FindAllStringSubmatch(code, -1) { 55 for _, k := range strings.Split(m[1], ",") { 56 if k = strings.TrimSpace(k); k != "" && k != "*" && !slices.Contains(t.Cites, k) { 57 t.Cites = append(t.Cites, k) 58 } 59 } 60 } 61 for _, m := range bibRe.FindAllStringSubmatch(code, -1) { 62 for _, k := range strings.Split(m[1], ",") { 63 k = strings.TrimSpace(k) 64 if k != "" && !strings.HasSuffix(k, ".bib") { 65 k += ".bib" 66 } 67 if k != "" && !slices.Contains(t.Bibs, k) { 68 t.Bibs = append(t.Bibs, k) 69 } 70 } 71 } 72 for _, m := range inputRe.FindAllStringSubmatch(code, -1) { 73 f := strings.TrimSpace(m[1]) 74 if filepath.Ext(f) == "" { 75 f += ".tex" 76 } 77 walk(f, depth+1) 78 } 79 } 80 } 81 walk(main, 0) 82 return t 83 } 84 85 func stripComment(line string) string { 86 for i := 0; i < len(line); i++ { 87 if line[i] == '\\' { 88 i++ 89 } else if line[i] == '%' { 90 return line[:i] 91 } 92 } 93 return line 94 }