md2bb-existing.sh 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/bin/bash
  2. win="$(xdotool getwindowfocus)" # we want this as early as possible, in case user switches window focus during execution
  3. # dependency checks
  4. for dep in xclip markdown sed perl; do
  5. type -f $dep >/dev/null || exit 1
  6. done
  7. perl -MHTML::Entities -e 1 || exit 1
  8. # I use discount for a markdown executable. YMMV
  9. md_opts="links,image,html,del,autolink,safelink,fencedcode,githubtags,nopants"
  10. # keep adding expressions for all possible tags
  11. expr="
  12. s#<p>##g
  13. s#</p>##g
  14. s#<h.>#[h]#g
  15. s#</h.>#[/h]#g
  16. s#<blockquote>#[quote]#g
  17. s#</blockquote>#[/quote]#g
  18. s#<code>#[code]#g
  19. s#</code>#[/code]#g
  20. s#<ul>#[list]#g
  21. s#</ul>#[/list]#g
  22. s#<ol>#[list=1]#g
  23. s#</ol>#[/list]#g
  24. s#<li>#[*]#g
  25. s#</li>##g
  26. s#<a href=\([^>]*\)>#[url=\1]#g
  27. s#</a>#[/url]#g
  28. s#<pre>##g
  29. s#</pre>##g
  30. s#<em>#[i]#g
  31. s#</em>#[/i]#g
  32. s#<i>#[i]#g
  33. s#</i>#[/i]#g
  34. s#<b>#[b]#g
  35. s#</b>#[/b]#g
  36. s#<br>##g
  37. s#<br/>##g
  38. s#<del>#[strike]#g
  39. s#</del>#[/strike]#g
  40. s#<strong>#[b]#g
  41. s#</strong>#[/b]#g
  42. "
  43. # let's use stderr (2) as the file descriptor to check for terminal
  44. [ -t 2 ] && text="$(</dev/stdin)" || text="$(xclip -o)"
  45. # The second sed expression compresses multiple empty lines into one
  46. text="$(echo "$text" | markdown -f "$md_opts" | sed -e "$expr" -e 'N;/^\n$/D;P;D;' | perl -CS -MHTML::Entities -pe 'decode_entities($_);')"
  47. # don't put closing tags on a separate line:
  48. text="${text//$'\n'[\//[\/}"
  49. [ -t 2 ] && echo "$text" && exit
  50. echo "$text" | xclip -selection clipboard
  51. xdotool key --clearmodifiers --window "$win" ctrl+v
  52. exit 0