Menu

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

AppleScriptの穴

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

カテゴリー: Text

base64エンコード、デコード v3

Posted on 2月 8, 2018 by Takaaki Naganoya

テキストのBase64エンコード/デコードを行うAppleScriptです。

このような基本的なデータ変換機能についてはAppleScript標準で持っていないため、Classic MacOS時代にはOSAX(Scripting Additions)で、Mac OS X時代になってからは他の言語処理系の機能を借りたり、Mac OS X用のOSAXを利用していたりしましたが、現在のmacOSではCocoaの機能を呼び出すのが一番手頃になってきました。

# サードパーティ製のOSAX(Scripting Additions)サポートはmacOS 10.14で廃止になりました。macOS標準搭載のStandard Additionsのみ利用可能です

AppleScript名:base64エンコード、デコード v3
— Created 2015-07-27 by Takaaki Naganoya
— Updated 2015-07-28 by Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to "ぴよまるソフトウェアPiyomaru Software"
set theNSString to current application’s NSString’s stringWithString:aStr
set theNSData to theNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
set bStr to base64StringFromFileString(aStr) of me
return bStr
–>  "44G044KI44G+44KL44K944OV44OI44Km44Kn44KiUGl5b21hcnUgU29mdHdhcmU="

–set aFilePath to POSIX path of (choose file)
–base64StringFromFileAtPath(aFilePath) of me

–Base 64 Decode
on detaFromBase64String(aStr)
  set dataFrom64 to current application’s NSData’s alloc()’s initWithBase64EncodedString:aStr options:(current application’s NSDataBase64DecodingIgnoreUnknownCharacters)
  
set aStr to current application’s NSString’s alloc()’s initWithData:dataFrom64 encoding:(current application’s NSUTF8StringEncoding)
  
return aStr as text –stringではなくtext
end detaFromBase64String

–Base64 Encode
on base64StringFromFileAtPath(aFilePath)
  set aDataFromFile to current application’s NSData’s dataWithContentsOfFile:aFilePath
  
set aBase64EncStr to aDataFromFile’s base64EncodedStringWithOptions:(current application’s NSDataBase64Encoding64CharacterLineLength)
  
return aBase64EncStr as text
end base64StringFromFileAtPath

–Base64 Encode
on base64StringFromFileString(aString)
  set bString to current application’s NSString’s stringWithString:aString
  
set aData to bString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aBase64EncStr to aData’s base64EncodedStringWithOptions:(current application’s NSDataBase64Encoding64CharacterLineLength)
  
return aBase64EncStr as text
end base64StringFromFileString

★Click Here to Open This Script 

Posted in Record Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

デコードしたQRコードのメールデータの各フィールドを取り出す v2.2

Posted on 2月 8, 2018 by Takaaki Naganoya
AppleScript名:デコードしたQRコードのメールデータの各フィールドを取り出す v2.2
— Created 2016-12-12 by Shane Stanley
— Modified 2016-12-14 by edama2
— Modified 2017-01-12 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to "こんにちは、ぴよまるです

MATMSG:TO:hiyoko@piyocast.com;SUB:たいとる;BODY:ほんぶん;;

Takaaki Naganoya
XXX-XXXX-XXXX

iPhoneから送信"

set aDict to (parseStrByParamlabelAndTail(aStr, "MATMSG:", ":", ";") of me)

set eMailAddrs to (aDict’s valueForKey:"TO") as string
–>  "hiyoko@piyocast.com"
set aSubject to (aDict’s valueForKey:"SUB") as string
–>  "たいとる"
set aBody to (aDict’s valueForKey:"BODY") as string
–>  "ほんぶん"

on parseStrByParamlabelAndTail(aParamStr, aDataHeader, aParamLabel, aParamTail)
  set theScanner to current application’s NSScanner’s scannerWithString:aParamStr
  
set aDict to current application’s NSMutableDictionary’s |dictionary|()
  
  
—Skip over the data header
  
set {theResult, theKey} to theScanner’s scanUpToString:aDataHeader intoString:(reference)
  
if theResult as boolean = false then return false –Error: Data header is not present
  
  
theScanner’s scanString:aDataHeader intoString:(missing value)
  
  
repeat until (theScanner’s isAtEnd as boolean)
    — terminate check, return the result (aDict) to caller
    
set {theResult, theKey} to theScanner’s scanUpToString:aParamLabel intoString:(reference)
    
    
— skip over separator
    
theScanner’s scanString:aParamLabel intoString:(missing value)
    
set {theResult, theValue} to theScanner’s scanUpToString:aParamTail intoString:(reference)
    
if theValue is missing value then set theValue to ""
    
    
— skip over separator
    
theScanner’s scanString:aParamTail intoString:(missing value)
    
    
aDict’s setObject:theValue forKey:theKey
  end repeat
  
  
return aDict
end parseStrByParamlabelAndTail

★Click Here to Open This Script 

Posted in Record Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

なろう系ルビタグを置換

Posted on 2月 8, 2018 by Takaaki Naganoya
AppleScript名:なろう系ルビタグを置換
— Created 2018-01-14 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

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

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

asHTMLexportLib v2

Posted on 2月 8, 2018 by Takaaki Naganoya

指定のAppleScript書類をスクリプトエディタでオープンし、書式情報を読み取ってURLリンク付きのHTML(テキスト)を生成するAppleScriptです。AppleScript Librariesとして他のScriptから呼び出して利用しています。

