カテゴリー: GUI Scripting

GUI Scripting的なUI Elementへの参照から所属するアプリケーション名を取得する

GUI Scripting的なUI Elementへの参照をもとに、そのUI Elementが所属するアプリケーション名を取得するAppleScriptです。

こんな、Safariの「ファイル」メニューの中にあるメニュー項目、

menu item “PDFとして書き出す...” of menu “ファイル” of menu bar item “ファイル” of menu bar 1 of application process “Safari”

があったとして、このオブジェクトが所属しているアプリケーション名を取得したいというケースがありました。上記の例では「Safari」がそれに該当します。

GUI Scripting的なお約束として、オブジェクト階層が上から下に向かって取得する場合には「entire contents」でまとめて取得できるのですが、下から上に向かってparentで取得できるわけでもなく、アプリケーションプロセス名をさかのぼって取得するといった処理ができていませんでした。

AppleScriptの「仕様」的には不可能です。

でも、不可能であることさえわかれば(正攻法では不可能なので)、いつものトリッキーかつ邪道な手口でなんとかなりそうです。

そうです、エラートラップ中で無理やりエラーを起こして、そのエラーメッセージの情報から取得してしまおうという、いつものやつです。

というわけで、GUI Elementの情報から所属アプリケーション名を取得できました。

最近は、さらなる「卑劣な手段」を用意しているので、そちらで華麗かつ卑劣に処理してもよかったのですが、とりあえず手短にまとめたかったのでいつものやつで処理しました。

AppleScript名:GUI Scripting的なUI Elementへの参照から所属するアプリケーション名を取得する.scptd

– Created by: Takaaki Naganoya
– Created on: 2018年09月17日

– Copyright © 2018 Piyomaru Software, All Rights Reserved

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

tell application "System Events"
set aRef to menu item "PDFとして書き出す..." of menu "ファイル" of menu bar item "ファイル" of menu bar 1 of application process "Safari"
end tell

set appName to retRootAppProcessNameFromGUIElementRef(aRef) of me
–> "Safari"

–GUI Scripting的なUI Elementへの参照から、rootのアプリケーションプロセス名を取得する
on retRootAppProcessNameFromGUIElementRef(aRef)
try
set aStr to aRef as string –force cause error
on error erM
set offsetA to offset of " of application \"System Events\"" in erM
set offsetB to offset of "«class pcap» " in erM
set appName to text (offsetB + (length of "«class pcap» ") + 1) thru (offsetA – 2) of erM
return appName as string
end try
end retRootAppProcessNameFromGUIElementRef

表示中のCotEditor書類の「次」のファイルを縦書きでオープン v2

CotEditorでオープン中の書類の「次」のファイルを縦書きでオープンするAppleScriptです。

CotEditorでオープン中の書類のパスを取得して、同一フォルダ内にあるファイル名一覧からオープン中の書類の「次」に該当する書類をオープンします。

ファイルオープン後にCotEditorのメニューをGUI Scriptingで強制的に操作して縦書きに設定します。

CotEditor v3.3.2のメニューにバグがあって、横書きのメニュー項目にも縦書きのメニュー項目にも「縦書き」と書いてあり、メニュー項目を名称で指定するとうまく動きません。そこだけItem No.で指定しています。このメニュー項目の不具合については、近い将来のアップデートで修正される見込みです。


さんかくCotEditor内蔵のScript Menuから実行するとGUI Scriptingの実行が制限されて縦書きにならない


さんかくOS側のScript Menuから実行すると問題なく実行できる

AppleScript名:表示中のCotEditor書類の「次」のファイルを縦書きでオープン v2
— 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"

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property SMSForder : a reference to current application’s SMSForder
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

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 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 aIndex to (SMSForder’s indexesOfItem:fileName inArray:bArray inverting:false) as list
if aIndex = {} then
display notification "Error: File Not Found"
return
end if

set bIndex to (contents of first item of aIndex) + 1 + 1 –0 based to 1 based conversion & next one
set aLen to length of (bArray as list)
if bIndex > aLen then
display notification "Error: Out of bounds"
return
end if

set newFile to contents of item bIndex of (bArray as list)
set newPath to parentFol & "/" & newFile

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 –縦書き表示

