import { htmlToText , HtmlToTextOptions } from "html-to-text" ; import { marked } from "marked" ; export function md2text ( markdown , columns = 76 ) { let quoteDepth = 0 ; const formatOptions = { wordwrap : columns , formatters : { headerFormatter : ( elem , walk , builder , options ) => { builder . openBlock ( { leadingLineBreaks : options . leadingLineBreaks || 2 } ) ; walk ( elem . children , builder ) ; builder . closeBlock ( { trailingLineBreaks : options . trailingLineBreaks || 2 , blockTransform : str => { const underline = str . substr ( str . lastIndexOf ( "\n" ) + 1 ) . replace ( /./g , "=" ) ; return `${ str }\n${ underline }` ; } } ) ; } , blockFormatter : ( elem , walk , builder , options ) => { builder . openBlock ( { leadingLineBreaks : options . leadingLineBreaks || 2 , reservedLineLength : quoteDepth ? 1 : 2 } ) ; quoteDepth ++ ; walk ( elem . children , builder ) ; quoteDepth -- ; builder . closeBlock ( { trailingLineBreaks : options . trailingLineBreaks || 2 , blockTransform : str => { return str . replace ( /^>/mg , ">>" ) . replace ( /^(?!>|$)/mg , "> " ) . replace ( /(^|\n)(\n)(?!$)/g , "$1>$2" ) ; } } ) ; } , } , selectors : [ { selector : "a" , options : { hideLinkHrefIfSameAsText : true , } , } , { selector : "h1" , options : { uppercase : false } , format : "headerFormatter" , } , { selector : "h2" , options : { uppercase : false } , format : "headerFormatter" , } , { selector : "h3" , options : { uppercase : false } , format : "headerFormatter" , } , { selector : "blockquote" , options : { trimEmptyLines : false } , format : "blockFormatter" } , ] , } ; return htmlToText ( marked . parse ( markdown ) , formatOptions ) ; }