From bd2880bbc6238ffc4954dba2690d357e4313a34c Mon Sep 17 00:00:00 2001 From: Douwe Maan Date: Thu, 19 Jan 2017 13:54:59 -0600 Subject: [PATCH] Improve handling of code blocks containing triple backticks --- app/assets/javascripts/copy_as_gfm.js.es6 | 22 +++++++++++++++++++--- spec/features/copy_as_gfm_spec.rb | 12 +++++++++++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/app/assets/javascripts/copy_as_gfm.js.es6 b/app/assets/javascripts/copy_as_gfm.js.es6 index 9cbeb782270..554849feb6b 100644 --- a/app/assets/javascripts/copy_as_gfm.js.es6 +++ b/app/assets/javascripts/copy_as_gfm.js.es6 @@ -116,7 +116,19 @@ if (lang === 'plaintext') { lang = ''; } - return `\`\`\`${lang}\n${text.trim()}\n\`\`\``; + text = text.trim(); + + // Prefixes lines with 4 spaces if the code contains triple backticks + if (lang === '' && text.match(/^```/gm)) { + return text.split('\n').map((s) => { + s = s.trim(); + if (s.length === 0) return ''; + + return ` ${s}`; + }).join('\n'); + } + + return `\`\`\`${lang}\n${text}\n\`\`\``; }, 'pre > code'(el, text) { // Don't wrap code blocks in `` @@ -207,8 +219,12 @@ return '-----'; }, 'table'(el, text) { - const theadText = CopyAsGFM.nodeToGFM(el.querySelector('thead')); - const tbodyText = CopyAsGFM.nodeToGFM(el.querySelector('tbody')); + const theadEl = el.querySelector('thead'); + const tbodyEl = el.querySelector('tbody'); + if (!theadEl || !tbodyEl) return false; + + const theadText = CopyAsGFM.nodeToGFM(theadEl); + const tbodyText = CopyAsGFM.nodeToGFM(tbodyEl); return theadText + tbodyText; }, diff --git a/spec/features/copy_as_gfm_spec.rb b/spec/features/copy_as_gfm_spec.rb index 6656d6a1e5d..f3a8447162c 100644 --- a/spec/features/copy_as_gfm_spec.rb +++ b/spec/features/copy_as_gfm_spec.rb @@ -270,13 +270,23 @@ describe 'Copy as GFM', feature: true, js: true do ``` GFM - <<-GFM.strip_heredoc + <<-GFM.strip_heredoc, ```ruby def foo bar end ``` GFM + + <<-GFM.strip_heredoc + Foo + + This is an example of GFM + + ```js + Code goes here + ``` + GFM ) end