AppleScript名:指定文字コードでファイル書き出し(UTF-16BE)v2 |
use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "高島屋" set aPath to choose file name set cStr to current application’s NSString’s stringWithString:aStr set thePath to POSIX path of aPath set aRes to cStr’s writeToFile:thePath atomically:false encoding:(current application’s NSUTF16BigEndianStringEncoding) |error|:(missing value) |
カテゴリー: Text
指定文字コードでファイル書き出し(SJIS)v2
AppleScript名:指定文字コードでファイル書き出し(SJIS)v2 |
use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "高島屋" set aPath to choose file name set cStr to current application’s NSString’s stringWithString:aStr set thePath to POSIX path of aPath set aRes to cStr’s writeToFile:thePath atomically:false encoding:(current application’s NSShiftJISStringEncoding) |error|:(missing value) |
指定文字コードでファイル書き出し(UTF-16)v2
AppleScript名:指定文字コードでファイル書き出し(UTF-16)v2 |
— Created 2014-11-11 by Takaaki Naganoya — 2014 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "高島屋" set aPath to choose file name set cStr to current application’s NSString’s stringWithString:aStr set thePath to POSIX path of aPath set aRes to cStr’s writeToFile:thePath atomically:false encoding:(current application’s NSUnicodeStringEncoding) |error|:(missing value) |
指定文字コードでファイル書き出し(UTF-8)v2
AppleScriptの世界観では、文字コードというものは「存在しない」かのように位置付けています。2020年的な状況においてはUTF-8で事足りると言いたいところですが、(日本国内的には)100%そういうわけにも行きません。
AppleScriptのファイル書き出しコマンド(writeコマンド)では、UTF-8だけは文字コード指定のオプションが存在しています。ただし、ほぼ隠し仕様で生AppleEventコードを記述する必要があり、文字列で記述できる「予約語」が設けられているわけではありません。
予約語が存在していないといいつつ、やはり文字コードを指定できないのは不便だったこともあってか、予約語が存在していないものの、特定のファイル書き込み操作を行うと確実にその文字コードでファイル書き込みが行えるという「暗黙の文字コード指定」という手段が存在しています(macOS 10.8でここにバグを作られて大問題になりましたが、10.8.xで修正されました)。
しかし、macOS 10.10以降ではCocoaの機能を手軽に呼び出せるようになったために、状況が一変します。Cocoaの機能さえ呼び出せば、文字コード指定を行ってのファイルの書き出しも読み込みもお手の物。すでに、Cocoaの機能呼び出しのない世界は考えられないほど。なので、Cocoaの機能をAppleScriptネイティブの機能と位置づけ、Cocoaの機能を用いて文字コード指定を柔軟に行えるファイル入出力ルーチンが整備されています。
AppleScriptネイティブのwriteコマンドは、このCocoaの機能に影響を受けています。Cocoaの機能を利用する宣言文、
use framework "Foundation"
がある場合には、writeコマンドをそのまま記述できず(実行時にエラーになる)、tell current application〜end tellのブロック内に記述する必要が出てきます。そのため、掲載のファイル書き出しルーチンのプログラムリスト「UTF8でファイル書き込み」には、一見して無意味と思えるtell current application〜end tellが記述されています。ただ、対処方法がわかっているので使い回しを行うファイル書き出しルーチン側に本記述を書いておくことにしています。
正直なところ、文字コード指定をともなうファイル入出力については、Cocoaの機能を利用した方が手軽なので(AppleScriptのファイル追記モードは便利ですが)Cocoaの機能を使う方法だけ掲載しておけばよいと考えます。ごくまれに、古いバージョンのOS用にScriptを書かなくてはならないとか、Cocoa Scriptingを考慮していない偏屈なアプリケーションのScriptingで必要になることがある、程度のものでしょうか。
AppleScript名:指定文字コードでファイル書き出し(UTF-8)v2 |
use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "高島屋" set aPath to choose file name set cStr to current application’s NSString’s stringWithString:aStr set thePath to POSIX path of aPath set aRes to cStr’s writeToFile:thePath atomically:false encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value) |
AppleScript名:UTF8でファイル書き込み |
set dFol to (path to desktop) as string set fullPath to dFol & "test_utf8.txt" set aStr to "髙島屋" set fRes to writeToFileAsUTF8(aStr, fullPath, false) of me on writeToFileAsUTF8(thisData, targetFile, appendF as boolean) tell current application try set the targetFile to the targetFile as text set the openTargetFile to open for access file targetFile with write permission if appendF is false then set eof of the openTargetFile to 0 write thisData to the openTargetFile as «class utf8» starting at eof close access the openTargetFile return true on error try close access file targetFile end try return false end try end tell end writeToFileAsUTF8 |
指定文字コードでファイル書き出し(EUC)
AppleScript名:指定文字コードでファイル書き出し(EUC) |
use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "高島屋" set aPath to choose file name set cStr to current application’s NSString’s stringWithString:aStr set thePath to POSIX path of aPath set aRes to cStr’s writeToFile:thePath atomically:false encoding:(current application’s NSJapaneseEUCStringEncoding) |error|:(missing value) |
文字エンコーディングを自動判別してファイル読み込み v1.2.1
AppleScript名:文字エンコーディングを自動判別してファイル読み込み v1.2.1 |
— Created 2014-12-28 by Takaaki Naganoya — Modified 2014-12-29 by Shane Stanley — Modified 2015-10-03 by Takaaki Naganoya use AppleScript version "2.5" use scripting additions use framework "Foundation" set aPath to POSIX path of (choose file) set aRes to readJapanesTextFileWithGuessingEncoding(aPath) of me set bRes to aRes as string –Read Japanese text with detecting its text encoding on readJapanesTextFileWithGuessingEncoding(aPOSIXpath as string) –ISO2022JP check set aNSData to current application’s NSData’s dataWithContentsOfFile:aPOSIXpath set aDataLength to aNSData’s |length|() if aDataLength > 1024 then set aDataLength to 1024 –0x1B check set anNSString to current application’s NSString’s stringWithString:(character id 27) — 0x1B set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding) set theRange to aNSData’s rangeOfData:theData options:0 range:(current application’s NSMakeRange(0, aDataLength)) –found 0x1B in aNSData if |length| of theRange = 1 and location of theRange < aDataLength then set aStr to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSISO2022JPStringEncoding)) –21 if aStr is not equal to missing value then return (aStr as text) — ISO2022JP end if –EUC set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSJapaneseEUCStringEncoding)) –log resValue if resValue is not equal to missing value then return (resValue as text) –UTF-8 set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUTF8StringEncoding)) –log resValue if resValue is not equal to missing value then return (resValue as text) –SHift JIS set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSShiftJISStringEncoding)) –log resValue if resValue is not equal to missing value then return (resValue as text) –UTF-16BE/LE/無印Unicodeは多数決を取る set resValue1 to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUTF16BigEndianStringEncoding)) as text –log resValue1 set sample1 to getTextSample(resValue1) of me set lang1 to specifyLanguageOfText(sample1) of me set para1 to length of (paragraphs of sample1) set words1 to length of (words of sample1) set resValue2 to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUTF16LittleEndianStringEncoding)) as text –log resValue2 set sample2 to getTextSample(resValue2) of me set lang2 to specifyLanguageOfText(sample2) of me set para2 to length of (paragraphs of sample2) set words2 to length of (words of sample2) set resValue3 to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUnicodeStringEncoding)) as text –log resValue3 set sample3 to getTextSample(resValue3) of me set lang3 to specifyLanguageOfText(sample3) of me set para3 to length of (paragraphs of sample3) set words3 to length of (words of sample3) –文字および文法的に見て「日本語」ならそれを返す if lang1 = "ja" then return resValue1 if lang2 = "ja" then return resValue2 if lang3 = "ja" then return resValue2 –文字化けしたときには、日本語の「Word」として認識されづらく、Paragraphも少ない(1とか)なので条件で除外する if para1 is not equal to 1 then if (words1 ≤ words2) or (words1 ≤ words3) then return resValue1 end if end if if para2 is not equal to 1 then if (words2 ≤ words1) or (words2 ≤ words3) then return resValue2 end if end if if para3 is not equal to 1 then if (words3 ≤ words1) or (words3 ≤ words2) then return resValue3 end if end if return false (* –おまけ(未確認) set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1251StringEncoding)) if resValue is not equal to missing value then return resValue set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1252StringEncoding)) if resValue is not equal to missing value then return resValue set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1253StringEncoding)) if resValue is not equal to missing value then return resValue set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1254StringEncoding)) if resValue is not equal to missing value then return resValue set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1250StringEncoding)) if resValue is not equal to missing value then return resValue return false *) end readJapanesTextFileWithGuessingEncoding on specifyLanguageOfText(aStr) set aNSstring to current application’s NSString’s stringWithString:aStr set tagSchemes to current application’s NSArray’s arrayWithObjects:(current application’s NSLinguisticTagSchemeLanguage) set tagger to current application’s NSLinguisticTagger’s alloc()’s initWithTagSchemes:tagSchemes options:0 tagger’s setString:aNSstring set aLanguage to tagger’s tagAtIndex:0 |scheme|:(current application’s NSLinguisticTagSchemeLanguage) tokenRange:(missing value) sentenceRange:(missing value) return aLanguage as text end specifyLanguageOfText on getTextSample(aText) set aLen to length of aText if aLen < 1024 then set bLen to aLen else set bLen to 1024 end if return (text 1 thru bLen of aText) end getTextSample |
なろう系ルビタグを置換
AppleScript名:なろう系ルビタグを置換 |
— Created 2018-01-14 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" –http://piyocast.com/as/archives/5117 property NSString : a reference to current application’s NSString property NSScanner : a reference to current application’s NSScanner property NSMutableArray : a reference to current application’s NSMutableArray property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp set aStr to " 数多国ある西方諸国だが、元を辿ればとある一つの国へとつながっていた。それは幻晶騎士(シルエットナイト)の力により西方の地に覇をとなえた人類が作り上げた超巨大国家、その名を“ファダーアバーデン”という。 西方暦一二八九年の現在において西方諸国を構成する主要国家、“ジャロウデク王国”、“クシェペルカ王国”、“ロカール諸国連合”、“|孤独なる十一《イレブンフラッグス》”などの国々は、全てかの巨大国家が分裂してできた残滓なのである。" –set aStr to getEditorText() –"|○o○o○《XXXXX》" –> "XXXXX" set bRes to trimStrHeaderFromTo(aStr, "|", "《", "》") of me –"aaaaa○○○(XXXXX)" –> "XXXXX" set cStr to trimStrHeaderFromToForward(bRes, "(", ")") of me (* " 数多国ある西方諸国だが、元を辿ればとある一つの国へとつながっていた。それはシルエットナイトの力により西方の地に覇をとなえた人類が作り上げた超巨大国家、その名を“ファダーアバーデン”という。 西方暦一二八九年の現在において西方諸国を構成する主要国家、“ジャロウデク王国”、“クシェペルカ王国”、“ロカール諸国連合”、“イレブンフラッグス”などの国々は、全てかの巨大国家が分裂してできた残滓なのである。" *) –"|○o○o○《XXXXX》" –> "XXXXX" on trimStrHeaderFromTo(aParamStr, headerStr, fromStr, toStr) set theScanner to NSScanner’s scannerWithString:aParamStr set anArray to NSMutableArray’s array() repeat until (theScanner’s isAtEnd as boolean) set {theResult, theKey} to theScanner’s scanUpToString:headerStr intoString:(reference) theScanner’s scanString:fromStr intoString:(missing value) set {theResult, theValue} to theScanner’s scanUpToString:fromStr intoString:(reference) if theValue is missing value then set theValue to "" theScanner’s scanString:fromStr intoString:(missing value) anArray’s addObject:theValue end repeat if anArray’s |count|() = 0 then return aParamStr copy aParamStr to curStr repeat with i in (anArray as list) set curStr to repChar(curStr, i & fromStr, "") of me end repeat set curStr to repChar(curStr, toStr, "") of me return curStr end trimStrHeaderFromTo –"aaaaa○○○(XXXXX)" –> "XXXXX" on trimStrHeaderFromToForward(aParamStr, fromStr, toStr) set theScanner to NSScanner’s scannerWithString:aParamStr set anArray to NSMutableArray’s array() repeat until (theScanner’s isAtEnd as boolean) set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference) set curLoc to (theScanner’s scanLocation()) + 1 –scan back to different kind of character set prevKind to detectCharKindMain(text (curLoc – 1) of aParamStr) of me repeat with i from curLoc – 2 to 1 by -1 set aStr to text i of aParamStr set curKind to detectCharKindMain(aStr) of me if prevKind is not equal to curKind then exit repeat end if end repeat try set tmpStr to text (i + 1) thru curLoc of aParamStr theScanner’s scanString:fromStr intoString:(missing value) set {theResult, theValue} to theScanner’s scanUpToString:fromStr intoString:(reference) if theValue is missing value then set theValue to "" theScanner’s scanString:fromStr intoString:(missing value) anArray’s addObject:tmpStr end try end repeat if anArray’s |count|() = 0 then return aParamStr copy aParamStr to curStr repeat with i in (anArray as list) set curStr to repChar(curStr, i, "") of me end repeat set curStr to repChar(curStr, toStr, "") of me return curStr end trimStrHeaderFromToForward on repChar(aStr, targStr, repStr) set aString to current application’s NSString’s stringWithString:aStr set bString to aString’s stringByReplacingOccurrencesOfString:targStr withString:repStr set cString to bString as string return cString end repChar –文字種別判定 on detectCharKindMain(aStr) set s1Res to chkKanji(aStr) of me set s2Res to chkKatakana(aStr) of me set s3Res to chkHiragana(aStr) of me set s4Res to chkLineFeed(aStr) of me set s5Res to chkSpecialSign(aStr) of me set s6Res to chkAlphaNumeric(aStr) if s1Res = true then set curKind to "Kanji" else if s2Res = true then set curKind to "Katakana" else if s3Res = true then set curKind to "Hiragana" else if s4Res = true then set curKind to "Line Feed" else if s5Res = true then set curKind to "Sign" else if s6Res = true then set curKind to "Alpha Numeric" end if return curKind end detectCharKindMain on chkKanji(aChar) return detectCharKind(aChar, "[一-龠]") of me end chkKanji on chkHiragana(aChar) return detectCharKind(aChar, "[ぁ-ん]") of me end chkHiragana on chkKatakana(aChar) return detectCharKind(aChar, "[ァ-ヶ]") of me end chkKatakana on chkLineFeed(aChar) return aChar is in {string id 10, string id 13, string id 13 & string id 10} end chkLineFeed on chkSpecialSign(aChar) return aChar is in {"「", "」", "『", "』", "ー", "―", "〜", "~", "!", "?", "&", "/", "《", "》", "#", "…", "・", "♪", "。", "、", ".", "々", "“", "”", "*", "(", ")", "(", ")", " ", " ", "§", "【", "】", "■", "%", "≒"} end chkSpecialSign on chkAlphaNumeric(aChar) return detectCharKind(aChar, "[a-zA-Z0-9a-zA-Z0-9]") of me –半角全角英数字 end chkAlphaNumeric on detectCharKind(aChar, aPattern) set aChar to NSString’s stringWithString:aChar set searchStr to NSString’s stringWithString:aPattern set matchRes to aChar’s rangeOfString:searchStr options:(NSRegularExpressionSearch) if matchRes’s location() = (current application’s NSNotFound) or (matchRes’s location() as number) > 9.99999999E+8 then return false else return true end if end detectCharKind on getEditorText() tell application "CotEditor" if (count every document) = 0 then return false tell front document return contents end tell end tell end getEditorText |
ASOCで英数字以外を削除して返す
AppleScript名:ASOCで英数字以外を削除して返す |
— Created 2015-12-02 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to "<< 98158999992aazaaZZZ >>" set bStr to returnNumberAndAlphabetCharsOnly(aStr) –> "98158999992aazaaZZZ" on returnNumberAndAlphabetCharsOnly(aStr) set anNSString to current application’s NSString’s stringWithString:aStr set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9A-Za-z]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()} return anNSString as text end returnNumberAndAlphabetCharsOnly |
AlphabetとNumericの混在かどうかを調べる
AppleScript名:AlphabetとNumericの混在かどうかを調べる |
— Created 2015-12-04 by Takaaki Naganoya — 2015 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aRes to chkMixtureOfNumericAndAlphabet("ABC") of me –> false set aRes to chkMixtureOfNumericAndAlphabet("123") of me –> false set aRes to chkMixtureOfNumericAndAlphabet("4f73vg1v") of me –Target –> true set aRes to chkMixtureOfNumericAndAlphabet("4f73vg1vあああ") of me –> false –数字とアルファベットの混在状態の時にtrueを返す on chkMixtureOfNumericAndAlphabet(checkString) set a0Res to chkAlphabetAndNumeric(checkString) of me set a1Res to chkNumeric(checkString) of me set a2Res to chkAlphabet(checkString) of me if {a0Res, a1Res, a2Res} = {true, false, false} then return true else return false end if end chkMixtureOfNumericAndAlphabet –数字のみかを調べて返す on chkNumeric(checkString) set digitCharSet to current application’s NSCharacterSet’s characterSetWithCharactersInString:"0123456789" set ret to my chkCompareString:checkString baseString:digitCharSet return ret as boolean end chkNumeric — アルファベットのみか調べて返す on chkAlphabet(checkString) set aStr to current application’s NSString’s stringWithString:checkString set allCharSet to current application’s NSMutableCharacterSet’s alloc()’s init() allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26)) allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26)) set aBool to my chkCompareString:aStr baseString:allCharSet return aBool as boolean end chkAlphabet — アルファベットと数字のみか調べて返す on chkAlphabetAndNumeric(checkString) set aStr to current application’s NSString’s stringWithString:checkString set allCharSet to current application’s NSMutableCharacterSet’s alloc()’s init() allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "0", 10)) allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "a", 26)) allCharSet’s addCharactersInRange:(current application’s NSMakeRange(ASCII number of "A", 26)) set aBool to my chkCompareString:aStr baseString:allCharSet return aBool as boolean end chkAlphabetAndNumeric on chkCompareString:checkString baseString:baseString set aScanner to current application’s NSScanner’s localizedScannerWithString:checkString aScanner’s setCharactersToBeSkipped:(missing value) aScanner’s scanCharactersFromSet:baseString intoString:(missing value) return (aScanner’s isAtEnd()) as boolean end chkCompareString:baseString: |
文字種別にカウントする v2
AppleScript名:文字種別にカウントする v2 |
— Created 2018-1-11 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" –http://piyocast.com/as/archives/5104 property NSString : a reference to current application’s NSString property NSNumber : a reference to current application’s NSNumber property NSDictionary : a reference to current application’s NSDictionary property NSCountedSet : a reference to current application’s NSCountedSet property NSMutableArray : a reference to current application’s NSMutableArray property NSNumberFormatter : a reference to current application’s NSNumberFormatter property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp set sourcePath to choose file of type {"public.plain-text"} tell current application set aStr to (read sourcePath as «class utf8») end tell set aRes to detectCharKindRating(aStr) of me –> {kanjiNum:563289, kanjiRating:22.0, hiraganaNum:1311933, hiraganaRating:51.2, katakanaNum:210161, katakanaRating:8.2, otherNum:478690, otherRating:18.7, totalCount:2564073}–Light Novel –> {kanjiNum:24960, kanjiRating:28.0, hiraganaNum:56080, hiraganaRating:62.9, katakanaNum:1063, katakanaRating:1.2, otherNum:7136, otherRating:8.0} –文学(坊ちゃん) on detectCharKindRating(aStr as string) set theCountedSet to NSCountedSet’s alloc()’s initWithArray:(characters of aStr) set theEnumerator to theCountedSet’s objectEnumerator() set cCount to 0 set hCount to 0 set kCount to 0 set oCount to 0 set totalC to length of aStr repeat set aValue to theEnumerator’s nextObject() if aValue is missing value then exit repeat set aStr to aValue as string set tmpCount to (theCountedSet’s countForObject:aValue) set s1Res to chkKanji(aStr) of me set s2Res to chkKatakana(aStr) of me set s3Res to chkHiragana(aStr) of me if s1Res = true then set cCount to cCount + tmpCount else if s2Res = true then set kCount to kCount + tmpCount else if s3Res = true then set hCount to hCount + tmpCount else set oCount to oCount + tmpCount end if end repeat set ckRes to roundingUp((cCount / totalC) * 100, 1) of me set kkRes to roundingUp((kCount / totalC) * 100, 1) of me set hgRes to roundingUp((hCount / totalC) * 100, 1) of me set otRes to roundingUp((oCount / totalC) * 100, 1) of me return {kanjiNum:cCount, kanjiRating:ckRes, hiraganaNum:hCount, hiraganaRating:hgRes, katakanaNum:kCount, katakanaRating:kkRes, otherNum:oCount, otherRating:otRes} end detectCharKindRating on chkKanji(aChar) return detectCharKind(aChar, "[一-龠]") of me end chkKanji on chkHiragana(aChar) return detectCharKind(aChar, "[ぁ-ん]") of me end chkHiragana on chkKatakana(aChar) return detectCharKind(aChar, "[ァ-ヶ]") of me end chkKatakana on detectCharKind(aChar, aPattern) set aChar to NSString’s stringWithString:aChar set searchStr to NSString’s stringWithString:aPattern set matchRes to aChar’s rangeOfString:searchStr options:(NSRegularExpressionSearch) if matchRes’s location() = (current application’s NSNotFound) or (matchRes’s location() as number) > 9.99999999E+8 then return false else return true end if end detectCharKind on roundingUp(aNum, aDigit as integer) set a to aNum as real set aFormatter to NSNumberFormatter’s alloc()’s init() aFormatter’s setMaximumFractionDigits:aDigit aFormatter’s setRoundingMode:(NSNumberFormatterRoundUp) set aStr to aFormatter’s stringFromNumber:(NSNumber’s numberWithFloat:a) return (aStr as text) as real end roundingUp |
文字種類変換(ASOC)
テキストの各種文字の変換を行うAppleScriptです。
半角カタカナから全角への変換など、いまやテキストエディタの機能など用いる必要もなく、Cocoaの機能を呼び出すと手軽に行うことができます。
AppleScript名:文字種類変換(ASOC) |
— Created 2017-09-06 by Shane Stanley — Modified 2017-09-06 by Takaaki Naganoya use AppleScript version "2.5" — (10.12) or later use framework "Foundation" use scripting additions –http://piyocast.com/as/archives/4811 property NSString : a reference to current application’s NSString property NSStringTransformFullwidthToHalfwidth : a reference to current application’s NSStringTransformFullwidthToHalfwidth property NSStringTransformHiraganaToKatakana : a reference to current application’s NSStringTransformHiraganaToKatakana property NSStringTransformLatinToHiragana : a reference to current application’s NSStringTransformLatinToHiragana property NSStringTransformLatinToKatakana : a reference to current application’s NSStringTransformLatinToKatakana property NSStringTransformToUnicodeName : a reference to current application’s NSStringTransformToUnicodeName property NSStringTransformToXMLHex : a reference to current application’s NSStringTransformToXMLHex set a01 to hanToZen("トウキョウト") of me –> "トウキョウト"–Zenkaku (Full Width) set a02 to zenToHan(a01) of me –> "トウキョウト" –Hankaku (Half Width) set a03 to katakanaToHiraganaTo(a01) of me –> "とうきょうと" set a04 to hiraganaToKatakana(a03) of me –> "トウキョウト" set a05 to hiraganaToalphabet(a03) of me –> "toukyouto" set a06 to alphabetToHiragana(a05) of me –> "とうきょうと" set a07 to katakanaToAlphabet(a04) of me –> "toukyouto" set a08 to alphabetToKatakana(a07) of me –> "トウキョウト" set a09 to characterToUnicodeName("あ") of me –> "\\N{HIRAGANA LETTER A}" set a10 to unicodeNameToCharacter(a09) of me –> "あ" set a11 to stringToXMLHex("あ") of me –> "あ" set a12 to xmlHexTostring(a11) of me –> "あ" –半角→全角変換 on hanToZen(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:true) as string end hanToZen –全角→半角変換 on zenToHan(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:false) as string end zenToHan –ひらがな→カタカナ変換 on hiraganaToKatakana(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:false) as string end hiraganaToKatakana –カタカナ→ひらがな変換 on katakanaToHiraganaTo(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:true) as string end katakanaToHiraganaTo –ローマ字→ひらがな変換 on alphabetToHiragana(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:false) as string end alphabetToHiragana –ひらがな→ローマ字変換 on hiraganaToalphabet(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:true) as string end hiraganaToalphabet –ローマ字→カタカナ変換 on alphabetToKatakana(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:false) as string end alphabetToKatakana –カタカナ→ローマ字変換 on katakanaToAlphabet(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:true) as string end katakanaToAlphabet –文字→Unicode Name変換 on characterToUnicodeName(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:false) as string end characterToUnicodeName –Unicode Name→文字変換 on unicodeNameToCharacter(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:true) as string end unicodeNameToCharacter –文字→XML Hex変換 on stringToXMLHex(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:false) as string end stringToXMLHex –XML Hex→文字変換 on xmlHexTostring(aStr) set aString to NSString’s stringWithString:aStr return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:true) as string end xmlHexTostring |
原稿用紙枚数シミュレーション(簡易版)v1
AppleScript名:原稿用紙枚数シミュレーション(簡易版)v1 |
— Created 2018-1-13 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" –http://piyocast.com/as/archives/5120 set aText to retTestText() of me set sRes to genkoSimulation(20, 20, aText) of me display notification "原稿用紙換算で約" & (sRes as string) & "枚です" –原稿用紙枚数シミュレーション(簡易版) on genkoSimulation(lineMax as integer, genkoLineMax as integer, aText as string) script spdT property aList : {} end script if aText = "" then return 0 set (aList of spdT) to characters of aText set charPointer to 1 set lineCounter to 1 set aLen to length of (aList of spdT) set i to 1 repeat while i < aLen set j to contents of item i of (aList of spdT) if j is in {string id 10, string id 13, string id 10 & string id 13} then set charPointer to 1 set lineCounter to lineCounter + 1 else set charPointer to charPointer + 1 if charPointer ≥ lineMax then set charPointer to 1 set lineCounter to lineCounter + 1 end if end if set i to i + 1 end repeat set totalPage to lineCounter div genkoLineMax set amariPage to lineCounter mod genkoLineMax if amariPage = 0 then — else set totalPage to totalPage + 1 end if return totalPage end genkoSimulation on retTestText() return "12345 あいうえお かきくけこ さしすせそ たちつてと なにぬねの はひふへほ まみむめも やいゆえよ わいうえを あいうえお かきくけこ さしすせそ たちつてと なにぬねの はひふへほ まみむめも やいゆえよ わいうえを 1234567890123456789ぉー" end retTestText |
love
Basicで作られた花文字プログラムを、AppleScriptに移植したものです。元は、ChipmunkBasic用のサンプルプログラムで、1996年作成のクレジットが銘打たれていますが、オリジナルはもっと昔に作られたものでしょう。
図形パターンは西新宿に置かれているロバート・インディアナ氏作のオブジェ「LOVE」(1965年発表)のデータそのものです。
下地に敷く文字は変更できますが、模様の文字列(LOVE)は固定データで持たせているので、そのままでは変更できません。
→ その後、英単語の花文字プログラムを作成してみました。
AppleScript名:love |
— Created 2015-02-15 by Takaaki Naganoya — 2015 Piyomaru Software (* 20 rem PRINT "THANKS TO ROBERT INDIANA AND DAVID AHL" 21 rem print "contributed by ATStarr@Amherst.Edu 1996" http://www.nicholson.com/rhn/basic/classic_programs/love.bas *) set charMode to "E" –J or E set aTargChar to "makiko" set outText to "" set aSpc to returnSpc(charMode) of me set aList to retLoveList() set aPos to 0 set charFlag to true –false:space char repeat with i in aList set j to contents of i if charFlag = true then set aText to retCirculateStrs(aTargChar, j) of me else set aText to retCirculateStrs(aSpc, j) of me end if set outText to outText & aText set charFlag to not charFlag set aPos to aPos + j if aPos ≥ 60 then set aPos to 0 set outText to outText & return set charFlag to true end if end repeat return outText on retLoveList() return {60, 1, 12, 26, 9, 12, 3, 8, 24, 17, 8, 4, 6, 23, 21, 6, 4, 6, 22, 12, 5, 6, 5, 4, 6, 21, 11, 8, 6, 4, 4, 6, 21, 10, 10, 5, 4, 4, 6, 21, 9, 11, 5, 4, 4, 6, 21, 8, 11, 6, 4, 4, 6, 21, 7, 11, 7, 4, 4, 6, 21, 6, 11, 8, 4, 4, 6, 19, 1, 1, 5, 11, 9, 4, 4, 6, 19, 1, 1, 5, 10, 10, 4, 4, 6, 18, 2, 1, 6, 8, 11, 4, 4, 6, 17, 3, 1, 7, 5, 13, 4, 4, 6, 15, 5, 2, 23, 5, 1, 29, 5, 17, 8, 1, 29, 9, 9, 12, 1, 13, 5, 40, 1, 1, 13, 5, 40, 1, 4, 6, 13, 3, 10, 6, 12, 5, 1, 5, 6, 11, 3, 11, 6, 14, 3, 1, 5, 6, 11, 3, 11, 6, 15, 2, 1, 6, 6, 9, 3, 12, 6, 16, 1, 1, 6, 6, 9, 3, 12, 6, 7, 1, 10, 7, 6, 7, 3, 13, 6, 6, 2, 10, 7, 6, 7, 3, 13, 14, 10, 8, 6, 5, 3, 14, 6, 6, 2, 10, 8, 6, 5, 3, 14, 6, 7, 1, 10, 9, 6, 3, 3, 15, 6, 16, 1, 1, 9, 6, 3, 3, 15, 6, 15, 2, 1, 10, 6, 1, 3, 16, 6, 14, 3, 1, 10, 10, 16, 6, 12, 5, 1, 11, 8, 13, 27, 1, 11, 8, 13, 27, 1, 60} end retLoveList –Return Space (English Char/Japanese Char) on returnSpc(aMode) if aMode = "E" then return " " –Single character Space if aMode = "J" then return " " –Japanese Double Width Space end returnSpc on retCirculateStrs(aText, repCharTimes) set aLen to length of aText set aTimes to repCharTimes div aLen set aMod to repCharTimes mod aLen set outStr to "" repeat aTimes times set outStr to outStr & aText end repeat if aMod is not equal to 0 then set aModStr to text 1 thru aMod of aText set outStr to outStr & aModStr end if return outStr end retCirculateStrs |
指定文字列前後から空白や改行を削除
AppleScript名:指定文字列前後から空白や改行を削除 |
— Created 2018-01-29 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" set aStr to " aaaaaa " set aString to current application’s NSString’s stringWithString:aStrset bStr to (aString’s stringByTrimmingCharactersInSet:(current application’s NSCharacterSet’s whitespaceAndNewlineCharacterSet())) return bStr as string –> "aaaaaa" |
自然言語による相対日付指定v15
AppleScript名:自然言語による相対日付指定v15 |
use AppleScript version "2.5" use scripting additions use framework "Foundation" –v15 ASOCの部品に入れ替え、macOS 10.11以降用にハンドラの型強制オプションをつけた –v14 10.8の上で動作するように書き換えた –The Calendar Scripting Module global d3List –3か月カレンダーの格納変数 global d4List –3か月カレンダーBの格納変数(当月の情報しか日付は入っていないカレンダー) global weekCounter — 今日が3か月カレンダーの何週目にあたるか set aDate to calcDate("今日", "") of me log {"今日:" & aDate as text} set aDate to calcDate("先々週", "水曜日") of me log {"先々週の水曜日:" & aDate as text} set aDate to calcDate("来週", "金曜") of me log {"来週の金曜日:" & aDate as text} on calcDate(param1 as string, param2 as string) –相対日付指定パラメータテーブル –data sample: {{"今日", "きょう"}, 0, "date"} –data format:{{"keyword_1", "keyword_2"…."keyword_n"}, vector, "class_of_this_keyword"} –Vector量をその場で(ユーザー環境に応じて)算出もしくは取得する必要がある場合には「999」を設定しておく set dDat to {{{"来年"}, 1, "year"}, {{"今年"}, 0, "year"}, {{"去年"}, -1, "year"}, {{"再来年"}, 2, "year"}, {{"今週"}, 0, "week"}, {{"先週"}, -1, "week"}, {{"先々週"}, -2, "week"}, {{"来週"}, 1, "week"}, {{"再来週"}, 2, "week"}, {{"今日", "きょう"}, 0, "date"}, {{"明日", "あした"}, 1, "date"}, {{"明後日", "あさって"}, 2, "date"}, {{"明々後日", "しあさって"}, 3, "date"}, {{"昨日", "きのう"}, -1, "date"}, {{"一昨日", "おととい"}, -2, "date"}, {{"一昨々日", "さきおととい"}, -3, "date"}, {{"次", "今度", "こんど", "つぎ"}, 1, "variable"}, {{"前"}, -1, "variable"}} –曜日指定パラメータ set wDat to {"日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日", "日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜", "にちようび", "げつようび", "かようび", "すいようび", "もくようび", "きんようび", "どようび", "にちよう", "げつよう", "かよう", "すいよう", "もくよう", "きんよう", "どよう"} –3か月カレンダーを作成 makeCalendar() of me –今日の日付を保持 set todayDate to current date –指定週の計算用ワーク変数 set targetWeek to 0 –指定月の計算用ワーク変数 set targetMonth to (month of todayDate) as number set targetYear to year of todayDate set targetDate to day of todayDate set aItem to "" repeat with i in dDat if param1 is in item 1 of i then copy i to aItem exit repeat end if end repeat if (item 3 of aItem) is "date" then log "Hit date class parameter" –dateレベルのパラメータの場合 set retDate to todayDate + (item 2 of aItem) * days set time of retDate to 0 return retDate –「時刻を問わない」ことを示す表現として、00時を指定してdate型を返す else if item 3 of aItem is "week" then log "hit week class parameter" –weekレベルのパラメータの場合 set targetWeek to weekCounter + (item 2 of aItem) if param2 is in wDat then –パラメータが「何曜日か?」を得る set tmpD to 1 repeat with j in wDat if param2 is contents of j then exit repeat set tmpD to tmpD + 1 end repeat if tmpD > 7 then set tmpD to tmpD mod 7 end if –今月か? if item tmpD of item targetWeek of d4List is 0 then –今月ではない場合 set tmp2 to item tmpD of item targetWeek of d3List if ((item 2 of aItem) < 0) then –今月ではなく、パラメータがマイナスの週計算を行う場合 –先月に入ったので月を減らす set targetMonth to targetMonth – 1 set tmp4 to (targetYear & "/" & targetMonth & "/" & tmp2) as string set ret2Date to date (tmp4 & " 0:00:00") return ret2Date else –来月として処理 set targetMonth to targetMonth + 1 set tmp4 to (targetYear & "/" & targetMonth & "/" & tmp2) as string set ret2Date to date (tmp4 & " 0:00:00") return ret2Date end if else –今月の場合の処理 set tmp2 to item tmpD of item targetWeek of d3List set tmp3 to day of todayDate set tmp4 to (targetYear & "/" & targetMonth & "/" & tmp2) as string set ret2Date to date (tmp4 & " 0:00:00") return ret2Date end if else –ここはエラーを返すべし("来週","")といったパターンになるので —-あるいは、「○○日」といったダイレクトパラメータの処理を行う –日付ダイレクトパラメータの処理 error "日付を特定するためのパラメータがありません" (* ただし、このように決め打ちでエラーメッセージを返すような実装は暫定仕様。 何が欠けているかをGUIフィードバックするのが最終的な実装 *) end if else if item 3 of aItem is "month" then –monthレベルのパラメータの場合 log "Hit month class parameter" else if item 3 of aItem is "year" then –yearレベルのパラメータの場合 log "Hit year class parameter" end if return "no hit" end calcDate –相対日付計算用の3か月カレンダーを作成する on makeCalendar() set aToday to current date –とりあえず、当月の情報を収集する set y1 to getYear(aToday) of me set m1 to getMonth(aToday) of me set d1 to getDate(aToday) of me set dy1 to getDay(aToday) of me set mlen1 to getMlen(y1, m1) of me set mXDay to getDay(aToday) of me –今日の曜日 –前月の情報を組み立てる if m1 is not equal to 1 then –2〜12月の場合 set y0 to y1 set m0 to m1 – 1 else –1月の場合 set y0 to y1 – 1 set m0 to 12 end if –前月の月の長さ set mLen0 to getMlen(y0, m0) of me –前月のみ開始日の曜日を求めておく必要がある(3か月カレンダーを作るため) set m0Date to (y0 & "/" & m0 & "/1 0:00:00") as text set m0Date to date m0Date set m0Day to getDay(m0Date) of me –1日の曜日 –翌月の情報を組み立てる if m1 is not equal to 12 then –1〜11月の場合 set y2 to y1 set m2 to m1 + 1 else –12月の場合 set y2 to y1 + 1 set m2 to 1 end if –翌月の月の長さ set mLen2 to getMlen(y2, m2) of me –3か月カレンダーの格納変数 set d3List to {} –3か月カレンダーBの格納変数(当月の情報しか日付は入っていないカレンダー) set d4List to {} set gapList to {0, 0, 0, 0, 0, 0, 0} set w1temp to items 1 thru (m0Day) of gapList set w2temp to items 1 thru (m0Day) of gapList set dayCounter to 1 –最初の1週目の要素を組み立てる repeat with i from m0Day to 7 set the end of w1temp to dayCounter set the end of w2temp to 0 set dayCounter to dayCounter + 1 end repeat set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} –前月の通常処理 repeat repeat with i from 1 to 7 set the end of w1temp to dayCounter set the end of w2temp to 0 set dayCounter to dayCounter + 1 if dayCounter > mLen0 then exit repeat end repeat if dayCounter > mLen0 then exit repeat set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} end repeat –ここから当月処理 –1週目 if i = 7 then set ii to 1 set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} else set ii to i + 1 end if set dayCounter to 1 –日付カウンタの初期化 repeat with j from ii to 7 set the end of w1temp to dayCounter set the end of w2temp to dayCounter set dayCounter to dayCounter + 1 end repeat set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} –当月の2週目以降 repeat repeat with j from 1 to 7 set the end of w1temp to dayCounter set the end of w2temp to dayCounter set dayCounter to dayCounter + 1 if dayCounter > mlen1 then exit repeat end repeat if dayCounter > mlen1 then exit repeat set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} end repeat –ここから翌月処理 –1週目 if j = 7 then set iii to 1 set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} else set iii to j + 1 end if set dayCounter to 1 –日付カウンタの初期化 repeat with j from iii to 7 set the end of w1temp to dayCounter set the end of w2temp to 0 set dayCounter to dayCounter + 1 end repeat set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} –翌月の2週目以降 repeat repeat with k from 1 to 7 set the end of w1temp to dayCounter set the end of w2temp to 0 set dayCounter to dayCounter + 1 if dayCounter > mlen1 then exit repeat end repeat if dayCounter > mlen1 then exit repeat set the end of d3List to w1temp set the end of d4List to w2temp set w1temp to {} set w2temp to {} end repeat if length of w1temp is not equal to 0 then set the end of d3List to w1temp set the end of d4List to w2temp end if –ここまで3か月カレンダーの生成 –3か月カレンダーにおいて今日が何週目かを算出 set weekCounter to 1 repeat with aWeek in d4List –裏リストで操作を行う –ただし、該当曜日しかチェックしないので全チェックに比べて速度7倍 set aDay to (item mXDay of aWeek) as number if aDay = (d1 as number) then exit repeat end if set weekCounter to weekCounter + 1 end repeat end makeCalendar –現在日時から曜日を取得を返す on getDay(aDate as date) return (weekday of aDate) as number end getDay –指定日の月のみ返す on getMonth(aDat as date) return (month of aDat) as number end getMonth –指定日の日付のみ返す on getDate(aDat as date) return (day of aDat) as number end getDate –指定日の年のみ返す on getYear(aDat as date) return (year of aDat) as number end getYear –現在のカレンダーで指定年月の日数を返す(国際化対応版) on getMlen(aYear as integer, aMonth as integer) set theNSCalendar to current application’s NSCalendar’s currentCalendar() set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:1 hour:0 minute:0 |second|:0 nanosecond:0 set theResult to theNSCalendar’s rangeOfUnit:(current application’s NSDayCalendarUnit) inUnit:(current application’s NSMonthCalendarUnit) forDate:theDate return |length| of theResult end getMlen |
クリップボードに入ったproperty宣言部分を見た目の描画サイズ(幅)と文字コードでソート
クリップボードに入れたproperty宣言文を見た目の描画サイズ(幅)で行単位の並べ替えを行うAppleScriptです。
property文でCocoaのClass名を定義しており、これを整形するために文字数で短いものから長いものへ並べてみたところ、プロポーショナルフォントで表示されるために「美しく」はなりませんでした。実際に仮装画面上でスタイル付きテキストの描画を行って、描画サイズ(幅)を取得して並べ替えを行ってみたものです。
OLD Style AppleScriptの機能の範囲では逆立ちしても実現できない処理内容です。
AppleScript名:クリップボードに入ったproperty宣言部分を見た目の描画サイズ(幅)と文字コードでソート |
— Created 2017-12-08 by Takaaki Naganoya — 2017 Piyomaru Software use AppleScript version "2.5" use scripting additions use framework "Foundation" use framework "AppKit" property NSFont : a reference to current application’s NSFont property NSData : a reference to current application’s NSData property NSColor : a reference to current application’s NSColor property NSArray : a reference to current application’s NSArray property NSString : a reference to current application’s NSString property NSDictionary : a reference to current application’s NSDictionary property NSPasteboard : a reference to current application’s NSPasteboard property NSCountedSet : a reference to current application’s NSCountedSet property NSMutableArray : a reference to current application’s NSMutableArray property NSSortDescriptor : a reference to current application’s NSSortDescriptor property NSAttributedString : a reference to current application’s NSAttributedString property NSMutableDictionary : a reference to current application’s NSMutableDictionary property NSFontAttributeName : a reference to current application’s NSFontAttributeName property NSKernAttributeName : a reference to current application’s NSKernAttributeName property NSMutableParagraphStyle : a reference to current application’s NSMutableParagraphStyle property NSLigatureAttributeName : a reference to current application’s NSLigatureAttributeName property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString property NSUnderlineStyleAttributeName : a reference to current application’s NSUnderlineStyleAttributeName property NSParagraphStyleAttributeName : a reference to current application’s NSParagraphStyleAttributeName property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName –クリップボードの内容を文字列として取得 set aStr to (the clipboard) as string if aStr = "" then display dialog "No Data in Clipboard" buttons {"OK"} default button 1 return end if –クリップボードの内容をStyled Stringで取得して最頻出フォントを取得 set clipboardAttrStr to getClipboardASStyledText() of me if clipboardAttrStr = missing value then display dialog "Can not get clipboard as Styled String" buttons {"OK"} default button 1 return end if set attrList to getAttributeRunsFromAttrString(clipboardAttrStr) of me set anArray to (NSArray’s arrayWithArray:attrList)’s valueForKeyPath:"fontName" set aFontList to (countItemsByItsAppearance(anArray) of me) set aFontName to theName of first item of aFontList –クリップボードから取得した文字データについて処理 set aList to paragraphs of aStr –行ごとにparseしてlist化 set bList to {} repeat with i in aList set j to contents of i if j ≠ {} then set jList to words of j if jList ≠ {} then if contents of first item of jList = "property" then set curLabel to contents of second item of jList –行をAttributed Stringとして組み立てて、画面描画時の仕上がりサイズを取得 set anAssrStr to makeRTFfromParameters(j, aFontName, 16, -2, 16) of me set aSize to anAssrStr’s |size|() –画面描画時のサイズを取得 if class of aSize = record then set attrStrWidth to width of aSize set attrStrHeight to height of aSize else if class of aSize = list then –macOS 10.13.xのバグ回避 copy aSize to {attrStrWidth, attrStrHeight} end if set the end of bList to {aLabel:curLabel, aCon:j, aWidth:attrStrWidth} end if end if end if end repeat if bList = {} then display dialog "Error" buttons {"OK"} default button 1 return end if –複数キーでソート(書式つきテキストの仕上がりサイズ幅、文字コード順でソート) set aArray to NSArray’s arrayWithArray:bList set desc1 to NSSortDescriptor’s sortDescriptorWithKey:"aWidth" ascending:true set desc2 to NSSortDescriptor’s sortDescriptorWithKey:"aLabel" ascending:true selector:"localizedCaseInsensitiveCompare:" set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2} –ソートしたlist of recordからaCon(元のproperty宣言行そのもの)を一括で取り出す set dArray to (NSMutableArray’s arrayWithArray:bArray)’s valueForKeyPath:"aCon" –listをデリミタつきのテキストに set dStr to retStrFromArrayWithDelimiter(dArray, return) of me set the clipboard to (dStr & return) –1D Listを文字列長でソート v2 on sort1DListByIndicatedStringLength(aList as list, aSortKey as string, sortOrder as boolean) set aArray to NSArray’s arrayWithArray:aList set descLabel1 to NSString’s stringWithString:(aSortKey & ".length") set descLabel2 to NSString’s stringWithString:aSortKey set desc1 to NSSortDescriptor’s sortDescriptorWithKey:descLabel1 ascending:sortOrder set desc2 to NSSortDescriptor’s sortDescriptorWithKey:descLabel2 ascending:true selector:"localizedCaseInsensitiveCompare:" set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2} return bArray as list end sort1DListByIndicatedStringLength –リストを指定デリミタをはさんでテキスト化 on retStrFromArrayWithDelimiter(aList as list, aDelim as string) set anArray to NSArray’s arrayWithArray:aList set aRes to anArray’s componentsJoinedByString:aDelim return aRes as text end retStrFromArrayWithDelimiter –書式つきテキストを組み立てる on makeRTFfromParameters(aStr as string, fontName as string, aFontSize as real, aKerning as real, aLineSpacing as real) set aVal1 to NSFont’s fontWithName:fontName |size|:aFontSize set aKey1 to (NSFontAttributeName) set aVal2 to NSColor’s blackColor() set aKey2 to (NSForegroundColorAttributeName) set aVal3 to aKerning set akey3 to (NSKernAttributeName) set aVal4 to 0 set akey4 to (NSUnderlineStyleAttributeName) set aVal5 to 2 –all ligature ON set akey5 to (NSLigatureAttributeName) set aParagraphStyle to NSMutableParagraphStyle’s alloc()’s init() aParagraphStyle’s setMinimumLineHeight:(aLineSpacing) aParagraphStyle’s setMaximumLineHeight:(aLineSpacing) set akey7 to (NSParagraphStyleAttributeName) set keyList to {aKey1, aKey2, akey3, akey4, akey5, akey7} set valList to {aVal1, aVal2, aVal3, aVal4, aVal5, aParagraphStyle} set attrsDictionary to NSMutableDictionary’s dictionaryWithObjects:valList forKeys:keyList set attrStr to NSMutableAttributedString’s alloc()’s initWithString:aStr attributes:attrsDictionary return attrStr end makeRTFfromParameters — クリップボードの内容をNSAttributedStringとして取り出して返す on getClipboardASStyledText() set theNSPasteboard to NSPasteboard’s generalPasteboard() set theAttributedStringNSArray to theNSPasteboard’s readObjectsForClasses:({NSAttributedString}) options:(missing value) set theNSAttributedString to theAttributedStringNSArray’s objectAtIndex:0 return theNSAttributedString end getClipboardASStyledText –指定のNSAttributedStringから書式情報をlist of recordで取得 on getAttributeRunsFromAttrString(theStyledText) script aSpd property styleList : {} end script set (styleList of aSpd) to {} —for output set thePureString to theStyledText’s |string|() –pure string from theStyledText set theLength to theStyledText’s |length|() set startIndex to 0 repeat until (startIndex = theLength) set {theAtts, theRange} to theStyledText’s attributesAtIndex:startIndex longestEffectiveRange:(reference) inRange:{startIndex, theLength – startIndex} set aText to (thePureString’s substringWithRange:theRange) as string set aColor to (theAtts’s valueForKeyPath:"NSColor") if aColor is not equal to missing value then set aSpace to aColor’s colorSpace() set aRed to (aColor’s redComponent()) * 255 set aGreen to (aColor’s greenComponent()) * 255 set aBlue to (aColor’s blueComponent()) * 255 set colList to {aRed as integer, aGreen as integer, aBlue as integer} set colStrForFind to (aRed as integer as string) & " " & (aGreen as integer as string) & " " & (aBlue as integer as string) else set colList to {0, 0, 0} set colStrForFind to "0 0 0" end if set aFont to (theAtts’s valueForKeyPath:"NSFont") if aFont is not equal to missing value then set aDFontName to aFont’s displayName() set aDFontSize to aFont’s pointSize() end if set the end of (styleList of aSpd) to {stringVal:aText, colorStr:colStrForFind, colorVal:colList, fontName:aDFontName as string, fontSize:aDFontSize} set startIndex to current application’s NSMaxRange(theRange) end repeat return (styleList of aSpd) end getAttributeRunsFromAttrString –1D Listをアイテムの出現頻度順でソートして返す on countItemsByItsAppearance(aList as list) set aSet to NSCountedSet’s alloc()’s initWithArray:aList set bArray to 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:(NSDictionary’s dictionaryWithObjects:{aValue, (aSet’s countForObject:aValue)} forKeys:{"theName", "numberOfTimes"}) end repeat set theDesc to NSSortDescriptor’s sortDescriptorWithKey:"numberOfTimes" ascending:false bArray’s sortUsingDescriptors:{theDesc} return bArray as list end countItemsByItsAppearance |
16進数文字列とNumberの相互変換 v2.2
AppleScript名:16進数文字列とNumberの相互変換 v2.2 |
— Created 2018-01-20 by Takaaki Naganoya — 2018 Piyomaru Software use AppleScript version "2.4" use scripting additions use framework "Foundation" repeat with i from 0 to 65535 set aRes to numToHexl(i) of hexKit set bRes to hextoNum(aRes) of hexKit if i ≠ bRes then display dialog "Not equal to " & (i as string) & " —> " & aRes & " —> " & bRes end repeat script hexKit property hexList : {missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, missing value, 10, 11, 12, 13, 14, 15} property stringSetList : {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"} –16進数文字列からNumberに変換 on hextoNum(hexText as string) set hList to characters of hexText set rhList to reverse of hList set digitNum to 0 set sumNum to 0 repeat with i in rhList set j to id of contents of i if j > 102 then return false set ofN to contents of item j of hexList of me if ofN = missing value then return false set sumNum to sumNum + (16 ^ digitNum) * (ofN) set digitNum to digitNum + 1 end repeat return sumNum as integer end hextoNum –数値を16進数文字列に変換 on numToHexl(origNum) if origNum = 0 then return "0" set resString to {} repeat if origNum ≤ 0 then exit repeat set resNum to (origNum mod 16) set resText to contents of item (resNum + 1) of stringSetList set resString to resText & resString set origNum to origNum div 16 end repeat return (resString as string) end numToHexl end script |
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: |
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 |
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 |