Advertisement
smeech

ConvertMarkdown.ps1

Nov 6th, 2024 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## Script to convert Markdown to Plain text, using an Espanso trigger:
  2.  
  3. #!/usr/bin/env pwsh
  4.  
  5. param (
  6.     [string]$markdownText
  7. )
  8.  
  9. # Function to convert Markdown to plain text
  10. function Convert-MarkdownToText {
  11.     param (
  12.         [string]$markdown
  13.     )
  14.  
  15.     # Split the input into lines to process each line individually
  16.     $lines = $markdown -split "`n"
  17.  
  18.     $inCodeBlock = $false
  19.     $plainTextLines = $lines | ForEach-Object {
  20.         # Toggle code block flag when encountering ``` lines
  21.         if ($_ -match '^\s*```') {
  22.            $inCodeBlock = -not $inCodeBlock
  23.            # Skip the ``` lines themselves
  24.            return
  25.        }
  26.  
  27.        # If inside a code block, capture content directly without modification
  28.        if ($inCodeBlock) {
  29.            return $_
  30.        }
  31.  
  32.        # Process each line for Markdown syntax if not in a code block
  33.        $_ -replace '^\s*#{1,6}\s*(.+)$', '$1' |                    # Remove headers
  34.         ForEach-Object { $_ -replace '\*\*([^\*]+)\*\*', '$1' } |    # Bold
  35.         ForEach-Object { $_ -replace '\*([^\*]+)\*', '$1' } |        # Italic
  36.         ForEach-Object { $_ -replace '__(.+?)__', '$1' } |           # Bold underline
  37.         ForEach-Object { $_ -replace '_(.+?)_', '$1' } |             # Italic underline
  38.         ForEach-Object { $_ -replace '\[([^\]]+)\]\([^\)]+\)', '$1' } | # Links
  39.         ForEach-Object { $_ -replace '!\[([^\]]*)\]\([^\)]+\)', '$1' } | # Images
  40.         ForEach-Object { $_ -replace '``(.+?)``', '$1' } |           # Inline code
  41.         ForEach-Object { $_ -replace '`(.+?)`', '$1' } |             # Inline code
  42.        ForEach-Object { $_ -replace '^\s*[-\*\+]\s+', '' } |        # Unordered list markers
  43.        ForEach-Object { $_ -replace '^\s*\d+\.\s+', '' } |          # Ordered list markers
  44.        ForEach-Object { $_ -replace '^\s*>\s+', '' } |              # Blockquotes
  45.        ForEach-Object { $_ -replace '\[\[([^\]]+)\]\]', '$1' }      # Convert [[text]] to text
  46.    }
  47.  
  48.    # Join the processed lines back into a single string
  49.    $plainText = ($plainTextLines -join "`n").Trim()
  50.  
  51.    return $plainText
  52. }
  53.  
  54. # Convert markdownText from input
  55. $plainText = Convert-MarkdownToText -markdown $markdownText
  56. Write-Output $plainText
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement