Skip to content

Instantly share code, notes, and snippets.

@mofosyne
Created July 30, 2024 11:53
Show Gist options
  • Save mofosyne/e0df76ed1daccc3f7667da333c5413b4 to your computer and use it in GitHub Desktop.
Save mofosyne/e0df76ed1daccc3f7667da333c5413b4 to your computer and use it in GitHub Desktop.
For markdown inline code. Find the longest contiguous sequence of backticks in the string then wrap string with appropriate number of backticks required to escape it
def escape_markdown_inline_code(value_string):
# Find the longest contiguous sequence of backticks in the string then
# wrap string with appropriate number of backticks required to escape it
max_backticks = max((len(match.group(0)) for match in re.finditer(r'`+', value_string)), default=0)
inline_code_marker = '`' * (max_backticks + 1)
# If the string starts or ends with a backtick, add a space at the beginning and end
if value_string.startswith('`') or value_string.endswith('`'):
value_string = f" {value_string} "
return f"{inline_code_marker}{value_string}{inline_code_marker}"
@mofosyne
Copy link
Author

Created for ggml-org/llama.cpp#8588 but may be useful for others

This is the expected output.

>>> escape_markdown_inline_code("hello world")
'`hello world`'
>>> escape_markdown_inline_code("hello ` world")
'``hello ` world``'
>>> escape_markdown_inline_code("hello `` world")
'```hello `` world```'
>>> escape_markdown_inline_code("`hello world`")
'`` `hello world` ``'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment