Syntax Highlighting Examples
Using rehype-prism-plus for custom code snippets in MDX
Zach Scroggins
Dec 01, 2021
·2 min read
Some creative heading
Look at all the colors!
shell
npm install
npm start
lib/utils/mdx.ts
import path from 'path';
import { bundleMDX } from 'mdx-bundler';
import readingTime from 'reading-time';
import remarkGfm from 'remark-gfm';
import rehypeSlug from 'rehype-slug';
import rehypeCodeTitles from 'rehype-code-titles';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import rehypePrism from 'rehype-prism-plus';
export const prepareMDX = async (source: string) => {
// point esbuild at the correct executable for platform
if (process.platform === 'win32') {
process.env.ESBUILD_BINARY_PATH = path.join(
process.cwd(),
'node_modules',
'esbuild-windows-64',
'esbuild.exe'
);
} else {
process.env.ESBUILD_BINARY_PATH = path.join(
process.cwd(),
'node_modules',
'esbuild',
'bin',
'esbuild'
);
}
const { code } = await bundleMDX({
source,
xdmOptions(options) {
options.remarkPlugins = [...(options?.remarkPlugins ?? []), remarkGfm];
options.rehypePlugins = [
...(options?.rehypePlugins ?? []),
rehypeSlug,
rehypeCodeTitles,
rehypePrism,
[
rehypeAutolinkHeadings,
{
properties: {
className: ['anchor'],
},
},
],
] as any;
return options;
},
});
return {
code,
readingTime: readingTime(source),
};
};
main.py
import string
VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
# accepts input string and returns pig latin
def generate_pig_latin(input):
# list of words from input
word_list = input.split()
# list to hold transformed words
transformed_list = []
for word in word_list:
# separate word from punctuation
if word[-1] in string.punctuation:
real_word = word[:-1]
word_end = word[-1]
else:
real_word = word
word_end = ""
# if word starts with vowel, append "yay", add to transformed_list
if word[0] in VOWELS:
transformed_list.append(real_word + "yay" + word_end)
else:
# move all consonants from beginning to end, append "ay", add to transformed_list
vowel_present = False
for j, letter in enumerate(word):
if letter in VOWELS:
transformed_list.append(
real_word[j:] + real_word[:j] + "ay" + word_end)
vowel_present = True
break
# if no vowels just append "ay", add to transformed_list
if(vowel_present == False):
transformed_list.append(
real_word[1:] + real_word[0] + "ay" + word_end)
return ' '.join(transformed_list)
def main():
print("Welcome to the Pig Latin Generator!\n")
print("Enter a sentence to transform it to Pig Latin:\n")
# get user input
user_input = input(">>> ")
# generate pig latin from user input
pig_latin = generate_pig_latin(user_input)
# print pig latin
print("\nTransformed: ", pig_latin)
if __name__ == "__main__":
main()