11import visit from 'unist-util-visit' ;
22import toString from 'mdast-util-to-string' ;
3- import { Root , Heading } from 'mdast' ;
3+ import { Root , Heading , Paragraph } from 'mdast' ;
44import { VFile as _VFile } from 'vfile' ;
55import { Transformer , Attacher , Settings } from 'unified' ;
66
@@ -23,7 +23,10 @@ export function readMatter(): Transformer {
2323
2424export function getTitle ( ) : Transformer {
2525 return ( tree : Root , file : VFile ) => {
26- if ( tree . children . findIndex ( _ => _ . type === 'heading' ) < 0 && ! ( / ^ \_ / . test ( file . basename ) ) ) {
26+ if ( tree . children . findIndex ( _ => _ . type === 'heading' ) < 0
27+ && ! ( / ^ \_ / . test ( file . basename ) )
28+ && tree . children . length > 0 )
29+ {
2730 const heading : Heading = {
2831 type : 'heading' ,
2932 depth : 1 ,
@@ -42,3 +45,26 @@ export function getTitle(): Transformer {
4245 } ) ;
4346 } ;
4447}
48+
49+ export function correctHeadings ( ) : Transformer {
50+ return ( tree : Root , file : VFile ) => {
51+ return visit ( tree , 'paragraph' , ( node : Paragraph , index : number , parent : any ) => {
52+
53+ const text : string = node . children [ 0 ] . value as string ;
54+ let re = new RegExp ( / ^ ( \# ) { 1 , 3 } / ) ;
55+ if ( re . test ( text ) ) {
56+ const hashes = text . match ( / ( \# ) { 1 , 3 } / ) [ 0 ] ;
57+ const _text = text . replace ( hashes , '' ) ;
58+
59+ const heading : Heading = {
60+ type : 'heading' ,
61+ depth : hashes . length as 2 | 1 | 3 | 4 | 5 | 6 ,
62+ children : [ { type : 'text' , value : _text } ]
63+ } ;
64+
65+ parent . children . splice ( index , 1 , heading ) ;
66+ }
67+
68+ } ) ;
69+ } ;
70+ }
0 commit comments