オリジナルは2006年ごろに作成したもので、「秘伝のタレ」よろしくその時々のOSの変更を反映させて使い続けています。

AppleScriptの書式(とくに色情報)をHTML書き出し時にどのように反映させるかについては、いろいろと「流派」があり、

 ・スクリプトエディタ上の色情報を読み取ってそのままカラータグで展開する派
 ・CSSなどで構文要素ごとにスタイルを指定する派

で、本Scriptは前者の方式で書かれた最古のScriptの末裔です。書き出しHTMLが長くなるというデメリットはあるものの、構造の単純さが幸いしてわずかな修正でメンテナンスを継続できています。

当初、AppleScriptからスクリプトエディタをコントロールすると不具合が多く、他のAppleScript開発環境(Script Debugger)からの実行を余儀なくされていました。macOS 10.6あたりでずいぶん安定して利用できるようになってきた記憶があります(10.3とか10.4はいま思い出しても辛かった)。

HTMLに埋め込むURLスキーム「applescript:」からは、AppleScriptの新規作成、作成中のAppleScript書類のカーソル位置へのペースト、書類末尾へのペーストなどの動作を指定できますが、結局Blogに10年前からつけているURLリンクもそれほど認識されておらず(なぜ??)、新規作成のリンクのみ付加するように変更しました。

また、「applescript:」のURLリンクでは生成するAppleScript書類のファイル名をあらかじめ指定できるようになっているものの、古いバージョンのmacOS(Mac OS X)ではこの名称指定が仇となってURLリンクが認識されないという問題が発生するため、名称も指定していません。

一応、書き出し対象ファイルがAppleScriptかJavaScriptかを判定して、書き出し時のカラーリングを変更するようになっています。OSAScriptフレームワーク経由で書類から直接OSA言語の種別は取得できるものの、スクリプトエディタ自体から情報を取得しても手間はたいして変わらないので現状のようになっています。

AppleScript名:asHTMLexportLib
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property quotChar : string id 34

property headerCol : "0000CC" –"0000CC" –ヘッダー部分(濃い色)
property bodyBackCol : "EEFFFF" –"EEFFFF" –Script本文下地(薄い色)
property footerCol : "66FFFF" –"66FFFF" –スクリプトリンク部分
property repMark : "_replacepoint_"

on run
  set aPath to choose file of type {"com.apple.applescript.script", "com.apple.applescript.script-bundle"}
  
set aRes to retScriptHTML(aPath) of me
end run

on retScriptHTML(aPath) –parameter is alias
  script spd
    property TIDsList : {}
    
property dataOut : {}
    
property textList : {}
    
property colorList : {}
  end script
  
  
set pName to "com.apple.ScriptEditor2"
  
  
tell application id pName
    set asDoc to open aPath
    
    
tell asDoc –front document
      set aInfo to properties
      
set curLang to name of language of aInfo –現在のOSA言語の名称を取得する
    end tell
    
    
–OSA Language名称をもとに色セットを変更する
    
changeColor(curLang) of me
    
    
set c to name of asDoc –front document
    
    
set aF to aPath as string –retMacOSpathList(aPath) of me
    
    
set contText to getContentsOfFile(asDoc) of me –front document
    
set encText to makeEncodedScript(contText) of me
    
    
set newLinkText to "applescript://com.apple.scripteditor?action=new&script=" & encText
    
–set insLinkText to "applescript://com.apple.scripteditor?action=insert&script=" & encText
    
–set apndLinkText to "applescript://com.apple.scripteditor?action=append&script=" & encText
    
    
set comText to description of asDoc –front document
    
    
set (textList of spd) to getAttributeRunOfFile(asDoc) of me —every attribute run of asDoc –front document
    
set (colorList of spd) to getColorOfAttributeRunOfFile(asDoc) of me —color of every attribute run of asDoc –front document
    
  end tell
  
  
set tabChar to string id 9
  
  
set (TIDsList of spd) to {{"\\", "\"}, {"’", "’"}, {"&", "&amp;"}, {">", "&gt;"}, {"<", "&lt;"}, {"  ", "  "}, {string id 13, "<br>"}, {string id 10, "<br>"}, {"\"", "&quot;"}}
  
  
  
set (dataOut of spd) to {}
  
  
set iCounter to 1
  
repeat with i in (textList of spd)
    set j to contents of i
    
    
set curDelim to AppleScript’s text item delimiters
    
repeat with eachItem in (TIDsList of spd)
      set AppleScript’s text item delimiters to contents of item 1 of eachItem
      
set j to every text item of j
      
set AppleScript’s text item delimiters to contents of item 2 of eachItem
      
set j to j as string
    end repeat
    
set AppleScript’s text item delimiters to curDelim
    
    
set cText to RBG2HTML(item iCounter of (colorList of spd)) of me
    
    
set the end of (dataOut of spd) to "<font color=" & cText & ">" & j & "</font>"
    
set iCounter to iCounter + 1
  end repeat
  
  
  
set htmlHeader to "<table width=" & quotChar & "100%" & quotChar & " border=" & quotChar & "0" & quotChar & "cellspacing=" & quotChar & "2" & quotChar & " cellpadding=" & quotChar & "2" & quotChar & ">
<tr>
<td bgcolor=\"#" & headerCol & "\"><font color=" & quotChar & "#FFFFFF" & quotChar & ">" & curLang & "名:" & c
  
  
if comText is not equal to "" then
    set comText to "<br><font size=" & quotChar & "2" & quotChar & ">【Comment】 " & comText & "</font><br>"
  end if
  
  
set htmlHeader2 to "</font></td>
</tr>
<tr>
<td bgcolor=\"#" & bodyBackCol & "\"><font size=\"3\">"
  
  
set htmlFooter1 to "</font></td>
</tr>
<tr>
<td bgcolor=\"#" & footerCol & "\"><p><font size=\"2\"><a href=\"" & newLinkText & "\">★Click Here to Open This Script</a> </font></p>
</td>
</tr>
</table>
"

  
  
set dataText to htmlHeader & comText & htmlHeader2 & ((dataOut of spd) as text) & htmlFooter1
  
set dataText to dataText as Unicode text
  
  
tell application id pName
    close asDoc without saving
    
–close front document without saving
  end tell
  
  
return dataText
end retScriptHTML

on makeEncodedScript(contText)
  set aList to every paragraph of contText
  
set aClass to class of aList
  
if aClass = list then
    set aLen to length of aList
  else
    set aLen to 1
  end if
  
  
set aaList to {}
  
  
set delim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to repMark
  
set bList to aList as text
  
set AppleScript’s text item delimiters to delim
  
  
set aaList to (retURLencodedStrings(bList) of me) as text
  
  
set search_string to retURLencodedStrings(repMark) of me –"%5Freplacepoint%5F" as text
  
set replacement_string to "%0D" as text
  
set bList to replace_chars(aaList, search_string, replacement_string) of me
  
  
return bList
end makeEncodedScript

–RGB値からHTMLの色指定に変換
on RBG2HTML(RGB_values)
  — NOTE: this sub-routine expects the RBG values to be from 0 to 65536
  
set the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
  
set the the hex_value to ""
  
repeat with i from 1 to the count of the RGB_values
    set this_value to (item i of the RGB_values) div 256
    
if this_value is 256 then set this_value to 255
    
set x to item ((this_value div 16) + 1) of the hex_list
    
set y to item (((this_value / 16 mod 1) * 16) + 1) of the hex_list
    
set the hex_value to (the hex_value & x & y) as string
  end repeat
  
return ("#" & the hex_value) as string
end RBG2HTML

on replace_chars(this_text, search_string, replacement_string)
  set AppleScript’s text item delimiters to the search_string
  
set the item_list to every text item of this_text
  
set AppleScript’s text item delimiters to the replacement_string
  
set this_text to the item_list as string
  
set AppleScript’s text item delimiters to ""
  
return this_text
end replace_chars

on retURLencodedStrings(aText)
  set aStr to current application’s NSString’s stringWithString:aText
  
set encodedStr to aStr’s stringByAddingPercentEncodingWithAllowedCharacters:(current application’s NSCharacterSet’s alphanumericCharacterSet())
  
return encodedStr as text
end retURLencodedStrings

on changeColor(aLang)
  if aLang = "AppleScript" then
    set headerCol to "0000CC" –"0000CC" –ヘッダー部分(濃い色)
    
set bodyBackCol to "EEFFFF" –"EEFFFF" –Script本文下地(薄い色)
    
set footerCol to "66FFFF" –"66FFFF" –スクリプトリンク部分
  else if aLang = "JavaScript" then
    set headerCol to "804000" –"0000CC" –ヘッダー部分(濃い色)
    
set bodyBackCol to "E2D3D3" –"EEFFFF" –Script本文下地(薄い色)
    
set footerCol to "E7AC53" –"66FFFF" –スクリプトリンク部分
  end if
end changeColor

on getContentsOfFile(asDoc)
  tell application id "com.apple.ScriptEditor2"
    set aCon to (properties of asDoc)
  end tell
  
return contents of aCon
end getContentsOfFile

on getAttributeRunOfFile(asDoc)
  tell application id "com.apple.ScriptEditor2"
    set aCon to (every attribute run of asDoc)
  end tell
  
return aCon
end getAttributeRunOfFile

on getColorOfAttributeRunOfFile(asDoc)
  tell application id "com.apple.ScriptEditor2"
    set aCon to color of (every attribute run of asDoc)
  end tell
  
return aCon
end getColorOfAttributeRunOfFile

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | 1 Comment

2D ListをCSVに v3(サニタイズ処理つき)

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:2D ListをCSVに v3(サニタイズ処理つき)
— Created 2015-10-01 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aNewFile to choose file name

set dataList to {{"0010", "ひよこタオルギフト", "200", "手に取ったとき、\"使うとき\"、ちょっと楽しくてかわいいひよこのタオル。", "●サイズ/H200㎜×W200㎜●素材/ひよこ羽毛100%●重量/170g●内容/5枚入り"}, {"0020", "ひよこホイッスル", "250", "今までにないデザインの、ひよこ型のホイッスル。ぴよ〜音を音階で吹き分けます。", "●サイズ/H60㎜×W40㎜×D10㎜●素材/プラスチック
●色/ひよこ色●重量/10g●付属品/首かけロープ付き
●型番/PIYO1"
}}

saveAsCSV(dataList, aNewFile) of me

–2D List to CSV file
on saveAsCSV(aList, aPath)
  –set crlfChar to (ASCII character 13) & (ASCII character 10)
  
set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
write_to_file(wholeText, bPath, false) of me
  
end saveAsCSV

