Files
shellscripts/export_tex.sh
T
2026-11-21 11:25:27 +07:00

275 lines
11 KiB
Bash
Executable File

#!/usr/bin/env bash
# export_tex.sh — export a LaTeX project as a zip, the way Overleaf's
# "Download Source" does: project-relative paths at the zip root (no wrapping
# folder), named <ProjectName>.zip with every non-letter/digit replaced by "_".
#
# Usage: ./export_tex.sh [options] [main.tex] [output]
# main.tex defaults to the first .tex in the current dir
# output *.zip → write that zip; anything else → plain directory
# (default: ./<ProjectName>.zip)
# Options:
# -a, --all Overleaf-style: take every file in the project tree except
# build artifacts, instead of tracing what main.tex uses
# -n, --name N project name used for the zip (default: source dir name)
# -h, --help show this help
set -euo pipefail
usage() { sed -n '2,/^$/{s/^# \{0,1\}//p}' "$0"; exit "${1:-0}"; }
# ── arguments ────────────────────────────────────────────────────────────────
MODE=trace
PROJECT_NAME=""
POS=()
while (($#)); do
case "$1" in
-a|--all) MODE=all ;;
-n|--name) PROJECT_NAME="${2:?--name needs a value}"; shift ;;
-h|--help) usage ;;
--) shift; POS+=("$@"); break ;;
-*) echo "Unknown option: $1" >&2; usage 1 ;;
*) POS+=("$1") ;;
esac
shift
done
TEX_FILE="${POS[0]:-}"
if [[ -z "$TEX_FILE" ]]; then
TEX_FILE=$(find . -maxdepth 1 -name '*.tex' -print -quit)
[[ -n "$TEX_FILE" ]] || { echo "No .tex file found." >&2; exit 1; }
fi
[[ -f "$TEX_FILE" ]] || { echo "File not found: $TEX_FILE" >&2; exit 1; }
TEX_FILE="$(realpath "$TEX_FILE")"
SRC_DIR="$(dirname "$TEX_FILE")"
TEX_BASE="$(basename "$TEX_FILE")"
JOB="${TEX_BASE%.tex}"
# Overleaf: project.name.replace(/[^\p{L}\p{Nd}]/gu, '_')
PROJECT_NAME="${PROJECT_NAME:-$(basename "$SRC_DIR")}"
SAFE_NAME="$(perl -CSA -e 'my $s = shift; $s =~ s/[^\p{L}\p{Nd}]/_/g; print $s' "$PROJECT_NAME")"
OUTPUT="${POS[1]:-$SAFE_NAME.zip}"
if [[ "$OUTPUT" == *.zip ]]; then
ZIP_OUT="$(realpath -m "$OUTPUT")"
EXPORT_DIR="$(mktemp -d)"
trap 'rm -rf "$EXPORT_DIR"' EXIT
else
ZIP_OUT=""
EXPORT_DIR="$(realpath -m "$OUTPUT")"
mkdir -p "$EXPORT_DIR"
fi
# latexmk output/aux dirs (from latexmkrc), used for .bbl lookup and exclusion
BUILD_DIRS=()
while IFS= read -r d; do
[[ -n "$d" ]] && BUILD_DIRS+=("${d%/}")
done < <(grep -hoP '\$(out|aux)_dir\s*=\s*["'\'']\K[^"'\'']+' \
"$SRC_DIR/latexmkrc" "$SRC_DIR/.latexmkrc" 2>/dev/null || true)
# find(1) arguments that skip VCS/hidden dirs, build dirs and our own output,
# so earlier exports are never picked up as sources
PRUNE=( \( -type d -path "$SRC_DIR/.*" -o -path "$EXPORT_DIR" )
[[ -n "$ZIP_OUT" ]] && PRUNE+=( -o -path "$ZIP_OUT" )
for d in "${BUILD_DIRS[@]}"; do PRUNE+=( -o -path "$SRC_DIR/$d" ); done
PRUNE+=( \) -prune -o )
# ── helpers ──────────────────────────────────────────────────────────────────
copy_rel() {
# Copy a file to EXPORT_DIR preserving its path relative to SRC_DIR.
local src="$1"
[[ -f "$src" ]] || { echo " [missing] $src"; return 0; }
if [[ "$src" != "$SRC_DIR"/* ]]; then
echo " [outside] $src (not under $SRC_DIR, skipped)"; return 0
fi
local rel="${src#"$SRC_DIR"/}"
local dest="$EXPORT_DIR/$rel"
[[ -e "$dest" ]] && return 0
mkdir -p "$(dirname "$dest")"
cp "$src" "$dest"
echo " $rel"
}
find_recursive() {
# Find file by basename+ext under SRC_DIR; prefer shallower paths.
local base="$1"; shift
local found="" ext
for ext in "$@"; do
found=$(find "$SRC_DIR" "${PRUNE[@]}" -type f -name "${base}${ext}" -print \
| awk '{ print gsub(/\//,"/")" "$0 }' | sort -n | head -1 \
| cut -d' ' -f2-)
[[ -n "$found" ]] && break
done
echo "$found"
}
strip_comments() {
# Drop everything after an unescaped % on each line
sed -E 's/(^|[^\\])%.*/\1/' "$1" | tr -d '\r'
}
args_of() {
# Print the mandatory {arg} of each \cmd (optional [..] allowed), one per
# line, splitting comma lists. $1 = regex alternation of command names.
grep -oP "\\\\($1)\\*?(\\[[^\\]]*\\])?\\{[^}]+\\}" \
| grep -oP '\{\K[^}]+' | tr ',' '\n' | sed -E 's/^\s+|\s+$//g' \
| grep -v '^$' || true
}
# ── mode "all": whole project tree minus build artifacts ─────────────────────
BUILD_EXT='aux|log|out|toc|lof|lot|loa|fls|fdb_latexmk|synctex\.gz|synctex|bcf|run\.xml|blg|bbl|nav|snm|vrb|idx|ilg|ind|glo|gls|glg|ist|xdv|dvi|thm|spl|brf'
if [[ "$MODE" == all ]]; then
echo "Collecting project tree from $SRC_DIR"
while IFS= read -r -d '' f; do
name="${f##*/}"
[[ "$name" =~ \.($BUILD_EXT)$ ]] && continue
[[ "$name" =~ ~$ || "$name" == *.swp ]] && continue
# earlier exports lying around in the project root
[[ "$f" == "$SRC_DIR/$name" && "$name" == *.zip ]] && continue
# compiled PDF of any .tex in the tree
[[ "$name" == *.pdf && -f "${f%.pdf}.tex" ]] && continue
copy_rel "$f"
done < <(find "$SRC_DIR" "${PRUNE[@]}" -type f -print0)
fi
# ── mode "trace": follow what main.tex actually uses ─────────────────────────
IMAGE_EXTS=(".pdf" ".png" ".jpg" ".jpeg" ".eps" ".svg" ".PNG" ".JPG" ".JPEG" ".PDF")
GRAPHICS_DIRS=("") # \graphicspath dirs, tried after the path as written
declare -A VISITED_TEX
copy_image() {
local img="${1#./}"
[[ "$img" == *"#"* ]] && return 0 # macro parameter such as #1
local dir ext
for dir in "${GRAPHICS_DIRS[@]}"; do
if [[ "$img" == *.* && -f "$SRC_DIR/$dir$img" ]]; then
copy_rel "$SRC_DIR/$dir$img"; return 0
fi
for ext in "${IMAGE_EXTS[@]}"; do
if [[ -f "$SRC_DIR/$dir$img$ext" ]]; then
copy_rel "$SRC_DIR/$dir$img$ext"; return 0
fi
done
done
# Fallback: recursive search by basename only
local f
f=$(find_recursive "${img##*/}" "" "${IMAGE_EXTS[@]}")
if [[ -n "$f" ]]; then copy_rel "$f"; else echo " [missing] $img"; fi
}
process_tex() {
local tex_path
tex_path="$(realpath "$1")"
[[ -n "${VISITED_TEX[$tex_path]:-}" ]] && return 0
VISITED_TEX["$tex_path"]=1
copy_rel "$tex_path"
local body
body="$(strip_comments "$tex_path")"
# \input, \include, \subfile, \InputIfFileExists — relative to the main
# file's directory, as LaTeX (and Overleaf) resolve them
local inc try
while IFS= read -r inc; do
for try in "$SRC_DIR/$inc.tex" "$SRC_DIR/$inc"; do
[[ -f "$try" ]] && { process_tex "$try"; continue 2; }
done
echo " [missing tex] $inc"
done < <(args_of 'input|include|subfile|InputIfFileExists' <<<"$body")
# \import{dir}{file} / \subimport{dir}{file}
while IFS=$'\t' read -r dir file; do
for try in "$SRC_DIR/$dir$file.tex" "$SRC_DIR/$dir$file"; do
[[ -f "$try" ]] && { process_tex "$try"; continue 2; }
done
echo " [missing tex] $dir$file"
done < <(grep -oP '\\(sub)?import\*?\{[^}]*\}\{[^}]+\}' <<<"$body" \
| sed -E 's/.*\{([^}]*)\}\{([^}]+)\}/\1\t\2/' || true)
# \graphicspath{{img/}{fig/}}
local d
while IFS= read -r d; do
[[ -n "$d" ]] && GRAPHICS_DIRS+=("${d%/}/")
done < <(grep -oP '\\graphicspath\{.*\}' <<<"$body" \
| grep -oP '(?<=\{)[^{}]+(?=\})' || true)
# One-argument macros that wrap \includegraphics{#1}
local macros="includegraphics|includesvg|includepdf" m
while IFS= read -r m; do
[[ -n "$m" ]] && macros+="|$m"
done < <(grep -oP '\\(re)?newcommand\{?\\\w+\}?\[1\]\{.*\\includegraphics(\[[^\]]*\])?\{#1\}' <<<"$body" \
| grep -oP '(?<=command)\{?\\\K\w+' || true)
local img
while IFS= read -r img; do
copy_image "$img"
done < <(grep -oP "\\\\($macros)\\*?(\\[[^\\]]*\\])?\\{[^}]+\\}" <<<"$body" \
| grep -oP '\{\K[^}]+' | sort -u || true)
}
if [[ "$MODE" == trace ]]; then
echo "Tracing $TEX_BASE"
process_tex "$TEX_FILE"
# Local packages/classes/styles: an Overleaf project carries these files,
# and classes load helpers (.clo/.cfg/.def) that can't be traced reliably
while IFS= read -r -d '' f; do
copy_rel "$f"
done < <(find "$SRC_DIR" -maxdepth 1 -type f \( -name '*.cls' -o -name '*.sty' \
-o -name '*.clo' -o -name '*.cfg' -o -name '*.def' -o -name '*.ldf' \
-o -name '*.bst' -o -name '*.bbx' -o -name '*.cbx' \) -print0)
SEARCH_FILES=("${!VISITED_TEX[@]}")
ALL_BODY="$(for f in "${SEARCH_FILES[@]}"; do strip_comments "$f"; done)"
# Document class / packages kept in subdirectories
while IFS= read -r p; do
f=$(find_recursive "$p" ".cls" ".sty")
[[ -n "$f" ]] && copy_rel "$f"
done < <(args_of 'documentclass|usepackage|RequirePackage|LoadClass' <<<"$ALL_BODY" | sort -u)
# Bibliography style (.bst) and biblatex style= / bibstyle= / citestyle=
while IFS= read -r s; do
f=$(find_recursive "$s" ".bst" ".bbx" ".cbx")
[[ -n "$f" ]] && copy_rel "$f"
done < <({ args_of 'bibliographystyle' <<<"$ALL_BODY"
grep -oP '\\usepackage\[[^\]]*\]\{biblatex\}' <<<"$ALL_BODY" \
| grep -oP '(bib|cite)?style\s*=\s*\{?\K[^},\]\s]+' || true; } | sort -u)
# Bibliography databases: \bibliography{a,b} and \addbibresource{x.bib}
while IFS= read -r bib; do
bib="${bib%.bib}"
if [[ -f "$SRC_DIR/$bib.bib" ]]; then
copy_rel "$SRC_DIR/$bib.bib"
else
f=$(find_recursive "${bib##*/}" ".bib")
if [[ -n "$f" ]]; then copy_rel "$f"; else echo " [missing] $bib.bib"; fi
fi
done < <(args_of 'bibliography|addbibresource|addglobalbib' <<<"$ALL_BODY" | sort -u)
fi
# ── pre-built .bbl ───────────────────────────────────────────────────────────
# Not part of an Overleaf source zip, but journals/arXiv want it. Look next to
# the .tex, then in latexmk's out/aux dirs; always export it beside the .tex.
for d in "" "${BUILD_DIRS[@]}"; do
BBL="$SRC_DIR/${d:+$d/}$JOB.bbl"
if [[ -f "$BBL" ]]; then
cp "$BBL" "$EXPORT_DIR/$JOB.bbl"
echo " $JOB.bbl (pre-built)"
break
fi
done
# ── package ──────────────────────────────────────────────────────────────────
echo ""
if [[ -n "$ZIP_OUT" ]]; then
rm -f "$ZIP_OUT"
mkdir -p "$(dirname "$ZIP_OUT")"
(cd "$EXPORT_DIR" && zip -qrXD "$ZIP_OUT" .)
echo "Done. $(zipinfo -1 "$ZIP_OUT" | wc -l) files → $ZIP_OUT"
else
echo "Done. Files exported to: $EXPORT_DIR/"
fi