建议不要用「让代码就像文字一样,从当前页继续,但如果当前页空间不足时自动换页」这种表述,而是用「breakable listings」
太困了,只给例子,个人觉得tcb是比较好的实践了...
你要综合看tcolorbox和listings的文档
几个关键的option为:
listing remove caption=falsecaption={Rust is Genshin Impact of coding}captionpos=t(这是默认值,可调)label={mycode}
\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{lipsum}
\usepackage[most]{tcolorbox}
\usepackage{hyperref}
\tcbuselibrary{listings}
\newtcbinputlisting{\mylisting}[2][]{%
enhanced jigsaw,sharp corners,title={example~code},empty,left=1cm,breakable,%
listing file={#2},listing only,listing remove caption=false,
listing options={numbers=left,breaklines,basicstyle=\ttfamily,caption={Rust is Genshin Impact of coding},captionpos=t,label={mycode}},#1%
}
\begin{filecontents*}[overwrite]{temp.rs}
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::Duration;
struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Message>,
}
impl ThreadPool {
fn new(size: usize) -> Result<ThreadPool, PoolCreationError> {
if size == 0 {
return Err(PoolCreationError::InvalidSize);
}
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
Ok(ThreadPool { workers, sender })
}
fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(Message::NewJob(job)).unwrap();
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv().unwrap();
match message {
Message::NewJob(job) => {
job();
}
Message::Terminate => break,
}
});
Worker {
id,
thread: Some(thread),
}
}
}
enum Message {
NewJob(Box<dyn FnOnce() + Send + 'static>),
Terminate,
}
#[derive(Debug)]
enum PoolCreationError {
InvalidSize,
}
fn is_prime(n: u64) -> bool {
if n <= 1 {
return false;
}
for i in 2..=(n as f64).sqrt() as u64 {
if n % i == 0 {
return false;
}
}
true
}
fn main() {
}
\end{filecontents*}
\begin{document}
I want to ref code \ref{mycode} here.
\lipsum[1]
\mylisting{temp.rs}
\lipsum[2]
\end{document}



















问 如何允许代码跨页 (breakable; across page) 并且让 caption 位于代码上方?