///|
/// `` carries nothing a renderer needs.
let remove_doctype : Plugin = {
  name: "removeDoctype",
  description: "remove the doctype declaration",
  run: (doc, _) => remove_top_level(doc, n => n is Doctype(_)),
}

///|
/// `` is optional for UTF-8 documents.
let remove_xml_proc_inst : Plugin = {
  name: "removeXMLProcInst",
  description: "remove the  declaration",
  run: (doc, _) => remove_top_level(doc, n => n is ProcInst("xml", _)),
}

///|
/// Comments starting with `!` are legal notices and are kept.
let remove_comments : Plugin = {
  name: "removeComments",
  description: "remove comments",
  run: (doc, ctx) => {
    let patterns = if ctx.has_param("preservePatterns") {
      ctx.param_strings("preservePatterns")
    } else {
      ["^!"]
    }
    let pred = fn(n : @xml.Node) -> Bool {
      n is Comment(c) &&
      !patterns
      .iter()
      .any(pattern => {
        if pattern.has_prefix("^") {
          c.has_prefix(pattern[1:])
        } else {
          c.contains(pattern)
        }
      })
    }
    let mut changed = remove_top_level(doc, pred)
    doc.each_element((e, _) => if remove_children(e, pred) { changed = true })
    changed
  },
}

///|
/// `` holds RDF/Dublin Core data from editors.
let remove_metadata : Plugin = {
  name: "removeMetadata",
  description: "remove ",
  run: (doc, _) => remove_elements(doc, (e, _) => e.name == "metadata"),
}

///|
/// Descriptions produced by editors ("Created with Sketch.") carry no meaning.
let remove_desc : Plugin = {
  name: "removeDesc",
  description: "remove editor generated ",
  run: (doc, _) => {
    remove_elements(doc, (e, _) => {
      e.name == "desc" &&
      (
        e.children.length() == 0 ||
        (
          e.children is [Text(t)] &&
          (t.has_prefix("Created with") || t.has_prefix("Created using"))
        )
      )
    })
  },
}

///|
/// Namespace prefixes used by editors for their private data.
let editor_namespaces : Array[String] = [
  "http://www.inkscape.org/namespaces/inkscape", "http://inkscape.sourceforge.net/DTD/sodipodi-0.dtd",
  "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd", "http://ns.adobe.com/AdobeIllustrator/10.0/",
  "http://ns.adobe.com/Graphs/1.0/", "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/",
  "http://ns.adobe.com/Variables/1.0/", "http://ns.adobe.com/SaveForWeb/1.0/", "http://ns.adobe.com/Extensibility/1.0/",
  "http://ns.adobe.com/Flows/1.0/", "http://ns.adobe.com/ImageReplacement/1.0/",
  "http://ns.adobe.com/GenericCustomNamespace/1.0/", "http://ns.adobe.com/XPath/1.0/",
  "http://schemas.microsoft.com/visio/2003/SVGExtensions/", "http://taptrix.com/vectorillustrator/svg_extensions",
  "http://www.figma.com/figma/ns", "http://purl.org/dc/elements/1.1/", "http://creativecommons.org/ns#",
  "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "http://www.serif.com/", "http://www.vector.evaxdesign.sk",
  "http://www.bohemiancoding.com/sketch/ns", "http://www.w3.org/2000/02/svg/testsuite/description/",
  "http://krita.org/namespaces/svg/krita", "https://boxy-svg.com",
]

///|
/// Drop the namespace declarations, elements and attributes of the editors
/// listed in `editor_namespaces`.
let remove_editors_ns_data : Plugin = {
  name: "removeEditorsNSData",
  description: "remove editor namespaces, elements and attributes",
  run: (doc, _) => {
    let prefixes : Array[String] = []
    let mut changed = false
    // find prefixes bound to editor namespaces and drop the declarations
    doc.each_element((e, _) => {
      if remove_attrs(e, (k, v) => {
          if k.has_prefix("xmlns:") && editor_namespaces.contains(v) {
            prefixes.push(k[6:].to_owned())
            true
          } else {
            false
          }
        }) {
        changed = true
      }
    })
    if prefixes.length() == 0 {
      return changed
    }
    let is_editor = fn(name : String) -> Bool {
      match name.find(":") {
        Some(i) => prefixes.contains(name[:i].to_owned())
        None => false
      }
    }
    if remove_elements(doc, (e, _) => is_editor(e.name)) {
      changed = true
    }
    doc.each_element((e, _) => {
      if remove_attrs(e, (k, _) => is_editor(k)) {
        changed = true
      }
    })
    changed
  },
}

