Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

Markdownのimglinkタグ行のリンク書き換え

Posted on 5月 3, 2018 by Takaaki Naganoya

Markdown書類からリンクしているローカルの画像(相対パス表記)へのリンクを書き換えるAppleScriptです。

MacDownが画像リンクの管理などは一切してくれないので、自前で(AppleScriptで)書き換えを行なっています。

ルートフォルダはフォルダ名が「–」ではじまるようにルールを(勝手に)決めており、各Markdown書類フォルダをさらに細分化した場合には、Markdown書類から画像フォルダへの相対パス指定が合わなくなってしまいます。

そこで、画像フォルダを求めてMarkdown書類の画像リンクを再計算して書き換えてみました。画像自体をルートフォルダからSpotlightで検索するようにしてもよいのですが、今回はとりあえずルールを自分で決めて自分で守っているので、このように処理してみました。

ただ、いまだにリンク画像のパスを手で書かされる(記述自体はAppleScriptでその場で計算しているので完全手書きではないですが)のには、いささかMarkdownの仕様の素朴さに呆れてしまうところです、、、、

AppleScript名:Markdownのimglinkタグ行のリンク書き換え
— Created 2017-01-26 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use mdLib : script "Metadata Lib" version "2.0.0" –https://www.macosxautomation.com/applescript/apps/

property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSScanner : a reference to current application’s NSScanner
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary
property NSMutableArray : a reference to current application’s NSMutableArray
property NSDataDetector : a reference to current application’s NSDataDetector
property NSAttributedString : a reference to current application’s NSAttributedString
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSTextCheckingTypeLink : a reference to current application’s NSTextCheckingTypeLink

set origPath to POSIX path of (choose folder with prompt "Markdown書類が入っているフォルダを選択")
set savePath to POSIX path of (choose folder with prompt "画像フォルダを選択")

set tmp2 to NSString’s stringWithString:savePath
set tmp3 to (tmp2’s lastPathComponent()) as string

–Spotlightで指定フォルダ以下のMarkdown書類を検索
set aRes to mdLib’s searchFolders:{origPath} searchString:("kMDItemKind == %@ ") searchArgs:{"Markdown Document"}

repeat with i in aRes
  
  
–テキストエンコーディングをUTF-8でMarkDown書類テキスト読み込み
  
set aText to (NSString’s stringWithContentsOfFile:(i) encoding:(NSUTF8StringEncoding) |error|:(missing value)) as string
  
  
–Markdown記法の画像タグが入っている場合のみ処理
  
set repLinkURLs to {} –パス置換対象リスト(oldPath, newPathでペア)
  
  
set aFreq to retFrequency(aText, "![") of me
  
  
if aFreq is not equal to 0 then
    set bList to parseStringParagraphs(NSString’s stringWithString:aText) of me
    
set aPredicates to NSPredicate’s predicateWithFormat_("SELF BEGINSWITH[cd] %@", "![")
    
set cList to (bList’s filteredArrayUsingPredicate:aPredicates) as list
    
    
–画像ダウンロードおよび、ダウンロードずみ画像への相対パスの計算ループ
    
repeat with ii in cList
      set jj to contents of ii –画像リンクのMarkdownタグ行
      
set tmpLinkPath to parseStrFromTo(jj, "(", ")") of me
      
      
set aStr to (NSString’s stringWithString:((contents of i) as string))
      
set aList to (aStr’s stringByDeletingLastPathComponent’s pathComponents()) as list of string or string
      
      
set aLen to length of aList
      
      
–リンク画像の相対パスを絶対パスに変換する
      
set rStr to (NSString’s stringWithString:tmpLinkPath)
      
set r2Str to rStr’s stringByDeletingLastPathComponent’s lastPathComponent() –フォルダ名(="9999_images")
      
set r3Str to (rStr’s lastPathComponent()) as string –ファイル名(="fake_scriptable.png")
      
      
–書籍のルートフォルダを求め、その直下にある画像フォルダを名指しで指定
      
repeat with i2 from aLen to 0 by -1
        set j to contents of (item i2 of aList)
        
if j begins with "–" then
          exit repeat
        end if
      end repeat
      
      
set f1Path to (items 1 thru i2 of aList) & r2Str & r3Str
      
set f2Path to (NSString’s pathWithComponents:f1Path) as string
      
      
–MarkDown書類と移動先の画像フォルダ中の画像の相対パスを求める
      
set newRelPath to calcRelativePathFromTwoAbsolutePaths(i, f2Path) of me
      
      
set the end of repLinkURLs to {tmpLinkPath, newRelPath}
      
    end repeat
    
    
–リンク書き換え
    
copy aText to bText
    
repeat with ii in repLinkURLs
      copy ii to {oldPath, newPath}
      
set bText to repChar(bText, oldPath, newPath) of me
    end repeat
    
    
–もともとのパスにMarkdown書類を上書き保存
    
set writeString to (NSString’s stringWithString:bText)
    
set ssRes to (writeString’s writeToFile:i atomically:true encoding:(NSUTF8StringEncoding) |error|:(missing value))
    
  end if
end repeat

–指定文字列内の指定キーワードの出現回数を取得する
on retFrequency(origText, aKeyText)
  set aRes to parseByDelim(origText, aKeyText) of me
  
