Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatic table of contents generation for Markdown #2281

Merged
merged 7 commits into from
Sep 15, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions browser/lib/markdown-toc-generator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/**
* @fileoverview Markdown table of contents generator
*/

import toc from 'markdown-toc'
import diacritics from 'diacritics-map'
import stripColor from 'strip-color'

const EOL = require('os').EOL

/**
* @caseSensitiveSlugify Custom slugify function
* Same implementation that the original used by markdown-toc (node_modules/markdown-toc/lib/utils.js),
* but keeps original case to properly handle https://github.com/BoostIO/Boostnote/issues/2067
*/
function caseSensitiveSlugify (str) {
function replaceDiacritics (str) {
return str.replace(/[À-ž]/g, function (ch) {
return diacritics[ch] || ch
})
}

function getTitle (str) {
if (/^\[[^\]]+\]\(/.test(str)) {
var m = /^\[([^\]]+)\]/.exec(str)
if (m) return m[1]
}
return str
}

str = getTitle(str)
str = stripColor(str)
// str = str.toLowerCase() //let's be case sensitive

// `.split()` is often (but not always) faster than `.replace()`
str = str.split(' ').join('-')
str = str.split(/\t/).join('--')
str = str.split(/<\/?[^>]+>/).join('')
str = str.split(/[|$&`~=\\\/@+*!?({[\]})<>=.,;:'"^]/).join('')
str = str.split(/[。?!,、;:“”【】()〔〕[]﹃﹄“ ”‘’﹁﹂—…-~《》〈〉「」]/).join('')
str = replaceDiacritics(str)
return str
}

const TOC_MARKER_START = '<!-- toc -->'
const TOC_MARKER_END = '<!-- tocstop -->'

/**
* Takes care of proper updating given editor with TOC.
* If TOC doesn't exit in the editor, it's inserted at current caret position.
* Otherwise,TOC is updated in place.
* @param editor CodeMirror editor to be updated with TOC
*/
export function generateInEditor (editor) {
const tocRegex = new RegExp(`${TOC_MARKER_START}[\\s\\S]*?${TOC_MARKER_END}`)

function tocExistsInEditor () {
return tocRegex.test(editor.getValue())
}

function updateExistingToc () {
const toc = generate(editor.getValue())
const search = editor.getSearchCursor(tocRegex)
while (search.findNext()) {
search.replace(toc)
}
}

function addTocAtCursorPosition () {
const toc = generate(editor.getRange(editor.getCursor(), {line: Infinity}))
editor.replaceRange(wrapTocWithEol(toc, editor), editor.getCursor())
}

if (tocExistsInEditor()) {
updateExistingToc()
} else {
addTocAtCursorPosition()
}
}

/**
* Generates MD TOC based on MD document passed as string.
* @param markdownText MD document
* @returns generatedTOC String containing generated TOC
*/
export function generate (markdownText) {
const generatedToc = toc(markdownText, {slugify: caseSensitiveSlugify})
return TOC_MARKER_START + EOL + EOL + generatedToc.content + EOL + EOL + TOC_MARKER_END
}

function wrapTocWithEol (toc, editor) {
const leftWrap = editor.getCursor().ch === 0 ? '' : EOL
const rightWrap = editor.getLine(editor.getCursor().line).length === editor.getCursor().ch ? '' : EOL
return leftWrap + toc + rightWrap
}

export default {
generate,
generateInEditor
}
9 changes: 9 additions & 0 deletions browser/main/Detail/MarkdownNoteDetail.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { formatDate } from 'browser/lib/date-formatter'
import { getTodoPercentageOfCompleted } from 'browser/lib/getTodoStatus'
import striptags from 'striptags'
import { confirmDeleteNote } from 'browser/lib/confirmDeleteNote'
import markdownToc from 'browser/lib/markdown-toc-generator'

class MarkdownNoteDetail extends React.Component {
constructor (props) {
Expand All @@ -47,6 +48,7 @@ class MarkdownNoteDetail extends React.Component {
this.dispatchTimer = null

this.toggleLockButton = this.handleToggleLockButton.bind(this)
this.generateToc = () => this.handleGenerateToc()
}

focus () {
Expand All @@ -59,6 +61,7 @@ class MarkdownNoteDetail extends React.Component {
const reversedType = this.state.editorType === 'SPLIT' ? 'EDITOR_PREVIEW' : 'SPLIT'
this.handleSwitchMode(reversedType)
})
ee.on('code:generate-toc', this.generateToc)
}

componentWillReceiveProps (nextProps) {
Expand All @@ -75,6 +78,7 @@ class MarkdownNoteDetail extends React.Component {

componentWillUnmount () {
ee.off('topbar:togglelockbutton', this.toggleLockButton)
ee.off('code:generate-toc', this.generateToc)
if (this.saveQueue != null) this.saveNow()
}

Expand Down Expand Up @@ -262,6 +266,11 @@ class MarkdownNoteDetail extends React.Component {
}
}

handleGenerateToc () {
const editor = this.refs.content.refs.code.editor
markdownToc.generateInEditor(editor)
}

handleFocus (e) {
this.focus()
}
Expand Down
15 changes: 14 additions & 1 deletion browser/main/Detail/SnippetNoteDetail.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import InfoPanelTrashed from './InfoPanelTrashed'
import { formatDate } from 'browser/lib/date-formatter'
import i18n from 'browser/lib/i18n'
import { confirmDeleteNote } from 'browser/lib/confirmDeleteNote'
import markdownToc from 'browser/lib/markdown-toc-generator'

const electron = require('electron')
const { remote } = electron
Expand All @@ -52,6 +53,7 @@ class SnippetNoteDetail extends React.Component {
}

this.scrollToNextTabThreshold = 0.7
this.generateToc = () => this.handleGenerateToc()
}

componentDidMount () {
Expand All @@ -65,6 +67,7 @@ class SnippetNoteDetail extends React.Component {
enableLeftArrow: allTabs.offsetLeft !== 0
})
}
ee.on('code:generate-toc', this.generateToc)
}

componentWillReceiveProps (nextProps) {
Expand All @@ -91,6 +94,16 @@ class SnippetNoteDetail extends React.Component {

componentWillUnmount () {
if (this.saveQueue != null) this.saveNow()
ee.off('code:generate-toc', this.generateToc)
}

handleGenerateToc () {
const { note, snippetIndex } = this.state
const currentMode = note.snippets[snippetIndex].mode
if (currentMode.includes('Markdown')) {
const currentEditor = this.refs[`code-${snippetIndex}`].refs.code.editor
markdownToc.generateInEditor(currentEditor)
}
}

handleChange (e) {
Expand Down Expand Up @@ -441,7 +454,7 @@ class SnippetNoteDetail extends React.Component {
const isSuper = global.process.platform === 'darwin'
? e.metaKey
: e.ctrlKey
if (isSuper && !e.shiftKey) {
if (isSuper && !e.shiftKey && !e.altKey) {
e.preventDefault()
this.addSnippet()
}
Expand Down
10 changes: 10 additions & 0 deletions lib/main-menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@ const file = {
{
type: 'separator'
},
{
label: 'Generate/Update Markdown TOC',
accelerator: 'Shift+Ctrl+T',
click () {
mainWindow.webContents.send('code:generate-toc')
}
},
{
type: 'separator'
},
{
label: 'Print',
accelerator: 'CommandOrControl+P',
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
"markdown-it-named-headers": "^0.0.4",
"markdown-it-plantuml": "^1.1.0",
"markdown-it-smartarrows": "^1.0.1",
"markdown-toc": "^1.2.0",
"mdurl": "^1.0.1",
"mermaid": "^8.0.0-rc.8",
"moment": "^2.10.3",
Expand Down
20 changes: 19 additions & 1 deletion tests/helpers/setup-browser-env.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import browserEnv from 'browser-env'
browserEnv(['window', 'document'])
browserEnv(['window', 'document', 'navigator'])

// for CodeMirror mockup
document.body.createTextRange = function () {
return {
setEnd: function () {},
setStart: function () {},
getBoundingClientRect: function () {
return {right: 0}
},
getClientRects: function () {
return {
length: 0,
left: 0,
right: 0
}
}
}
}

window.localStorage = {
// polyfill
Expand Down
Loading