AppleScript名:テキストのパーセント表記を数値に変換する |
— Created 2018-03-18 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to current application’s NSString’s stringWithString:"80%" set aNum to aStr’s intValue() –> 80 set bNum to aStr’s doubleValue() –> 80.0 |
カテゴリー: Text
shebangっぽい行から実行プログラムを取得してスクリプト言語の拡張子を取得
shebangを含む複数行のテキストからshebang(らしきもの)を検索して、実行プログラム名を取得し、実行するScript言語のファイルの拡張子を判定するAppleScriptです。
RTFで記述したシェルスクリプトやRubyのスクリプトのスケルトンに、色分けしたパラメータ部分のデータを差し替えてRubyやシェルスクリプトの実行ファイルを動的に書き出し、所定のスクリプト言語処理系で実行するAppleScriptを書いたときに用いたものです。
割と処理内容はヘロヘロでたいした固い処理は行なっていませんが、凶悪な処理を行うためのキーパーツです。
AppleScript名:shebangっぽい行から実行プログラムを取得してスクリプト言語の拡張子を取得 |
set aText to "#!/usr/bin/env python import re " set aLang to splitLangFromShebangStr(aText) of me if aLang = false then error "This data seems not a shebang" set aExt to detectScriptFileExtension(aLang) of me return {aLang, aExt} –> {"python", "py"} –shebangっぽい行から実行プログラム名を抽出 on splitLangFromShebangStr(aText) set aTmpList to paragraphs of aText repeat with i in aTmpList set j to contents of i if j starts with "#!" then set aWorkList to words of j set aLang to contents of last item of aWorkList return aLang end if end repeat return false end splitLangFromShebangStr on detectScriptFileExtension(aLang) ignoring case if aLang = "Ruby" then return "rb" else if aLang = "Python" then return "py" else if aLang = "perl" then return "pl" else if aLang = "sh" then return "sh" else return "" end if end ignoring end detectScriptFileExtension |
指定のテキストから言語コードや言語名を取得する
指定のテキストの言語コードや言語名を取得するAppleScriptです。
比較的短い文章でも言語判定ができるという特徴がありますが、文章が長くなったり、セリフの文章が増えると日本語として判定できないといった欠点も持っています。
テキストを文ごとに分割し、「」といった記号を削除すると言語判定の精度を維持できています。とくに、文学作品などのテキストは得意ですが、ラノベ風の文章の言語判定は苦手なようです。
こうした派手めの機能にはどうしても得手、不得手というか構造的にあからさまな弱点を抱えることが多いので、早めに弱点を把握しておくことが重要です。
AppleScript名:指定のテキストから言語コードや言語名を取得する |
— Created 2017-04-10 by Shane Stanley use AppleScript version "2.4" use scripting additions use framework "Foundation" set str1 to "Ilmatyynyalukseni on täynnä ankeriaita." set str2 to "Luftputebåten min er full av ål" set str3 to "私の名前は長野谷です。" set str4 to "أنشأ فوكوزاوا يوكيتشي (١٨٣٥–١٩٠١) في اكتوبر عام ١٨٥٨ مدرسة للدراسات الهولندية (تحولت بعد ذلك لمدرسة للغة الانكليزية) في ايدو (طوكيو حاليا). يعد فوكوزاوا يوكيتشي من أحد مؤسسي نهضة اليابان الحديثة، فونهتم بمدرستنا بنوع التعليم الذي ينمي القدرات الإبداعية والفنية التي يتطلب توافرها في طلاب الجامعة بحيث لا ينشغل الطلاب باختبار قبول الجامعات ونحترم استقلالية وتفرد كل طالب وذلك في جو دافئ في بيئة طبيعية مليئة بأشجار" set str5 to "게이오 기주쿠는 어디에나 있는 학교의 하나로 만족하지 않습니다. 게이오 기주쿠는 기주쿠(義塾, 의숙)에서 배우는 학생과 교원이 일본의 ’기품의 원천’ 및 ’지덕의 모범’이 되는 것을 목표로 하는 학숙(學塾)입니다. " set str6 to "庆应义塾不是仅仅满足于成为常常见到的一般性学校。" set a1Res to guessLanguageCodeOf(str1) of me –> "fi" set a2Res to guessLanguageCodeOf(str2) of me –> "sv" set a3Res to guessLanguageCodeOf(str3) of me –> "ja" set a4Res to guessLanguageCodeOf(str4) of me –> "ar" set a5Res to guessLanguageCodeOf(str5) of me –> "ko" set a6Res to guessLanguageCodeOf(str6) of me –> "zh-Hans" set b1Res to guessLanguageOf(str1) of me –> "Finnish" set b2Res to guessLanguageOf(str2) of me –> "Swedish" set b3Res to guessLanguageOf(str3) of me –> "Japanese" set b4Res to guessLanguageOf(str4) of me –> "Arabic" set b5Res to guessLanguageOf(str5) of me –> "Korean" set b6Res to guessLanguageOf(str6) of me –> "Chinese" on guessLanguageOf(theString) set theTagger to current application’s NSLinguisticTagger’s alloc()’s initWithTagSchemes:{current application’s NSLinguisticTagSchemeLanguage} options:0 theTagger’s setString:theString set languageID to theTagger’s tagAtIndex:0 |scheme|:(current application’s NSLinguisticTagSchemeLanguage) tokenRange:(missing value) sentenceRange:(missing value) return ((current application’s NSLocale’s localeWithLocaleIdentifier:"en")’s localizedStringForLanguageCode:languageID) as text end guessLanguageOf on guessLanguageCodeOf(theString) set theTagger to current application’s NSLinguisticTagger’s alloc()’s initWithTagSchemes:{current application’s NSLinguisticTagSchemeLanguage} options:0 theTagger’s setString:theString set languageID to theTagger’s tagAtIndex:0 |scheme|:(current application’s NSLinguisticTagSchemeLanguage) tokenRange:(missing value) sentenceRange:(missing value) return languageID as text end guessLanguageCodeOf |
Language Detection -53 languages- langdetect
ApitoreのREST API「Language Detection -53 languages-」を呼び出して、指定したテキストの言語(日本語とか英語とか)を推定するAppleScriptです。
# Apitoreは2019年5月31日をもってサービスを終了
Language-Detectionは、テキストの言語判定を行います。検索機能に言語の絞り込みを付けたい場合や、テキストに対して言語別の処理をしたい場合に利用します。
本AppleScript利用のためには、Apitoreにサインアップしてアカウントを作成し、新規プロジェクトを作成(Test AppleScriptとか)。そこに、本APIを利用できるように登録し、「アクセストークン」を取得する必要があります。
アクセストークンを取得せずに掲載状態のまま本AppleScriptを実行してもエラーになります。
取得したアクセストークンを本AppleScript中のretAccessToken()ハンドラ内に記載し、実行してください。
本REST APIを評価した感想は、言語判定可能なテキスト分量がやや長め(俳句や短歌程度だとダメ。Twitter投稿ぐらいの文字数があれば大丈夫)でありつつ、APIに突っ込める文字の長さに制限があるため、対象のテキストをすべて渡すのではなく、テキストの一部を抜粋して評価を行うのが適しているように思われました。
AppleScript名:Language Detection -53 languages- langdetect |
— Created 2016-10-27 by Takaaki Naganoya — 2016 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set targStr to "This is a pen. This is an apple. This is applepen." set reqURLStr to "https://api.apitore.com/api/22/langdetect/get" set accessToken to retAccessToken() of me set aRec to {access_token:accessToken, |text|:targStr} set aURL to retURLwithParams(reqURLStr, aRec) of me set aRes to callRestGETAPIAndParseResults(aURL) of me set aRESCode to (responseCode of aRes) set aRESTres to (json of aRes) return aRESTres as list of string or string –GET methodのREST APIを呼ぶ on callRestGETAPIAndParseResults(aURL) set aRequest to current application’s NSMutableURLRequest’s requestWithURL:(current application’s |NSURL|’s URLWithString:aURL) aRequest’s setHTTPMethod:"GET" aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData) aRequest’s setHTTPShouldHandleCookies:false aRequest’s setTimeoutInterval:60 aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept" set aRes to current application’s NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value) set resList to aRes as list set bRes to contents of (first item of resList) set resStr to current application’s NSString’s alloc()’s initWithData:bRes encoding:(current application’s NSUTF8StringEncoding) set jsonString to current application’s NSString’s stringWithString:resStr set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding) set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value) –Get Response Code & Header set dRes to contents of second item of resList if dRes is not equal to missing value then set resCode to (dRes’s statusCode()) as number set resHeaders to (dRes’s allHeaderFields()) as record else set resCode to 0 set resHeaders to {} end if return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders} end callRestGETAPIAndParseResults on retAccessToken() return "xxXXXxxX-XxXx-XXXX-xXXX-XXxXXxxXxxXx" –API Tore Access Token end retAccessToken on retURLwithParams(aBaseURL, aRec) set aDic to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec set aKeyList to (aDic’s allKeys()) as list set aValList to (aDic’s allValues()) as list set aLen to length of aKeyList set qList to {} repeat with i from 1 to aLen set aName to contents of item i of aKeyList set aVal to contents of item i of aValList set the end of qList to (current application’s NSURLQueryItem’s queryItemWithName:aName value:aVal) end repeat set aComp to current application’s NSURLComponents’s alloc()’s initWithString:aBaseURL aComp’s setQueryItems:qList set aURL to (aComp’s |URL|()’s absoluteString()) as text return aURL end retURLwithParams |
表示中のCotEditor書類の「前」のファイルを縦書きでオープン v3
CotEditor内のScript Menuに入れて、現在オープン中の(連番つき)テキストファイルと同一フォルダに入っているテキストファイルのうち、番号が「前」に該当するファイルのXattr(拡張属性)を操作して、CotEditorの縦書き属性を追加し、CotEditorのファイルオープン時にデフォルトで縦書き表示を行うAppleScriptです。
前バージョンではGUI Scriptingを使っていたため、CotEditor内蔵Script MenuではなくOS側のScript Menuから呼び出すことしかできませんでした。本バージョンでは、CotEditor内蔵メニューから呼び出せます。
CotEditor内蔵Script Menuから呼べると、ファイル名に指定の特殊文字を入れておくことで、キーボードショートカットから呼び出せるようになります。
–> XAttribute.framework (To ~/Library/Frameworks/)
AppleScript名:表示中のCotEditor書類の「前」のファイルを縦書きでオープン v3 |
— Created 2017-12-15 by Takaaki Naganoya — Modified 2018-02-28 by Takaaki Naganoya — 2018 Piyomaru Software –v3:Xattrに追記してCotEditorでデフォルト縦書き表示を行わせた。CotEditorのアプリケーション内のScript Menuから実行可能に use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "XAttribute" –https://github.com/rylio/OTMXAttribute 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 –returns POSIX path, not alias or file 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 & previous 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 –Add Vertical Xattribute (for CotEditor only) set xRes to addXAttrToFile(newPath, "com.coteditor.VerticalText", "1") of me –Open Previous Document 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 –指定フォルダ内の指定文字列を含むファイル名のファイルを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:(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: on addXAttrToFile(aFile, anXattr, aValue) –Get Xattr String set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if anAttribute is not equal to missing value then –Already Exists set tmpRes to removeXAttrFromFile(aFile, anXattr) of me if tmpRes = false then return false end if –Set Xattr set xRes to (current application’s OTMXAttribute’s setAttributeAtPath:aFile |name|:anXattr value:aValue |error|:(missing value)) if xRes = missing value then return false return (xRes as boolean) end addXAttrToFile on removeXAttrFromFile(aFile, anXattr) –Get Xattr String set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if anAttribute = missing value then return true –There is no use to remove xattr –Remove Xattr set xRes to (current application’s OTMXAttribute’s removeAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if xRes = missing value then return false return (xRes as boolean) end removeXAttrFromFile |
表示中のCotEditor書類の「次」のファイルを縦書きでオープン v3
CotEditor内のScript Menuに入れて、現在オープン中の(連番つき)テキストファイルと同一フォルダに入っているテキストファイルのうち、番号が「次」に該当するファイルのXattr(拡張属性)を操作して、CotEditorの縦書き属性を追加し、CotEditorのファイルオープン時にデフォルトで縦書き表示を行うAppleScriptです。
前バージョンではGUI Scriptingを使っていたため、CotEditor内蔵Script MenuではなくOS側のScript Menuから呼び出すことしかできませんでした。本バージョンでは、CotEditor内蔵メニューから呼び出せます。
–> XAttribute.framework (To ~/Library/Frameworks/)
AppleScript名:表示中のCotEditor書類の「次」のファイルを縦書きでオープン v3 |
— Created 2017-12-15 by Takaaki Naganoya — Modified 2018-02-28 by Takaaki Naganoya — 2018 Piyomaru Software –v3:Xattrに追記してCotEditorでデフォルト縦書き表示を行わせた。CotEditorのアプリケーション内のScript Menuから実行可能に use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "XAttribute" –https://github.com/rylio/OTMXAttribute 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 –returns POSIX path, not alias or file 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 –Add Vertical Xattribute (for CotEditor only) set xRes to addXAttrToFile(newPath, "com.coteditor.VerticalText", "1") of me –Open Next Document 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 –指定フォルダ内の指定文字列を含むファイル名の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: on addXAttrToFile(aFile, anXattr, aValue) –Get Xattr String set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if anAttribute is not equal to missing value then –Already Exists set tmpRes to removeXAttrFromFile(aFile, anXattr) of me if tmpRes = false then return false end if –Set Xattr set xRes to (current application’s OTMXAttribute’s setAttributeAtPath:aFile |name|:anXattr value:aValue |error|:(missing value)) if xRes = missing value then return false return (xRes as boolean) end addXAttrToFile on removeXAttrFromFile(aFile, anXattr) –Get Xattr String set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if anAttribute = missing value then return true –There is no use to remove xattr –Remove Xattr set xRes to (current application’s OTMXAttribute’s removeAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if xRes = missing value then return false return (xRes as boolean) end removeXAttrFromFile |
OTMXAttributeで指定ファイルにxattrを追加してテキストファイルにCotEditor縦書き表示属性を付加する
指定テキストファイルのXattr(拡張属性)を操作して、CotEditorの縦書き属性を追加し、CotEditorのファイルオープン時にデフォルトで縦書き表示を行うAppleScriptです。
–> XAttribute.framework (To ~/Library/Frameworks/)
try! macOS meet-upの席上でCotEditorメンテナーの1024jpさんに
「(CotEditorに)デフォルトでプレーンテキストの縦書き表示を行わせる機能ってないんでしょうか?」
と聞いてみたら、本Xattrの存在を教えてもらえました。
これで、GUI Scriptingを併用せずに縦書き表示ができるようになったので、CotEditor内蔵Script Menuからでも縦書きで表示させるファイルを切り替えるようなScriptを呼び出せました。
▲デフォルト時
▲本ScriptによりXattrを追加してFinderからオープン、あるいはCotEditorからオープンを行なった状態
AppleScript名:OTMXAttributeで指定ファイルにxattrを追加する |
— Created 2018-02-28 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "XAttribute" –https://github.com/rylio/OTMXAttribute set aFile to POSIX path of (choose file) set xRes to addXAttrToFile(aFile, "com.coteditor.VerticalText", "1") on addXAttrToFile(aFile, anXattr, aValue) –Get Xattr String set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if anAttribute is not equal to missing value then –Already Exists set tmpRes to removeXAttrFromFile(aFile, anXattr) of me if tmpRes = false then return false end if –Set Xattr set xRes to (current application’s OTMXAttribute’s setAttributeAtPath:aFile |name|:anXattr value:aValue |error|:(missing value)) if xRes = missing value then return false return (xRes as boolean) end addXAttrToFile on removeXAttrFromFile(aFile, anXattr) –Get Xattr String set anAttribute to (current application’s OTMXAttribute’s stringAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if anAttribute = missing value then return true –There is no use to remove xattr –Remove Xattr set xRes to (current application’s OTMXAttribute’s removeAttributeAtPath:aFile |name|:anXattr |error|:(missing value)) if xRes = missing value then return false return (xRes as boolean) end removeXAttrFromFile |
選択中のメール本文のSHA3チェックサムを計算
Mail.appで選択中のメール本文のSHA3チェックサムを計算するAppleScriptです。
macOS VistaことmacOS 10.13。もう、10.13.xのバージョン中に状況が好転するような気配がまったくしないこのOS。2018年6月のWWDCで次の10.14を発表して「アップデート間隔を伸ばす」と言ったところで、同じCEO、同じスタッフ、同じ開発期間でまた2018年10月にリリースするとかいったら「同じことの繰り返し」になるのではないかと戦々恐々としています。
macOS 10.13のMail.appでメールの文字化けなどが報告されているため、実際に同じ文面のメールのチェックサムを10.12と10.13で比較するためにこのAppleScriptを書いてみました。
結果は、とくに文字化けもなく同じチェックサム値が得られたものの、OSごと勝手にクラッシュしてシャットダウンするとか、Mail.appのルールが着信したてのメールに効かない時があるとか、Finderが不安定だとか、日本語入力時に辞書の用例が表示されると選択した候補で変換候補を確定できないとか、日本語入力時に確定後も変換ウィンドウが消えないとか、いまだにけっこうムチャクチャなOSです。
AppleScript名:選択中のメール本文のSHA3チェックサムを計算 |
— Created 2017-02-25 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" use framework "SHA3Kit" –https://github.com/jaeggerr/NSString-SHA3 set aMailBody to getSelectedMailBody() of me if aMailBody = false then error "No Selection" set origData to (current application’s NSString’s stringWithString:aMailBody) set aHash1 to (origData’s sha3:256) as string –> "C69C8E08D1E6A8DA53C4E00D02D5DB5C2937722730CF63C1EC44E59B57A3B03F" on getSelectedMailBody() tell application "Mail" set aaSel to selection if aaSel = {} or aaSel = "" then return false set aSel to first item of aaSel set aCon to content of aSel return aCon end tell end getSelectedMailBody |
選択中のメール本文のHexダンプを取得
AppleScript名:選択中のメール本文のHexダンプを取得 |
— Created 2017-02-25 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aMailBody to getSelectedMailBody() of me if aMailBody = false then error "No Selection" set theNSString to current application’s NSString’s stringWithString:aMailBody set aList to hexDumpString(theNSString) of me return aList on getSelectedMailBody() tell application "Mail" set aaSel to selection if aaSel = {} or aaSel = "" then return false set aSel to first item of aaSel set aCon to content of aSel return aCon end tell end getSelectedMailBody on hexDumpString(theNSString) set theNSData to theNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding) set theString to (theNSData’s |description|()’s uppercaseString()) –Remove "<" ">" characters in head and tail set tLength to (theString’s |length|()) – 2 set aRange to current application’s NSMakeRange(1, tLength) set theString2 to theString’s substringWithRange:aRange –Replace Space Characters set aString to current application’s NSString’s stringWithString:theString2 set bString to aString’s stringByReplacingOccurrencesOfString:" " withString:"" set aResList to splitString(bString, 2) –> {"E3", "81", "82", "E3", "81", "84", "E3", "81", "86", "E3", "81", "88", "E3", "81", "8A"} return aResList end hexDumpString –Split NSString in specified aNum characters on splitString(aText, aNum) set aStr to current application’s NSString’s stringWithString:aText if aStr’s |length|() ≤ aNum then return aText set anArray to current application’s NSMutableArray’s new() set mStr to current application’s NSMutableString’s stringWithString:aStr set aRange to current application’s NSMakeRange(0, aNum) repeat while (mStr’s |length|()) > 0 if (mStr’s |length|()) < aNum then anArray’s addObject:(current application’s NSString’s stringWithString:mStr) mStr’s deleteCharactersInRange:(current application’s NSMakeRange(0, mStr’s |length|())) else anArray’s addObject:(mStr’s substringWithRange:aRange) mStr’s deleteCharactersInRange:aRange end if end repeat return (current application’s NSArray’s arrayWithArray:anArray) as list end splitString |
与えられたデータのうちIPアドレスとして妥当なもののみを抽出
AppleScript名:与えられたデータのうちIPアドレスとして妥当なもののみを抽出 |
— Created 2018-01-03 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" property NSPredicate : a reference to current application’s NSPredicate property NSArray : a reference to current application’s NSArray set aaList to {"112.4.208.194", "17.20.30..12"} set aResList to {} repeat with i in aaList set j to contents of i set the end of aResList to chkIPAddressFormat(j) of me end repeat aResList on chkIPAddressFormat(aStr as string) set aList to {aStr} set anArray to NSArray’s arrayWithArray:aList set aPred to NSPredicate’s predicateWithFormat:"SELF MATCHES ’[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}’" set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list return (length of bRes = 1) as boolean end chkIPAddressFormat |
指定リストから、Regexpで要素を抽出(NSPredicate)
AppleScript名:指定リストから、Regexpで要素を抽出(NSPredicate) |
— Created 2017-10-29 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set stringArray to current application’s NSArray’s arrayWithArray:{"adobe", "22", "microsoft", "99"} set thePred to current application’s NSPredicate’s predicateWithFormat:"self MATCHES ’\\\\d\\\\d’" set bList to (stringArray’s filteredArrayUsingPredicate:thePred) as list –> {"22", "99"} |
正規表現で数字を抽出(NSRegularExpressionSearch)
AppleScript名:正規表現で数字を抽出(NSRegularExpressionSearch) |
— Created 2017-12-17 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "126 ひよこ豆コーヒー豆だだちゃ豆" set n1Res to filterNumStr(aStr) of me log result –> "126" set aStr to "ひよこ豆コーヒー豆だだちゃ豆 345" set n2Res to filterNumStr(aStr) of me log result –> "345 set aStr to "ひよこ豆コーヒー豆999だだちゃ豆" set n3Res to filterNumStr(aStr) of me log result –> 999 on filterNumStr(aStr as string) set aLen to length of aStr set regStr to "\\d{1," & (aLen as string) & "}" set aRes to findStrByPattern(aStr, regStr) of me return aRes as {boolean, number} end filterNumStr on findStrByPattern(aText as string, regStr as string) set anNSString to current application’s NSString’s stringWithString:aText set aRange to anNSString’s rangeOfString:regStr options:(current application’s NSRegularExpressionSearch) if aRange = {location:0, length:0} then return "" set bStr to anNSString’s substringWithRange:aRange return bStr as string end findStrByPattern |
Numbers上で選択中の列のデータからIPアドレスを抽出(NSPredicate)
AppleScript名:Numbers上で選択中の列のデータからIPアドレスを抽出(NSPredicate) |
— Created 2018-01-03 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" –http://piyocast.com/as/archives/5080 property NSPredicate : a reference to current application’s NSPredicate property NSArray : a reference to current application’s NSArray set aList to getSelectionDataFromNumbers() of me set anArray to NSArray’s arrayWithArray:aList set aPred to NSPredicate’s predicateWithFormat:"SELF MATCHES ’[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}’" set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list –> {"XX.XX.XX.XXX", "XXX.XX.XXX.XXX", "XXX.XXX.XX.XXX", …..} on getSelectionDataFromNumbers() tell application "Numbers" tell front document tell active sheet tell table 1 set aList to value of every cell of selection range end tell end tell end tell end tell return aList end getSelectionDataFromNumbers |
指数表示数値を文字列化
指数表示の数値を文字列化するAppleScriptです。
AppleScriptの数値変数で表現可能な範囲は割と狭く、±1.79769E308。実数部は9桁です。
そのため、不意に指数表示になってしまったデータから指数表現を解除して、数値文字列に変換し、適宜bcコマンドなどで数値文字列同士の演算を行うことがままあります。そういう場合に使用します。
AppleScript text item delimitersを活用していることから、あきらかに自分が組んだScriptではありません(なるべく避けるので)。たぶん、Mailing Listに流れていたScriptです。
AppleScript名:指数表示数値を文字列化 |
set longNumber to "1082204521" set exponent to longNumber as number –> 1.082204521E+9 set numberString to Stringify(exponent) on Stringify(x) — for E+ numbers set x to x as string set {tids, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, {"E+"}} if (count (text items of x)) = 1 then set AppleScript’s text item delimiters to {tids} return x else set {n, z} to {text item 1 of x, (text item 2 of x) as integer} set AppleScript’s text item delimiters to {tids} set i to character 1 of n set decSepChar to character 2 of n — "." or "," set d to text 3 thru -1 of n set l to count d if l > z then return (i & (text 1 thru z of d) & decSepChar & (text (z + 1) thru -1 of d)) else repeat (z – l) times set d to d & "0" end repeat return (i & d) end if end if end Stringify |
序数を求めるルーチン同士を比較
AppleScript名:序数を求めるルーチン同士を比較 |
repeat with i from 1 to 1000 set a to retOrdinalNumStr(i) of me set b to getOrdinalNumber(i) of me log {a, b} end repeat –数値を与えると序数の文字列を返す on retOrdinalNumStr(aNum) set aStr to aNum as string –下1桁の数字を取得 set last1Str to last character of aStr –下2桁目の数字を取得 if length of aStr > 1 then set last2Str to character -2 of aStr else set last2Str to "" end if –場合分け set retStr to "" if last1Str = "1" then if last2Str = "1" then set retStr to "th" –11 else set retStr to "st" end if else if last1Str = "2" then if last2Str = "1" then set retStr to "th" –12 else set retStr to "nd" end if else if last1Str = "3" then if last2Str = "1" then set retStr to "th" –13 else set retStr to "rd" end if else set retStr to "th" end if return aStr & retStr end retOrdinalNumStr — 序数表現に変更 on getOrdinalNumber(anyInteger) if (anyInteger mod 10) = 1 and (anyInteger mod 100) ≠ 11 then set tempList to anyInteger & "st" else if (anyInteger mod 10) = 2 and (anyInteger mod 100) ≠ 12 then set tempList to anyInteger & "nd" else if (anyInteger mod 10) = 3 and (anyInteger mod 100) ≠ 13 then set tempList to anyInteger & "rd" else set tempList to anyInteger & "th" end if return tempList as text end getOrdinalNumber |
文字で書いた数値を本物の数値に変換
仰々しくタイトルを書いていますが、なんのことはない文字で書いた数字文字列の数値へのcastを行う処理です。
AppleScriptのネイティブのやりかただと、
set a to "12345" set b to a as number
という程度ですみます(Adobe Illustratorへのtellブロック内で上記のScriptを実行しないでください。L*a*b*色空間のaとbの1文字の予約語を持っているので、動作がおかしくなります)。
本Scriptで紹介しているのは、Cocoaのオブジェクトの数値文字列をCocoaの数値オブジェクト(NSNumber)に変換するものです。
本来はNSNumberのままなのですが、Scripting Bridgeの仕様でNSNumberになったものは自動でAppleScriptの数値まで変換されます。
AppleScript名:文字で書いた数値を本物の数値に変換 |
— Created 2014-12-28 by Takaaki Naganoya — 2014 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set j to "123456789" set aStr to current application’s NSString’s stringWithString:j set aNum to aStr’s intValue() |
数値の桁数を求める v2
AppleScript名:数値の桁数を求める v2 |
— Created 2014-12-04 by Takaaki Naganoya — 2014 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use bPlus : script "BridgePlus" set aList to {} set aRes to 0 repeat with i from 1 to 9999 by 1 set d to getDigit(i) of me if aRes is not equal to d then set the end of aList to {i, d} set aRes to d end if end repeat aList –> {{1, 1}, {10, 2}, {100, 3}, {1000, 4}} –数値の桁数を求める(マイナスの数は想定外) on getDigit(aNum as integer) load framework set b to ((current application’s SMSForder’s log10ValueOf:aNum)) set c to b as real set d to round c rounding down return (d + 1) end getDigit |
BridgePlusがmacOS 10.15以降でうまく動かない環境もあるので、数値演算ライブラリcalcLibASを呼び出すものも掲載しておきます。
AppleScript名:数値の桁数を求める v3.scpt |
— – Created by: Takaaki Naganoya – Created on: 2020/06/30 — – Copyright © 2020 Piyomaru Software, All Rights Reserved — use AppleScript version "2.4" use scripting additions use framework "Foundation" use calSub : script "calcLibAS" –http://piyocast.com/as/asinyaye set aRes1 to getNumDigit(-9999) of me –> 3 set aRes2 to getNumDigit(100) of me –> 2 on getNumDigit(aNum) set a2Val to abs aNum return round (log10 a2Val) rounding down end getNumDigit |
数値にゼロパディングしたテキストを返す
AppleScript名:数値にゼロパディングしたテキストを返す |
set aNum to 1 set aStr to retZeroPaddingText(aNum, 4) of me –数値にゼロパディングしたテキストを返す on retZeroPaddingText(aNum, aLen) set tText to ("0000000000" & aNum as text) set tCount to length of tText set resText to text (tCount – aLen + 1) thru tCount of tText return resText end retZeroPaddingText |
数値を指定桁でゼロパディング
AppleScript名:数値を指定桁でゼロパディング |
— Created 2015-08-05 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aTEXT to numToZeroPaddingStr(99, 4, "0") –> "0099" set aTEXT to numToZeroPaddingStr(99999999, 20, "0") –> "00000000000099999999" –整数の値に指定桁数ゼロパディングして文字列で返す on numToZeroPaddingStr(aNum as integer, aDigit as integer, paddingChar as text) set aNumForm to current application’s NSNumberFormatter’s alloc()’s init() aNumForm’s setPaddingPosition:(current application’s NSNumberFormatterPadBeforePrefix) aNumForm’s setPaddingCharacter:paddingChar aNumForm’s setMinimumIntegerDigits:aDigit set bNum to current application’s NSNumber’s numberWithInt:aNum set aStr to aNumForm’s stringFromNumber:bNum return aStr as text end numToZeroPaddingStr |
ローマ数字エンコーダー、デコーダー v2
AppleScript名:ローマ数字エンコーダー、デコーダー v2 |
— Created 2015-11-16 by Takaaki Naganoya — Modified 2017-05-18 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" –http://stackoverflow.com/questions/14762282/how-to-convert-a-roman-numeral-to-an-nsnumer repeat with i from 1 to 3999 set aRes to numberToRomanNumerals(i) of me set bRes to romanNumeralsToNumber(aRes) of me log {i, aRes, bRes} end repeat –Roman Number String Encoder on numberToRomanNumerals(aNum) if (aNum < 0 or aNum > 3999) then return "" –条件が間違っていたので直した(2017/5/18) set r_ones to {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"} set r_tens to {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"} set r_hunds to {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"} set r_thouds to {"M", "MM", "MMM", "MMMM", "MMMMM", "MMMMMM", "MMMMMMM", "MMMMMMMM", "MMMMMMMMM"} set ones to aNum mod 10 set tens to (aNum – ones) mod 100 set hundreds to (aNum – tens – ones) mod 1000 set thou to (aNum – hundreds – tens – ones) mod 10000 set tens to tens / 10 set hundreds to hundreds / 100 set thou to thou / 1000 set rNum to current application’s NSString’s stringWithString:"" if thou > 0 then set rNum to rNum’s stringByAppendingString:(item thou of r_thouds) if hundreds > 0 then set rNum to rNum’s stringByAppendingString:(item hundreds of r_hunds) if tens > 0 then set rNum to rNum’s stringByAppendingString:(item tens of r_tens) if ones > 0 then set rNum to rNum’s stringByAppendingString:(item ones of r_ones) return rNum as text end numberToRomanNumerals –Roman Number String Decoder on romanNumeralsToNumber(str) — Piero Garzotto (http://scriptbuilders.net/files/romannumerals1.0.html) local str, r, i set r to 0 repeat with i from 1 to count str set r to r + (item (offset of (item i of str) in "mdclxvi") of ¬ {1000, 500, 100, 50, 10, 5, 1}) * (((((offset of ¬ (item (i + 1) of (str & "@")) in "mdclxvi@") ≥ (offset of ¬ (item i of str) in "mdclxvi")) as integer) * 2) – 1) end repeat return r end romanNumeralsToNumber |