on write_to_file(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end write_to_file

on repChar(origText as text, targChar as text, repChar as text)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repChar

★Click Here to Open This Script 

Posted in file list Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

CSVのParse 5(ASOC)

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:CSVのParse 5(ASOC)
–Created By Shane Stanley 2015/03/12
–Commented & Arranged By Takaaki Naganoya 2015/03/12

use scripting additions
use framework "Foundation"

set theString to "cust1,\"prod,1\",season 1,
cust1,prod1,season2,
cust2,prod1,event1,season1
cust2,prod3,event1,season 1"

its makeListsFromCSV:theString commaIs:","
–>  {​​​​​{​​​​​​​"cust1", ​​​​​​​"prod,1", ​​​​​​​"season 1"​​​​​}, ​​​​​{​​​​​​​"cust1", ​​​​​​​"prod1", ​​​​​​​"season2"​​​​​}, ​​​​​{​​​​​​​"cust2", ​​​​​​​"prod1", ​​​​​​​"event1", ​​​​​​​"season1"​​​​​}, ​​​​​{​​​​​​​"cust2", ​​​​​​​"prod3", ​​​​​​​"event1", ​​​​​​​"season 1"​​​​​}​​​}

–CSV Parser ASOC ver (Translated from "ASObjCExtras.framework" Objective-C version)
on makeListsFromCSV:theString commaIs:theComma
  
  
set theRows to {} –最終的に出力するデータ(2D Listになる)
  
  
set newLineCharSet to current application’s NSCharacterSet’s newlineCharacterSet() –改行キャラクタ
  
set importantCharSet to current application’s NSMutableCharacterSet’s characterSetWithCharactersInString:("\"" & theComma) –カンマ
  
  
importantCharSet’s formUnionWithCharacterSet:newLineCharSet
  
  
set theNSScanner to current application’s NSScanner’s scannerWithString:theString
  
theNSScanner’s setCharactersToBeSkipped:(missing value)
  
  
  
–データ末尾を検出するまでループ
  
repeat while (theNSScanner’s isAtEnd() as integer = 0)
    
    
set insideQuotes to false
    
set finishedRow to false
    
set theColumns to {}
    
set currentColumn to ""
    
    
–すべての行を処理終了するまでループ(行内部の処理)
    
repeat while (not finishedRow)
      
      
set {theResult, tempString} to theNSScanner’s scanUpToCharactersFromSet:importantCharSet intoString:(reference)
      
–log {"theResult", theResult, "tempString", tempString}
      
      
if theResult as integer = 1 then set currentColumn to currentColumn & (tempString as text)
      
–log {"currentColumn", currentColumn}
      
      
–データ末尾検出
      
if theNSScanner’s isAtEnd() as integer = 1 then
        if currentColumn is not "" then set end of theColumns to currentColumn
        
set finishedRow to true
        
      else
        –データ末尾ではない場合
        
set {theResult, tempString} to theNSScanner’s scanCharactersFromSet:newLineCharSet intoString:(reference)
        
        
if theResult as integer = 1 then
          
          
if insideQuotes then
            –ダブルクォート文字内の場合
            
set currentColumn to currentColumn & (tempString as text)
          else
            –ダブルクォート内ではない場合
            
if currentColumn is not "" then set end of theColumns to currentColumn
            
set finishedRow to true
          end if
          
        else
          –行末文字が見つからない場合
          
set theResult to theNSScanner’s scanString:"\"" intoString:(missing value)
          
          
if theResult as integer = 1 then
            –ダブルクォート文字が見つかった場合
            
if insideQuotes then
              –ダブルクォート文字内の場合
              
set theResult to theNSScanner’s scanString:"\"" intoString:(missing value)
              
              
if theResult as integer = 1 then
                set currentColumn to currentColumn & "\""
              else
                set insideQuotes to (not insideQuotes)
              end if
            else
              –ダブルクォート文字内ではない場合
              
set insideQuotes to (not insideQuotes)
            end if
            
          else
            –ダブルクォート文字が見つからなかった場合
            
set theResult to theNSScanner’s scanString:theComma intoString:(missing value) –カンマの検索
            
            
if theResult as integer = 1 then
              if insideQuotes then
                set currentColumn to currentColumn & theComma
              else
                set end of theColumns to currentColumn
                
set currentColumn to ""
                
theNSScanner’s scanCharactersFromSet:(current application’s NSCharacterSet’s whitespaceCharacterSet()) intoString:(missing value)
              end if
            end if
          end if
        end if
      end if
      
    end repeat
    
    
if (count of theColumns) > 0 then set end of theRows to theColumns –行データ(1D List)をtheRowsに追加(2D List)
    
  end repeat
  
  
return theRows
  
end makeListsFromCSV:commaIs:

★Click Here to Open This Script 

Posted in file list Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

CSVのParse 4a(ASOC)

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:CSVのParse 4a(ASOC)
— Created 2015-03-11 by Shane Stanley
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 someString to read (choose file of type {"public.comma-separated-values-text"})

set theData to current application’s SMSForder’s arrayFromCSV:someString commaIs:","
set theData to (current application’s SMSForder’s subarraysIn:theData paddedWith:"" |error|:(missing value)) as list
–>  {​​​​​{​​​​​​​"cust1", ​​​​​​​"prod,1", ​​​​​​​"season 1", ​​​​​​​""​​​​​}, ​​​​​{​​​​​​​"cust1", ​​​​​​​"prod1", ​​​​​​​"season 2", ​​​​​​​""​​​​​}, ​​​​​{​​​​​​​"cust2", ​​​​​​​"prod1", ​​​​​​​"event1", ​​​​​​​"season 1"​​​​​}, ​​​​​{​​​​​​​"cust2", ​​​​​​​"prod2", ​​​​​​​"event1", ​​​​​​​"season 2"​​​​​}, ​​​​​{​​​​​​​"cust2", ​​​​​​​"prod3", ​​​​​​​"event1", ​​​​​​​"season 1"​​​​​}​​​}

★Click Here to Open This Script 

Posted in file list Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

なんでもデータを文字列化 v2

Posted on 2月 7, 2018 by Takaaki Naganoya

数値でもリストでもレコードでもなんでも文字列化するAppleScriptです。

大規模なシステムを作っているときに、ログに詳細なデータを書き込む必要があって、その入り組んだrecordから各種要素を取り出すのが嫌だったので、「そのまま文字列化してしまえ」と考えて作成したものです。

エラートラップを仕掛けてわざとエラーを発生させ、エラーメッセージに表記されているデータを加工して出力するというトリッキーかつやけっぱちな処理内容ですが、たしかに動作し、日本語以外の言語環境でもきちんと動くためひそかに利用されている処理です。

ただし、本ルーチンではアプリケーションのオブジェクトを含むデータの文字列化が行えないので、のちになって作成したOSAScriptControllerで実際にAppleScriptを実行して結果をすべて文字列で取得するようなタイプのものに入れ替えています。

AppleScript名:なんでもデータを文字列化 v2
set a to {{aName:"PiyoPiyo", anAge:10}, {aName:"Piyoko", anAge:9}} –record in list
–set a to {aName:"PiyoPiyo", anAge:10}–record
–set a to {{1, 2, 3}, {4, 5, 6}}–list
–set a to 1.0 as real–real
–set a to 1 as integer–integer
–set a to "1.0" as string–string
–set a to true–boolean
–set a to front window of application "Finder"–アプリケーションのオブジェクトはエラーになるよ!
–set a to missing value

set aRes to convToStr(a) of somethingToStrKit
–> "{{aName:\"PiyoPiyo\", anAge:10}, {aName:\"Piyoko\", anAge:9}}"

–リストでもレコードでもなんでも文字列化して返すキット
script somethingToStrKit
  
  
on convToStr(aRec)
    
    
set aClass to (class of aRec) as string
    
    
if (aClass = "integer") or (aClass = "number") or (aClass = "real") or (aClass = "string") or (aClass = "text") or (aClass = "Unicode text") or (aClass = "boolean") then
      set aRes to aRec as string
    else if aClass is "list" then
      set aRes to listToString(aRec)
    else if aClass is "record" then
      set aRes to recToString(aRec)
    else
      try
        set aRes to aRec as string
      on error
        –アプリケーションのオブジェクトとかはエラーで返す
        
return false
      end try
    end if
    
    
return aRes
    
  end convToStr
  
  
  
–レコードをStringに変換
  
  
–エラートラップを使って、わざとエラーを発生させ、エラーメッセージからレコードをstringに変換する
  
on recToString(aRec)
    
    
–レコードを無理矢理stringにcastして、エラーメッセージを取得する
    
try
      set a to aRec as string –ここでエラー発生
    on error aMes
      set a to aMes
    end try
    
    
–エラーメッセージ文字列から、元のレコードの情報を組み立てる
    
set b to trimStrFromTo(a, "{", "}")
    
set b to "{" & b & "}"
    
    
return b
    
  end recToString
  
  
  
on trimStrFromTo(aStr, fromStr, toStr)
    –fromStrは前から探す
    
if fromStr is not equal to "" then
      set sPos to (offset of fromStr in aStr) + 1
    else
      set sPos to 1
    end if
    
    
–toStrは後ろから探す
    
if toStr is not equal to "" then
      set b to (reverse of characters of aStr) as string
      
set ePos to (offset of toStr in b)
      
set ePos to ((length of aStr) – ePos)
    else
      set ePos to length of aStr
    end if
    
set aRes to text sPos thru ePos of aStr
    
    
return aRes
    
  end trimStrFromTo
  
  
  
–リストおよびリストに入ったレコードをStringに変換
  
  
on listToString(aList)
    set listText to {"{"}
    
set quotChar to ASCII character 34
    
set firstFlag to true
    
    
repeat with i in aList
      set j to contents of i
      
set aClass to (class of i) as string
      
if (aClass = "integer") or (aClass = "number") or (aClass = "real") then
        set the end of listText to (getFirst(firstFlag) of me & j as text)
        
set firstFlag to false
      else if (aClass = "string") or (aClass = "text") or (aClass = "Unicode text") then
        set the end of listText to ((getFirst(firstFlag) of me & quotChar & j as text) & quotChar)
        
set firstFlag to false
      else if aClass is "list" then
        set the end of listText to (getFirst(firstFlag) & listToString(j)) –ちょっと再帰処理
        
set firstFlag to false
      else if aClass is "record" then
        set the end of listText to (getFirst(firstFlag) & recToString(j))
        
set firstFlag to false
      end if
    end repeat
    
    
set the end of listText to "}"
    
set listText to listText as text
    
    
return listText
  end listToString
  
  
on getFirst(aFlag)
    if aFlag = true then return ""
    
if aFlag = false then return ", "
  end getFirst
  
end script

★Click Here to Open This Script 

Posted in list Record Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 2 Comments

Markdown書類から見出し(Header)行を抽出_v2

Posted on 2月 6, 2018 by Takaaki Naganoya

Markdown書類を選択し、正規表現で見出し(Header)行を抽出するAppleScriptです。

# Header Level 1
## Header Level 2
### Header Level 3
#### Header Level 4

のようなデータを処理すると、

{{1, " Header Level 1"}, {2, " Header Level 2"}, {3, " Header Level 3"}, {4, " Header Level 4"}}

のように {{level number, “header text”}…} と結果を出力します。

AppleScript名:Markdown書類から見出し(Header)行を抽出_v2
— Created 2017-08-12 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://piyocast.com/as/archives/4776

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

set aFile to choose file of type {"net.daringfireball.markdown"} –Markdown書類のUTI
set aStr to (read aFile as «class utf8»)
set aList to retHeaders(aStr) of me
–>  {​​​​​{​​​​​​​3, ​​​​​​​"choose file, choose folderで選んだ対象の名称変更"​​​​​}, ​​​​​{​​​​​​​3, ​​​​​​​"choose folderで選んだフォルダ内のファイルの名称変更"​​​​​}, ​​​​​{​​​​​​​3, ​​​​​​​"Finder上で選んだ(selection)ファイルの名称変更"​​​​​}, ​​​​​{​​​​​​​3, ​​​​​​​"POSIX pathのファイルの名称変更"​​​​​}, ​​​​​{​​​​​​​3, ​​​​​​​"ファイルを移動させたうえで名称変更"​​​​​}, ​​​​​{​​​​​​​3, ​​​​​​​"要注意事項(超重要、生死にかかわる)"​​​​​}​​​}

on retHeaders(aCon)
  set tList to {}
  
set regStr to "^#{1,6}[^#]*?$"
  
  
set headerList to my findPattern:regStr inString:aCon
  
repeat with i in headerList
    set j to contents of i
    
set regStr2 to "^#{1,6}[^#]*?"
    
set headerLevel to length of first item of (my findPattern:regStr2 inString:j)
    
set the end of tList to {headerLevel, text (headerLevel + 1) thru -1 in j}
  end repeat
  
  
return tList
end retHeaders

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

★Click Here to Open This Script 

Posted in Markdown Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

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

Posted on 2月 6, 2018 by Takaaki Naganoya

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

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

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

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


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

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

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

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

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

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

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

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

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

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

set tList to textInPDFinEachPage(newPath) of me

set pCount to 1
set midashOchiList to {}
repeat with i in tList
  set j to (contents of i) as string
  
  
repeat with ii in aList
    set jj to (contents of second item of ii) as string
    
–set jj2 to replaceText(jj, "(", "(") of me
    
–set jj3 to replaceText(jj2, ")", ")") of me
    
    
if (j ends with jj) then
      set the end of midashOchiList to {pCount, jj}
    end if
  end repeat
  
set pCount to pCount + 1
end repeat

return midashOchiList

on retHeaders(aCon)
  set tList to {}
  
set regStr to "^#{1,6}[^#]*?$"
  
  
set headerList to my findPattern:regStr inString:aCon
  
repeat with i in headerList
    set j to contents of i
    
set regStr2 to "^#{1,6}[^#]*?"
    
set headerLevel to length of first item of (my findPattern:regStr2 inString:j)
    
set tmpHeader1 to text (headerLevel + 1) thru -1 in j
    
–ヘッダーの前後から空白文字をトリミング
    
set tmpHeader2 to trimWhiteSpaceFromHeadAndTail(tmpHeader1) of me
    
    
–ヘッダー部でPDF書き出ししたときに全角文字が半角文字に置換されてしまうケースに対処
    
set tmpHeader3 to replaceText(tmpHeader2, "(", "(") of me
    
set tmpHeader4 to replaceText(tmpHeader3, ")", ")") of me
    
    
set the end of tList to {headerLevel, tmpHeader4}
  end repeat
  
  
return tList
end retHeaders

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

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

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

on textInPDFinEachPage(thePath)
  set aList to {}
  
  
set anNSURL to (current application’s |NSURL|’s fileURLWithPath:thePath)
  
set theDoc to current application’s PDFDocument’s alloc()’s initWithURL:anNSURL
  
  
set theCount to theDoc’s pageCount() as integer
  
  
repeat with i from 1 to theCount
    set thePage to (theDoc’s pageAtIndex:(i – 1))
    
set curStr to (thePage’s |string|())
    
set curStr2 to curStr’s decomposedStringWithCanonicalMapping() –Normalize Text with NFC
    
set targString to string id 13 & string id 10 & string id 32 & string id 65532 –Object Replacement Character
    
set bStr to (curStr2’s stringByTrimmingCharactersInSet:(current application’s NSCharacterSet’s characterSetWithCharactersInString:targString))
    
set the end of aList to (bStr as string)
  end repeat
  
  
return aList
end textInPDFinEachPage

–注意!! ここでGUI Scriptingを使用。バージョンが変わったときにメニュー階層などの変更があったら書き換え
on macDownForceSave()
  activate application "MacDown"
  
tell application "System Events"
    tell process "MacDown"
      — File > Export > PDF
      
click menu item 2 of menu 1 of menu item 14 of menu 1 of menu bar item 3 of menu bar 1
      
      
–Go to Desktop Folder
      
keystroke "d" using {command down}
      
      
–Save Button on Sheet
      
click button 1 of sheet 1 of window 1
    end tell
  end tell
end macDownForceSave

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

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

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

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

★Click Here to Open This Script 

Posted in GUI Scripting Markdown PDF Text | Tagged 10.11savvy 10.12savvy 10.13savvy MacDown | Leave a comment

指定のMarkdown書類を走査して指定文字列(Question)をカウント

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:指定のMarkdown書類を走査して指定文字列(Question)をカウント
— Created 2017-11-14 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set origPath to (choose file of type {"net.daringfireball.markdown"} with prompt "処理対象のMarkdown書類を選択")

set aText to (read origPath as «class utf8»)
set aFreq to retFrequency(aText, ">Q") of me

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

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

★Click Here to Open This Script 

Posted in Markdown Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

listからHTML Tableの生成 v2

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:listからHTML Tableの生成 v2
— Created 2017-02-24 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aList to {{"1", "2", "3"}, {"3", "4", "5"}, {"5", "6", "7"}}
set aHeader to "<html><head><title>First</title><style>table , td, table , tr, th{border:1px solid #333333;padding:2px;}</style></head><body><table ><tr><th>Col1</th><th>Col2</th><th>Col3</th><th>Col4</th><th>Col5</th></tr>"
set aTable to "<tr><td>%@</td><td> </td><td>%@</td><td>%@</td><td>%@</td></tr>"
set aFooter to "</table></body></html>"

set aHTMLres to retTableHTML(aList, aHeader, aTable, aFooter) of me

on retTableHTML(aList, aHeaderHTML, aTableHTML, aFooterHTML)
  set allHTML to current application’s NSMutableString’s stringWithString:aHeaderHTML
  
  
set aCounter to 1
  
repeat with i in aList
    set j to contents of i
    
set tmpList to (current application’s NSArray’s arrayWithArray:j)
    
set aRowHTML to current application’s NSString’s stringWithFormat_(aTableHTML, (aCounter as string), tmpList’s objectAtIndex:0, tmpList’s objectAtIndex:1, tmpList’s objectAtIndex:2)
    (
allHTML’s appendString:aRowHTML)
    
set aCounter to aCounter + 1
  end repeat
  
  (
allHTML’s appendString:aFooterHTML)
  
  
allHTML
end retTableHTML

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定のテキストからHTMLタグを除去(NSScanner)

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:指定のテキストからHTMLタグを除去(NSScanner)
— Created 2016-12-12 by Shane Stanley
— Modified 2016-12-14 by edama2
— Modified 2017-11-28 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–set aStr to read (choose file)
set aStr to "<a>repeat</a>~end repeat<BR>"
set aRes to (trimStrFromTo(aStr, "<", ">") of me)
–>  "repeat~end repeat"

on trimStrFromTo(aParamStr, fromStr, toStr)
  set theScanner to current application’s NSScanner’s scannerWithString:aParamStr
  
set anArray to current application’s NSMutableArray’s array()
  
  
repeat until (theScanner’s isAtEnd as boolean)
    set {theResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference)
    
    
theScanner’s scanString:fromStr intoString:(missing value)
    
set {theResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference)
    
if theValue is missing value then set theValue to ""
    
    
theScanner’s scanString:toStr 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, fromStr & i & toStr, "") of me
  end repeat
  
  