return ((count every item of aRes) – 1)
end retFrequency

on parseByDelim(aData, aDelim)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set dList to text items of aData
  
set AppleScript’s text item delimiters to curDelim
  
return dList
end parseByDelim

–テキストを行ごとにparseしてNSArrayに
on parseStringParagraphs(anNSString)
  set anArray to NSMutableArray’s alloc()’s init()
  
set aRange to current application’s NSMakeRange(0, anNSString’s |length|())
  
  
repeat while aRange’s |length|() > 0
    set subRange to anNSString’s lineRangeForRange:(current application’s NSMakeRange(aRange’s location(), 0))
    
    
–行が改行コードまで取得されるので、改行コードを除外するように微調整
    
copy subRange to tmpRange
    
set tmpRange’s |length| to ((subRange’s |length|()) – 1) –微調整
    
set aLine to anNSString’s substringWithRange:tmpRange
    
anArray’s addObject:aLine
    
    
set aRange’s location to (current application’s NSMaxRange(subRange))
    
set aRange’s |length| to ((aRange’s |length|()) – (subRange’s |length|()))
  end repeat
  
  
return anArray
end parseStringParagraphs

on repChar(origText, targStr, repStr)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

on parseStrFromTo(aParamStr, fromStr, toStr)
  set theScanner to NSScanner’s scannerWithString:aParamStr
  
set anArray to NSMutableArray’s array()
  
  
repeat until (theScanner’s isAtEnd as boolean)
    — terminate check, return the result (aDict) to caller
    
set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference)
    
    
— skip over separator
    
theScanner’s scanString:fromStr intoString:(missing value)
    
set {theResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference)
    
if theValue is missing value then set theValue to "" –>追加
    
    
— skip over separator
    
theScanner’s scanString:toStr intoString:(missing value)
    
    
anArray’s addObject:theValue
  end repeat
  
  
if (anArray’s |count|()) as integer = 1 then
    return theValue as list of string or string
  else
    return anArray as list
  end if
end parseStrFromTo

–2つの絶対パス間の相対パスを求める
on calcRelativePathFromTwoAbsolutePaths(aPOSIXfile as string, bPOSIXfile as string)
  set aStr to NSString’s stringWithString:aPOSIXfile
  
set bStr to NSString’s stringWithString:bPOSIXfile
  
  
set aList to aStr’s pathComponents() as list
  
set bList to bStr’s pathComponents() as list
  
  
set aLen to length of aList
  
set bLen to length of bList
  
  
if aLen ≥ bLen then
    copy aLen to aMax
  else
    copy bLen to aMax
  end if
  
  
repeat with i from 1 to aMax
    set aTmp to contents of item i of aList
    
set bTmp to contents of item i of bList
    
    
if aTmp is not equal to bTmp then
      exit repeat
    end if
  end repeat
  
  
set bbList to items i thru -1 of bList
  
set aaItem to (length of aList) – i
  
  
set tmpStr to {}
  
repeat with ii from 1 to aaItem
    set the end of tmpStr to ".."
  end repeat
  
  
set allRes to NSString’s pathWithComponents:(tmpStr & bbList)
  
return allRes as text
end calcRelativePathFromTwoAbsolutePaths

★Click Here to Open This Script 

More from my site

  • CotEditorで編集中のMarkdown書類をPDFプレビューCotEditorで編集中のMarkdown書類をPDFプレビュー
  • Numbersの選択中の表を取得してMarkdown書式の表に変換する v2Numbersの選択中の表を取得してMarkdown書式の表に変換する v2
  • MacDownで編集中のMarkDown書類で見出しが見出し落ちしていないかチェックMacDownで編集中のMarkDown書類で見出しが見出し落ちしていないかチェック
  • Wikipedia経由で2つの単語の共通要素を計算するcommon elements Lib Script LibraryWikipedia経由で2つの単語の共通要素を計算するcommon elements Lib Script Library
  • 画面上の指定座標にマウスカーソルを強制移動させてクリック画面上の指定座標にマウスカーソルを強制移動させてクリック
  • checkboxLibをアップデート(3)sdefにサンプルドキュメントを入れるcheckboxLibをアップデート(3)sdefにサンプルドキュメントを入れる
(Visited 129 times, 1 visits today)
Posted in file File path Markdown Spotlight Text | Tagged 10.11savvy 10.12savvy 10.13savvy MacDown | Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • Xcode 14.2でAppleScript App Templateを復活させる
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • 従来と異なるmacOS 13の性格?
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib
  • macOS 12.5.1、11.6.8でFinderのselectionでスクリーンショット画像をopenできない問題
  • macOS 13でNSNotFoundバグふたたび
  • ChatGPTでchatに対する応答文を取得
  • 新発売:iWork Scripting Book with AppleScript
  • Finderの隠し命令openVirtualLocationが発見される
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • あのコン過去ログビューワー(暫定版)

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (277) 12.0savvy (185) 13.0savvy (55) CotEditor (60) Finder (47) iTunes (19) Keynote (98) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (56) Pages (37) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKUserScriptInjectionTimeAtDocumentEnd (18) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC