Skip to content

Commit

Permalink
feat: capture the toc between two html comments
Browse files Browse the repository at this point in the history
This commit closes #5,
by adding this feature, we can update the toc between two comments
instead of creating a new on top of it
  • Loading branch information
ycd committed Jan 22, 2021
1 parent 7ad78a9 commit 755a472
Showing 1 changed file with 34 additions and 8 deletions.
42 changes: 34 additions & 8 deletions pkg/toc/toc.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,19 +170,45 @@ func convertToHTML(file []byte) (string, error) {
return buf.String(), nil
}

// TODO(ycd): make file writing more
// memory efficient and safe
func (t *toc) writeToFile(markdown string) error {
// reformatMarkdown loads the entire string in the memory,
// finds the end and starting position for pos
// deletes the older one and creates a new.
//
// if you are concerned about the performance, usually markdown files
// are smaller than 3MB. So it would be pretty fast.
func (t *toc) reformatMarkdown(markdown string) (string, error) {
search := "<!--toc-->"
finish := "<!-- end of toc -->"

// Get indexes of ending position of <!--toc-->
// get the ending position of finish if exists.
finishPos := strings.Index(markdown, finish)
idx := strings.Index(markdown, search)

idx := strings.Index(markdown, search) + len(search) + 1
if idx == 10 {
return errors.New("toc path is missing, add '<!--toc--->' to your markdown")
if idx == -1 {
return "", errors.New("ERROR: toc path is missing, add '<!--toc--->' to your markdown")
}

newText := markdown[:idx] + "\n" + t.String() + markdown[idx:]
// Set index to end of <!--toc-->
idx = idx + len(search)

if finishPos != -1 {
markdown = (markdown[:idx]) + markdown[finishPos+len(finish):]
}

markdown = markdown[:idx] + "\n" + t.String() + "\n" + finish + markdown[idx:]

return markdown, nil
}

func (t *toc) writeToFile(markdown string) error {

markdown, err := t.reformatMarkdown(markdown)
if err != nil {
return err
}

err := ioutil.WriteFile(t.Options.Path, []byte(newText), 0644)
err = ioutil.WriteFile(t.Options.Path, []byte(markdown), 0644)
if err != nil {
return err
}
Expand Down

0 comments on commit 755a472

Please sign in to comment.