return curStr
end trimStrFromTo

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

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでUUID文字列を取得する

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCでUUID文字列を取得する
— Created 2015-08-14 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aUUID to current application’s NSUUID’s UUID()
–>  (__NSConcreteUUID) <__NSConcreteUUID 0x7f87d814d000> 6737A4CD-D509-42F5-BD0C-DB894127424D

set aStr to aUUID’s UUIDString()
–>  (NSString) "6737A4CD-D509-42F5-BD0C-DB894127424D"

set bStr to aStr as text
–> "6737A4CD-D509-42F5-BD0C-DB894127424D"

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

伏字文字列を作成する v4

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:伏字文字列を作成する v4
— Created 2015-09-09 by Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to "これは秘密のInformationです。" –Alphabet & Numeric以外でも置換可能
set bStr to makeUnprintableChars(aStr)
–>  "xxxxxxXxxxxxxxxxxxx。"

on makeUnprintableChars(aStr)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[\\p{Lu}\\p{Lt}\\p{Nd}]" withString:"X" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[\\p{Ll}\\p{Lm}\\p{Lo}]" withString:"x" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end makeUnprintableChars

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでテキストを行ごとにparseしてNSArrayに

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCでテキストを行ごとにparseしてNSArrayに
— Created 2015-07-02 17:32:59 +0900 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aText to "ABCDE
01234
あいうえお
かきくけこ
さしすせそ
たちつてと
なにぬねの"

