tags: python qt pyside markdown title: Simple Markdown Viewer Using WebView This uses [pandoc](https://github.com/jgm/pandoc) to do the heavy lifting. Also note that if all you want is a markdown view and you're happy with e.g `google-chrome`, then consider the following ```bash #!/bin/bash A="$(mktemp --suffix=.html)" pandoc --quiet -f markdown_phpextra -t html -s "$@" >| "$A" && google-chrome "$A" ``` and also for arbitrary input formats: ``` #!/bin/bash L="$1" shift A="$(mktemp --suffix=.html)" pandoc --quiet -f "$L" -t html -s "$@" >| "$A" && google-chrome "$A" ``` It would be an easy exercise to modify the Python below to allow arbitrary languages in a similar way. # The source ```py #!/usr/bin/env python from PySide6.QtCore import * from PySide6.QtGui import * from PySide6.QtWidgets import * from PySide6.QtWebEngineWidgets import * from subprocess import run, PIPE import sys args = sys.argv[1:] if len(args) == 0: args = ["-"] # cache stdin if - is one of the args # doing it this way causes multiple -'s to duplicate stdin # rather than reading from stdin multiple times if "-" in args: stdin = sys.stdin.read() markdown = "" for x in args: if x == "-": markdown += stdin else: try: with open(x) as f: markdown += f.read() except Exception: print(f"Failed to read {x}",file=sys.stderr) continue markdown += "\n\n" m = run(["pandoc","--quiet","-f","markdown","-t","html","-s"],input=markdown.encode(),stdout=PIPE,stderr=PIPE) if m.returncode != 0: print(f"#Fail markdown") exit(1) html = m.stdout.decode() class View(QWidget): def __init__(self,html): super().__init__() self.webview = QWebEngineView(self) self.webview.setHtml(html) self.webview.resize(self.rect().size()) def resizeEvent(self,e): self.webview.resize(self.rect().size()) def keyPressEvent(self,e): if e.text().lower() == "q": app.quit() app = QApplication() view = View(html) view.show() app.exec() ``` To allow for arbitrary languages, I do (where source is now in the variable `source` instead of `markdown`) ``` args = sys.argv[1:] lang = "markdown_phpextra" if len(args) == 0: args = ["-"] if len(args) > 1: lang = args.pop(0) ... m = run(["pandoc","--quiet","-f",lang,"-t","html","-s"],input=source.encode(),stdout=PIPE,stderr=PIPE) ```