浏览代码

fix: improve handling of math and diagrams

Block math in body can now be wrapped in "<div>$$...$$</div>" tags
Inline math in body can now be wrapping in "`$...$`" backticks
Diagrams can now be created without shortcodes: "```mermaid ... ```"
George Cushen 6 年之前
父节点
当前提交
0cffd47aca

+ 15 - 0
assets/js/academic.js

@@ -404,6 +404,17 @@
     $('#TableOfContents li').addClass('nav-item');
     $('#TableOfContents li a').addClass('nav-link');
 
+    // Fix Mermaid.js clash with Highlight.js.
+    let mermaids = [];
+    [].push.apply(mermaids, document.getElementsByClassName('language-mermaid'));
+    for (i = 0; i < mermaids.length; i++) {
+      $(mermaids[i]).unwrap('pre');  // Remove <pre> wrapper.
+      $(mermaids[i]).replaceWith(function(){
+        // Convert <code> block to <div> and add `mermaid` class so that Mermaid will parse it.
+        return $("<div />").append($(this).contents()).addClass('mermaid');
+      });
+    }
+
     // Get theme variation (day/night).
     let defaultThemeVariation;
     if ($('body').hasClass('dark')) {
@@ -461,6 +472,10 @@
     // Re-initialize Scrollspy with dynamic navbar height offset.
     fixScrollspy();
 
+    // Fix inline math (workaround lack of Mathjax support in Blackfriday).
+    // Note `.MathJax_Preview` won't exist until after Mathjax has parsed the page, so call on page *load*.
+    $('.MathJax_Preview').unwrap('code');
+
     if (window.location.hash) {
       // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
       if (window.location.hash == "#top") {

+ 18 - 3
assets/js/mathjax-config.js

@@ -1,6 +1,21 @@
 window.MathJax = {
-  CommonHTML: { linebreaks: { automatic: true } },
-  tex2jax: { inlineMath: [ ['$', '$'], ['\\(','\\)'] ], displayMath: [ ['$$','$$'], ['\\[', '\\]'] ], processEscapes: false },
-  TeX: { noUndefined: { attributes: { mathcolor: 'red', mathbackground: '#FFEEEE', mathsize: '90%' } } },
+  CommonHTML: {linebreaks: {automatic: true}},
+  tex2jax: {
+    inlineMath: [['$', '$'], ['\\(', '\\)']],
+    displayMath: [['$$', '$$'], ['\\[', '\\]']],
+    processEscapes: false,
+    skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']  // Remove `code` (required for inline math).
+  },
+  TeX: {noUndefined: {attributes: {mathcolor: 'red', mathbackground: '#FFEEEE', mathsize: '90%'}}},
   messageStyle: 'none'
 };
+
+MathJax.Hub.Queue(function() {
+  // Fix inline math wrapped in <code> tags after MathJax finishes running.
+  // This is a workaround to overcome a shortcoming of Blackfriday Markdown.
+  // See discussion in Hugo Docs.
+  let all = MathJax.Hub.getAllJax(), i;
+  for (i = 0; i < all.length; i += 1) {
+    all[i].SourceElement().parentNode.className += ' has-jax';
+  }
+});

+ 1 - 0
assets/sass/academic/_integrations.scss

@@ -2,4 +2,5 @@
 div.mermaid {
   width: 100%;
   text-align: center;
+  margin-bottom: 1rem;
 }

+ 8 - 4
exampleSite/config/_default/params.toml

@@ -24,16 +24,20 @@ twitter = ""
 #   To enable, place an image in `static/img/` and reference its filename below. To disable, set the value to "".
 logo = ""
 
-# Enable global source code highlighting? true/false
+# Enable source code highlighting? true/false
 # Documentation: https://sourcethemes.com/academic/docs/writing-markdown-latex/#highlighting-options
 highlight = true
-# highlight_languages = ["r"]  # Add support for highlighting additional languages
+highlight_languages = ["r"]  # Add support for highlighting additional languages
 # highlight_style = "github"  # For supported styles, see https://cdnjs.com/libraries/highlight.js/
 
-# Enable global LaTeX math rendering?
-#   If false, you can enable it locally on a per page basis.
+# Enable LaTeX math rendering? true/false
+#   If false, you can enable math on a per page basis as needed.
 math = false
 
+# Enable diagram rendering? true/false
+#   If false, you can enable diagrams on a per page basis as needed.
+diagram = false
+
 # Privacy pack
 #   Show a cookie consent message to visitors
 #   Anonymize IP in Google Analytics (if enabled)

+ 143 - 0
exampleSite/content/post/writing.md

@@ -0,0 +1,143 @@
+---
+title: Writing technical content in Academic
+date: 2019-07-12
+math: true
+diagram: true
+---
+
+Academic is designed to give technical content creators a seamless experience. You can focus on the content and Academic handles the rest.
+
+Highlight your code snippets, take notes on math classes, and draw diagrams from textual representation.
+
+On this page, you'll find some examples of the types of technical content that can be rendered with Academic.
+
+## Examples
+
+### Code
+
+Academic supports a Markdown extension for highlighting code syntax. You can enable this feature by toggling the `highlight` option in your `config/_default/params.toml` file.
+
+    ```python
+    import pandas as pd
+    data = pd.read_csv("data.csv")
+    data.head()
+    ```
+
+renders as
+
+```python
+import pandas as pd
+data = pd.read_csv("data.csv")
+data.head()
+```
+
+### Math
+
+Academic supports a Markdown extension for $\LaTeX$ math. You can enable this feature by toggling the `math` option in your `config/_default/params.toml` file or by adding `math: true` to your page front matter.
+
+Note that math blocks should be wrapped with `<div>...</div>` and inline math wrapped with `<span>...</span>` as otherwise your math will be parsed as Markdown.
+
+```html
+<div>$$
+\gamma_{n} = \frac{ 
+\left | \left (\mathbf x_{n} - \mathbf x_{n-1} \right )^T 
+\left [\nabla F (\mathbf x_{n}) - \nabla F (\mathbf x_{n-1}) \right ] \right |}
+{\left \|\nabla F(\mathbf{x}_{n}) - \nabla F(\mathbf{x}_{n-1}) \right \|^2}
+$$</div>
+```
+
+renders as `$\gamma_{n} = \frac{\mathbf x_{n}}{y}$`  $\gamma_{n} = \frac{\mathbf x_{n}}{y}$
+
+<div>
+$$\gamma_{n} = \frac{ \left | \left (\mathbf x_{n} - \mathbf x_{n-1} \right )^T \left [\nabla F (\mathbf x_{n}) - \nabla F (\mathbf x_{n-1}) \right ] \right |}{\left \|\nabla F(\mathbf{x}_{n}) - \nabla F(\mathbf{x}_{n-1}) \right \|^2}$$
+</div>
+
+### Diagrams
+
+Academic supports a Markdown extension for diagrams. You can enable this feature by toggling the `diagram` option in your `config/_default/params.toml` file or by adding `diagram: true` to your page front matter.
+
+An example **flowchart**:
+
+    ```mermaid
+    graph TD;
+      A-->B;
+      A-->C;
+      B-->D;
+      C-->D;
+    ```
+
+renders as
+
+```mermaid
+graph TD;
+  A-->B;
+  A-->C;
+  B-->D;
+  C-->D;
+```
+
+An example **sequence diagram**:
+
+    ```mermaid
+    sequenceDiagram
+      participant Alice
+      participant Bob
+      Alice->John: Hello John, how are you?
+      loop Healthcheck
+          John->John: Fight against hypochondria
+      end
+      Note right of John: Rational thoughts <br/>prevail...
+      John-->Alice: Great!
+      John->Bob: How about you?
+      Bob-->John: Jolly good!
+    ```
+
+renders as
+
+```mermaid
+sequenceDiagram
+  participant Alice
+  participant Bob
+  Alice->John: Hello John, how are you?
+  loop Healthcheck
+      John->John: Fight against hypochondria
+  end
+  Note right of John: Rational thoughts <br/>prevail...
+  John-->Alice: Great!
+  John->Bob: How about you?
+  Bob-->John: Jolly good!
+```
+
+An example **Gantt diagram**:
+
+    ```mermaid
+    gantt
+      dateFormat  YYYY-MM-DD
+      section Section
+      A task           :a1, 2014-01-01, 30d
+      Another task     :after a1  , 20d
+      section Another
+      Task in sec      :2014-01-12  , 12d
+      another task      : 24d
+    ```
+
+renders as
+
+```mermaid
+gantt
+  dateFormat  YYYY-MM-DD
+  section Section
+  A task           :a1, 2014-01-01, 30d
+  Another task     :after a1  , 20d
+  section Another
+  Task in sec      :2014-01-12  , 12d
+  another task      : 24d
+```
+
+### Task lists
+
+You can even write your todo lists in Academic too:
+
+- [x] Write math example
+- [x] Write diagram example
+- [ ] Do something else