| AppleScript名:iTunesライブラリのジャンル集計 |
| — Created 2016-11-02 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "iTunesLibrary" –http://piyocast.com/as/archives/4301 set library to current application’s ITLibrary’s libraryWithAPIVersion:"1.0" |error|:(missing value) if library is equal to missing value then return set playLists to library’s allPlaylists() set gArray to library’s allMediaItems()’s genre set aRes to countItemsByItsAppearance(gArray) of me –> {{theName:"サウンドトラック", numberOfTimes:1722}, {theName:"ロック", numberOfTimes:956}, {theName:"Podcast", numberOfTimes:721}, {theName:"クラシック", numberOfTimes:540}, {theName:"ポップ", numberOfTimes:529}, {theName:"J-Pop", numberOfTimes:382}, {theName:"アニメ", numberOfTimes:332}, {theName:missing value, numberOfTimes:287}, {theName:"Pop", numberOfTimes:279}, {theName:"社会/文化", numberOfTimes:279}, {theName:"World", numberOfTimes:218}, {theName:"ジャズ", numberOfTimes:188}, {theName:"Soundtrack", numberOfTimes:188}, {theName:"エレクトロニック", numberOfTimes:170}, {theName:"Classical", numberOfTimes:166}, {theName:"iTunes U", numberOfTimes:155}, {theName:"Rock", numberOfTimes:148}, {theName:"R&B", numberOfTimes:125}, {theName:"ニューエイジ", numberOfTimes:104}, {theName:"Unclassifiable", numberOfTimes:81}, {theName:"歌謡曲", numberOfTimes:58}, {theName:"オルタナティブ", numberOfTimes:58}, {theName:"Children’s", numberOfTimes:57}, {theName:"Holiday", numberOfTimes:38}, {theName:"Data", numberOfTimes:32}, {theName:"イージーリスニング", numberOfTimes:31}, {theName:"ワールド", numberOfTimes:30}, {theName:"ヴォーカル", numberOfTimes:29}, {theName:"ヒップホップ/ ラップ", numberOfTimes:24}, {theName:"Anime", numberOfTimes:23}, {theName:"フォーク", numberOfTimes:19}, {theName:"soundtrack", numberOfTimes:19}, {theName:"ブルース", numberOfTimes:15}, {theName:"ディズニー", numberOfTimes:15}, {theName:"シンガーソングライター", numberOfTimes:15}, {theName:"Easy Listening", numberOfTimes:14}, {theName:"ラテン", numberOfTimes:14}, {theName:"個人ジャーナル", numberOfTimes:14}, {theName:"Electronica/Dance", numberOfTimes:14}, {theName:"J-POP", numberOfTimes:9}, {theName:"New Age", numberOfTimes:9}, {theName:"アクション/アドベンチャー", numberOfTimes:9}, {theName:"ダンス", numberOfTimes:9}, {theName:"マンガ", numberOfTimes:7}, {theName:"演歌", numberOfTimes:7}, {theName:"プログラミング", numberOfTimes:7}, {theName:"Video", numberOfTimes:5}, {theName:"ホリデー", numberOfTimes:5}, {theName:"青年", numberOfTimes:5}, {theName:"キッズ/ファミリー", numberOfTimes:5}, {theName:"カントリー", numberOfTimes:4}, {theName:"R&B/ソウル", numberOfTimes:4}, {theName:"科学/医学", numberOfTimes:4}, {theName:"ビジネス", numberOfTimes:3}, {theName:"Latin", numberOfTimes:3}, {theName:"ヒップホップ/ラップ", numberOfTimes:3}, {theName:"チルドレン・ミュージック", numberOfTimes:3}, {theName:"#NIPPONSEI @ IRC.MIRCX.COM", numberOfTimes:2}, {theName:"コメディ", numberOfTimes:2}, {theName:"Technology", numberOfTimes:2}, {theName:"R&B/ソウル", numberOfTimes:2}, {theName:"ファンタジー", numberOfTimes:2}, {theName:"ユーティリティ", numberOfTimes:2}, {theName:"Vocal", numberOfTimes:2}, {theName:"ドラマ", numberOfTimes:2}, {theName:"社会科学", numberOfTimes:1}, {theName:"グラフィックノベル", numberOfTimes:1}, {theName:"コンピュータ/テクノロジー", numberOfTimes:1}, {theName:"伝記/自叙伝", numberOfTimes:1}, {theName:"女性", numberOfTimes:1}, {theName:"科学/自然", numberOfTimes:1}, {theName:"その他", numberOfTimes:1}, {theName:"児童書フィクション", numberOfTimes:1}, {theName:"業界/職業", numberOfTimes:1}, {theName:"レゲエ", numberOfTimes:1}, {theName:"Lifestyle & Home", numberOfTimes:1}, {theName:"マネジメント/リーダーシップ", numberOfTimes:1}, {theName:"スポークンワード", numberOfTimes:1}, {theName:"Dance", numberOfTimes:1}, {theName:"インストゥルメンタル", numberOfTimes:1}, {theName:"ライトノベル", numberOfTimes:1}, {theName:"SF/ファンタジー", numberOfTimes:1}, {theName:"ソーシャルネットワーキング", numberOfTimes:1}, {theName:"コンピュータ", numberOfTimes:1}, {theName:"146", numberOfTimes:1}, {theName:"健康/フィットネス", numberOfTimes:1}, {theName:"148", numberOfTimes:1}, {theName:"Electronic", numberOfTimes:1}, {theName:"仕事効率化", numberOfTimes:1}, {theName:"ライフスタイル", numberOfTimes:1}, {theName:"フィクション/文学", numberOfTimes:1}, {theName:"NHK FM(東京)", numberOfTimes:1}, {theName:"Seattle Pacific University – Latin", numberOfTimes:1}, {theName:"インスピレーショナル", numberOfTimes:1}, {theName:"日本/アジア", numberOfTimes:1}, {theName:"ブック", numberOfTimes:1}, {theName:"Kayokyoku", numberOfTimes:1}, {theName:"Folk", numberOfTimes:1}, {theName:"Romance", numberOfTimes:1}} –出現回数で集計 on countItemsByItsAppearance(aList) set aSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList set bArray to current application’s NSMutableArray’s array() set theEnumerator to aSet’s objectEnumerator() repeat set aValue to theEnumerator’s nextObject() if aValue is missing value then exit repeat bArray’s addObject:(current application’s NSDictionary’s dictionaryWithObjects:{aValue, (aSet’s countForObject:aValue)} forKeys:{"theName", "numberOfTimes"}) end repeat –出現回数(numberOfTimes)で降順ソート set theDesc to current application’s NSSortDescriptor’s sortDescriptorWithKey:"numberOfTimes" ascending:false bArray’s sortUsingDescriptors:{theDesc} return bArray as list end countItemsByItsAppearance |
Googleで検索して結果を返す v2
Webブラウザを併用せず、Googleの検索エンジンに直接問い合わせを行い、結果をCocoaの機能を用いて検索結果URLの一覧を取得するAppleScriptです。
オリジナル v1はShane Stanleyが作成、あまりに洗練された処理内容に絶句しました。さらに、処理内容が内容だけに、Shaneから見せられて「掲載はちょっと検討させて」と返事をしてしまったほど。
他のプログラミング言語でも同様の実装例が見られたので、問題視されないレベルと判断して掲載しました。
ただ、その一方でオリジナル版からの改良も行い、オリジナルでは20件ぐらいだった検索件数の拡張を行なって100件までの検索が行えるようにしたものがこのv2です。
長期間かつ大量の検索をGoogleの検索エンジンに対して行う場合には、REST API経由で行なってください。
追記(2019/08/20)
しばらく動いていましたが、Google側のWeb表示の仕様が変わって検索できなくなりました。ただし、検索結果のNSXMLDocumentからのURL抽出処理を変更することで、対応は可能と思われます(やっていませんが)。REST APIのドキュメント化された仕様は変わらないため、検索を行うにはREST API経由のほうが安心です。
追記(2020)
CotEditorのPowerPackにこれの改訂版を入れてあり、CotEditorで選択中の語句でGoogle検索できるようにしてあります。これの動作状況で様子を見ているところです。
| AppleScript名:Googleで検索して結果を返す v4 |
| — Created 2017-03-31 by Shane Stanley — Modified 2019-09-18 by Takaaki Naganoya use AppleScript version "2.4" use framework "Foundation" use scripting additions property theResult : {} set theQuery to "戦場の絆" set paramObj to {myQuery:theQuery, myMax:10} my performSelectorOnMainThread:"searchByGoogle:" withObject:(paramObj) waitUntilDone:true return my theResult –> {"http://web.gundam-kizuna.jp/sp/",…….} on searchByGoogle:paramObj set theQuery to myQuery of paramObj set maxNum to myMax of paramObj — build and escape query string set theQuery to current application’s NSString’s stringWithString:theQuery set theQuery to theQuery’s stringByReplacingOccurrencesOfString:space withString:"+" set escQuery to theQuery’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s URLQueryAllowedCharacterSet()) — do search set searchURLString to current application’s NSString’s stringWithFormat_("https://www.google.com/search?client=safari&rls=en&ie=UTF-8&oe=UTF-8&q=%@&complete=0&num=%@&as_qdr=all", escQuery, (maxNum as string)) set theURL to current application’s |NSURL|’s URLWithString:searchURLString set {theData, theError} to current application’s NSData’s dataWithContentsOfURL:theURL options:0 |error|:(reference) if theData = missing value then error (theError’s localizedDescription() as text) — convert to XML set {theXMLDoc, theError} to current application’s NSXMLDocument’s alloc()’s initWithData:theData options:(current application’s NSXMLDocumentTidyHTML) |error|:(reference) if theXMLDoc = missing value then error (theError’s localizedDescription() as text) –検索結果として返してくるclass要素名を固定で書かない方法を模索するべき? — filter via XPath and predicate set xpathStr to "//*[@class=\"kCrYT\"]/a/@href" –ここが問題 set {theNodes, theError} to theXMLDoc’s nodesForXPath:xpathStr |error|:(reference) if theNodes = missing value then error (theError’s localizedDescription() as text) set nodeStrings to (theNodes’s valueForKey:"stringValue") set thePred to current application’s NSPredicate’s predicateWithFormat:"self BEGINSWITH ’/url?q=’" set nodeStrings to nodeStrings’s filteredArrayUsingPredicate:thePred — trim URL strings set theURLStrings to {} repeat with aString in nodeStrings set theOffset to (aString’s rangeOfString:"&") set end of theURLStrings to (aString’s substringWithRange:{7, (theOffset’s location) – 7}) as text end repeat set my theResult to theURLStrings end searchByGoogle: |
Safariのダウンロードフォルダを求めるv4
本ScriptはSafariのダウンロードフォルダのパスを求めるためのものですが、macOSおよびSafariのアップデートによって動かなくなりました。
現時点では設定値からダウンロードフォルダを知ることはできないようです。セキュリティ上「できては困る」という判断が行われたものでしょうか。
なので、Spotlightの機能を用いて、「Download」フォルダを検索し、見つかったものの一覧からユーザーに選んでもらうとか、デフォルト状態のDownloadフォルダを指定してみて存在しなかったらユーザーに選択してもらうといった方法になると思われます。
| AppleScript名:Safariのダウンロードフォルダを求めるv4 |
| use AppleScript version "2.4" use scripting additions use framework "Foundation" getSafariDownloadFolder() of me –> alias "Cherry:Users:me:Downloads:" –By Phillip Aker, Mark J Reed on getSafariDownloadFolder() set preferencesPath to POSIX path of (path to preferences) set bundleId to bundle identifier of (info for (path to application "Safari")) set safariPrefsFile to preferencesPath & bundleId & ".plist" tell application "System Events" to set folderName to get value of property list item "DownloadsPath" of property list file safariPrefsFile set pathString to current application’s NSString’s stringWithString:folderName set dlPath to pathString’s stringByExpandingTildeInPath() as string return (POSIX file dlPath) as alias end getSafariDownloadFolder |
ダークモード/ライトモードの切り替え
Dark Modeのトグル切り替えを行うAppleScriptです。
System Eventsに問い合わせて、appearance preferencesのDark Modeがtrueならダークモード、Dark Modeがfalseならライトモード(通常モード)です。
# Mac App Store用アプリケーションの中で使うとリジェクトの原因になります
| AppleScript名:ダークモードの検出 v2 |
| tell application "System Events" tell appearance preferences set dark mode to not dark mode end tell end tell |
Safariの最前面のWindowに新規tabをURLを指定しつつ作成
| AppleScript名:Safariの最前面のWindowに新規tabをURLを指定しつつ作成 |
| tell application "Safari" tell window 1 make new tab with properties {URL:"http://piyocast.com/as/"} end tell end tell |
最前面のウィンドウのタイトルを取得する2
| AppleScript名:最前面のウィンドウのタイトルを取得する2 |
| set aTitle to getPageTitleOfFrontmostWindow()
on getPageTitleOfFrontmostWindow() tell application "Safari" if (count every window) = 0 then return false tell window 1 set aProp to properties end tell set aDoc to document of aProp set aText to name of aDoc end tell return aText end getPageTitleOfFrontmostWindow |
Safariで選択部分のテキストを取得する2
| AppleScript名:Safariで選択部分のテキストを取得する2 |
| tell application "Safari" set aRes to do JavaScript "var selObj = window.getSelection(); var selStr = (selObj).getRangeAt(0); unescape(selStr);" in document 1 end tell aRes |
Safariの最前面のドキュメントのテキストを取得するv2
| AppleScript名:Safariの最前面のドキュメントのテキストを取得するv2 |
| –フレームを使っていないことが前提条件 tell application "Safari" set wCount to count every window if wCount = 0 then display dialog "Safariでウィンドウがオープンされていません" buttons {"OK"} default button 1 return end if tell front document set aURL to URL –> http://piyocast.com/as/archives/155 set aTitle to name –> "SafariでURLをローディング – AppleScirpt Hole" –set aCon to text –log aCon end tell set aText to text of front document –本文テキスト end tell |
SafariでURLをローディング
本処理は最近のSafariでは正しくローディング検出できないようになってきたため、書き直したルーチン「SafariでURLローディング完了検出」を利用してください。
| AppleScript名:SafariでURLをローディング |
| set aURL to "http://www.piyocast.com/as/" –set aURL to "" tell application "Safari" set d to count every window if d = 0 then make new window tell document 1 set URL to aURL end tell else if aURL is not equal to "" then tell document 1 set URL to aURL end tell end if end if page_loaded(10) of me set a to do JavaScript "document.title" in document 1 end tell on page_loaded(timeout_value) repeat with i from 1 to (timeout_value * 10) tell application "Safari" if (do JavaScript "document.readyState" in document 1) is "complete" then return true else if i is the timeout_value then return false else delay 0.1 end if end tell end repeat return false end page_loaded |
TextEditで色置換 v2
| AppleScript名:TextEditで色置換 v2 |
| — Created 2018-01-09 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html load framework (* set targColor to {65535, 10023, 4626} set newColor to {19018, 0, 59109} repTextEditColor(targColor, newColor) of me *) set targColor to {19018, 0, 59109} set newColor to {65535, 10023, 4626} repTextEditColor(targColor, newColor) of me on repTextEditColor(targColor, newColor) set hitIndex to {} tell application "TextEdit" tell text of front document set colList to color of every attribute run end tell end tell set hitIndex to (current application’s SMSForder’s indexesOfItem:targColor inArray:(colList) inverting:false) as list tell application "TextEdit" tell text of front document repeat with i in hitIndex ignoring application responses set color of attribute run (i + 1) to newColor –0 based index to 1 based index conversion end ignoring end repeat end tell end tell end repTextEditColor |
指定のテキストファイルをオープンする
| AppleScript名:指定のテキストファイルをオープンする |
| set a to choose file file of type {"public.plain-text"} tell application "TextEdit" open a end tell |
TextEditでmake時にデータを与えつつ新規ドキュメント作成
| AppleScript名:TextEditでmake時にデータを与えつつ新規ドキュメント作成 |
| set a to "あいうえお"
tell application "TextEdit" make new document with properties {text:a} end tell |
TextEditの文章のうち赤くマークされた行をカウントする
macOS標準装備のテキストエディットで編集中の文章のうち、赤くマークされた行をカウントするAppleScriptです。
RGB値で抽出してカウントします。30年前からやっている原始レベルの処理です。値が同じ箇所を抽出するだけならバカでもできます。
いま現在AppleScriptで実現しているのは、「赤っぽい色」の箇所を抽出する「カラードメイン処理」です。RGB値だと値が1つでも違っていたら別物として判定されてしまいますが、カラードメイン処理では「赤系統の色」を計算して判定できるものです。
→ TextEditの文章のうち赤っぽい色でマークされた箇所をピックアップする v2
→ TextEditの文章のうち赤っぽい色でマークされた行をカウントする v2
→ TextEdit本文色に応じて青っぽい色は男性の音声で、赤っぽい色は女性の音声で読み上げ
| AppleScript名:TextEditの文章のうち赤くマークされた行をカウントする |
| set rNum to 0
tell application "TextEdit" tell text of document 1 set pCount to (count paragraphs) repeat with i from 1 to pCount set aCol to color of paragraph i if aCol = {65535, 0, 0} then –{r, g, b} set rNum to rNum + 1 end if end repeat end tell end tell return {pCount, rNum} |
TextEditで文字数をカウントする
| AppleScript名:TextEditで文字数をカウントする |
| tell application "TextEdit" tell front document set a to text of it end tell set tLen to length of a display dialog (tLen as string) & "文字です" with title "この文章の文字数は…" buttons {"OK"} default button 1 with icon 1 end tell –18058 |
TextEditの本文取得
| AppleScript名:TextEditの本文取得 |
| tell application "TextEdit" tell front document set a to text of it end tell end tell |
CotEditor 3の選択範囲を書き換える
| AppleScript名:CotEditor 3の選択範囲を書き換える |
| tell application "CotEditor" tell document 1 properties of selection –> {range:{0, 4}, class:text selection, line range:{1, 1}, contents:"似ている"} set contents of selection to "ほぼおなじ" end tell end tell |
CotEditorでオープン中の最前面の書類の本文テキストを取得する
| AppleScript名:CotEditorでオープン中の最前面の書類の本文テキストを取得する |
| set aRes to getCotEditorText() of me
on getCotEditorText() tell application "CotEditor" if (count every document) = 0 then return false tell front document set aText to contents end tell end tell end getCotEditorText |
CotEditorの最前面で表示中のDocumentを縦書き表示に
CotEditorで表示中のテキストファイルを、GUI Scripting経由で縦書き表示するAppleScriptです。
CotEditorの途中のバージョンでメニュー構成が変更になったため、本Scriptは動かなくなりました。
とりあえず、メニュー変更に追従して書き換えを行なって使っていましたが、根本的な解決策を1024jpさんに教えてもらえたので(Xattributeの書き換え)、そちらをおすすめします。
| AppleScript名:CotEditorの最前面で表示中のDocumentを縦書き表示に |
| makeWinVertical() of me
on makeWinVertical() activate application "CotEditor" tell application "System Events" tell process "CotEditor" try click menu item "縦書きで表示" of menu 1 of menu bar item "フォーマット" of menu bar 1 end try end tell end tell end makeWinVertical |
表示中のCotEditor書類と同じフォルダでラベルがついているものから選択して表示
| AppleScript名:表示中のCotEditor書類と同じフォルダでラベルがついているものから選択して表示 |
| — Created 2017-12-15 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use bPlus : script "BridgePlus" use mdLib : script "Metadata Lib" version "1.0.0" property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles property NSPredicate : a reference to current application’s NSPredicate property NSMutableArray : a reference to current application’s NSMutableArray property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants property NSFileManager : a reference to current application’s NSFileManager property |NSURL| : a reference to current application’s |NSURL| property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants property NSArray : a reference to current application’s NSArray property NSSortDescriptor : a reference to current application’s NSSortDescriptor property SMSForder : a reference to current application’s SMSForder load framework tell application "CotEditor" set dCount to count every document if dCount = 0 then return tell front document set curPath to path end tell tell window 1 set aBounds to bounds end tell end tell set aPath to current application’s NSString’s stringWithString:curPath set fileName to (aPath’s lastPathComponent()) –ファイル名 set pathExtension to aPath’s pathExtension() as string set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ –同じフォルダから同じ拡張子のファイルのファイル名を取得 –set fList to my getFilesByIncludedStringInName:(pathExtension) fromDirectory:(parentFol) exceptPackages:(true) set fList to spotlightFindByLabels({1, 2, 3, 4, 5, 6, 7}, parentFol) of me –昇順ソート set aArray to NSArray’s arrayWithArray:fList set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:" set bArray to aArray’s sortedArrayUsingDescriptors:{desc1} set cList to bArray as list set selRes to choose from list cList if selRes = false then return –Cancel set newPath to contents of first item of selRes tell application "CotEditor" set oldDoc to front document open (POSIX file newPath) as alias tell window 1 set bounds to aBounds end tell close oldDoc without saving end tell makeWinVertical() of me –縦書き表示 –Make CotEditor’s front window to Vertical display mode (Tategaki) on makeWinVertical() activate application "CotEditor" tell application "System Events" tell process "CotEditor" try click menu item "縦書きで表示" of menu 1 of menu bar item "フォーマット" of menu bar 1 end try end tell end tell end makeWinVertical on retFileFormatUTI(aExt as string) if aExt begins with "." then set aExt to text 2 thru -1 of aExt return (current application’s SMSForder’s UTIForExtension:aExt) end retFileFormatUTI on spotlightFindByLabels(aLabelList as list, thePath as string) set aList to makeRepeatinglList(length of aLabelList, "kMDItemFSLabel == %@") set aStr to retStrFromArrayWithDelimiter(aList, " OR ") of me set fRes to mdLib’s searchFolders:{thePath} searchString:aStr searchArgs:aLabelList return fRes end spotlightFindByLabels –リストを指定デリミタをはさんでテキスト化 on retStrFromArrayWithDelimiter(aList as list, aDelim as string) set anArray to current application’s NSArray’s arrayWithArray:aList return (anArray’s componentsJoinedByString:aDelim) as string end retStrFromArrayWithDelimiter –指定回数、指定アイテムを連結したリストを作成 on makeRepeatinglList(hitNum as integer, hitItem as string) set outList to {} repeat hitNum times set the end of outList to hitItem end repeat return outList end makeRepeatinglList |
表示中のCotEditor書類と同じフォルダで各書類の1行目で選択して表示
| AppleScript名:表示中のCotEditor書類と同じフォルダで各書類の1行目で選択して表示 |
| — Created 2017-12-15 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use bPlus : script "BridgePlus" use mdLib : script "Metadata Lib" version "1.0.0" use jLib : script "japaneseTextEncodingDetector" property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles property NSPredicate : a reference to current application’s NSPredicate property NSMutableArray : a reference to current application’s NSMutableArray property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants property NSFileManager : a reference to current application’s NSFileManager property |NSURL| : a reference to current application’s |NSURL| property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants property NSArray : a reference to current application’s NSArray property NSSortDescriptor : a reference to current application’s NSSortDescriptor property SMSForder : a reference to current application’s SMSForder load framework tell application "CotEditor" set dCount to count every document if dCount = 0 then return tell front document set curPath to path end tell tell window 1 set aBounds to bounds end tell end tell set aPath to current application’s NSString’s stringWithString:curPath set fileName to (aPath’s lastPathComponent()) –ファイル名 set pathExtension to aPath’s pathExtension() as string set parentFol to (aPath’s stringByDeletingLastPathComponent()) as string —親フォルダ –同じフォルダから同じ拡張子のファイルのファイル名を取得 set fList to my getFilesByIncludedStringInName:(pathExtension) fromDirectory:(parentFol) exceptPackages:(true) –昇順ソート set aArray to NSArray’s arrayWithArray:fList set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:" set bArray to aArray’s sortedArrayUsingDescriptors:{desc1} set cList to bArray as list –ダイアログ表示用のデータを作成 set ccList to {} repeat with i in cList set j to POSIX path of (i as string) set aStr to readJapanesTextFileWithGuessingEncoding(j) of jLib if aStr = missing value or aStr = false then display dialog "Encoding Error" return end if set aPath to (current application’s NSString’s stringWithString:j) set fileName to (aPath’s lastPathComponent()) as string –ファイル名 set aFirst to first item of paragraphs of aStr set the end of ccList to (fileName & " / " & aFirst) end repeat set aMes to "項目を選択してください" set selRes to retItemFromListByItemNo(ccList, aMes) of me if selRes = false then return –Cancel set newPath to contents of item selRes of cList tell application "CotEditor" set oldDoc to front document open (POSIX file newPath) as alias tell window 1 set bounds to aBounds end tell close oldDoc without saving end tell makeWinVertical() of me –縦書き表示 –Make CotEditor’s front window to Vertical display mode (Tategaki) on makeWinVertical() activate application "CotEditor" tell application "System Events" tell process "CotEditor" try click menu item "縦書きで表示" of menu 1 of menu bar item "フォーマット" of menu bar 1 end try end tell end tell end makeWinVertical on retFileFormatUTI(aExt as string) if aExt begins with "." then set aExt to text 2 thru -1 of aExt return (current application’s SMSForder’s UTIForExtension:aExt) end retFileFormatUTI on spotlightFindByLabels(aLabelList as list, thePath as string) set aList to makeRepeatinglList(length of aLabelList, "kMDItemFSLabel == %@") set aStr to retStrFromArrayWithDelimiter(aList, " OR ") of me set fRes to mdLib’s searchFolders:{thePath} searchString:aStr searchArgs:aLabelList return fRes end spotlightFindByLabels –リストを指定デリミタをはさんでテキスト化 on retStrFromArrayWithDelimiter(aList as list, aDelim as string) set anArray to current application’s NSArray’s arrayWithArray:aList return (anArray’s componentsJoinedByString:aDelim) as string end retStrFromArrayWithDelimiter –指定回数、指定アイテムを連結したリストを作成 on makeRepeatinglList(hitNum as integer, hitItem as string) set outList to {} repeat hitNum times set the end of outList to hitItem end repeat return outList end makeRepeatinglList –指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する on getFileNamesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean) set fileManager to NSFileManager’s defaultManager() set aURL to |NSURL|’s fileURLWithPath:sourceFolder set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer) + ((NSDirectoryEnumerationSkipsSubdirectoryDescendants) as integer) set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value) set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr) set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates –Remove Folders From found URL Array set anArray to NSMutableArray’s alloc()’s init() repeat with i in foundItemList set j to contents of i set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value)) –Collect files if (isDirectory as boolean = false) then (anArray’s addObject:j) else if (packageF = false) then –Allow Package files? set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(current application’s NSURLIsPackageKey) |error|:(missing value)) if (isPackage as boolean) = true then (anArray’s addObject:j) end if end if end repeat return (anArray’s valueForKey:"lastPathComponent") as list end getFileNamesByIncludedStringInName:fromDirectory:exceptPackages: –指定フォルダ内の指定文字列を含むファイル名のファイルをPOSIX pathのlistで抽出する on getFilesByIncludedStringInName:(fileNameStr as string) fromDirectory:(sourceFolder) exceptPackages:(packageF as boolean) set fileManager to NSFileManager’s defaultManager() set aURL to |NSURL|’s fileURLWithPath:sourceFolder set theOptions to ((NSDirectoryEnumerationSkipsPackageDescendants) as integer) + ((NSDirectoryEnumerationSkipsHiddenFiles) as integer) + ((NSDirectoryEnumerationSkipsSubdirectoryDescendants) as integer) set directoryContents to fileManager’s contentsOfDirectoryAtURL:aURL includingPropertiesForKeys:{} options:theOptions |error|:(missing value) set findPredicates to NSPredicate’s predicateWithFormat_("lastPathComponent CONTAINS %@", fileNameStr) set foundItemList to directoryContents’s filteredArrayUsingPredicate:findPredicates –Remove Folders From found URL Array set anArray to NSMutableArray’s alloc()’s init() repeat with i in foundItemList set j to contents of i set {theResult, isDirectory} to (j’s getResourceValue:(reference) forKey:(NSURLIsDirectoryKey) |error|:(missing value)) –Collect files if (isDirectory as boolean = false) then (anArray’s addObject:j) else if (packageF = false) then –Allow Package files? set {theResult, isPackage} to (j’s getResourceValue:(reference) forKey:(current application’s NSURLIsPackageKey) |error|:(missing value)) if (isPackage as boolean) = true then (anArray’s addObject:j) end if end if end repeat return (anArray’s valueForKey:"path") as list end getFilesByIncludedStringInName:fromDirectory:exceptPackages: –リストから選択してアイテム番号を返す on retItemFromListByItemNo(aList, aMes) set aRes to choose from list aList with prompt aMes if aRes = false then return 0 set aRes to contents of item 1 of aRes set hitNum to 1 repeat with i in aList set j to contents of i if j is equal to aRes then exit repeat end if set hitNum to hitNum + 1 end repeat return hitNum end retItemFromListByItemNo |