///|
/// Collapse whitespace inside attribute values.
let cleanup_attrs : Plugin = {
  name: "cleanupAttrs",
  description: "clean up whitespace in attribute values",
  run: (doc, _) => {
    let mut changed = false
    doc.each_element((e, _) => {
      for kv in e.attrs.to_array() {
        let (k, v) = kv
        let cleaned = collapse_space(v)
        if cleaned != v {
          e.attrs[k] = cleaned
          changed = true
        }
      }
    })
    changed
  },
}

///|
fn collapse_space(v : String) -> String {
  guard needs_collapse(v) else { return v }
  let sb = StringBuilder()
  let mut pending_space = false
  let mut started = false
  for c in v {
    if c == ' ' || c == '\n' || c == '\t' || c == '\r' {
      pending_space = true
    } else {
      if pending_space && started {
        sb.write_char(' ')
      }
      pending_space = false
      started = true
      sb.write_char(c)
    }
  }
  sb.to_string()
}

///|
/// Attributes with an empty value, except `id`, `d` and the conditional
/// processing attributes whose empty value hides the element.
let remove_empty_attrs : Plugin = {
  name: "removeEmptyAttrs",
  description: "remove attributes with empty values",
  run: (doc, _) => {
    let mut changed = false
    doc.each_element((e, _) => {
      // an empty id may still be a target and an empty d is handled by
      // removeHiddenElems; empty conditional processing attributes hide
      // the element so they must be kept
      if remove_attrs(e, (k, v) => {
          v.is_empty() &&
          k != "id" &&
          k != "d" &&
          !conditional_processing_attrs.contains(k)
        }) {
        changed = true
      }
    })
    changed
  },
}

///|
/// Conditional processing attributes: an empty value makes the element
/// fail the test and not be rendered, so the attribute must be kept.
let conditional_processing_attrs : Set[String] = Set([
  "requiredFeatures", "requiredExtensions", "systemLanguage",
])

///|
/// ``/`` without content and `` without a target.
let remove_empty_text : Plugin = {
  name: "removeEmptyText",
  description: "remove empty ,  and ",
  run: (doc, _) => {
    remove_elements(doc, (e, _) => {
      ((e.name == "text" || e.name == "tspan") && e.children.length() == 0) ||
      (
        e.name == "tref" &&
        !e.attrs.contains("href") &&
        !e.attrs.contains("xlink:href")
      )
    })
  },
}

///|
/// Container elements (``, ``, ...) with no children, unless they
/// are referenced or otherwise meaningful (masks, `` branches, filters).
let remove_empty_containers : Plugin = {
  name: "removeEmptyContainers",
  description: "remove empty container elements",
  run: (doc, _) => {
    let removed_ids : Set[String] = Set([])
    let changed = remove_elements(doc, (e, parent) => {
      guard e.children.length() == 0 &&
        container_elements.contains(e.name) &&
        e.name != "svg" else {
        false
      }
      // an empty pattern with attributes may carry reusable configuration
      if e.name == "pattern" && e.attrs.length() > 0 {
        return false
      }
      // an empty mask with an id hides the masked element
      if e.name == "mask" && e.attrs.contains("id") {
        return false
      }
      // a  inside  is a meaningful branch
      if parent is Some(p) && p.name == "switch" {
        return false
      }
      // a  with a filter (attribute or inline style) still renders
      if e.name == "g" && has_filter(e) {
        return false
      }
      if e.attrs.contains("id") {
        removed_ids.add(e.attrs.get("id").unwrap())
      }
      true
    })
    // remove  elements that referenced a now-removed empty container
    if removed_ids.length() > 0 &&
      remove_elements(doc, (e, _) => {
        if e.name != "use" {
          return false
        }
        for k, v in e.attrs {
          if (k == "href" || k.has_suffix(":href")) && v.has_prefix("#") {
            if removed_ids.contains(v[1:].to_owned()) {
              return true
            }
          }
        }
        false
      }) {
      true
    } else {
      changed
    }
  },
}

///|
/// Elements that are never rendered.
let remove_hidden_elems : Plugin = {
  name: "removeHiddenElems",
  description: "remove elements that are not rendered",
  run: (doc, _) => {
    let ids = referenced_ids(doc)
    // a stylesheet can override presentation attributes, so with