–指定フォルダ内の指定文字列を含むファイル名の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:(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 getFilesByIncludedStringInName:fromDirectory:exceptPackages:

–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 3 of menu 1 of menu item "文章の方向" of menu 1 of menu bar item "フォーマット" of menu bar 1
end try
end tell
end tell
end makeWinVertical

MacDownで編集中のMarkDown書類で見出しが見出し落ちしていないかチェック

MacDownで編集中のMarkdown書類をいったんデスクトップにPDF書き出しして、見出しがページ末尾に位置していないか(見出し落ち)をチェックするAppleScriptです。

MacDownのAppleScript対応機能が少ないので、ほとんどAppleScriptだけで処理しています。Cocoaの機能を呼べるようになったので、とくに問題ありません。

MacDownで編集中の最前面のMarkdown書類からパスを取得し、AppleScriptで直接ファイルから内容を読み込み、正規表現で見出し一覧を取得します。

MacDownからGUI Scripting経由でメニューをコントロールしてPDF書き出しを行い、ページ単位でPDFからテキストを抽出。不要な空白文字列などを削除。


さんかくいわゆる「見出し落ち」の状態。ページ末尾に見出し項目が存在している

各ページのテキストが見出しの内容で終了していれば、結果出力用の変数midashiOchiListに{ページ数, 見出し名称} を追加して出力します。

–> {{2, “対象となるFramework”}}

AppleScript名:MacDownで編集中のMarkDown書類で見出しが見出し落ちしていないかチェック
— Created 2017年08月12日 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "Quartz"

property NSString : a reference to current application’s NSString
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSRegularExpression : a reference to current application’s NSRegularExpression
property NSRegularExpressionAnchorsMatchLines : a reference to current application’s NSRegularExpressionAnchorsMatchLines
property NSRegularExpressionDotMatchesLineSeparators : a reference to current application’s NSRegularExpressionDotMatchesLineSeparators

set docName to getFrontmostMarkdownDocName() of me
if docName = false then return

set newName to repFileNameExtension(docName, ".pdf") of me
set newPath to (POSIX path of (path to desktop)) & newName
set dRes to deleteItemAt(newPath) of me –前回実行時にデスクトップに残った同名のPDFを削除する

–Markdownのソースを元ファイルから直接読み出す
set docSourcePath to getFrontmostMarkdownFullPath() of me
set aStr to (read (docSourcePath as alias) as «class utf8»)

–getHeader List
set aList to retHeaders(aStr) of me

–Export Markdown to PDF (desktop folder)
macDownForceSave() of me

set tList to textInPDFinEachPage(newPath) of me

set pCount to 1
set midashOchiList to {}
repeat with i in tList
set j to (contents of i) as string

repeat with ii in aList
set jj to (contents of second item of ii) as string
–set jj2 to replaceText(jj, "(", "(") of me
–set jj3 to replaceText(jj2, ")", ")") of me

if (j ends with jj) then
set the end of midashOchiList to {pCount, jj}
end if
end repeat
set pCount to pCount + 1
end repeat

return midashOchiList

on retHeaders(aCon)
set tList to {}
set regStr to "^#{1,6}[^#]*?$"

set headerList to my findPattern:regStr inString:aCon
repeat with i in headerList
set j to contents of i
set regStr2 to "^#{1,6}[^#]*?"
set headerLevel to length of first item of (my findPattern:regStr2 inString:j)
set tmpHeader1 to text (headerLevel + 1) thru -1 in j
–ヘッダーの前後から空白文字をトリミング
set tmpHeader2 to trimWhiteSpaceFromHeadAndTail(tmpHeader1) of me

–ヘッダー部でPDF書き出ししたときに全角文字が半角文字に置換されてしまうケースに対処
set tmpHeader3 to replaceText(tmpHeader2, "(", "(") of me
set tmpHeader4 to replaceText(tmpHeader3, ")", ")") of me

set the end of tList to {headerLevel, tmpHeader4}
end repeat

return tList
end retHeaders

on findPattern:thePattern inString:theString
set theOptions to ((NSRegularExpressionDotMatchesLineSeparators) as integer) + ((NSRegularExpressionAnchorsMatchLines) as integer)
set theRegEx to NSRegularExpression’s regularExpressionWithPattern:thePattern options:theOptions |error|:(missing value)
set theFinds to theRegEx’s matchesInString:theString options:0 range:{location:0, |length|:length of theString}
set theFinds to theFinds as list — so we can loop through
set theResult to {} — we will add to this
set theNSString to NSString’s stringWithString:theString
repeat with i from 1 to count of items of theFinds
set theRange to (item i of theFinds)’s range()
set end of theResult to (theNSString’s substringWithRange:theRange) as string
end repeat
return theResult
end findPattern:inString:

–指定文字列の前後から空白をトリミング
on trimWhiteSpaceFromHeadAndTail(aStr as string)
set aString to NSString’s stringWithString:aStr
set bString to aString’s stringByTrimmingCharactersInSet:(NSCharacterSet’s whitespaceAndNewlineCharacterSet())
return bString as list of string or string –as anything
end trimWhiteSpaceFromHeadAndTail

–ファイル名の拡張子を置換する
on repFileNameExtension(origName, newExt)
set aName to current application’s NSString’s stringWithString:origName
set theExtension to aName’s pathExtension()
if (theExtension as string) is not equal to "" then
set thePathNoExt to aName’s stringByDeletingPathExtension()
set newName to (thePathNoExt’s stringByAppendingString:newExt)
else
set newName to (aName’s stringByAppendingString:newExt)
end if

return newName as string
end repFileNameExtension

on textInPDFinEachPage(thePath)
set aList to {}

set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePath)
set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL

