pub mod code_block_tools;
pub mod config;
pub mod doc_comment_lint;
pub mod embedded_lint;
pub mod exit_codes;
pub mod filtered_lines;
pub mod fix_coordinator;
pub mod inline_config;
pub mod linguist_data;
pub mod lint_context;
pub mod markdownlint_config;
pub mod profiling;
pub mod rule;
#[cfg(feature = "native")]
pub mod vscode;
pub mod workspace_index;
#[macro_use]
pub mod rule_config;
#[macro_use]
pub mod rule_config_serde;
pub mod rules;
pub mod types;
pub mod utils;
#[cfg(feature = "native")]
pub mod lsp;
#[cfg(feature = "native")]
pub mod output;
#[cfg(feature = "native")]
pub mod parallel;
#[cfg(feature = "native")]
pub mod performance;
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
pub mod wasm;
pub use rules::heading_utils::{Heading, HeadingStyle};
pub use rules::*;
pub use crate::lint_context::{LineInfo, LintContext, ListItemInfo};
use crate::rule::{LintResult, Rule, RuleCategory};
use crate::utils::calculate_indentation_width_default;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[derive(Debug, Default)]
struct ContentCharacteristics {
has_headings: bool, has_lists: bool, has_links: bool, has_code: bool, has_emphasis: bool, has_html: bool, has_tables: bool, has_blockquotes: bool, has_images: bool, }
fn has_potential_indented_code_indent(line: &str) -> bool {
calculate_indentation_width_default(line) >= 4
}
impl ContentCharacteristics {
fn analyze(content: &str) -> Self {
let mut chars = Self { ..Default::default() };
let mut has_atx_heading = false;
let mut has_setext_heading = false;
for line in content.lines() {
let trimmed = line.trim();
if !has_atx_heading && trimmed.starts_with('#') {
has_atx_heading = true;
}
if !has_setext_heading && (trimmed.chars().all(|c| c == '=' || c == '-') && trimmed.len() > 1) {
has_setext_heading = true;
}
if !chars.has_lists
&& (line.contains("* ")
|| line.contains("- ")
|| line.contains("+ ")
|| trimmed.starts_with("* ")
|| trimmed.starts_with("- ")
|| trimmed.starts_with("+ ")
|| trimmed.starts_with('*')
|| trimmed.starts_with('-')
|| trimmed.starts_with('+'))
{
chars.has_lists = true;
}
if !chars.has_lists
&& ((line.chars().next().is_some_and(|c| c.is_ascii_digit())
&& (line.contains(". ") || line.contains('.')))
|| (trimmed.starts_with('>')
&& trimmed.chars().any(|c| c.is_ascii_digit())
&& (trimmed.contains(". ") || trimmed.contains('.'))))
{
chars.has_lists = true;
}
if !chars.has_links
&& (line.contains('[')
|| line.contains("http://")
|| line.contains("https://")
|| line.contains("ftp://")
|| line.contains("www."))
{
chars.has_links = true;
}
if !chars.has_images && line.contains("![") {
chars.has_images = true;
}
if !chars.has_code
&& (line.contains('`') || line.contains("~~~") || has_potential_indented_code_indent(line))
{
chars.has_code = true;
}
if !chars.has_emphasis && (line.contains('*') || line.contains('_')) {
chars.has_emphasis = true;
}
if !chars.has_html && line.contains('<') {
chars.has_html = true;
}
if !chars.has_tables && line.contains('|') {
chars.has_tables = true;
}
if !chars.has_blockquotes && line.starts_with('>') {
chars.has_blockquotes = true;
}
}
chars.has_headings = has_atx_heading || has_setext_heading;
chars
}
fn should_skip_rule(&self, rule: &dyn Rule) -> bool {
match rule.category() {
RuleCategory::Heading => !self.has_headings,
RuleCategory::List => !self.has_lists,
RuleCategory::Link => !self.has_links && !self.has_images,
RuleCategory::Image => !self.has_images,
RuleCategory::CodeBlock => !self.has_code,
RuleCategory::Html => !self.has_html,
RuleCategory::Emphasis => !self.has_emphasis,
RuleCategory::Blockquote => !self.has_blockquotes,
RuleCategory::Table => !self.has_tables,
RuleCategory::Whitespace | RuleCategory::FrontMatter | RuleCategory::Other => false,
}
}
}
#[cfg(feature = "native")]
fn compute_content_hash(content: &str) -> String {
blake3::hash(content.as_bytes()).to_hex().to_string()
}
#[cfg(not(feature = "native"))]
fn compute_content_hash(content: &str) -> String {
use std::hash::{DefaultHasher, Hash, Hasher};
let mut hasher = DefaultHasher::new();
content.hash(&mut hasher);
format!("{:016x}", hasher.finish())
}
pub fn lint(
content: &str,
rules: &[Box<dyn Rule>],
verbose: bool,
flavor: crate::config::MarkdownFlavor,
source_file: Option<std::path::PathBuf>,
config: Option<&crate::config::Config>,
) -> LintResult {
let (result, _file_index) = lint_and_index(content, rules, verbose, flavor, source_file, config);
result
}
pub fn build_file_index_only(
content: &str,
rules: &[Box<dyn Rule>],
flavor: crate::config::MarkdownFlavor,
source_file: Option<std::path::PathBuf>,
) -> crate::workspace_index::FileIndex {
let content_hash = compute_content_hash(content);
let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
if content.is_empty() {
return file_index;
}
let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
for rule in rules {
if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
rule.contribute_to_index(&lint_ctx, &mut file_index);
}
}
file_index
}
pub fn lint_and_index(
content: &str,
rules: &[Box<dyn Rule>],
_verbose: bool,
flavor: crate::config::MarkdownFlavor,
source_file: Option<std::path::PathBuf>,
config: Option<&crate::config::Config>,
) -> (LintResult, crate::workspace_index::FileIndex) {
let mut warnings = Vec::new();
let content_hash = compute_content_hash(content);
let mut file_index = crate::workspace_index::FileIndex::with_hash(content_hash);
#[cfg(not(target_arch = "wasm32"))]
let _overall_start = Instant::now();
if content.is_empty() {
return (Ok(warnings), file_index);
}
let lint_ctx = crate::lint_context::LintContext::new(content, flavor, source_file);
let inline_config = lint_ctx.inline_config();
let (file_disabled, persistent_transitions, line_disabled) = inline_config.export_for_file_index();
file_index.file_disabled_rules = file_disabled;
file_index.persistent_transitions = persistent_transitions;
file_index.line_disabled_rules = line_disabled;
let characteristics = ContentCharacteristics::analyze(content);
let applicable_rules: Vec<_> = rules
.iter()
.filter(|rule| !characteristics.should_skip_rule(rule.as_ref()))
.collect();
let _total_rules = rules.len();
let _applicable_count = applicable_rules.len();
#[cfg(not(target_arch = "wasm32"))]
let profile_rules = std::env::var("RUMDL_PROFILE_RULES").is_ok();
#[cfg(target_arch = "wasm32")]
let profile_rules = false;
let inline_overrides = inline_config.get_all_rule_configs();
let merged_config = if !inline_overrides.is_empty() {
config.map(|c| c.merge_with_inline_config(inline_config))
} else {
None
};
let effective_config = merged_config.as_ref().or(config);
let mut recreated_rules: std::collections::HashMap<String, Box<dyn crate::rule::Rule>> =
std::collections::HashMap::new();
if let Some(cfg) = effective_config {
for rule_name in inline_overrides.keys() {
if let Some(recreated) = crate::rules::create_rule_by_name(rule_name, cfg) {
recreated_rules.insert(rule_name.clone(), recreated);
}
}
}
for rule in &applicable_rules {
#[cfg(not(target_arch = "wasm32"))]
let _rule_start = Instant::now();
if rule.should_skip(&lint_ctx) {
continue;
}
let effective_rule: &dyn crate::rule::Rule = recreated_rules
.get(rule.name())
.map(|r| r.as_ref())
.unwrap_or(rule.as_ref());
let result = effective_rule.check(&lint_ctx);
match result {
Ok(rule_warnings) => {
let filtered_warnings: Vec<_> = rule_warnings
.into_iter()
.filter(|warning| {
if lint_ctx
.line_info(warning.line)
.is_some_and(|info| info.in_kramdown_extension_block)
{
return false;
}
let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
let base_rule_name = if let Some(dash_pos) = rule_name_to_check.find('-') {
&rule_name_to_check[..dash_pos]
} else {
rule_name_to_check
};
{
let end = if warning.end_line >= warning.line {
warning.end_line
} else {
warning.line
};
!(warning.line..=end).any(|line| inline_config.is_rule_disabled(base_rule_name, line))
}
})
.map(|mut warning| {
if let Some(cfg) = config {
let rule_name_to_check = warning.rule_name.as_deref().unwrap_or(rule.name());
if let Some(override_severity) = cfg.get_rule_severity(rule_name_to_check) {
warning.severity = override_severity;
}
}
warning
})
.collect();
warnings.extend(filtered_warnings);
}
Err(e) => {
log::error!("Error checking rule {}: {}", rule.name(), e);
return (Err(e), file_index);
}
}
#[cfg(not(target_arch = "wasm32"))]
{
let rule_duration = _rule_start.elapsed();
if profile_rules {
eprintln!("[RULE] {:6} {:?}", rule.name(), rule_duration);
}
#[cfg(not(test))]
if _verbose && rule_duration.as_millis() > 500 {
log::debug!("Rule {} took {:?}", rule.name(), rule_duration);
}
}
}
for rule in rules {
if rule.cross_file_scope() == crate::rule::CrossFileScope::Workspace {
rule.contribute_to_index(&lint_ctx, &mut file_index);
}
}
#[cfg(not(test))]
if _verbose {
let skipped_rules = _total_rules - _applicable_count;
if skipped_rules > 0 {
log::debug!("Skipped {skipped_rules} of {_total_rules} rules based on content analysis");
}
}
(Ok(warnings), file_index)
}
pub fn run_cross_file_checks(
file_path: &std::path::Path,
file_index: &crate::workspace_index::FileIndex,
rules: &[Box<dyn Rule>],
workspace_index: &crate::workspace_index::WorkspaceIndex,
config: Option<&crate::config::Config>,
) -> LintResult {
use crate::rule::CrossFileScope;
let mut warnings = Vec::new();
for rule in rules {
if rule.cross_file_scope() != CrossFileScope::Workspace {
continue;
}
match rule.cross_file_check(file_path, file_index, workspace_index) {
Ok(rule_warnings) => {
let filtered: Vec<_> = rule_warnings
.into_iter()
.filter(|w| !file_index.is_rule_disabled_at_line(rule.name(), w.line))
.map(|mut warning| {
if let Some(cfg) = config
&& let Some(override_severity) = cfg.get_rule_severity(rule.name())
{
warning.severity = override_severity;
}
warning
})
.collect();
warnings.extend(filtered);
}
Err(e) => {
log::error!("Error in cross-file check for rule {}: {}", rule.name(), e);
return Err(e);
}
}
}
Ok(warnings)
}
pub fn get_profiling_report() -> String {
profiling::get_report()
}
pub fn reset_profiling() {
profiling::reset()
}
pub fn get_regex_cache_stats() -> std::collections::HashMap<String, u64> {
crate::utils::regex_cache::get_cache_stats()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rule::Rule;
use crate::rules::{MD001HeadingIncrement, MD009TrailingSpaces};
#[test]
fn test_content_characteristics_analyze() {
let chars = ContentCharacteristics::analyze("");
assert!(!chars.has_headings);
assert!(!chars.has_lists);
assert!(!chars.has_links);
assert!(!chars.has_code);
assert!(!chars.has_emphasis);
assert!(!chars.has_html);
assert!(!chars.has_tables);
assert!(!chars.has_blockquotes);
assert!(!chars.has_images);
let chars = ContentCharacteristics::analyze("# Heading");
assert!(chars.has_headings);
let chars = ContentCharacteristics::analyze("Heading\n=======");
assert!(chars.has_headings);
let chars = ContentCharacteristics::analyze("* Item\n- Item 2\n+ Item 3");
assert!(chars.has_lists);
let chars = ContentCharacteristics::analyze("1. First\n2. Second");
assert!(chars.has_lists);
let chars = ContentCharacteristics::analyze("[link](url)");
assert!(chars.has_links);
let chars = ContentCharacteristics::analyze("Visit https://example.com");
assert!(chars.has_links);
let chars = ContentCharacteristics::analyze("");
assert!(chars.has_images);
let chars = ContentCharacteristics::analyze("`inline code`");
assert!(chars.has_code);
let chars = ContentCharacteristics::analyze("~~~\ncode block\n~~~");
assert!(chars.has_code);
let chars = ContentCharacteristics::analyze("Text\n\n indented code\n\nMore text");
assert!(chars.has_code);
let chars = ContentCharacteristics::analyze("Text\n\n\ttab indented code\n\nMore text");
assert!(chars.has_code);
let chars = ContentCharacteristics::analyze("Text\n\n \tmixed indent code\n\nMore text");
assert!(chars.has_code);
let chars = ContentCharacteristics::analyze("Text\n\n \ttab after space\n\nMore text");
assert!(chars.has_code);
let chars = ContentCharacteristics::analyze("*emphasis* and _more_");
assert!(chars.has_emphasis);
let chars = ContentCharacteristics::analyze("<div>HTML content</div>");
assert!(chars.has_html);
let chars = ContentCharacteristics::analyze("| Header | Header |\n|--------|--------|");
assert!(chars.has_tables);
let chars = ContentCharacteristics::analyze("> Quote");
assert!(chars.has_blockquotes);
let content = "# Heading\n* List item\n[link](url)\n`code`\n*emphasis*\n<p>html</p>\n| table |\n> quote\n";
let chars = ContentCharacteristics::analyze(content);
assert!(chars.has_headings);
assert!(chars.has_lists);
assert!(chars.has_links);
assert!(chars.has_code);
assert!(chars.has_emphasis);
assert!(chars.has_html);
assert!(chars.has_tables);
assert!(chars.has_blockquotes);
assert!(chars.has_images);
}
#[test]
fn test_content_characteristics_should_skip_rule() {
let chars = ContentCharacteristics {
has_headings: true,
has_lists: false,
has_links: true,
has_code: false,
has_emphasis: true,
has_html: false,
has_tables: true,
has_blockquotes: false,
has_images: false,
};
let heading_rule = MD001HeadingIncrement::default();
assert!(!chars.should_skip_rule(&heading_rule));
let trailing_spaces_rule = MD009TrailingSpaces::new(2, false);
assert!(!chars.should_skip_rule(&trailing_spaces_rule));
let chars_no_headings = ContentCharacteristics {
has_headings: false,
..Default::default()
};
assert!(chars_no_headings.should_skip_rule(&heading_rule));
}
#[test]
fn test_lint_empty_content() {
let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
let result = lint("", &rules, false, crate::config::MarkdownFlavor::Standard, None, None);
assert!(result.is_ok());
assert!(result.unwrap().is_empty());
}
#[test]
fn test_lint_with_violations() {
let content = "## Level 2\n#### Level 4"; let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
let result = lint(
content,
&rules,
false,
crate::config::MarkdownFlavor::Standard,
None,
None,
);
assert!(result.is_ok());
let warnings = result.unwrap();
assert!(!warnings.is_empty());
assert_eq!(warnings[0].rule_name.as_deref(), Some("MD001"));
}
#[test]
fn test_lint_with_inline_disable() {
let content = "<!-- rumdl-disable MD001 -->\n## Level 2\n#### Level 4";
let rules: Vec<Box<dyn Rule>> = vec![Box::new(MD001HeadingIncrement::default())];
let result = lint(
content,
&rules,
false,
crate::config::MarkdownFlavor::Standard,
None,
None,
);
assert!(result.is_ok());
let warnings = result.unwrap();
assert!(warnings.is_empty()); }
#[test]
fn test_lint_rule_filtering() {
let content = "# Heading\nJust text";
let rules: Vec<Box<dyn Rule>> = vec![
Box::new(MD001HeadingIncrement::default()),
];
let result = lint(
content,
&rules,
false,
crate::config::MarkdownFlavor::Standard,
None,
None,
);
assert!(result.is_ok());
}
#[test]
fn test_get_profiling_report() {
let report = get_profiling_report();
assert!(!report.is_empty());
assert!(report.contains("Profiling"));
}
#[test]
fn test_reset_profiling() {
reset_profiling();
let report = get_profiling_report();
assert!(report.contains("disabled") || report.contains("no measurements"));
}
#[test]
fn test_get_regex_cache_stats() {
let stats = get_regex_cache_stats();
assert!(stats.is_empty() || !stats.is_empty());
for count in stats.values() {
assert!(*count > 0);
}
}
#[test]
fn test_content_characteristics_edge_cases() {
let chars = ContentCharacteristics::analyze("-"); assert!(!chars.has_headings);
let chars = ContentCharacteristics::analyze("--"); assert!(chars.has_headings);
let chars = ContentCharacteristics::analyze("*emphasis*"); assert!(chars.has_lists);
let chars = ContentCharacteristics::analyze("1.Item"); assert!(chars.has_lists);
let chars = ContentCharacteristics::analyze("text > not a quote");
assert!(!chars.has_blockquotes);
}
}