import { workspace } from "vscode" ; /**
 * The main class to add markdown index.
 *
 * Inspired by firjq (https://github.com/firejq/markdown_index/blob/master/src/MarkdownIndex.ts)
 *
 * modify by legendmohe
 */ export class MarkdownIndex { private _indexBase : string = "#" ; constructor ( ) { const configuration = workspace . getConfiguration ( "markdownIndex" ) ; const configBase = configuration . get < string > ( "indexBase" ) ; if ( configBase && configBase . length > 0 ) { this . _indexBase = configBase ; } } private _addPrefix ( line , prefix , markCount ) { let markIndex = line . indexOf ( this . _indexBase ) ; if ( markIndex == - 1 ) { markIndex = 0 ; } var re = new RegExp ( '(^\\s*\\' + this . _indexBase + '+)\\s*((\\d+\\.)+)\\s+' , "g" ) ; line = line . replace ( re , "$1" ) ; return line . substr ( 0 , markIndex + markCount ) + " " + prefix + " " + line . substr ( markIndex + markCount ) . trim ( ) ; } private _countStartsWith ( fliter , chars ) { let count = 0 ; chars . some ( element => { if ( fliter ( element ) ) { count ++ ; return false ; } else { return true ; } } ) ; return count ; } private _addIndex ( content , lastMarkCount , prefix , cursor ) { let targetMarkCount = 0 ; let isInCodeArea = false ; while ( cursor < content . length ) { let line = content [ cursor ] ; if ( line . startsWith ( "```" ) ) { isInCodeArea = ! isInCodeArea ; cursor ++ ; continue ; } if ( isInCodeArea == false && line . startsWith ( this . _indexBase ) ) { targetMarkCount = this . _countStartsWith ( x => { return x == this . _indexBase ; } , line . split ( "" ) ) ; break ; } cursor ++ ; } let seq = 1 ; while ( cursor < content . length ) { let markCount = this . _countStartsWith ( x => { return x == this . _indexBase ; } , content [ cursor ] . split ( "" ) ) ; if ( markCount == targetMarkCount && markCount > lastMarkCount ) { let curPrefix = prefix + seq + "." ; content [ cursor ] = this . _addPrefix ( content [ cursor ] , curPrefix , markCount ) ; seq ++ ; cursor = this . _addIndex ( content , markCount , curPrefix , cursor + 1 ) ; } else if ( markCount <= lastMarkCount ) { cursor -- ; break ; } cursor ++ ; } return cursor ; } public addMarkdownIndex ( content ) { this . _addIndex ( content , 0 , "" , 0 ) ; return content ; } }