1
0
Fork 0
mirror of https://github.com/lise-henry/crowbook synced 2024-04-20 00:53:48 +02:00

chore: fixes clippy

This commit is contained in:
Geobert Quach 2023-01-02 12:54:36 +00:00
parent cd1739382b
commit 40ca4e9771
22 changed files with 174 additions and 240 deletions

View File

@ -13,6 +13,7 @@ license = "LGPL-2.1+"
publish = true
build = "build.rs"
autobins = false
rust-version = "1.58"
exclude = [
"docs/*",

View File

@ -76,7 +76,7 @@ pub fn get_lang() -> Option<String> {
}
/// Gets the book options in a (key, value) list, or print an error
pub fn get_book_options<'a>(matches: &'a ArgMatches) -> Vec<(&'a str, &'a str)> {
pub fn get_book_options(matches: &ArgMatches) -> Vec<(&str, &str)> {
let mut output = vec![];
if let Some(iter) = matches.get_many::<String>("set") {
let v: Vec<_> = iter.collect();
@ -111,11 +111,11 @@ pub fn set_book_options(book: &mut Book, matches: &ArgMatches) -> String {
let options = get_book_options(matches);
for (key, value) in options {
let res = book.options.set(&key, &value);
let res = book.options.set(key, value);
if let Err(err) = res {
print_error_and_exit(&lformat!("Error in setting key {}: {}", key, err), false);
}
output.push_str(&format!("{}: {}\n", key, value));
output.push_str(&format!("{key}: {value}\n"));
}
output
}
@ -167,7 +167,7 @@ lang: en
f.write_all(lformat!("\n## List of chapters\n").as_bytes())
.unwrap();
for file in values {
f.write_all(format!("+ {}\n", file).as_bytes()).unwrap();
f.write_all(format!("+ {file}\n").as_bytes()).unwrap();
}
if let Some(s) = matches.get_one::<String>("BOOK") {
println!(

View File

@ -56,7 +56,7 @@ fn render_format(book: &mut Book, emoji: bool, matches: &ArgMatches, format: &st
};
if let Err(err) = result {
print_error(&format!("{}", err), emoji)
print_error(&format!("{err}"), emoji)
}
}
@ -107,7 +107,7 @@ pub fn try_main() -> Result<()> {
let result = book.get_template(template.as_ref());
match result {
Ok(s) => {
println!("{}", s);
println!("{s}");
exit(0);
}
Err(_) => print_error_and_exit(
@ -211,7 +211,7 @@ pub fn try_main() -> Result<()> {
match res {
Ok(..) => {}
Err(err) => {
book.set_error(&format!("{}", err));
book.set_error(&format!("{err}"));
return Err(err);
}
}
@ -221,7 +221,7 @@ pub fn try_main() -> Result<()> {
if matches.get_flag("stats") {
let stats = Stats::new(&book, matches.get_flag("verbose"));
println!("{}", stats);
println!("{stats}");
exit(0);
}
@ -271,6 +271,6 @@ pub fn try_main() -> Result<()> {
pub fn real_main() {
if let Err(err) = try_main() {
print_error_and_exit(&format!("{}", err), false);
print_error_and_exit(&format!("{err}"), false);
}
}

View File

@ -515,7 +515,7 @@ impl Book {
/// ```
pub fn read_config<R: Read>(&mut self, mut source: R) -> Result<&mut Book> {
fn get_filename<'a>(source: &Source, s: &'a str) -> Result<&'a str> {
let words: Vec<&str> = (&s[1..]).split_whitespace().collect();
let words: Vec<&str> = (s[1..]).split_whitespace().collect();
if words.len() > 1 {
return Err(Error::config_parser(
source,
@ -551,17 +551,14 @@ impl Book {
let mut line_number = 0;
let mut is_next_line_ok: bool;
loop {
if let Some(next_line) = lines.peek() {
if next_line.starts_with(|c| match c {
'-' | '+' | '!' | '@' => true,
_ => c.is_digit(10),
}) {
break;
}
} else {
while let Some(next_line) = lines.peek() {
if next_line.starts_with(|c| match c {
'-' | '+' | '!' | '@' => true,
_ => c.is_ascii_digit(),
}) {
break;
}
line = lines.next().unwrap();
line_number += 1;
self.source.set_line(line_number);
@ -578,15 +575,14 @@ impl Book {
if let Some(next_line) = lines.peek() {
let doc = YamlLoader::load_from_str(next_line);
if doc.is_err() {
is_next_line_ok = false;
} else {
let doc = doc.unwrap();
if let Ok(doc) = doc {
if !doc.is_empty() && doc[0].as_hash().is_some() {
is_next_line_ok = true;
} else {
is_next_line_ok = false;
}
} else {
is_next_line_ok = false;
}
} else {
break;
@ -659,7 +655,7 @@ impl Book {
// hidden chapter
let file = get_filename(&self.source, line)?;
self.add_chapter(Number::Hidden, file, false)?;
} else if line.starts_with(|c: char| c.is_digit(10)) {
} else if line.starts_with(|c: char| c.is_ascii_digit()) {
// chapter with specific number
let parts: Vec<_> = line
.splitn(2, |c: char| c == '.' || c == ':' || c == '+')
@ -681,9 +677,8 @@ impl Book {
)
})?;
self.add_chapter(Number::Specified(number), file, true)?;
} else if line.starts_with('@') {
} else if let Some(subline) = line.strip_prefix('@') {
/* Part */
let subline = &line[1..];
if subline.starts_with(|c: char| c.is_whitespace()) {
let subline = subline.trim();
let ast = Parser::from(self).parse_inline(subline)?;
@ -698,7 +693,7 @@ impl Book {
/* Numbered part */
let file = get_filename(&self.source, subline)?;
self.add_chapter(Number::DefaultPart, file, true)?;
} else if subline.starts_with(|c: char| c.is_digit(10)) {
} else if subline.starts_with(|c: char| c.is_ascii_digit()) {
/* Specified part*/
let parts: Vec<_> = subline
.splitn(2, |c: char| c == '.' || c == ':' || c == '+')
@ -838,7 +833,7 @@ impl Book {
if !self.is_proofread() && fmt.contains("proofread") {
return false;
}
self.options.get_path(&format!("output.{}", fmt)).is_ok()
self.options.get_path(&format!("output.{fmt}")).is_ok()
})
.map(|s| s.to_string())
.collect();
@ -880,7 +875,7 @@ impl Book {
self.bar_finish(
Crowbar::Spinner(bar),
CrowbarState::Error,
&format!("{}", err),
&format!("{err}"),
);
error!(
"{}",
@ -906,7 +901,7 @@ impl Book {
);
let path = path.into();
match self.formats.get(format) {
Some(&(ref description, ref renderer)) => {
Some((description, renderer)) => {
let path = if path.ends_with("auto") {
let file = if let Some(s) = self
.source
@ -972,7 +967,7 @@ impl Book {
);
let bar = self.add_spinner_to_multibar(format);
match self.formats.get(format) {
Some(&(ref description, ref renderer)) => match renderer.render(self, f) {
Some((description, renderer)) => match renderer.render(self, f) {
Ok(_) => {
self.bar_finish(
Crowbar::Spinner(bar),
@ -1219,16 +1214,13 @@ impl Book {
{
let last = self.chapters.last_mut().unwrap();
for token in &mut last.content {
match *token {
Token::Header(ref mut n, _) => {
let new = *n + level;
if !(0..=6).contains(&new) {
return Err(Error::parser(Source::new(file),
if let Token::Header(ref mut n, _) = *token {
let new = *n + level;
if !(0..=6).contains(&new) {
return Err(Error::parser(Source::new(file),
lformat!("this subchapter contains a heading that, when adjusted, is not in the right range ({} instead of [0-6])", new)));
}
*n = new;
}
_ => {}
*n = new;
}
}
}
@ -1335,17 +1327,13 @@ impl Book {
_ => {
return Err(Error::config_parser(
&self.source,
lformat!("invalid template '{template}'", template = template),
lformat!("invalid template '{template}'"),
))
}
};
if let Ok(ref s) = option {
let mut f = File::open(s).map_err(|_| {
Error::file_not_found(
&self.source,
format!("template '{template}'", template = template),
s.to_owned(),
)
Error::file_not_found(&self.source, format!("template '{template}'"), s.to_owned())
})?;
let mut res = String::new();
f.read_to_string(&mut res).map_err(|_| {
@ -1396,7 +1384,7 @@ impl Book {
}
format!("{:X}", Roman::from(n as i16))
} else {
format!("{}", n)
format!("{n}")
};
Ok(number)
}
@ -1419,17 +1407,17 @@ impl Book {
};
let mut data = self.get_metadata(&mut f)?;
if !title.is_empty() {
data = data.insert_bool(format!("has_{}_title", header_type), true);
data = data.insert_bool(format!("has_{header_type}_title"), true);
}
let number = self.get_header_number(header, n)?;
let header_name = self
.options
.get_str(&format!("rendering.{}", header_type))
.get_str(&format!("rendering.{header_type}"))
.map(|s| s.to_owned())
.unwrap_or_else(|_| lang::get_str(self.options.get_str("lang").unwrap(), header_type));
data = data
.insert_str(format!("{}_title", header_type), title.clone())
.insert_str(format!("{header_type}_title"), title.clone())
.insert_str(header_type, header_name.clone())
.insert_str("number", number.clone());
let data = data.build();
@ -1445,10 +1433,10 @@ impl Book {
} else {
let template = compile_str(
self.options
.get_str(&format!("rendering.{}.template", header_type))
.get_str(&format!("rendering.{header_type}.template"))
.unwrap(),
&self.source,
&format!("rendering.{}.template", header_type),
&format!("rendering.{header_type}.template"),
)?;
template.render_data(&mut res, &data)?;
}
@ -1518,12 +1506,12 @@ impl Book {
match content {
Ok(content) => {
if !content.is_empty() {
mapbuilder = mapbuilder.insert_str(format!("{}_raw", key), raw);
mapbuilder = mapbuilder.insert_str(format!("{key}_raw"), raw);
mapbuilder = mapbuilder.insert_str(key.clone(), content);
mapbuilder = mapbuilder.insert_bool(format!("has_{}", key), true);
mapbuilder = mapbuilder.insert_bool(format!("has_{key}"), true);
} else {
mapbuilder = mapbuilder.insert_bool(format!("has_{}", key), false);
mapbuilder = mapbuilder.insert_bool(format!("has_{key}"), false);
}
}
Err(err) => {
@ -1539,7 +1527,7 @@ impl Book {
}
}
} else {
mapbuilder = mapbuilder.insert_bool(format!("has_{}", key), false);
mapbuilder = mapbuilder.insert_bool(format!("has_{key}"), false);
}
}
@ -1567,7 +1555,7 @@ impl Book {
Ok(docs) => {
// Use this yaml block to set options only if 1) it is valid
// 2) the option is activated
if docs.len() >= 1 && docs[0].as_hash().is_some() {
if !docs.is_empty() && docs[0].as_hash().is_some() {
let hash = docs[0].as_hash().unwrap();
for (key, value) in hash {
match self

View File

@ -70,7 +70,7 @@ impl Book {
pub fn private_add_progress_bar(&mut self, emoji: bool) {
self.bars.emoji = emoji;
let multibar = Arc::new(MultiProgress::new());
self.bars.multibar = Some(multibar.clone());
self.bars.multibar = Some(multibar);
let b = self
.bars
.multibar
@ -154,7 +154,7 @@ impl Book {
let bar = multibar.add(ProgressBar::new_spinner());
bar.enable_steady_tick(Duration::from_millis(200));
bar.set_message(lformat!("waiting..."));
bar.set_prefix(format!("{}:", key));
bar.set_prefix(format!("{key}:"));
let i = self.bars.spinners.len();
self.bars.spinners.push(bar);
self.bar_set_style(Crowbar::Spinner(i), CrowbarState::Running);
@ -249,22 +249,18 @@ impl Book {
.progress_chars("##-");
}
bar => {
style = style.tick_chars(&format!("{}{}", tick_chars, end_tick));
style = style.tick_chars(&format!("{tick_chars}{end_tick}"));
match bar {
Crowbar::Spinner(_) => {
style = style
.template(&format!(
"{{spinner:.bold.{color}}} {{prefix}} {{wide_msg}}",
color = color
"{{spinner:.bold.{color}}} {{prefix}} {{wide_msg}}"
))
.expect("Error in spinner progress bar style");
}
_ => {
style = style
.template(&format!(
"{{spinner:.bold.{color}}} {{prefix}}{{wide_msg}}",
color = color
))
.template(&format!("{{spinner:.bold.{color}}} {{prefix}}{{wide_msg}}"))
.expect("Error in progress bar style");
}
};

View File

@ -521,7 +521,7 @@ impl BookOptions {
if &key == "output" {
for format in &inner {
self.set_yaml(
Yaml::String(format!("output.{}", format)),
Yaml::String(format!("output.{format}")),
Yaml::String(String::from("auto")),
)
.map_err(|_| {
@ -998,7 +998,7 @@ impl BookOptions {
let mut previous_is_comment = true;
for (comment, key, o_type, default) in Self::options_to_vec() {
// Don't display deprecated options if md is not set
if !md && comment.trim() == &lformat!("Deprecated options") {
if !md && comment.trim() == lformat!("Deprecated options") {
return out;
}
if key.is_none() {
@ -1060,6 +1060,7 @@ impl BookOptions {
}
/// OPTIONS to a vec of tuples (comment, key, type, default value)
#[allow(clippy::type_complexity)]
fn options_to_vec() -> Vec<(
&'static str,
Option<&'static str>,
@ -1072,8 +1073,8 @@ impl BookOptions {
if line.is_empty() {
continue;
}
if line.starts_with('#') {
out.push((&line[1..], None, None, None));
if let Some(stripped) = line.strip_prefix('#') {
out.push((stripped, None, None, None));
continue;
}
let v: Vec<_> = line.split(" #").collect();

View File

@ -533,9 +533,9 @@ impl<'a> EpubRenderer<'a> {
)
})?;
let mut new_content = if initial.is_alphanumeric() {
format!("<span class = \"initial\">{}</span>", initial)
format!("<span class = \"initial\">{initial}</span>")
} else {
format!("{}", initial)
format!("{initial}")
};
for c in chars {
new_content.push(c);
@ -569,12 +569,9 @@ impl<'a> EpubRenderer<'a> {
== 3;
Ok(format!(
"<a {} href = \"#note-dest-{}\"><sup id = \
\"note-source-{}\">[{}]</sup></a>",
"<a {} href = \"#note-dest-{reference}\"><sup id = \
\"note-source-{reference}\">[{reference}]</sup></a>",
if epub3 { "epub:type = \"noteref\"" } else { "" },
reference,
reference,
reference
))
}
Token::FootnoteDefinition(ref reference, ref vec) => {
@ -588,17 +585,15 @@ impl<'a> EpubRenderer<'a> {
let html: &mut HtmlRenderer = this.as_mut();
let note_number = format!(
"<p class = \"note-number\">
<a href = \"#note-source-{}\">[{}]</a>
<a href = \"#note-source-{reference}\">[{reference}]</a>
</p>\n",
reference, reference
);
let inner = if epub3 {
format!(
"<aside epub:type = \"footnote\" id = \"note-dest-{}\">{}</aside>",
reference, inner_content
"<aside epub:type = \"footnote\" id = \"note-dest-{reference}\">{inner_content}</aside>"
)
} else {
format!("<a id = \"note-dest-{}\" />{}", reference, inner_content)
format!("<a id = \"note-dest-{reference}\" />{inner_content}")
};
html.add_footnote(note_number, inner);
@ -611,7 +606,7 @@ impl<'a> EpubRenderer<'a> {
/// Generate a file name given an int
fn filenamer(i: usize) -> String {
format!("chapter_{:03}.xhtml", i)
format!("chapter_{i:03}.xhtml")
}
derive_html! {EpubRenderer<'a>, EpubRenderer::static_render_token}
@ -620,7 +615,7 @@ pub struct Epub {}
impl BookRenderer for Epub {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.epub", book_name))
Ok(format!("{book_name}.epub"))
}
fn render(&self, book: &Book, to: &mut dyn Write) -> Result<()> {

View File

@ -70,9 +70,9 @@ impl Source {
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(ref file) = self.file {
write!(f, "{}", file)?;
write!(f, "{file}")?;
if let Some(line) = self.line {
write!(f, ":{}", line)?;
write!(f, ":{line}")?;
}
} else {
write!(f, "<UNKNOWN FILE>")?;
@ -268,15 +268,15 @@ impl error::Error for Error {
fn description(&self) -> &str {
match self.inner {
Inner::Default(ref s)
| Inner::Parser(ref s)
| Inner::Zipper(ref s)
| Inner::BookOption(ref s)
| Inner::ConfigParser(ref s)
| Inner::InvalidOption(ref s)
| Inner::Render(ref s)
| Inner::Template(ref s)
| Inner::Syntect(ref s)
| Inner::GrammarCheck(ref s) => s.as_ref(),
| Inner::Parser(ref s)
| Inner::Zipper(ref s)
| Inner::BookOption(ref s)
| Inner::ConfigParser(ref s)
| Inner::InvalidOption(ref s)
| Inner::Render(ref s)
| Inner::Template(ref s)
| Inner::Syntect(ref s)
| Inner::GrammarCheck(ref s) => s.as_ref(),
Inner::FileNotFound(..) => "File not found",
}
@ -287,15 +287,15 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let source = &self.source;
if let Some(ref file) = source.file {
write!(f, "{}", file)?;
write!(f, "{file}")?;
if let Some(line) = source.line {
write!(f, ":{}", line)?;
write!(f, ":{line}")?;
}
write!(f, ": ")?;
}
match self.inner {
Inner::Default(ref s) => write!(f, "{}", s),
Inner::Default(ref s) => write!(f, "{s}"),
Inner::GrammarCheck(ref s) => {
write!(
f,
@ -363,7 +363,7 @@ pub type Result<T> = result::Result<T, Error>;
/// Implement our Error from mustache::Error
impl From<mustache::Error> for Error {
fn from(err: mustache::Error) -> Error {
Error::template(Source::empty(), format!("{}", err))
Error::template(Source::empty(), format!("{err}"))
}
}
@ -408,7 +408,7 @@ impl From<syntect::Error> for Error {
fn from(err: syntect::Error) -> Error {
Error::syntect(
Source::empty(),
lformat!("syntect error: {error}", error = err)
lformat!("syntect error: {error}", error = err),
)
}
}

View File

@ -78,7 +78,7 @@ impl GrammalecteChecker {
let res = checker
.client
.get(&format!("http://localhost:{}", port))
.get(format!("http://localhost:{port}"))
.send()
.map_err(|e| {
Error::grammar_check(
@ -113,7 +113,7 @@ impl GrammalecteChecker {
let mut res = self
.client
.post(&format!("http://localhost:{}/gc_text/fr", self.port))
.post(format!("http://localhost:{}/gc_text/fr", self.port))
.body(query)
.send()
.map_err(|e| {

View File

@ -67,7 +67,7 @@ impl GrammarChecker {
let res = checker
.client
.get(&format!("http://localhost:{}/v2/languages", port))
.get(format!("http://localhost:{port}/v2/languages"))
.send()
.map_err(|e| {
Error::grammar_check(
@ -99,7 +99,7 @@ impl GrammarChecker {
let mut res = self
.client
.post(&format!("http://localhost:{}/v2/check", self.port))
.post(format!("http://localhost:{}/v2/check", self.port))
.body(query)
.send()
.map_err(|e| {

View File

@ -248,7 +248,7 @@ impl<'a> HtmlRenderer<'a> {
} else if self.current_numbering >= n {
let numbers = self.get_numbers();
Ok(HeaderData {
text: format!("{} {}", numbers, c_title),
text: format!("{numbers} {c_title}"),
number: numbers,
header: String::new(),
title: c_title,
@ -373,8 +373,7 @@ impl<'a> HtmlRenderer<'a> {
for (note_number, footnote) in self.footnotes.drain(..) {
write!(
res,
"<div class = \"sidenote\">\n{} {}\n</div>\n",
note_number, footnote
"<div class = \"sidenote\">\n{note_number} {footnote}\n</div>\n",
)
.unwrap();
}
@ -407,13 +406,12 @@ impl<'a> HtmlRenderer<'a> {
res,
"<tr class = \"notes\">
<td class = \"note-number\">
{}
{note_number}
</td>
<td class = \"note\">
{}
{footnote}
</td>
</tr>\n",
note_number, footnote
</tr>\n"
)
.unwrap();
}
@ -449,9 +447,7 @@ impl<'a> HtmlRenderer<'a> {
"<span class = \"repetition\" \
style = \"text-decoration-line: underline; \
text-decoration-style: wavy; \
text-decoration-color: {colour}\">{content}</span>",
colour = colour,
content = content
text-decoration-color: {colour}\">{content}</span>"
))
} else {
Ok(content)
@ -506,10 +502,7 @@ impl<'a> HtmlRenderer<'a> {
let content = this.render_vec(vec)?;
this.as_mut().current_par += 1;
let par = this.as_ref().current_par;
Ok(format!(
"<p id = \"para-{}\"{}>{}</p>\n",
par, class, content
))
Ok(format!("<p id = \"para-{par}\"{class}>{content}</p>\n"))
}
Token::Header(n, ref vec) => {
let data = this.as_mut().render_title(n, vec)?;
@ -556,11 +549,10 @@ impl<'a> HtmlRenderer<'a> {
let output = if let Some(ref syntax) = this.as_ref().syntax {
syntax.to_html(s, language)?
} else if language.is_empty() {
format!("<pre><code>{}</code></pre>\n", s)
format!("<pre><code>{s}</code></pre>\n")
} else {
format!(
"<pre><code class = \"language-{}\">{}</code></pre>\n",
language,
"<pre><code class = \"language-{language}\">{}</code></pre>\n",
escape::html(s)
)
};
@ -575,7 +567,7 @@ impl<'a> HtmlRenderer<'a> {
if n == 1 {
String::new()
} else {
format!(" start = \"{}\"", n)
format!(" start = \"{n}\"")
},
this.render_vec(vec)?
)),
@ -598,12 +590,11 @@ impl<'a> HtmlRenderer<'a> {
};
Ok(format!(
"<a href = \"{}\"{}>{}</a>",
url,
"<a href = \"{url}\"{}>{}</a>",
if title.is_empty() {
String::new()
} else {
format!(" title = \"{}\"", title)
format!(" title = \"{title}\"")
},
this.render_vec(vec)?
))
@ -616,16 +607,14 @@ impl<'a> HtmlRenderer<'a> {
if token.is_image() {
Ok(format!(
"<img src = \"{}\" title = \"{}\" alt = \"{}\" />",
url, title, content
"<img src = \"{url}\" title = \"{title}\" alt = \"{content}\" />",
))
} else {
Ok(format!(
"<div class = \"image\">
<img src = \"{}\" title = \"{}\" alt = \
\"{}\" />
<img src = \"{url}\" title = \"{title}\" alt = \
\"{content}\" />
</div>",
url, title, content
))
}
}
@ -639,25 +628,23 @@ impl<'a> HtmlRenderer<'a> {
Token::TableRow(ref vec) => Ok(format!("<tr>\n{}</tr>\n", this.render_vec(vec)?)),
Token::TableCell(ref vec) => {
let tag = if this.as_ref().table_head { "th" } else { "td" };
Ok(format!("<{}>{}</{}>", tag, this.render_vec(vec)?, tag))
Ok(format!("<{tag}>{}</{tag}>", this.render_vec(vec)?))
}
Token::TableHead(ref vec) => {
this.as_mut().table_head = true;
let s = this.render_vec(vec)?;
this.as_mut().table_head = false;
Ok(format!("<tr>\n{}</tr>\n", s))
Ok(format!("<tr>\n{s}</tr>\n"))
}
Token::FootnoteReference(ref reference) => Ok(format!(
"<a href = \"#note-dest-{}\"><sup id = \
\"note-source-{}\">[{}]</sup></a>",
reference, reference, reference
"<a href = \"#note-dest-{reference}\"><sup id = \
\"note-source-{reference}\">[{reference}]</sup></a>",
)),
Token::FootnoteDefinition(ref reference, ref vec) => {
let note_number = format!(
"<p class = \"note-number\">
<a href = \"#note-source-{}\">[{}]</a>
<a href = \"#note-source-{reference}\">[{reference}]</a>
</p>\n",
reference, reference
);
let inner = format!(
@ -752,7 +739,7 @@ impl<'a> HtmlRenderer<'a> {
} else {
let tokens = Parser::from(this.as_ref().book).parse(&content, None)?;
let content = this.render_vec(&tokens)?;
Ok(format!("<footer id = \"footer\">{}</footer>", content))
Ok(format!("<footer id = \"footer\">{content}</footer>"))
}
}

View File

@ -73,7 +73,7 @@ impl<'a> HtmlDirRenderer<'a> {
.add_link(chapter.filename.as_str(), filenamer(i));
}
if let Ok(metadata) = fs::metadata(&dest_path) {
if let Ok(metadata) = fs::metadata(dest_path) {
if metadata.is_file() {
return Err(Error::render(
&self.html.book.source,
@ -91,7 +91,7 @@ impl<'a> HtmlDirRenderer<'a> {
path = dest_path.display()
)
);
fs::remove_dir_all(&dest_path).map_err(|e| {
fs::remove_dir_all(dest_path).map_err(|e| {
Error::render(
&self.html.book.source,
lformat!(
@ -106,7 +106,7 @@ impl<'a> HtmlDirRenderer<'a> {
fs::DirBuilder::new()
.recursive(true)
.create(&dest_path)
.create(dest_path)
.map_err(|e| {
Error::render(
&self.html.book.source,
@ -331,7 +331,7 @@ impl<'a> HtmlDirRenderer<'a> {
.map_image(&self.html.book.source, favicon)?;
mapbuilder = mapbuilder.insert_str(
"favicon",
format!("<link rel = \"icon\" href = \"{}\">", favicon),
format!("<link rel = \"icon\" href = \"{favicon}\">"),
);
}
if self.html.highlight == Highlight::Js {
@ -437,7 +437,7 @@ impl<'a> HtmlDirRenderer<'a> {
.map_image(&self.html.book.source, favicon)?;
mapbuilder = mapbuilder.insert_str(
"favicon",
format!("<link rel = \"icon\" href = \"{}\">", favicon),
format!("<link rel = \"icon\" href = \"{favicon}\">"),
);
}
if self.html.highlight == Highlight::Js {
@ -499,7 +499,7 @@ impl<'a> HtmlDirRenderer<'a> {
// dir does not exist, create it
fs::DirBuilder::new()
.recursive(true)
.create(&dest_dir)
.create(dest_dir)
.map_err(|e| {
Error::render(
&self.html.book.source,
@ -536,7 +536,7 @@ impl<'a> HtmlDirRenderer<'a> {
/// Generate a file name given an int
fn filenamer(i: usize) -> String {
format!("chapter_{:03}.html", i)
format!("chapter_{i:03}.html")
}
derive_html! {HtmlDirRenderer<'a>, HtmlRenderer::static_render_token}

View File

@ -84,7 +84,7 @@ impl<'a> HtmlIfRenderer<'a> {
gen_code.push_str(&rendered.replace('"', "\\\"").replace('\n', "\\\n"));
gen_code.push('"');
for var in &variables {
gen_code.push_str(&format!(".replace(/{{{{{var}}}}}/, {var})", var = var));
gen_code.push_str(&format!(".replace(/{{{{{var}}}}}/, {var})"));
}
gen_code.push(';');
i = end + 2;
@ -97,31 +97,26 @@ impl<'a> HtmlIfRenderer<'a> {
if contains_md {
gen_code = format!(
"var crowbook_return_variable = \"\";
{}
{gen_code}
return crowbook_return_variable.replace(/<\\/ul><ul>/g, '');\n",
gen_code
);
}
let container = if !contains_md { "p" } else { "div" };
let id = self.n_fn;
self.fn_defs.push_str(&format!(
"function fn_{id}() {{
{code}
{gen_code}
}}\n",
id = id,
code = gen_code
));
self.curr_init.push_str(&format!(
" result = fn_{id}();
if (result != undefined) {{
document.getElementById(\"result_{id}\").innerHTML = result;
}}\n",
id = id
));
let content = format!(
"<{container} id = \"result_{id}\"></{container}>\n",
id = (self.n_fn),
container = container
);
self.n_fn += 1;
Ok(content)
@ -153,11 +148,9 @@ return crowbook_return_variable.replace(/<\\/ul><ul>/g, '');\n",
{
let html_if: &mut HtmlIfRenderer = this.as_mut();
let code = format!(
"if (passageCount(state.current_id) {expr}) {{
"if (passageCount(state.current_id) {language}) {{
{code};
}}\n",
code = code,
expr = language
);
let content = html_if.parse_inner_code(&code)?;
Ok(content)
@ -189,7 +182,7 @@ return crowbook_return_variable.replace(/<\\/ul><ul>/g, '');\n",
for (i, chapter) in self.html.book.chapters.iter().enumerate() {
self.html
.handler
.add_link(chapter.filename.as_str(), format!("#chapter-{}", i));
.add_link(chapter.filename.as_str(), format!("#chapter-{i}"));
}
let pre_code = self
@ -247,10 +240,9 @@ return crowbook_return_variable.replace(/<\\/ul><ul>/g, '');\n",
}
chapters.push(format!(
"<div id = \"chapter-{}\" class = \"chapter\">
{}
"<div id = \"chapter-{i}\" class = \"chapter\">
{chapter_content}
</div>",
i, chapter_content
));
self.fn_defs.push_str(&format!(
"initFns.push(function () {{
@ -337,7 +329,7 @@ return crowbook_return_variable.replace(/<\\/ul><ul>/g, '');\n",
.map_image(&self.html.book.source, favicon)?;
mapbuilder = mapbuilder.insert_str(
"favicon",
format!("<link rel = \"icon\" href = \"{}\">", favicon),
format!("<link rel = \"icon\" href = \"{favicon}\">"),
);
}
if self.html.highlight == Highlight::Js {
@ -347,7 +339,7 @@ return crowbook_return_variable.replace(/<\\/ul><ul>/g, '');\n",
.get_template("html.highlight.js")?
.as_bytes()
.to_base64(base64::STANDARD);
let highlight_js = format!("data:text/javascript;base64,{}", highlight_js);
let highlight_js = format!("data:text/javascript;base64,{highlight_js}");
mapbuilder = mapbuilder
.insert_bool("highlight_code", true)
.insert_str(
@ -377,7 +369,7 @@ pub struct HtmlIf {}
impl BookRenderer for HtmlIf {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.html", book_name))
Ok(format!("{book_name}.html"))
}
fn render(&self, book: &Book, to: &mut dyn io::Write) -> Result<()> {

View File

@ -79,13 +79,13 @@ impl<'a> HtmlSingleRenderer<'a> {
/// Render books as a standalone HTML file
pub fn render_book(&mut self) -> Result<String> {
let menu_svg = img::MENU_SVG.to_base64(base64::STANDARD);
let menu_svg = format!("data:image/svg+xml;base64,{}", menu_svg);
let menu_svg = format!("data:image/svg+xml;base64,{menu_svg}");
let book_svg = img::BOOK_SVG.to_base64(base64::STANDARD);
let book_svg = format!("data:image/svg+xml;base64,{}", book_svg);
let book_svg = format!("data:image/svg+xml;base64,{book_svg}");
let pages_svg = img::PAGES_SVG.to_base64(base64::STANDARD);
let pages_svg = format!("data:image/svg+xml;base64,{}", pages_svg);
let pages_svg = format!("data:image/svg+xml;base64,{pages_svg}");
let mut content = String::new();
@ -101,7 +101,7 @@ impl<'a> HtmlSingleRenderer<'a> {
for (i, chapter) in self.html.book.chapters.iter().enumerate() {
self.html
.handler
.add_link(chapter.filename.as_str(), format!("#chapter-{}", i));
.add_link(chapter.filename.as_str(), format!("#chapter-{i}"));
}
for (i, chapter) in self.html.book.chapters.iter().enumerate() {
@ -297,7 +297,7 @@ impl<'a> HtmlSingleRenderer<'a> {
.map_image(&self.html.book.source, favicon)?;
mapbuilder = mapbuilder.insert_str(
"favicon",
format!("<link rel = \"icon\" href = \"{}\">", favicon),
format!("<link rel = \"icon\" href = \"{favicon}\">"),
);
}
if !self.html.toc.is_empty() {
@ -311,7 +311,7 @@ impl<'a> HtmlSingleRenderer<'a> {
.get_template("html.highlight.js")?
.as_bytes()
.to_base64(base64::STANDARD);
let highlight_js = format!("data:text/javascript;base64,{}", highlight_js);
let highlight_js = format!("data:text/javascript;base64,{highlight_js}");
mapbuilder = mapbuilder
.insert_bool("highlight_code", true)
.insert_str(
@ -342,7 +342,7 @@ pub struct ProofHtmlSingle {}
impl BookRenderer for HtmlSingle {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.html", book_name))
Ok(format!("{book_name}.html"))
}
fn render(&self, book: &Book, to: &mut dyn io::Write) -> Result<()> {
@ -360,7 +360,7 @@ impl BookRenderer for HtmlSingle {
impl BookRenderer for ProofHtmlSingle {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.proof.html", book_name))
Ok(format!("{book_name}.proof.html"))
}
fn render(&self, book: &Book, to: &mut dyn io::Write) -> Result<()> {

View File

@ -43,7 +43,7 @@ pub fn get_str(lang: &str, s: &str) -> String {
key = s,
lang = lang
));
if let &Yaml::String(ref result) = yaml {
if let Yaml::String(result) = yaml {
result.clone()
} else {
panic!(

View File

@ -129,9 +129,8 @@ impl<'a> LatexRenderer<'a> {
let numbering = self.book.options.get_i32("rendering.num_depth").unwrap() - 1;
write!(
content,
"\\setcounter{{tocdepth}}{{{}}}
\\setcounter{{secnumdepth}}{{{}}}\n",
numbering, numbering
"\\setcounter{{tocdepth}}{{{numbering}}}
\\setcounter{{secnumdepth}}{{{numbering}}}\n",
)?;
if self.book.options.get_bool("rendering.inline_toc").unwrap() {
@ -140,7 +139,7 @@ impl<'a> LatexRenderer<'a> {
for (i, chapter) in self.book.chapters.iter().enumerate() {
self.handler
.add_link(chapter.filename.as_str(), format!("chapter-{}", i));
.add_link(chapter.filename.as_str(), format!("chapter-{i}"));
}
for (i, chapter) in self.book.chapters.iter().enumerate() {
@ -153,7 +152,7 @@ impl<'a> LatexRenderer<'a> {
content.push_str(&self.render_token(&v[0])?);
offset = 1;
}
writeln!(content, "\\label{{chapter-{}}}", i)?;
writeln!(content, "\\label{{chapter-{i}}}")?;
content.push_str(&self.render_vec(&v[offset..])?);
}
self.source = Source::empty();
@ -246,7 +245,7 @@ impl<'a> LatexRenderer<'a> {
if let Ok(tex_font_size) = self.book.options.get_i32("tex.font.size") {
data = data
.insert_bool("has_tex_size", true)
.insert_str("tex_size", format!("{}", tex_font_size));
.insert_str("tex_size", format!("{tex_font_size}"));
}
// If class isn't book, set open_any to true, so margins are symetric.
@ -331,12 +330,8 @@ impl<'a> Renderer for LatexRenderer<'a> {
)
})?;
let mut first_word = String::new();
loop {
let c = if let Some(next_char) = chars.peek() {
*next_char
} else {
break;
};
while let Some(next_char) = chars.peek() {
let c = *next_char;
if !c.is_whitespace() {
first_word.push(c);
chars.next();
@ -348,12 +343,9 @@ impl<'a> Renderer for LatexRenderer<'a> {
let rest = chars.collect::<String>();
if initial.is_alphanumeric() {
Ok(format!(
"\\lettrine{{{}}}{{{}}}{}",
initial, first_word, rest
))
Ok(format!("\\lettrine{{{initial}}}{{{first_word}}}{rest}"))
} else {
Ok(format!("{}{}{}", initial, first_word, rest))
Ok(format!("{initial}{first_word}{rest}"))
}
} else {
Ok(content.into_owned())
@ -452,15 +444,13 @@ impl<'a> Renderer for LatexRenderer<'a> {
format!(
"\\begin{{spverbatim}}
{code}
\\end{{spverbatim}}",
code = code
\\end{{spverbatim}}"
)
};
res = format!(
"\\begin{{mdcodeblock}}
{}
\\end{{mdcodeblock}}",
res
{res}
\\end{{mdcodeblock}}"
);
Ok(res)
}
@ -504,11 +494,7 @@ impl<'a> Renderer for LatexRenderer<'a> {
))
}
};
format!(
"\\setcounter{{{counter}}}{{{n}}}\n",
counter = counter,
n = n - 1
)
format!("\\setcounter{{{counter}}}{{{n}}}\n", n = n - 1)
};
let result = format!(
"\\begin{{enumerate}}
@ -526,14 +512,13 @@ impl<'a> Renderer for LatexRenderer<'a> {
if self.hyperref && self.handler.contains_link(url) {
Ok(format!(
"\\hyperref[{}]{{{}}}",
"\\hyperref[{}]{{{content}}}",
escape::tex(self.handler.get_link(url)),
content
))
} else {
let url = escape::tex(url.as_str());
if content == url {
Ok(format!("\\url{{{}}}", content))
Ok(format!("\\url{{{content}}}"))
} else if self
.book
.options
@ -541,18 +526,17 @@ impl<'a> Renderer for LatexRenderer<'a> {
.unwrap()
{
Ok(format!(
"\\href{{{}}}{{{}}}\\protect\\footnote{{\\url{{{}}}}}",
url, content, url
"\\href{{{url}}}{{{content}}}\\protect\\footnote{{\\url{{{url}}}}}"
))
} else {
Ok(format!("\\href{{{}}}{{{}}}", url, content))
Ok(format!("\\href{{{url}}}{{{content}}}"))
}
}
}
Token::StandaloneImage(ref url, _, _) => {
if ResourceHandler::is_local(url) {
let img = self.handler.map_image(&self.source, url.as_str())?;
Ok(format!("\\mdstandaloneimage{{{}}}\n", img))
Ok(format!("\\mdstandaloneimage{{{img}}}\n"))
} else {
debug!(
"{}",
@ -585,7 +569,7 @@ impl<'a> Renderer for LatexRenderer<'a> {
Ok(String::new())
}
}
Token::FootnoteReference(ref reference) => Ok(format!("\\footnotemark[{}]", reference)),
Token::FootnoteReference(ref reference) => Ok(format!("\\footnotemark[{reference}]")),
Token::FootnoteDefinition(ref reference, ref v) => Ok(format!(
"\\footnotetext[{}]{{{}}}",
reference,
@ -625,13 +609,12 @@ impl<'a> Renderer for LatexRenderer<'a> {
if self.proofread {
match *annotation {
Data::GrammarError(ref s) => Ok(format!(
"\\underline{{{}}}\\protect\\footnote{{{}}}",
content,
"\\underline{{{content}}}\\protect\\footnote{{{}}}",
escape::tex(s.as_str())
)),
Data::Repetition(ref colour) => {
if !self.escape && colour == "red" {
Ok(format!("\\underline{{{}}}", content))
Ok(format!("\\underline{{{content}}}"))
} else {
Ok(content)
}
@ -652,7 +635,7 @@ pub struct ProofPdf;
impl BookRenderer for Latex {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.tex", book_name))
Ok(format!("{book_name}.tex"))
}
fn render(&self, book: &Book, to: &mut dyn io::Write) -> Result<()> {
@ -670,7 +653,7 @@ impl BookRenderer for Latex {
impl BookRenderer for ProofLatex {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.proof.tex", book_name))
Ok(format!("{book_name}.proof.tex"))
}
fn render(&self, book: &Book, to: &mut dyn io::Write) -> Result<()> {
@ -688,7 +671,7 @@ impl BookRenderer for ProofLatex {
impl BookRenderer for Pdf {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.pdf", book_name))
Ok(format!("{book_name}.pdf"))
}
fn render(&self, book: &Book, to: &mut dyn io::Write) -> Result<()> {
@ -699,7 +682,7 @@ impl BookRenderer for Pdf {
impl BookRenderer for ProofPdf {
fn auto_path(&self, book_name: &str) -> Result<String> {
Ok(format!("{}.proof.pdf", book_name))
Ok(format!("{book_name}.proof.pdf"))
}
fn render(&self, book: &Book, to: &mut dyn io::Write) -> Result<()> {

View File

@ -65,7 +65,7 @@ impl RepetitionDetector {
/// Check repetitions in a vector of tokens.
///
/// This modifies the AST
pub fn check_chapter(&self, tokens: &mut Vec<Token>) -> Result<()> {
pub fn check_chapter(&self, tokens: &mut [Token]) -> Result<()> {
let fuzzy = if self.fuzzy {
Some(self.fuzzy_threshold)
} else {

View File

@ -81,7 +81,7 @@ impl ResourceHandler {
return Err(Error::file_not_found(
source,
lformat!("image"),
format!("{}", file),
format!("{file}"),
));
}
@ -122,7 +122,7 @@ impl ResourceHandler {
return Err(Error::file_not_found(
source,
lformat!("image"),
format!("{}", file),
format!("{file}"),
));
}
};
@ -146,7 +146,7 @@ impl ResourceHandler {
);
return Ok(file);
}
Some(s) => format!("data:{};base64,{}", s, base64),
Some(s) => format!("data:{s};base64,{base64}"),
}
};
@ -254,7 +254,7 @@ pub fn get_files(list: &[String], base: &str) -> Result<Vec<String>> {
let mut out: Vec<String> = vec![];
let base = Path::new(base);
for path in list {
let abs_path = base.join(&path);
let abs_path = base.join(path);
let res = fs::metadata(&abs_path);
match res {
Err(err) => {

View File

@ -46,5 +46,5 @@ pub fn fill(msg: &str, indent: &str) -> String {
let options = textwrap::Options::new(width.into())
.initial_indent(indent)
.subsequent_indent(indent);
textwrap::fill(msg, &options)
textwrap::fill(msg, options)
}

View File

@ -82,10 +82,7 @@ impl Syntax {
let res: String = syntect::html::styled_line_to_highlighted_html(&regions[..], bg)?;
formatted_code.push_str(&res);
}
Ok(format!(
"<pre>{}</pre>",
formatted_code
))
Ok(format!("<pre>{formatted_code}</pre>"))
}
pub fn to_tex(&self, code: &str, language: &str) -> Result<String> {
@ -107,32 +104,26 @@ impl Syntax {
content = content
.replace('\n', "\\\\{}\n")
.replace(' ', "\\hphantom{ }\\allowbreak{}");
content = format!("\\texttt{{{}}}", content);
content = format!("\\texttt{{{content}}}");
if style.foreground != Color::BLACK {
let r = style.foreground.r as f32 / 255.0;
let g = style.foreground.g as f32 / 255.0;
let b = style.foreground.b as f32 / 255.0;
content = format!(
"\\textcolor[rgb]{{{r}, {g}, {b}}}{{{text}}}",
r = r,
g = g,
b = b,
text = content
);
content = format!("\\textcolor[rgb]{{{r}, {g}, {b}}}{{{content}}}");
}
if style.font_style.contains(FontStyle::BOLD) {
content = format!("\\textbf{{{}}}", content);
content = format!("\\textbf{{{content}}}");
}
if style.font_style.contains(FontStyle::ITALIC) {
content = format!("\\emph{{{}}}", content);
content = format!("\\emph{{{content}}}");
}
if style.font_style.contains(FontStyle::UNDERLINE) {
content = format!("\\underline{{{}}}", content);
content = format!("\\underline{{{content}}}");
}
formatted_code.push_str(&content);
}
}
Ok(format!("{{\\sloppy {}}}", formatted_code))
Ok(format!("{{\\sloppy {formatted_code}}}"))
}
}

View File

@ -82,8 +82,8 @@ pub fn insert_annotation(
let mut pos = pos;
let mut found_left = None;
let mut found_right = None;
for i in 0..tokens.len() {
let recurse = match tokens[i] {
for (i, item) in tokens.iter_mut().enumerate() {
let recurse = match item {
Token::Str(ref s) => {
let len = s.chars().count();
if pos < len || (pos == len && found_left.is_some()) {
@ -121,7 +121,7 @@ pub fn insert_annotation(
}
_ => {
if let Some(inner) = tokens[i].inner() {
if let Some(inner) = item.inner() {
let len = count_length(inner);
// Only recurse if the two is in this subtree
if pos < len {
@ -151,7 +151,7 @@ pub fn insert_annotation(
// Moved out of the match 'thanks' to borrowcheck
if recurse {
if let Some(ref mut inner) = tokens[i].inner_mut() {
if let Some(ref mut inner) = item.inner_mut() {
if let Some(new_pos) = insert_annotation(inner, annotation, pos, length) {
pos = new_pos;
} else {

View File

@ -75,7 +75,7 @@ This is forbidden because we are supposed \
// dir does not exist, create it
DirBuilder::new()
.recursive(true)
.create(&dest_dir)
.create(dest_dir)
.map_err(|_| {
Error::zipper(lformat!(
"could not create temporary directory in {path}",