rust/src/librustdoc/html/markdown.rs

954 lines
37 KiB
Rust
Raw Normal View History

// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Markdown formatting for rustdoc
//!
2017-03-28 17:54:11 +00:00
//! This module implements markdown formatting through the pulldown-cmark
//! rust-library. This module exposes all of the
//! functionality through a unit-struct, `Markdown`, which has an implementation
//! of `fmt::Display`. Example usage:
//!
//! ```rust,ignore
2017-03-28 17:54:11 +00:00
//! use rustdoc::html::markdown::{Markdown, MarkdownOutputStyle};
//!
//! let s = "My *markdown* _text_";
2017-03-28 17:54:11 +00:00
//! let html = format!("{}", Markdown(s, MarkdownOutputStyle::Fancy));
//! // ... something using html
//! ```
#![allow(non_camel_case_types)]
use std::ascii::AsciiExt;
use std::cell::RefCell;
use std::collections::HashMap;
use std::default::Default;
use std::fmt::{self, Write};
use std::str;
2016-02-11 10:09:01 +00:00
use syntax::feature_gate::UnstableFeatures;
use syntax::codemap::Span;
2015-12-03 23:48:59 +00:00
use html::render::derive_id;
use html::toc::TocBuilder;
use html::highlight;
use html::escape::Escape;
use test;
use pulldown_cmark::{self, Event, Parser, Tag};
2017-03-08 00:01:23 +00:00
2017-03-11 00:43:36 +00:00
#[derive(Copy, Clone)]
pub enum MarkdownOutputStyle {
Compact,
Fancy,
}
impl MarkdownOutputStyle {
pub fn is_compact(&self) -> bool {
match *self {
MarkdownOutputStyle::Compact => true,
_ => false,
}
}
pub fn is_fancy(&self) -> bool {
match *self {
MarkdownOutputStyle::Fancy => true,
_ => false,
}
}
}
/// A unit struct which has the `fmt::Display` trait implemented. When
/// formatted, this struct will emit the HTML corresponding to the rendered
/// version of the contained markdown string.
// The second parameter is whether we need a shorter version or not.
2017-03-11 00:43:36 +00:00
pub struct Markdown<'a>(pub &'a str, pub MarkdownOutputStyle);
/// A unit struct like `Markdown`, that renders the markdown with a
/// table of contents.
pub struct MarkdownWithToc<'a>(pub &'a str);
/// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
pub struct MarkdownHtml<'a>(pub &'a str);
/// Returns Some(code) if `s` is a line that should be stripped from
/// documentation but used in example code. `code` is the portion of
/// `s` that should be used in tests. (None for lines that should be
/// left as-is.)
fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
let trimmed = s.trim();
if trimmed == "#" {
Some("")
} else if trimmed.starts_with("# ") {
2015-01-18 00:15:52 +00:00
Some(&trimmed[2..])
} else {
None
}
}
/// Returns a new string with all consecutive whitespace collapsed into
/// single spaces.
///
/// Any leading or trailing whitespace will be trimmed.
fn collapse_whitespace(s: &str) -> String {
2015-09-18 18:34:16 +00:00
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
// Information about the playground if a URL has been specified, containing an
// optional crate name and the URL.
thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
RefCell::new(None)
});
2017-03-11 15:27:54 +00:00
macro_rules! event_loop_break {
2017-03-25 18:07:52 +00:00
($parser:expr, $toc_builder:expr, $shorter:expr, $buf:expr, $escape:expr, $id:expr,
2017-03-25 00:48:33 +00:00
$($end_event:pat)|*) => {{
2017-03-25 18:07:52 +00:00
fn inner(id: &mut Option<&mut String>, s: &str) {
if let Some(ref mut id) = *id {
id.push_str(s);
}
}
2017-03-11 15:27:54 +00:00
while let Some(event) = $parser.next() {
match event {
$($end_event)|* => break,
Event::Text(ref s) => {
2017-03-31 17:02:46 +00:00
debug!("Text");
2017-03-25 18:07:52 +00:00
inner($id, s);
2017-03-25 00:48:33 +00:00
if $escape {
2017-03-25 18:07:52 +00:00
$buf.push_str(&format!("{}", Escape(s)));
2017-03-25 00:48:33 +00:00
} else {
$buf.push_str(s);
}
2017-03-11 15:27:54 +00:00
}
2017-03-31 17:02:46 +00:00
Event::SoftBreak => {
debug!("SoftBreak");
if !$buf.is_empty() {
$buf.push(' ');
}
2017-03-11 15:27:54 +00:00
}
x => {
2017-03-25 18:07:52 +00:00
looper($parser, &mut $buf, Some(x), $toc_builder, $shorter, $id);
2017-03-11 15:27:54 +00:00
}
}
}
}}
}
struct ParserWrapper<'a> {
parser: Parser<'a>,
// The key is the footnote reference. The value is the footnote definition and the id.
footnotes: HashMap<String, (String, u16)>,
}
impl<'a> ParserWrapper<'a> {
pub fn new(s: &'a str) -> ParserWrapper<'a> {
ParserWrapper {
parser: Parser::new_ext(s, pulldown_cmark::OPTION_ENABLE_TABLES |
pulldown_cmark::OPTION_ENABLE_FOOTNOTES),
footnotes: HashMap::new(),
}
}
pub fn next(&mut self) -> Option<Event<'a>> {
self.parser.next()
}
pub fn get_entry(&mut self, key: &str) -> &mut (String, u16) {
let new_id = self.footnotes.keys().count() + 1;
let key = key.to_owned();
self.footnotes.entry(key).or_insert((String::new(), new_id as u16))
}
}
pub fn render(w: &mut fmt::Formatter,
s: &str,
print_toc: bool,
2017-03-11 00:43:36 +00:00
shorter: MarkdownOutputStyle) -> fmt::Result {
fn code_block(parser: &mut ParserWrapper, buffer: &mut String, lang: &str) {
2017-03-31 17:02:46 +00:00
debug!("CodeBlock");
2017-03-08 00:01:23 +00:00
let mut origtext = String::new();
2017-03-11 00:43:36 +00:00
while let Some(event) = parser.next() {
match event {
Event::End(Tag::CodeBlock(_)) => break,
Event::Text(ref s) => {
origtext.push_str(s);
2017-03-08 00:01:23 +00:00
}
2017-03-11 00:43:36 +00:00
_ => {}
2017-03-08 00:01:23 +00:00
}
}
let origtext = origtext.trim_left();
debug!("docblock: ==============\n{:?}\n=======", origtext);
let lines = origtext.lines().filter(|l| {
stripped_filtered_line(*l).is_none()
});
let text = lines.collect::<Vec<&str>>().join("\n");
let block_info = if lang.is_empty() {
LangString::all_false()
} else {
LangString::parse(lang)
};
if !block_info.rust {
buffer.push_str(&format!("<pre><code class=\"language-{}\">{}</code></pre>",
lang, text));
return
}
2017-03-08 00:01:23 +00:00
PLAYGROUND.with(|play| {
// insert newline to clearly separate it from the
// previous block so we can shorten the html output
2017-03-08 22:56:00 +00:00
buffer.push('\n');
2017-03-08 00:01:23 +00:00
let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
if url.is_empty() {
return None;
}
let test = origtext.lines().map(|l| {
stripped_filtered_line(l).unwrap_or(l)
}).collect::<Vec<&str>>().join("\n");
let krate = krate.as_ref().map(|s| &**s);
let test = test::maketest(&test, krate, false,
&Default::default());
let channel = if test.contains("#![feature(") {
"&amp;version=nightly"
} else {
""
};
// These characters don't need to be escaped in a URI.
// FIXME: use a library function for percent encoding.
fn dont_escape(c: u8) -> bool {
(b'a' <= c && c <= b'z') ||
(b'A' <= c && c <= b'Z') ||
(b'0' <= c && c <= b'9') ||
c == b'-' || c == b'_' || c == b'.' ||
c == b'~' || c == b'!' || c == b'\'' ||
c == b'(' || c == b')' || c == b'*'
}
let mut test_escaped = String::new();
for b in test.bytes() {
if dont_escape(b) {
test_escaped.push(char::from(b));
} else {
write!(test_escaped, "%{:02X}", b).unwrap();
}
}
Some(format!(
r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
url, test_escaped, channel
))
});
2017-03-08 22:56:00 +00:00
buffer.push_str(&highlight::render_with_highlighting(
&text,
Some("rust-example-rendered"),
None,
playground_button.as_ref().map(String::as_str)));
2017-03-08 00:01:23 +00:00
});
}
fn heading(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle, level: i32) {
2017-03-31 17:02:46 +00:00
debug!("Heading");
2017-03-08 00:01:23 +00:00
let mut ret = String::new();
2017-03-25 18:07:52 +00:00
let mut id = String::new();
event_loop_break!(parser, toc_builder, shorter, ret, true, &mut Some(&mut id),
Event::End(Tag::Header(_)));
2017-03-11 00:43:36 +00:00
ret = ret.trim_right().to_owned();
2017-03-08 00:01:23 +00:00
let id = id.chars().filter_map(|c| {
if c.is_alphanumeric() || c == '-' || c == '_' {
if c.is_ascii() {
Some(c.to_ascii_lowercase())
} else {
Some(c)
}
} else if c.is_whitespace() && c.is_ascii() {
Some('-')
} else {
None
}
}).collect::<String>();
let id = derive_id(id);
let sec = toc_builder.as_mut().map_or("".to_owned(), |builder| {
format!("{} ", builder.push(level as u32, ret.clone(), id.clone()))
});
// Render the HTML
buffer.push_str(&format!("<h{lvl} id=\"{id}\" class=\"section-header\">\
<a href=\"#{id}\">{sec}{}</a></h{lvl}>",
2017-03-08 00:01:23 +00:00
ret, lvl = level, id = id, sec = sec));
}
fn inline_code(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("InlineCode");
2017-03-08 00:01:23 +00:00
let mut content = String::new();
2017-03-25 18:07:52 +00:00
event_loop_break!(parser, toc_builder, shorter, content, false, id, Event::End(Tag::Code));
2017-03-11 15:27:54 +00:00
buffer.push_str(&format!("<code>{}</code>",
Escape(&collapse_whitespace(content.trim_right()))));
}
fn link(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
shorter: MarkdownOutputStyle, url: &str, title: &str,
id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("Link");
let mut content = String::new();
event_loop_break!(parser, toc_builder, shorter, content, true, id,
Event::End(Tag::Link(_, _)));
if title.is_empty() {
buffer.push_str(&format!("<a href=\"{}\">{}</a>", url, content));
} else {
buffer.push_str(&format!("<a href=\"{}\" title=\"{}\">{}</a>",
url, Escape(title), content));
}
}
fn image(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
2017-03-25 18:07:52 +00:00
shorter: MarkdownOutputStyle, url: &str, mut title: String,
id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("Image");
2017-03-25 18:07:52 +00:00
event_loop_break!(parser, toc_builder, shorter, title, true, id,
Event::End(Tag::Image(_, _)));
buffer.push_str(&format!("<img src=\"{}\" alt=\"{}\">", url, title));
2017-03-08 22:56:00 +00:00
}
fn paragraph(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("Paragraph");
2017-03-08 22:56:00 +00:00
let mut content = String::new();
2017-03-25 18:07:52 +00:00
event_loop_break!(parser, toc_builder, shorter, content, true, id,
Event::End(Tag::Paragraph));
2017-03-11 00:43:36 +00:00
buffer.push_str(&format!("<p>{}</p>", content.trim_right()));
2017-03-08 22:56:00 +00:00
}
fn table_cell(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
2017-03-31 17:02:46 +00:00
debug!("TableCell");
let mut content = String::new();
2017-03-25 18:07:52 +00:00
event_loop_break!(parser, toc_builder, shorter, content, true, &mut None,
2017-03-11 15:27:54 +00:00
Event::End(Tag::TableHead) |
Event::End(Tag::Table(_)) |
Event::End(Tag::TableRow) |
Event::End(Tag::TableCell));
buffer.push_str(&format!("<td>{}</td>", content.trim()));
}
fn table_row(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
2017-03-31 17:02:46 +00:00
debug!("TableRow");
let mut content = String::new();
2017-03-11 00:43:36 +00:00
while let Some(event) = parser.next() {
match event {
Event::End(Tag::TableHead) |
Event::End(Tag::Table(_)) |
Event::End(Tag::TableRow) => break,
Event::Start(Tag::TableCell) => {
2017-03-28 17:54:11 +00:00
table_cell(parser, &mut content, toc_builder, shorter);
2017-03-11 00:43:36 +00:00
}
x => {
2017-03-25 18:07:52 +00:00
looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
}
}
}
buffer.push_str(&format!("<tr>{}</tr>", content));
}
fn table_head(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
2017-03-31 17:02:46 +00:00
debug!("TableHead");
let mut content = String::new();
2017-03-11 00:43:36 +00:00
while let Some(event) = parser.next() {
match event {
Event::End(Tag::TableHead) | Event::End(Tag::Table(_)) => break,
Event::Start(Tag::TableCell) => {
2017-03-28 17:54:11 +00:00
table_cell(parser, &mut content, toc_builder, shorter);
2017-03-11 00:43:36 +00:00
}
x => {
2017-03-25 18:07:52 +00:00
looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
}
}
}
2017-03-11 00:43:36 +00:00
if !content.is_empty() {
buffer.push_str(&format!("<thead><tr>{}</tr></thead>", content.replace("td>", "th>")));
}
}
fn table(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
2017-03-11 00:43:36 +00:00
shorter: MarkdownOutputStyle) {
2017-03-31 17:02:46 +00:00
debug!("Table");
let mut content = String::new();
let mut rows = String::new();
2017-03-11 00:43:36 +00:00
while let Some(event) = parser.next() {
match event {
Event::End(Tag::Table(_)) => break,
Event::Start(Tag::TableHead) => {
2017-03-28 17:54:11 +00:00
table_head(parser, &mut content, toc_builder, shorter);
}
2017-03-11 00:43:36 +00:00
Event::Start(Tag::TableRow) => {
2017-03-28 17:54:11 +00:00
table_row(parser, &mut rows, toc_builder, shorter);
2017-03-11 00:43:36 +00:00
}
_ => {}
}
}
buffer.push_str(&format!("<table>{}{}</table>",
content,
2017-03-11 00:43:36 +00:00
if shorter.is_compact() || rows.is_empty() {
String::new()
} else {
format!("<tbody>{}</tbody>", rows)
}));
}
fn blockquote(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
2017-03-31 17:02:46 +00:00
debug!("BlockQuote");
2017-03-11 00:43:36 +00:00
let mut content = String::new();
2017-03-25 18:07:52 +00:00
event_loop_break!(parser, toc_builder, shorter, content, true, &mut None,
Event::End(Tag::BlockQuote));
2017-03-11 00:43:36 +00:00
buffer.push_str(&format!("<blockquote>{}</blockquote>", content.trim_right()));
}
fn list_item(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle) {
2017-03-31 17:02:46 +00:00
debug!("ListItem");
2017-03-11 00:43:36 +00:00
let mut content = String::new();
while let Some(event) = parser.next() {
match event {
Event::End(Tag::Item) => break,
Event::Text(ref s) => {
2017-03-25 18:07:52 +00:00
content.push_str(&format!("{}", Escape(s)));
2017-03-11 00:43:36 +00:00
}
x => {
2017-03-25 18:07:52 +00:00
looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
2017-03-11 00:43:36 +00:00
}
}
2017-04-03 22:24:08 +00:00
if shorter.is_compact() {
break
}
2017-03-11 00:43:36 +00:00
}
buffer.push_str(&format!("<li>{}</li>", content));
}
fn list(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
2017-04-03 22:24:08 +00:00
shorter: MarkdownOutputStyle, is_sorted_list: bool) {
2017-03-31 17:02:46 +00:00
debug!("List");
2017-03-11 00:43:36 +00:00
let mut content = String::new();
while let Some(event) = parser.next() {
match event {
Event::End(Tag::List(_)) => break,
Event::Start(Tag::Item) => {
list_item(parser, &mut content, toc_builder, shorter);
}
x => {
2017-03-25 18:07:52 +00:00
looper(parser, &mut content, Some(x), toc_builder, shorter, &mut None);
2017-03-11 00:43:36 +00:00
}
}
2017-04-03 22:24:08 +00:00
if shorter.is_compact() {
break
}
2017-03-11 00:43:36 +00:00
}
2017-04-03 22:24:08 +00:00
buffer.push_str(&format!("<{0}>{1}</{0}>",
if is_sorted_list { "ol" } else { "ul" },
content));
2017-03-11 00:43:36 +00:00
}
fn emphasis(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("Emphasis");
2017-03-11 00:43:36 +00:00
let mut content = String::new();
2017-03-25 18:07:52 +00:00
event_loop_break!(parser, toc_builder, shorter, content, false, id,
Event::End(Tag::Emphasis));
2017-03-11 00:43:36 +00:00
buffer.push_str(&format!("<em>{}</em>", content));
}
fn strong(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
2017-03-25 18:07:52 +00:00
shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("Strong");
2017-03-11 00:43:36 +00:00
let mut content = String::new();
2017-03-25 18:07:52 +00:00
event_loop_break!(parser, toc_builder, shorter, content, false, id,
Event::End(Tag::Strong));
2017-03-11 00:43:36 +00:00
buffer.push_str(&format!("<strong>{}</strong>", content));
}
fn footnote(parser: &mut ParserWrapper, buffer: &mut String,
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("FootnoteDefinition");
let mut content = String::new();
event_loop_break!(parser, toc_builder, shorter, content, true, id,
Event::End(Tag::FootnoteDefinition(_)));
buffer.push_str(&content);
}
fn rule(parser: &mut ParserWrapper, buffer: &mut String, toc_builder: &mut Option<TocBuilder>,
shorter: MarkdownOutputStyle, id: &mut Option<&mut String>) {
2017-03-31 17:02:46 +00:00
debug!("Rule");
let mut content = String::new();
event_loop_break!(parser, toc_builder, shorter, content, true, id,
Event::End(Tag::Rule));
buffer.push_str("<hr>");
}
fn looper<'a>(parser: &'a mut ParserWrapper, buffer: &mut String, next_event: Option<Event<'a>>,
2017-03-25 18:07:52 +00:00
toc_builder: &mut Option<TocBuilder>, shorter: MarkdownOutputStyle,
id: &mut Option<&mut String>) -> bool {
2017-03-08 00:01:23 +00:00
if let Some(event) = next_event {
match event {
Event::Start(Tag::CodeBlock(lang)) => {
2017-03-28 17:54:11 +00:00
code_block(parser, buffer, &*lang);
2017-03-08 00:01:23 +00:00
}
Event::Start(Tag::Header(level)) => {
2017-03-28 17:54:11 +00:00
heading(parser, buffer, toc_builder, shorter, level);
2017-03-08 00:01:23 +00:00
}
Event::Start(Tag::Code) => {
2017-03-28 17:54:11 +00:00
inline_code(parser, buffer, toc_builder, shorter, id);
2017-03-08 22:56:00 +00:00
}
Event::Start(Tag::Paragraph) => {
2017-03-25 18:07:52 +00:00
paragraph(parser, buffer, toc_builder, shorter, id);
2017-03-08 22:56:00 +00:00
}
Event::Start(Tag::Link(ref url, ref t)) => {
link(parser, buffer, toc_builder, shorter, url, t.as_ref(), id);
}
Event::Start(Tag::Image(ref url, ref t)) => {
image(parser, buffer, toc_builder, shorter, url, t.as_ref().to_owned(), id);
2017-03-08 00:01:23 +00:00
}
Event::Start(Tag::Table(_)) => {
table(parser, buffer, toc_builder, shorter);
}
2017-03-11 00:43:36 +00:00
Event::Start(Tag::BlockQuote) => {
blockquote(parser, buffer, toc_builder, shorter);
}
2017-04-03 22:24:08 +00:00
Event::Start(Tag::List(x)) => {
list(parser, buffer, toc_builder, shorter, x.is_some());
2017-03-11 00:43:36 +00:00
}
Event::Start(Tag::Emphasis) => {
2017-03-25 18:07:52 +00:00
emphasis(parser, buffer, toc_builder, shorter, id);
2017-03-11 00:43:36 +00:00
}
Event::Start(Tag::Strong) => {
2017-03-25 18:07:52 +00:00
strong(parser, buffer, toc_builder, shorter, id);
2017-03-11 00:43:36 +00:00
}
Event::Start(Tag::Rule) => {
rule(parser, buffer, toc_builder, shorter, id);
}
Event::Start(Tag::FootnoteDefinition(ref def)) => {
2017-03-31 17:02:46 +00:00
debug!("FootnoteDefinition");
let mut content = String::new();
let def = def.as_ref();
footnote(parser, &mut content, toc_builder, shorter, id);
let entry = parser.get_entry(def);
let cur_id = (*entry).1;
(*entry).0.push_str(&format!("<li id=\"ref{}\">{}&nbsp;<a href=\"#supref{0}\" \
rev=\"footnote\">↩</a></p></li>",
cur_id,
if content.ends_with("</p>") {
&content[..content.len() - 4]
} else {
&content
}));
}
Event::FootnoteReference(ref reference) => {
2017-03-31 17:02:46 +00:00
debug!("FootnoteReference");
let entry = parser.get_entry(reference.as_ref());
buffer.push_str(&format!("<sup id=\"supref{0}\"><a href=\"#ref{0}\">{0}</a>\
</sup>",
(*entry).1));
}
2017-03-31 17:02:46 +00:00
Event::HardBreak => {
debug!("HardBreak");
if shorter.is_fancy() {
buffer.push_str("<br>");
} else if !buffer.is_empty() {
buffer.push(' ');
}
}
2017-03-11 17:09:59 +00:00
Event::Html(h) | Event::InlineHtml(h) => {
2017-03-31 17:02:46 +00:00
debug!("Html/InlineHtml");
2017-03-11 17:09:59 +00:00
buffer.push_str(&*h);
}
2017-03-08 00:01:23 +00:00
_ => {}
}
2017-03-11 00:43:36 +00:00
shorter.is_fancy()
2017-03-08 00:01:23 +00:00
} else {
2017-03-08 22:56:00 +00:00
false
}
}
let mut toc_builder = if print_toc {
Some(TocBuilder::new())
} else {
None
};
let mut buffer = String::new();
let mut parser = ParserWrapper::new(s);
2017-03-08 22:56:00 +00:00
loop {
let next_event = parser.next();
2017-03-25 18:07:52 +00:00
if !looper(&mut parser, &mut buffer, next_event, &mut toc_builder, shorter, &mut None) {
2017-03-08 00:01:23 +00:00
break
}
}
if !parser.footnotes.is_empty() {
let mut v: Vec<_> = parser.footnotes.values().collect();
v.sort_by(|a, b| a.1.cmp(&b.1));
buffer.push_str(&format!("<div class=\"footnotes\"><hr><ol>{}</ol></div>",
v.iter()
.map(|s| s.0.as_str())
.collect::<Vec<_>>()
.join("")));
}
2017-03-08 00:01:23 +00:00
let mut ret = toc_builder.map_or(Ok(()), |builder| {
write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
});
2017-03-08 00:01:23 +00:00
if ret.is_ok() {
ret = w.write_str(&buffer);
}
ret
}
2017-03-08 00:01:23 +00:00
pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
tests.set_position(position);
let mut parser = Parser::new(doc);
let mut prev_offset = 0;
let mut nb_lines = 0;
let mut register_header = None;
'main: while let Some(event) = parser.next() {
match event {
Event::Start(Tag::CodeBlock(s)) => {
let block_info = if s.is_empty() {
LangString::all_false()
} else {
LangString::parse(&*s)
};
if !block_info.rust {
continue
}
let mut test_s = String::new();
let mut offset = None;
loop {
let event = parser.next();
if let Some(event) = event {
match event {
Event::End(Tag::CodeBlock(_)) => break,
Event::Text(ref s) => {
test_s.push_str(s);
if offset.is_none() {
offset = Some(parser.get_offset());
2017-03-08 00:01:23 +00:00
}
}
_ => {}
2017-03-08 00:01:23 +00:00
}
} else {
break 'main;
2017-03-08 00:01:23 +00:00
}
}
let offset = offset.unwrap_or(0);
let lines = test_s.lines().map(|l| {
stripped_filtered_line(l).unwrap_or(l)
});
let text = lines.collect::<Vec<&str>>().join("\n");
nb_lines += doc[prev_offset..offset].lines().count();
let line = tests.get_line() + (nb_lines - 1);
let filename = tests.get_filename();
tests.add_test(text.to_owned(),
block_info.should_panic, block_info.no_run,
block_info.ignore, block_info.test_harness,
block_info.compile_fail, block_info.error_codes,
line, filename);
prev_offset = offset;
2017-03-08 00:01:23 +00:00
}
Event::Start(Tag::Header(level)) => {
register_header = Some(level as u32);
}
Event::Text(ref s) if register_header.is_some() => {
let level = register_header.unwrap();
if s.is_empty() {
tests.register_header("", level);
} else {
tests.register_header(s, level);
}
register_header = None;
}
_ => {}
2017-03-08 00:01:23 +00:00
}
}
}
2015-01-28 13:34:18 +00:00
#[derive(Eq, PartialEq, Clone, Debug)]
struct LangString {
original: String,
should_panic: bool,
no_run: bool,
ignore: bool,
rust: bool,
test_harness: bool,
2016-01-05 22:38:11 +00:00
compile_fail: bool,
2016-06-09 21:50:52 +00:00
error_codes: Vec<String>,
}
impl LangString {
fn all_false() -> LangString {
LangString {
original: String::new(),
should_panic: false,
no_run: false,
ignore: false,
rust: true, // NB This used to be `notrust = false`
test_harness: false,
2016-01-05 22:38:11 +00:00
compile_fail: false,
2016-06-09 21:50:52 +00:00
error_codes: Vec::new(),
}
}
fn parse(string: &str) -> LangString {
let mut seen_rust_tags = false;
let mut seen_other_tags = false;
let mut data = LangString::all_false();
2016-06-09 21:50:52 +00:00
let mut allow_compile_fail = false;
let mut allow_error_code_check = false;
if UnstableFeatures::from_environment().is_nightly_build() {
allow_compile_fail = true;
allow_error_code_check = true;
}
data.original = string.to_owned();
let tokens = string.split(|c: char|
!(c == '_' || c == '-' || c.is_alphanumeric())
);
for token in tokens {
match token {
"" => {},
"should_panic" => { data.should_panic = true; seen_rust_tags = true; },
"no_run" => { data.no_run = true; seen_rust_tags = true; },
"ignore" => { data.ignore = true; seen_rust_tags = true; },
"rust" => { data.rust = true; seen_rust_tags = true; },
2016-01-05 22:38:11 +00:00
"test_harness" => { data.test_harness = true; seen_rust_tags = true; },
"compile_fail" if allow_compile_fail => {
data.compile_fail = true;
seen_rust_tags = true;
data.no_run = true;
2016-06-09 21:50:52 +00:00
}
x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
if let Ok(_) = x[1..].parse::<u32>() {
data.error_codes.push(x.to_owned());
seen_rust_tags = true;
} else {
seen_other_tags = true;
}
}
_ => { seen_other_tags = true }
}
}
data.rust &= !seen_other_tags || seen_rust_tags;
data
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 23:45:07 +00:00
impl<'a> fmt::Display for Markdown<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Markdown(md, shorter) = *self;
// This is actually common enough to special-case
if md.is_empty() { return Ok(()) }
render(fmt, md, false, shorter)
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 23:45:07 +00:00
impl<'a> fmt::Display for MarkdownWithToc<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let MarkdownWithToc(md) = *self;
2017-03-11 00:43:36 +00:00
render(fmt, md, true, MarkdownOutputStyle::Fancy)
}
}
impl<'a> fmt::Display for MarkdownHtml<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let MarkdownHtml(md) = *self;
// This is actually common enough to special-case
if md.is_empty() { return Ok(()) }
2017-03-11 00:43:36 +00:00
render(fmt, md, false, MarkdownOutputStyle::Fancy)
}
}
pub fn plain_summary_line(md: &str) -> String {
2017-03-08 00:01:23 +00:00
struct ParserWrapper<'a> {
inner: Parser<'a>,
is_in: isize,
is_first: bool,
}
2017-03-08 00:01:23 +00:00
impl<'a> Iterator for ParserWrapper<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
let next_event = self.inner.next();
if next_event.is_none() {
return None
}
let next_event = next_event.unwrap();
let (ret, is_in) = match next_event {
Event::Start(Tag::Paragraph) => (None, 1),
Event::Start(Tag::Link(_, ref t)) if !self.is_first => {
(Some(t.as_ref().to_owned()), 1)
}
2017-03-25 00:48:33 +00:00
Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
Event::End(Tag::Code) => (Some("`".to_owned()), -1),
Event::Start(Tag::Header(_)) => (None, 1),
Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
Event::End(Tag::Link(_, ref t)) => (Some(t.as_ref().to_owned()), -1),
2017-03-25 00:48:33 +00:00
Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
2017-03-08 00:01:23 +00:00
_ => (None, 0),
};
if is_in > 0 || (is_in < 0 && self.is_in > 0) {
self.is_in += is_in;
}
if ret.is_some() {
self.is_first = false;
ret
} else {
Some(String::new())
}
}
}
2017-03-08 00:01:23 +00:00
let mut s = String::with_capacity(md.len() * 3 / 2);
let mut p = ParserWrapper {
inner: Parser::new(md),
is_in: 0,
is_first: true,
};
while let Some(t) = p.next() {
if !t.is_empty() {
s.push_str(&t);
}
}
2017-03-08 00:01:23 +00:00
s
}
#[cfg(test)]
mod tests {
2017-03-11 00:43:36 +00:00
use super::{LangString, Markdown, MarkdownHtml, MarkdownOutputStyle};
2015-09-18 18:39:05 +00:00
use super::plain_summary_line;
use html::render::reset_ids;
#[test]
fn test_lang_string_parse() {
fn t(s: &str,
2016-01-05 22:38:11 +00:00
should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
2016-06-09 21:50:52 +00:00
compile_fail: bool, error_codes: Vec<String>) {
assert_eq!(LangString::parse(s), LangString {
should_panic: should_panic,
no_run: no_run,
ignore: ignore,
rust: rust,
test_harness: test_harness,
2016-01-05 22:38:11 +00:00
compile_fail: compile_fail,
2016-06-09 21:50:52 +00:00
error_codes: error_codes,
original: s.to_owned(),
})
}
2016-01-05 22:38:11 +00:00
// marker | should_panic| no_run| ignore| rust | test_harness| compile_fail
2016-06-09 22:34:46 +00:00
// | error_codes
t("", false, false, false, true, false, false, Vec::new());
t("rust", false, false, false, true, false, false, Vec::new());
t("sh", false, false, false, false, false, false, Vec::new());
t("ignore", false, false, true, true, false, false, Vec::new());
t("should_panic", true, false, false, true, false, false, Vec::new());
t("no_run", false, true, false, true, false, false, Vec::new());
t("test_harness", false, false, false, true, true, false, Vec::new());
t("compile_fail", false, true, false, true, false, true, Vec::new());
t("{.no_run .example}", false, true, false, true, false, false, Vec::new());
t("{.sh .should_panic}", true, false, false, true, false, false, Vec::new());
t("{.example .rust}", false, false, false, true, false, false, Vec::new());
t("{.test_harness .rust}", false, false, false, true, true, false, Vec::new());
}
#[test]
fn issue_17736() {
let markdown = "# title";
2017-03-11 00:43:36 +00:00
format!("{}", Markdown(markdown, MarkdownOutputStyle::Fancy));
reset_ids(true);
}
#[test]
fn test_header() {
fn t(input: &str, expect: &str) {
2017-03-11 00:43:36 +00:00
let output = format!("{}", Markdown(input, MarkdownOutputStyle::Fancy));
2017-03-25 18:07:52 +00:00
assert_eq!(output, expect, "original: {}", input);
reset_ids(true);
}
2017-03-25 00:48:33 +00:00
t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
<a href=\"#foo-bar\">Foo bar</a></h1>");
t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
t("### **Foo** *bar* baz!?!& -_qux_-%",
2017-03-25 18:07:52 +00:00
"<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
<a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
<em>bar</em> baz!?!&amp; -<em>qux</em>-%</a></h3>");
t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
2017-03-25 00:48:33 +00:00
"<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
<a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> &amp; *bar?!* \
<em><code>baz</code></em> #qux</a></h4>");
}
2015-12-05 22:09:20 +00:00
#[test]
fn test_header_ids_multiple_blocks() {
fn t(input: &str, expect: &str) {
2017-03-11 00:43:36 +00:00
let output = format!("{}", Markdown(input, MarkdownOutputStyle::Fancy));
2017-03-25 18:07:52 +00:00
assert_eq!(output, expect, "original: {}", input);
2015-12-05 22:09:20 +00:00
}
let test = || {
2017-03-25 00:48:33 +00:00
t("# Example", "<h1 id=\"example\" class=\"section-header\">\
<a href=\"#example\">Example</a></h1>");
t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
<a href=\"#panics\">Panics</a></h1>");
t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
<a href=\"#example-1\">Example</a></h1>");
t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
<a href=\"#main-1\">Main</a></h1>");
t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
<a href=\"#example-2\">Example</a></h1>");
t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
<a href=\"#panics-1\">Panics</a></h1>");
2015-12-05 22:09:20 +00:00
};
test();
reset_ids(true);
2015-12-05 22:09:20 +00:00
test();
}
#[test]
fn test_plain_summary_line() {
fn t(input: &str, expect: &str) {
let output = plain_summary_line(input);
2017-03-25 18:07:52 +00:00
assert_eq!(output, expect, "original: {}", input);
}
t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
t("code `let x = i32;` ...", "code `let x = i32;` ...");
t("type `Type<'static>` ...", "type `Type<'static>` ...");
t("# top header", "top header");
t("## header", "header");
}
2016-12-23 07:12:56 +00:00
#[test]
fn test_markdown_html_escape() {
fn t(input: &str, expect: &str) {
let output = format!("{}", MarkdownHtml(input));
2017-03-25 18:07:52 +00:00
assert_eq!(output, expect, "original: {}", input);
2016-12-23 07:12:56 +00:00
}
2017-03-25 00:48:33 +00:00
t("`Struct<'a, T>`", "<p><code>Struct&lt;&#39;a, T&gt;</code></p>");
t("Struct<'a, T>", "<p>Struct&lt;&#39;a, T&gt;</p>");
2016-12-23 07:12:56 +00:00
}
}