set aArray to parseParagraphs(aText) of me
set aRes to countArrayItems(aArray) of me
–>  7

–最初のアイテム
set bRes to retFirstObject(aArray) of me
–>  (NSString) "ABCDE"

–最後のアイテム
set cRes to retLastObject(aArray) of me
–>  (NSString) "なにぬねの"

–指定アイテム目のアイテム
set dRes to retNthObject(aArray, 2) of me
–>  (NSString) "01234"

–テキストを改行でParseしてArrayに
on parseParagraphs(a)
  
  
set aStr to current application’s NSString’s stringWithString:a
  
set retStr to current application’s NSString’s stringWithString:(string id 10)
  
set aRes to (aStr’s componentsSeparatedByString:retStr) –parse strings by return
  
  
return aRes
  
end parseParagraphs

–与えられた配列の要素数を返す
on countArrayItems(aArray)
  set aRes to aArray’s |count|()
  
return aRes
end countArrayItems

–与えられた配列の最初の要素を返す
on retFirstObject(aArray)
  set a to aArray’s firstObject()
  
return a
end retFirstObject

–与えられた配列の最後の要素を返す
on retLastObject(aArray)
  set a to aArray’s lastObject()
  
return a
end retLastObject

–与えられた配列の指定アイテム目の要素を返す
on retNthObject(aArray, nTh)
  if nTh ≤ 0 then return false
  
  
set aIndex to current application’s NSNumber’s numberWithInt:((nTh – 1) as integer)
  
set aRes to aArray’s objectAtIndex:aIndex
  
  
return aRes
end retNthObject

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCで文字を逆順に v2(CJK文字などマルチバイト対応)

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCで文字を逆順に v2(CJK文字などマルチバイト対応)
— Created 2015-09-01 by Takaaki Naganoya
— Modified 2015-09-01 by Shane Stanley –Consider CJK Characters & Emoji
–http://stackoverflow.com/questions/6720191/reverse-nsstring-text
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aUUID to (current application’s NSUUID’s UUID()’s UUIDString()) as text
–>  "46EF17B7-CB3E-4DD9-BA8A-013D3B30A80A"

set aUUID to "😀😐" & aUUID & "😀😐"
–>  "😀😐46EF17B7-CB3E-4DD9-BA8A-013D3B30A80A😀😐"

set revUUID to reversedStr(aUUID) as text
–>  "😐😀A08A03B3D310-A8AB-9DD4-E3BC-7B71FE64😐😀"

on reversedStr(paramStr as text)
  set aStr to current application’s NSString’s stringWithString:paramStr
  
set strLength to aStr’s |length|()
  
set revStr to current application’s NSMutableString’s stringWithCapacity:strLength
  
