Change stylesheets for Markdown files...

Hello!

I have been reading through various MD topics here and decided that nothing fit my needs so I knocked together an AS which works for me and I thought it may be helpful to somebody else.

You only need to change the stylesFolder property at the start of the script to point to where you keep your CSS files.

Cheers!

property stylesFolder : "Library/Application Support/Marked/Custom CSS"
property favouriteTheme : "Firates"

set home to do shell script "echo $HOME"
set themes to paragraphs of (do shell script "for i in " & home & "/" & quoted form of stylesFolder & "/*.css; do basename \"$i\" .css; done")
set cr to ASCII character 13
set lf to ASCII character 10

set favouriteTheme to choose from list themes with prompt "Select your favorite theme:" default items favouriteTheme

tell application id "DNtp"
	set theSelection to the selection as list
	repeat with thisItem in theSelection
		if the kind of thisItem is "Markdown" then
			set thePath to the path of thisItem
			set theText to do shell script "perl -pe 's|<link rel=.stylesheet.*?>||' " & quoted form of thePath & " | tr '" & cr & "' '" & lf & "' | sed '/./,$!d'"
			set link to "<link rel=\"stylesheet\" href=\"file://" & home & "/" & stylesFolder & "/" & favouriteTheme & ".css\">"
			set the plain text of thisItem to link & return & return & theText
		end if
	end repeat
end tell
1 Like

Interesting approach. Thanks for sharing

Here’s a small enhancement to choose if the links should be at the bottom or the top of the file.

property stylesFolder : "Library/Application Support/Marked/Custom CSS"
property favouriteTheme : "Firates"
property linkPosition : "bottom"

set home to do shell script "echo $HOME"
set themes to paragraphs of (do shell script "for i in " & home & "/" & quoted form of stylesFolder & "/*.css; do basename \"$i\" .css; done")
set cr to ASCII character 13
set lf to ASCII character 10

set favouriteTheme to choose from list themes with prompt "Select your favorite theme:" default items favouriteTheme

tell application id "DNtp"
	set theSelection to the selection as list
	repeat with thisItem in theSelection
		if the kind of thisItem is "Markdown" then
			set thePath to the path of thisItem
			set link to "<link rel=\"stylesheet\" href=\"file://" & home & "/" & stylesFolder & "/" & favouriteTheme & ".css\">"
			set theText to do shell script "perl -pe 's|<link rel=.stylesheet.*?>||' " & quoted form of thePath & " | tr '" & cr & "' '" & lf & "' | sed -e :a -e '/[^[:blank:]]/,$!d; /^[[:space:]]*$/{ $d; N; ba' -e '}'"
			if linkPosition is "bottom" then
				set theText to theText & return & return & link
			else
				set theText to link & return & return & theText
			end if
			set the plain text of thisItem to theText
		end if
	end repeat
end tell