set theCount to theDoc’s pageCount() as integer

repeat with i from 1 to theCount
set thePage to (theDoc’s pageAtIndex:(i – 1))
set curStr to (thePage’s |string|())
set curStr2 to curStr’s decomposedStringWithCanonicalMapping() –Normalize Text with NFC
set targString to string id 13 & string id 10 & string id 32 & string id 65532 –Object Replacement Character
set bStr to (curStr2’s stringByTrimmingCharactersInSet:(current application’s NSCharacterSet’s characterSetWithCharactersInString:targString))
set the end of aList to (bStr as string)
end repeat

return aList
end textInPDFinEachPage

–注意!! ここでGUI Scriptingを使用。バージョンが変わったときにメニュー階層などの変更があったら書き換え
on macDownForceSave()
activate application "MacDown"
tell application "System Events"
tell process "MacDown"
— File > Export > PDF
click menu item 2 of menu 1 of menu item 14 of menu 1 of menu bar item 3 of menu bar 1

–Go to Desktop Folder
keystroke "d" using {command down}

–Save Button on Sheet
click button 1 of sheet 1 of window 1
end tell
end tell
end macDownForceSave

on getFrontmostMarkdownDocName()
tell application "MacDown"
set dList to every document
set dCount to count every item of dList
if dCount is not equal to 1 then
display notification "Markdown document is not only one."
return false
end if

tell document 1
set docName to name
end tell
return docName
end tell
end getFrontmostMarkdownDocName

on getFrontmostMarkdownFullPath()
tell application "MacDown"
tell document 1
set aProp to properties
end tell
end tell

set aPath to (file of aProp)
end getFrontmostMarkdownFullPath

–任意のデータから特定の文字列を置換
on replaceText(origData, origText, repText)
set curDelim to AppleScript’s text item delimiters
set AppleScript’s text item delimiters to {origText}
set origData to text items of origData
set AppleScript’s text item delimiters to {repText}
set origData to origData as text
set AppleScript’s text item delimiters to curDelim
–set b to origData as text
return origData
end replaceText

–指定のPOSIX pathのファイルを強制削除(あってもなくてもいい)
on deleteItemAt(aPOSIXpath)
set theNSFileManager to current application’s NSFileManager’s defaultManager()
set theResult to theNSFileManager’s removeItemAtPath:(aPOSIXpath) |error|:(missing value)
return (theResult as integer = 1) as boolean
end deleteItemAt

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書類と同じフォルダで各書類の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

表示中の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"
–http://piyocast.com/as/archives/5034

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property SMSForder : a reference to current application’s SMSForder
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSDirectoryEnumerationSkipsPackageDescendants : a reference to current application’s NSDirectoryEnumerationSkipsPackageDescendants
property NSDirectoryEnumerationSkipsSubdirectoryDescendants : a reference to current application’s NSDirectoryEnumerationSkipsSubdirectoryDescendants

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 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 aIndex to (SMSForder’s indexesOfItem:fileName inArray:bArray inverting:false) as list
if aIndex = {} then
display notification "Error: File Not Found"
return
end if

set bIndex to (contents of first item of aIndex) + 1 + 1 –0 based to 1 based conversion & next one
set aLen to length of (bArray as list)
if bIndex > aLen then
display notification "Error: Out of bounds"
return
end if

set newFile to contents of item bIndex of (bArray as list)
set newPath to parentFol & "/" & newFile

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 –縦書き表示

–指定フォルダ内の指定文字列を含むファイル名の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:(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 getFilesByIncludedStringInName:fromDirectory:exceptPackages:

–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