"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const katex_1 = __importDefault(require("katex"));
const highlight_js_1 = __importDefault(require("highlight.js"));
const markdown_it_1 = __importDefault(require("markdown-it"));
const constant_1 = __importDefault(require("lodash/constant"));
const logger = __importStar(require("../../utils/logger"));
const HighlightRule_1 = require("./highlight/HighlightRule");
const Highlighter_1 = require("./highlight/Highlighter");
const markdown_it_alt_frontmatter_1 = require("./plugins/markdown-it-alt-frontmatter");
const markdown_it_icons_1 = require("./plugins/markdown-it-icons");
const markdown_it_center_text_1 = require("./plugins/markdown-it-center-text");
const markdown_it_colour_text_1 = require("./plugins/markdown-it-colour-text");
const markdown_it_double_delimiter_1 = require("./plugins/markdown-it-double-delimiter");
const markdown_it_footnotes_1 = require("./plugins/markdown-it-footnotes");
const markdown_it_radio_button_1 = require("./plugins/markdown-it-radio-button");
const markdown_it_block_embed_1 = __importDefault(require("./plugins/markdown-it-block-embed"));
const markdownIt = (0, markdown_it_1.default)({ html: true, linkify: true });
markdownIt.linkify.set({ fuzzyLink: false });
const _ = {
    constant: constant_1.default,
};
// markdown-it plugins
markdownIt.use((0, markdown_it_double_delimiter_1.createDoubleDelimiterInlineRule)('%%', 'dimmed', 'emphasis'))
    .use((0, markdown_it_double_delimiter_1.createDoubleDelimiterInlineRule)('!!', 'underline', 'dimmed'))
    .use((0, markdown_it_double_delimiter_1.createDoubleDelimiterInlineRule)('++', 'large', 'underline'))
    .use((0, markdown_it_double_delimiter_1.createDoubleDelimiterInlineRule)('--', 'small', 'large'));
markdownIt.use(require('markdown-it-mark'))
    .use(require('markdown-it-sub'))
    .use(require('markdown-it-sup'))
    .use(require('@tlylt/markdown-it-imsize'), { autofill: false })
    .use(require('markdown-it-table-of-contents'))
    .use(require('markdown-it-task-lists'), { enabled: true })
    .use(require('markdown-it-linkify-images'), { imgClass: 'img-fluid' })
    .use(require('markdown-it-texmath'), { engine: katex_1.default, delimiters: ['dollars', 'brackets'] })
    .use(require('markdown-it-attrs'))
    .use(markdown_it_radio_button_1.radioButtonPlugin, { enabled: true, label: true })
    .use(markdown_it_block_embed_1.default)
    .use(markdown_it_icons_1.markdownItIconsPlugin)
    .use(markdown_it_footnotes_1.footnotePlugin)
    .use(markdown_it_center_text_1.centertext_plugin)
    .use(markdown_it_colour_text_1.colourTextPlugin)
    .use(markdown_it_alt_frontmatter_1.altFrontmatterPlugin);
