Last active
August 29, 2015 14:06
-
-
Save pierre3/b17830375b620d1557a5 to your computer and use it in GitHub Desktop.
お好みのテキストエディタにMarkdownプレビュー機能を追加するPowerShellスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# このスクリプト自身が格納されているディレクトリを取得 | |
$Script:scriptDir = Split-Path $MyInvocation.MyCommand.Definition -Parent | |
<# | |
.Synopsis | |
Markdownテキストのプレビュー | |
.DESCRIPTION | |
Markdown形式で記述されたテキストファイルの内容をHTMLに変換し、ブラウザでプレビュー表示します。 | |
.EXAMPLE | |
PS C:\> Start-Markdown .\markdownText.md | |
#> | |
function Start-Markdown | |
{ | |
Param( | |
# Markdownテキストファイルのパス | |
[string]$Path | |
) | |
# HTMLテンプレート | |
$html= | |
@' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Markdown Preview</title> | |
</head> | |
<body> | |
{0} | |
</body> | |
</html> | |
'@ | |
# 指定したファイルが無ければ作る | |
if(-not(Test-Path $Path)) | |
{ | |
New-Item $Path -ItemType file -Force | |
} | |
# Markdownテキストが格納されているディレクトリをフルパスで取得 | |
$sourceDir = Split-Path (Get-ChildItem $Path).FullName -Parent | |
# プレビュー用HTMLの保存先 | |
$previewDir = "$scriptDir\Html" | |
if(-not(Test-Path $previewDir)) | |
{ | |
New-Item $previewDir -ItemType directory | |
} | |
$previewPath = "$previewDir\MarkdownPreview.html" | |
# MarkdownSharpのコンパイル & Markdown オブジェクトの生成 | |
Add-Type -Path "$scriptDir\CSharp\MarkdownSharp.cs" ` | |
-ReferencedAssemblies System.Configuration | |
$markdown = New-Object MarkdownSharp.Markdown | |
# Internet Exploroler を起動 | |
$ie = New-Object -ComObject InternetExplorer.Application | |
$ie.StatusBar = $false | |
$ie.AddressBar = $false | |
$ie.MenuBar = $false | |
$ie.ToolBar = $false | |
# Markdownテキストファイルの内容を変換してHTMLファイルとして保存 | |
$rawText = Get-Content $Path -raw | |
$html -f $markdown.Transform($rawText) | Out-File $previewPath -Encoding utf8 | |
# ブラウザで表示 | |
$ie.Navigate($previewPath) | |
$ie.Visible = $true | |
# Markdownテキストファイルの変更を監視する File Watcherを生成 | |
$watcher = New-Object System.IO.FileSystemWatcher | |
$watcher.Path = $sourceDir | |
$watcher.Filter = Split-Path $Path -Leaf | |
$watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor [System.IO.NotifyFilters]::LastWrite | |
# Markdownテキストファイルを、その拡張子に関連付けされたアプリケーション(エディタ)で起動する | |
start $Path | |
# ファイルが変更されるのを監視し、変更されたらMarkdownテキストをHTMLに変換してInternet Explorerでプレビューする | |
while($ie.ReadyState -ne $null) | |
{ | |
$result = $watcher.WaitForChanged([System.IO.WatcherChangeTypes]::Changed, 5000) | |
if(-not $result.TimedOut) | |
{ | |
$rawText = Get-Content $Path -raw | |
$html -f $markdown.Transform($rawText) | Out-File $previewPath -Encoding utf8 | |
$ie.Refresh() | |
} | |
Start-Sleep -Milliseconds 100 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment