ASKBOT / askbot-devel

Askbot is a Django/Python Q&A forum. **Contributors README**: https://github.com/ASKBOT/askbot-devel#how-to-contribute. Commercial hosting of Askbot and support are available at https://askbot.com
Other
1.56k stars 628 forks source link

Syntax highlighting with fenced-code-blocks is broken #897

Open bendavis78 opened 3 years ago

bendavis78 commented 3 years ago

I want the following markdown code to work:

```python
if True:
    print("hello")

I've added a custom `ASKBOT_MARKDOWN_CLASS` to load fenced-code-blocks extension:
```python
import markdown2

class Markdown(markdown2.Markdown):
    def __init__(self, *args, **kwargs):
        extras = kwargs.get('extras', list())
        extras.extend([
            'fenced-code-blocks'
        ])
        kwargs['extras'] = extras
        super().__init__(*args, **kwargs)

When writing the question with the above markdown, it does not show the preview correctly: image

When I submit the question, it does render correctly on the first load: image

However, when I refresh the page, the code loses newlines (and the syntax colors are oddly different): image

bendavis78 commented 3 years ago

After some investigation, I found the following issues:

  1. Askbot is loading middleware askbot.middleware.spaceless.SpacelessMiddleware, which strips all whitespace from the response. This is really not needed, and is destructive, as whitespace sometimes contains valuable information. The source even has a #FIXME: why do we even have this? comment next to it. Removing this fixed the issue of newlines being stripped (you also have to modify askbot/startup_procedures.py to avoid the startup error).
  2. Askbot is doing some front-end syntax highlighting which conflicts with the back-end highlighting. I disabled this by putting the following in my skin template (at the end):
    <script type="text/javascript">
        lanai.highlightSyntax = function(){/* noop */};
    </script>
  3. The front-end preview appears to be rendered by WMD. Ideally, the preview should always reflect what the back-end will render, and should run the markdown through a backend render function in order to render the preview. I haven't found a simple way to do this, but will post here if I find a better solution.
bendavis78 commented 3 years ago

I wasn't able to find an easy solution to server-side rendering, but was able to implement it in my own fork: https://github.com/BoldIdeaInc/askbot-devel/commit/04e64226016ef6dc719bc215525ba369c2668cb6

(note: this completely replaces client-side rendering, not sure what other side effects it may have)

I don't plan on submitting a PR for that change, as I think it involves more of a design discussion.