// fix table style
markdownIt.renderer.rules.table_open = _.constant('<div class="table-responsive"><table class="markbind-table table table-bordered table-striped">');
markdownIt.renderer.rules.table_close = _.constant('</table></div>');
function getAttribute(token, attr, deleteAttribute = false) {
    const index = token.attrIndex(attr);
    if (index === -1) {
        return undefined;
    }
    if (token.attrs === null) {
        return undefined;
    }
    // tokens are stored as an array of two-element-arrays:
    // e.g. [ ['highlight-lines', '1,2,3'], ['start-from', '1'] ]
    const value = token.attrs[index][1];
    if (deleteAttribute) {
        token.attrs.splice(index, 1);
    }
    return value;
}
// syntax highlight code fences and add line numbers
markdownIt.renderer.rules.fence = (tokens, idx, options, env, slf) => {
    const token = tokens[idx];
    const lang = token.info || '';
    let str = token.content;
    str = str.replace(/\t/g, '    '); // Convert tabs to 4 spaces by default
    let highlighted = false;
    let lines = [];
    const startFromRawValue = getAttribute(token, 'start-from', true);
    const startFromOneBased = startFromRawValue === undefined
        ? 1
        : Math.max(1, parseInt(startFromRawValue, 10) || 1);
    const startFromZeroBased = startFromOneBased - 1;
    if (startFromRawValue) {
        if (startFromOneBased > 1) {
            // counter is incremented on each span, so we need to subtract 1
            token.attrJoin('style', `counter-reset: line ${startFromZeroBased};`);
        }
        const existingClass = getAttribute(token, 'class') || '';
        const lineNumbersRegex = /(^|\s)line-numbers($|\s)/;
        const hasLineNumbers = lineNumbersRegex.test(existingClass);
        if (!hasLineNumbers) {
            token.attrJoin('class', 'line-numbers');
        }
    }
    const highlightLinesInput = getAttribute(token, 'highlight-lines', true);
    let highlightRules = [];
    if (highlightLinesInput) {
        highlightRules = HighlightRule_1.HighlightRule.parseAllRules(highlightLinesInput, -startFromZeroBased, str);
    }
    if (lang && highlight_js_1.default.getLanguage(lang)) {
        try {
            /* With highlightjs version >= v10.7.0, usage of continuation is deprecated
      
            For the purposes of line-by-line highlighting, we have to first highlight the
            whole block, then split the resulting html string according to '\n', and add
            the corresponding opening and closing tags for the html string to be well-formed and
            maintain the correct state per line.
      
            Ref: https://github.com/MarkBind/markbind/pull/1521
            */
            lines = highlight_js_1.default.highlight(str, { language: lang, ignoreIllegals: true }).value.split('\n');
            const tokenStack = [];
            lines = lines.map((line) => {
                const prepend = tokenStack.map(tok => `<span class="${tok}">`).join('');
                const re = /<span class="(.*?)">|<\/span>/g; // match all (<span class="xyz"> and </span>)
                let matchArr = re.exec(line);
                while (matchArr !== null) {
                    const [match, captureGrp] = matchArr;
                    if (match === '</span>') {
                        // pop from stack
                        tokenStack.shift();
                    }
                    else {
                        // push to stack
                        tokenStack.unshift(captureGrp);
                    }
                    matchArr = re.exec(line);
                }
                const append = '</span>'.repeat(tokenStack.length);
                return prepend + line + append;
            });
            highlighted = true;
        }
        catch (ex) {
            logger.error(`Error processing code block line ${ex}`);
        }
    }
    if (!highlighted) {
        lines = markdownIt.utils.escapeHtml(str).split('\n');
    }
    lines.pop(); // last line is always a single '\n' newline, so we remove it
    str = lines.map((line, index) => {
        const currentLineNumber = index + 1;
        // Firstly, we determine if there are whole line/text highlights
        const immediateHighlight = highlightRules.flatMap(rule => rule.getHighlightType(currentLineNumber)).find(({ highlightType }) => {
            if (highlightType === HighlightRule_1.HIGHLIGHT_TYPES.WholeLine) {
                return true;
            }
            if (highlightType === HighlightRule_1.HIGHLIGHT_TYPES.WholeText) {
                return true;
            }
            return false;
        });
        // Apply the WholeLine and WholeText highlight here
        if (immediateHighlight) {
            const highlightColor = immediateHighlight.color || '';
            if (immediateHighlight.highlightType === HighlightRule_1.HIGHLIGHT_TYPES.WholeLine) {
                return Highlighter_1.Highlighter.highlightWholeLine(line, highlightColor);
            }
            if (immediateHighlight.highlightType === HighlightRule_1.HIGHLIGHT_TYPES.WholeText) {
                return Highlighter_1.Highlighter.highlightWholeText(line, highlightColor);
            }
        }
        // Next, handle partial text highlight logic here
        const boundsWithColors = highlightRules.flatMap(rule => rule.getHighlightType(currentLineNumber)
            .filter(({ highlightType, bounds }) => highlightType === HighlightRule_1.HIGHLIGHT_TYPES.PartialText && bounds)
            .flatMap(({ bounds, color }) => bounds.map(bound => ({ bounds: bound, color: color || '' }))));
        if (boundsWithColors.length > 0) {
            return Highlighter_1.Highlighter.highlightPartOfText(line, boundsWithColors);
        }
        // Default case: wrap in span
        return `<span>${line}\n</span>`;
    }).join('');
    token.attrJoin('class', 'hljs');
    if (highlighted) {
        token.attrJoin('class', lang);
    }
    const heading = token.attrGet('heading');
    const codeBlockContent = `<pre><code ${slf.renderAttrs(token)}>${str}</code></pre>`;
    if (heading) {
        const renderedHeading = markdownIt.renderInline(heading);
        const headingStyle = (renderedHeading === heading)
            ? 'code-block-heading'
            : 'code-block-heading inline-markdown-heading';
        return '<div class="code-block">'
            + `<div class="${headingStyle}"><span>${renderedHeading}</span></div>`
            + `<div class="code-block-content">${codeBlockContent}</div>`
            + '</div>';
    }
    return codeBlockContent;
};
// highlight inline code
markdownIt.renderer.rules.code_inline
    = (tokens, idx, options, env, slf) => {
        const token = tokens[idx];
        const lang = token.attrGet('class');
        const inlineClass = 'hljs inline';
        if (lang && highlight_js_1.default.getLanguage(lang)) {
            token.attrSet('class', `${inlineClass} ${lang}`);
            return `<code${slf.renderAttrs(token)}>${highlight_js_1.default.highlight(token.content, { language: lang, ignoreIllegals: true }).value}</code>`;
        }
        token.attrSet('class', `${inlineClass} no-lang`);
        return `<code${slf.renderAttrs(token)}>${markdownIt.utils.escapeHtml(token.content)}</code>`;
    };
const fixedNumberEmojiDefs = require('./patches/markdown-it-emoji-fixed');
markdownIt.use(require('markdown-it-emoji'), {
    defs: fixedNumberEmojiDefs,
});
markdownIt.createDoubleDelimiterInlineRule = markdown_it_double_delimiter_1.createDoubleDelimiterInlineRule;
module.exports = markdownIt;
//# sourceMappingURL=index.js.map