set charIndex to strLength – 1
  
repeat while charIndex > -1
    set subStrRange to aStr’s rangeOfComposedCharacterSequenceAtIndex:charIndex
    
revStr’s appendString:(aStr’s substringWithRange:subStrRange)
    
set charIndex to (location of subStrRange) – 1
  end repeat
  
  
return revStr
end reversedStr

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCで文字列の長さを求める

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCで文字列の長さを求める
— Created 2015-09-02 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set a to current application’s NSMutableString’s stringWithString:"あいうえお"
set b to a’s |length|()
–>  5

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

バージョン番号文字列からメジャーバージョンを取り出し数値として返す v4

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:バージョン番号文字列からメジャーバージョンを取り出し数値として返す v4
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set a to "10.0.1"
set b to retMajorVersionNumber(a) of me
–> 10

set a to "9.10"
set b to retMajorVersionNumber(a) of me
–> 9

–バージョン番号文字列からメジャーバージョンを取り出し数値として返す
on retMajorVersionNumber(a)
  
  
set aStr to current application’s NSString’s stringWithString:a
  
–> "10.0.1" (NSString)
  
  
set aRes to (aStr’s componentsSeparatedByString:".")
  
–> {"10","0","1"} (NSArray)
  
  
set bRes to aRes’s firstObject()
  
–> "10" (NSString)
  
  
set cRes to bRes’s integerValue()
  
–> 10
  
  
return cRes as integer
  
end retMajorVersionNumber

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでbase64エンコード、デコード v3

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:ASOCでbase64エンコード、デコード v3
— Created 2015-07-27 by Takaaki Naganoya
— Updated 2015-07-28 by Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to "ぴよまるソフトウェアPiyomaru Software"
set theNSString to current application’s NSString’s stringWithString:aStr
set theNSData to theNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
set bStr to base64StringFromFileString(aStr) of me
return bStr
–>  "44G044KI44G+44KL44K944OV44OI44Km44Kn44KiUGl5b21hcnUgU29mdHdhcmU="

set aFilePath to POSIX path of (choose file)
base64StringFromFileAtPath(aFilePath) of me

–Base 64 Decode
on detaFromBase64String(aStr)
  set dataFrom64 to current application’s NSData’s alloc()’s initWithBase64EncodedString:aStr options:(current application’s NSDataBase64DecodingIgnoreUnknownCharacters)
  
set aStr to current application’s NSString’s alloc()’s initWithData:dataFrom64 encoding:(current application’s NSUTF8StringEncoding)
  
return aStr as text –stringではなくtext
end detaFromBase64String

–Base64 Encode
on base64StringFromFileAtPath(aFilePath)
  set aDataFromFile to current application’s NSData’s dataWithContentsOfFile:aFilePath
  
set aBase64EncStr to aDataFromFile’s base64EncodedStringWithOptions:(current application’s NSDataBase64Encoding64CharacterLineLength)
  
return aBase64EncStr as text
end base64StringFromFileAtPath

–Base64 Encode
on base64StringFromFileString(aString)
  set bString to current application’s NSString’s stringWithString:aString
  
set aData to bString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aBase64EncStr to aData’s base64EncodedStringWithOptions:(current application’s NSDataBase64Encoding64CharacterLineLength)
  
return aBase64EncStr as text
end base64StringFromFileString

★Click Here to Open This Script 

Posted in Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • macOS 15でも変化したText to Speech環境
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • AppleScript入門① AppleScriptってなんだろう?
  • Script Debuggerの開発と販売が2025年に終了
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • NSObjectのクラス名を取得 v2.1
  • 有害ではなくなっていたSpaces
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • Xcode上のAppleScriptObjCのプログラムから、Xcodeのログ欄へのメッセージ出力を実行

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (135) CotEditor (66) Finder (51) iTunes (19) Keynote (119) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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