use crate::converter::inline::wrapped::emit_code_span;
use crate::options::ConversionOptions;
use crate::text;
use tl::{NodeHandle, Parser};
type Context = crate::converter::Context;
type DomContext = crate::converter::DomContext;
pub fn handle(
tag_name: &str,
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
dom_ctx: &DomContext,
) {
match tag_name {
"kbd" | "samp" => {
handle_kbd_samp(tag_name, node_handle, parser, output, options, ctx, depth, dom_ctx);
}
_ => {}
}
}
fn handle_kbd_samp(
_tag_name: &str,
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
depth: usize,
dom_ctx: &DomContext,
) {
use crate::converter::{append_inline_suffix, chomp_inline, walk_node};
let Some(node) = node_handle.get(parser) else { return };
let tag = match node {
tl::Node::Tag(tag) => tag,
_ => return,
};
let children = tag.children();
if ctx.in_code {
for child_handle in children.top().iter() {
walk_node(child_handle, parser, output, options, ctx, depth + 1, dom_ctx);
}
return;
}
let mut content = String::with_capacity(32);
let code_ctx = Context {
in_code: true,
..ctx.clone()
};
for child_handle in children.top().iter() {
walk_node(
child_handle,
parser,
&mut content,
options,
&code_ctx,
depth + 1,
dom_ctx,
);
}
let normalized = text::normalize_whitespace(&content);
let (prefix, suffix, trimmed) = chomp_inline(&normalized);
if content.is_empty() {
return;
}
let body = if trimmed.is_empty() {
normalized.as_str()
} else {
trimmed
};
let emit_prefix = if trimmed.is_empty() { "" } else { prefix };
let emit_suffix = if trimmed.is_empty() { "" } else { suffix };
output.push_str(emit_prefix);
emit_kbd_samp_segments(
body,
emit_prefix.is_empty(),
output,
options,
node_handle,
parser,
dom_ctx,
);
append_inline_suffix(output, emit_suffix, !body.is_empty(), node_handle, parser, dom_ctx);
}
fn emit_kbd_samp_segments(
body: &str,
may_merge_first: bool,
output: &mut String,
options: &ConversionOptions,
node_handle: &NodeHandle,
parser: &Parser,
dom_ctx: &DomContext,
) {
let separator = crate::converter::main_helpers::hard_break_marker(options.newline_style);
let mut first = true;
for segment in body.split('\n').filter(|segment| !segment.is_empty()) {
if first {
let mut span = String::with_capacity(segment.len() + 2);
render_code_span(segment, &mut span);
if may_merge_first {
emit_code_span(&span, segment, output, node_handle, parser, dom_ctx);
} else {
output.push_str(&span);
}
} else {
output.push_str(separator);
render_code_span(segment, output);
}
first = false;
}
}
fn render_code_span(body: &str, span: &mut String) {
span.push('`');
span.push_str(body);
span.push('`');
}