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

タグ: Script Editor

as anything

Posted on 4月 3, 2019 by Takaaki Naganoya

as anythingについてまとまった情報がなかったので、まとめておきました。結論めいたものはとくになく、ただ、手持ちの情報を並べてみただけの内容なのでご容赦ください。「これはこうあるべき!」とかいう提言とかは一切ありません。

割と最近なas anythingとの遭遇

つい最近まで、ながらく存在自体を知らなかったのが、このanythingという予約語です。

AppleScriptの用語辞書をASObjC Explorer 4で書いて試していたとき、パラメータの型に「any」というものが存在していることには気づいていましたが、それでも「anything」という予約語があることには気づきませんでした。

本格的に知ったのは、applescript-stdlibを漁っていたときです。

同ライブラリはトリッキーなScriptの記述方法の見本市みたいになっていて、内容自体の完全理解についてはサジを投げた状態でしたが、見たことのない記述にいろいろ行き当たりました(もっと読みやすく書いてほしかった ^ー^;;)。

delegateの呼び出し先にscriptオブジェクト内部のハンドラを指定したりと、「そんな書き方できるんだ。やらんけど」と、まるで古文書をひもとくような感覚(これを見ていると、こーゆー風にblocks構文をAppleScriptでも記述できればいいのに、と思います)。

そこで見つけた「as anything」表記。これは一体なんなんでしょう?

いい加減に使えてとても便利なas anything

実際に動かしてみたところ、「あーー、この機能昔から欲しかったわー」という内容でした。anonymous classとでもいうのでしょうか。castするときにclass名を指定しないワイルドカードなclassと理解しました。

「as anything」でAppleScriptのデータ型はそのまま、AppleScriptのデータ型にcast可能なCocoaのデータはAppleScriptのデータ型に変換。変換不能なCocoaのデータ型についてはそのまま、という処理をしてくれます。

# ただし要素数が1つのNSArrayをas anythingでAppleScript Objetに変換すると、listではなく中身のデータが取り出されてしまう(型が合わなくなる)ので、注意が必要とのこと(Thanks Shane!)
# なので、あらかじめNSArrayが返ってくることがわかっている場合には、as list。NSArrayか他のデータ(missing valueとか)が返ってくる場合には、as {missing value, list} などとするとよいでしょう

BridgePlus的にいえば、「ASify without BridgePlus」といったところでしょうか。CocoaとAppleScriptの間でデータをやりとりするのにえっらく都合がよかったのです。かくして、「as anything」を愛用しまくるスタイルが確立。

ただ、anythingは言語仕様のはざまで埋もれかけていた「枝葉末節」の中の一番の「枝葉」ともいうべき、言語仕様の極北。AppleScript Language Guideにも記載されていないほどの枝葉仕様。

AppleScriptObjCのプログラム中に書くと、予約語が用意されていないためか「as anything」が「as list of string or string」などと解釈されてしまいます(動作自体はanythingと同じ)。

anythingについては、Apple側がわりとぞんざいに仕様を放置していたきらいがあります。問題が起こらないかぎり放っておこう、と。as «class isot»のようにある日突然(Mac OS X 10.5で)消えてなくなったりしないかちょっと不安に感じたこともありましたが、一応まがりなりにも予約語が割り振られているので(生Apple Eventを記述させられないので)、そんなに簡単に消えないとは思います。

主要開発環境で足並みそろわず

雑に放置していたAppleに対して、この問題に正面から向き合っていた集団が存在します。それが、Script DebuggerのメーカーであるLate Night Softwareです。

macOS 10.12や10.13上ではあいかわらずASOCのプログラムでは「as anything」が「as list of string or string」と解釈されますが、macOS 10.14で対応に差が出ました。

Script Debugger上では「anything」が「any」と解釈され、スクリプトエディタ上では「anything」と解釈されます。

macOS 10.14上でのスクリプトエディタで「as anything」が「as list of string or string」のように化けないのはいいと思います。ただ、Script DebuggerのメーカーであるLate Night Software側ではこれに「any」という別の予約語を割り振ったようで、、、、足並みがそろっていません。

一応、macOS 10.14上のスクリプトエディタv2.11上で「as anything」と記述したScriptを、同じくmacOS 10.14上のScript Debuggerに持っていくと「as any」と表示されます。いったん中間コードにコンパイルされたものは問題がないようです。

問題になるのは、Blogなどに掲載されている文字の状態のAppleScriptで、anythingについてはコンパイル(構文確認)時に気をつける必要がありそうです(メイン環境が10.14に移行していないのでちょっとまだ他人事)。

困ったときの古文書だより

一応、現代AppleScriptのルーツの資料とされている「AppleScriptLanguageGuide 1.3.7」(1999/5/5)のPDFを確認してみると、けっこう悩ましい内容が記述されています。

自分はanythingをclassか何かだと思っていたのですが、そこには定数(constants)だと書かれています。AppleScript version 1.3.7のころには、missing value(不定値)みたいな運用が行われていたようです。

AppleのEngineering Teamの見解は?

匿名希望の方がApple Engineering Teamに問い合わせしたところ「そんなマイナーな予約語は使うな」という返答であったとか。その一方でmacOS 10.14で「anything」の「list or list of string」への解釈化けが抑止されたりしているわけで、いまひとつわかりにくいというのが現状です。

Posted in OSA | Tagged 10.12savvy 10.13savvy 10.14savvy Script Debugger Script Editor | Leave a comment

オープン中のScriptをすべて書き換える

Posted on 1月 19, 2019 by Takaaki Naganoya

Script Editorでオープン中のAppleScript書類に対してすべて文字置換を行って、変更があれば保存を行うAppleScriptです。

Xcodeで作成するAppleScriptアプリケーションのプロジェクトで、サブScriptをZipアーカイブに入れ、展開しては順次呼び出すようにしていました。

サブスクリプト側とメインのAppleScriptアプリケーション側はUser Defaultsを介してパラメータのやりとりを行っていますが、Bundle IDの大文字/小文字の記述ミスからうまくパラメータの受け渡しが行えませんでした。

そこで、すべてのサブスクリプトを書き換えることにしたのですが、順次オープンして書き換えたのでは、(サブスクリプトの数が多すぎて)手間がかかり書き換えミスの可能性も否定できません。テキストエディタでは、BBEditなどで指定ディレクトリ以下のテキストファイルに対してすべて処理する機能が実装されていますが、Script DebuggerなどAppleScriptの編集プログラムにその機能が実装されているのは見たことがありません。

処理内容も簡単なので、その場で作ってしまいました。

なお、Script EditorをコントロールするAppleScriptは、大事をとってScript Editor以外のプログラム上で実行することが推奨されます。Script DebuggerかmacOS標準搭載のスクリプトメニューです。

Mac OS X 10.4の頃までは、Script Editor上でScript EditorをコントロールするAppleScriptを書いて実行するといろいろ不具合が出ていました。Mac OS X 10.5以降でずいぶん改善された印象があります。

本AppleScriptのような処理内容では、単なる文字置換ではなく、指定の構文要素(文字定数など)に該当するものがあれば置換を行うなど、より高度な処理を行うものに書き換えていくとよいでしょう。さすがに変数名の置換は作って使っていますが、文字定数やコメント内容を対象にするものを用意しておいてもいいように思えます。

AppleScript名:オープン中のScriptをすべて書き換える.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/01/19
—
–  Copyright © 2019 MyCompanyName, All Rights Reserved
—

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

set origStr to "jp.piyomarusoft.samplebundleid"
set toStr to "jp.piyomarusoft.sampleBundleID"

tell application "Script Editor"
  set dList to every document
  
  
repeat with i in dList
    set j to contents of i
    
    
tell j
      
      
set aCon to text of it
      
set bCon to repChar(aCon, origStr, toStr) of me
      
      
considering case
        if aCon is not equal to bCon then
          set text of it to bCon
          
save
        end if
      end considering
      
    end tell
    
  end repeat
end tell

–文字置換ルーチン
on repChar(origText as string, targStr as string, repStr as string)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

★Click Here to Open This Script 

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

AppleScriptの構文色分けカラーフォーマットをplistから読み込む

Posted on 3月 7, 2018 by Takaaki Naganoya

AppleScriptの構文色分けフォーマットをplistから読み込むAppleScriptです。

ただし、本Scriptで取得した色情報はスクリプトエディタ上で設定した内容と若干RGB値が異なるため、色情報をもとに構文要素を判定するような処理に本Scriptをそのまま用いることは推奨しません。

AppleScript名:AppleScriptの構文色分けカラーフォーマットをplistから読み込む
— Created 2013-11-11 by Shane Stanley
— Changed 2014-12-14 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set cList to getAppleScriptSourceColors() of me
–> {​​​​​{​​​​​​​redValue:37265, ​​​​​​​greenValue:10280, ​​​​​​​blueValue:37008, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:15672, ​​​​​​​greenValue:3071, ​​​​​​​blueValue:15832, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:3598, ​​​​​​​greenValue:15934, ​​​​​​​blueValue:64507, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:30840, ​​​​​​​greenValue:13364, ​​​​​​​blueValue:52171, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:64764, ​​​​​​​greenValue:10794, ​​​​​​​blueValue:7196, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:0, ​​​​​​​greenValue:0, ​​​​​​​blueValue:0, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:37265, ​​​​​​​greenValue:21074, ​​​​​​​blueValue:4369, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:0, ​​​​​​​greenValue:0, ​​​​​​​blueValue:0, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:10023, ​​​​​​​greenValue:51657, ​​​​​​​blueValue:51657, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:3855, ​​​​​​​greenValue:15934, ​​​​​​​blueValue:64507, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:7967, ​​​​​​​greenValue:46774, ​​​​​​​blueValue:64764, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:33153, ​​​​​​​greenValue:14906, ​​​​​​​blueValue:55769, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:23901, ​​​​​​​greenValue:13878, ​​​​​​​blueValue:37522, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:47484, ​​​​​​​greenValue:3164, ​​​​​​​blueValue:32926, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:6491, ​​​​​​​greenValue:47213, ​​​​​​​blueValue:32320, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:40001, ​​​​​​​greenValue:37149, ​​​​​​​blueValue:1331, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:20379, ​​​​​​​greenValue:0, ​​​​​​​blueValue:35059, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}, ​​​​​{​​​​​​​redValue:4539, ​​​​​​​greenValue:35536, ​​​​​​​blueValue:35798, ​​​​​​​fontName:"Osaka", ​​​​​​​fontSize:13.0​​​​​}​​​}

–AppleScriptの構文色分けのカラー値をRGBで取得する
on getAppleScriptSourceColors()
  
  
— get the info as a dictionary
  
set thePath to current application’s NSString’s stringWithString:"~/Library/Preferences/com.apple.applescript.plist"
  
set thePath to thePath’s stringByExpandingTildeInPath()
  
set theInfo to current application’s NSDictionary’s dictionaryWithContentsOfFile:thePath
  
  
— extract relevant part and loop through
  
set theArray to (theInfo’s valueForKey:"AppleScriptSourceAttributes") as list
  
  
set colList to {}
  
  
repeat with i from 1 to count of theArray
    set anEntry to item i of theArray
    
log anEntry
    
    
set colorData to NSColor of anEntry
    
set theColor to (current application’s NSUnarchiver’s unarchiveObjectWithData:colorData)
    
    
set {rVal, gVal, bVal} to retColListFromNSColor(theColor, 65535) of me
    
    
set fontData to NSFont of anEntry
    
set theFont to (current application’s NSUnarchiver’s unarchiveObjectWithData:fontData)
    
    
set aFontName to theFont’s displayName() as text
    
set aFontSize to theFont’s pointSize()
    
    
set aColRec to {redValue:rVal, greenValue:gVal, blueValue:bVal, fontName:aFontName, fontSize:aFontSize}
    
    
set the end of colList to aColRec
  end repeat
  
  
return colList
end getAppleScriptSourceColors

–NSColorからRGBの値を取り出す
on retColListFromNSColor(aCol, aMAX as integer)
  set aRed to round ((aCol’s redComponent()) * aMAX) rounding as taught in school
  
set aGreen to round ((aCol’s greenComponent()) * aMAX) rounding as taught in school
  
set aBlue to round ((aCol’s blueComponent()) * aMAX) rounding as taught in school
  
  
if aRed > aMAX then set aRed to aMAX
  
if aGreen > aMAX then set aGreen to aMAX
  
if aBlue > aMAX then set aBlue to aMAX
  
  
return {aRed, aGreen, aBlue}
end retColListFromNSColor

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | 3 Comments

指定パスのAppleScript書類がコンパイル済みかどうかチェック

Posted on 3月 7, 2018 by Takaaki Naganoya
AppleScript名:指定パスのAppleScript書類がコンパイル済みかどうかチェック
— Created 2014-12-16 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "OSAKit"

property |NSURL| : a reference to current application’s |NSURL|
property OSAScript : a reference to current application’s OSAScript

–指定AppleScriptがコンパイルずみ(中間コードへの翻訳の意)かどうかをしらべる
set a to (choose file of type {"com.apple.applescript.script-bundle", "com.apple.applescript.script", "com.apple.applescript.text"})
set asRes to chkAScompiled(a) as list of string or string
–> true or false

–指定のAppleScriptファイルがコンパイル(構文確認+中間言語化)ずみかどうかを取得する
on chkAScompiled(anAlias as {alias, string})
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of anAlias)
  
set asO to OSAScript’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value)
  
  
try
    set compF to asO’s isCompiled() as boolean
    
return compF
  on error
    return false
  end try
end chkAScompiled

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | Leave a comment

nameを指定してOSA言語のインスタンスを生成する

Posted on 3月 6, 2018 by Takaaki Naganoya

name(名称)を指定してOSA言語のインスタンスを生成するテストを行うAppleScriptです。

このあたりの話は、スクリプトエディタ上では直接取得できますし、コマンドラインからだとosalangコマンドを実行すれば名称一覧を取得できます。Cocoa経由でどの程度の情報が取得できるのか、ちょっと試してながらく放置したままになっていました。

再度、OSAKit系の情報を探してみても……見当たらない(ーー;

以前にAppleEvent Managerのドキュメントをまるごとオフラインにしていた前科があるので、担当に「(オフラインになっていて)見えないんだけど?」と確認したところ………

 「何が見えないんだ? 最初からそんなもんないぞ。これまでにドキュメントを作ったこともない」

と言われる始末。余計悪いわ(ーー;;;

というわけで、Web上にドキュメントが掲載されていないOSAKit系の情報については、Xcode上から、以下のように操作してヘッダーファイルの内容を確認することが必要なようです。

AppleScript名:nameを指定してOSA言語のインスタンスを生成する
— Created 2018-03-05 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "OSAKit"

property OSALanguage : a reference to current application’s OSALanguage
property OSALanguageInstance : a reference to current application’s OSALanguageInstance

set anOSALanguageInstance to OSALanguageInstance’s languageInstanceWithLanguage:(OSALanguage’s defaultLanguage())
set aLanguage to anOSALanguageInstance’s |language|()’s |name|() as string
–> "AppleScript"

set bLanguage to OSALanguage’s languageForName:"AppleScript"
set bName to bLanguage’s |name|() as string
–> "AppleScript"

set cLanguage to OSALanguage’s languageForName:"JavaScript"
set cName to cLanguage’s |name|() as string
–> "JavaScript"

set langArray to (OSALanguage’s availableLanguages()’s valueForKeyPath:"name") as list
–> {"AppleScript", "JavaScript"}

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | Leave a comment

Script Editorをコントロールして各構文要素の色情報を取得する v5

Posted on 3月 5, 2018 by Takaaki Naganoya

Script Editorをコントロールして、AppleScriptの各構文要素の色情報を取得するAppleScriptです。

AppleScriptの構文要素の色分けを取得するのに、当初はplistファイルから読み込んでいたのですが、途中から(Mac OS X 10.5あたり?)plistファイルのフォーマットがテキスト形式からバイナリ形式に変更になり、AppleScriptから読み込んでも判定できない内容になりました(Cocoaの機能を使うと読み取れるのですが)。

そこで、「プログラム的には意味はないが、対象の構文要素が入っているテキスト」でAppleScriptを新規ドキュメントを作成してコンパイル(構文確認)を実行。新規ドキュメントからリッチテキストとして書式情報を取得し、想定した文字の位置から指定構文要素に対応する色情報を取得します。

plistの保存形式が途中で変更されたのとは別に、書式つきテキスト(attribute runs)の挙動もOSバージョンによって微妙に変わってきました。

同じデータを与えても、書式の区切りが微妙に変わって、書式(色)情報を固定の箇所から読み取っていてはそのようなOSバージョン変更に伴う挙動の微妙な変更に対応し切れませんでした。そのため、文字列をサーチして毎回動的にデータ位置を検出するように書き換えた経緯があります。

本ルーチンは、変数名のリネーム用に作成したので構文要素確認用のダミーテキストは最低限のものだけを含んでいますが、その気になればすべての構文要素の色情報を取得可能です。

これとは別に、Cocoaの機能を用いてplistから構文書式情報を取得するAppleScriptも存在するものの、計算して微妙に色情報が合わないので、9年前に作成した本ルーチンを使い続けています(当時)。

→ さすがに重要なルーチンなので、Cocoa系の機能を使って処理するように書き換えました。いまはCocoa系ルーチンを使っています

AppleScript名:Script Editorをコントロールして各構文要素の色情報を取得する v5
— Created 2009-06-01 by Takaaki Naganoya
— 2009-2018 Piyomaru Software

set scList to getRexicalColorOfScriptEditor() of me
–> {{32053, 4213, 32213}, {15672, 3071, 15831}, {2841, 6963, 64125}, {8259, 42547, 64473}, {0, 0, 0}, {32202, 16452, 3889}}
–色書式データ。先頭から順番に、、、
–新規テキスト, 演算子など, スクリプティング予約語, コマンド名, 値(数値、データ), 変数およびサブルーチン名

–スクリプトエディタの各構文要素の指定色を返す
–v5の変更点:Leopard以降のStyle runsの挙動変化(スペースを分離する/しない)に対応し、動的にサンプル文を走査するようにした
–v4の変更点:構文要素検出時のテンポラリウィンドウ作成時にScript Editorを隠す
–v3の変更点:重複時のエラー検出を追加
on getRexicalColorOfScriptEditor()
  set aRes to setVisibleOfSpecifiedProcess("Script Editor", false) of me
  
  
set rexList to {"+", "set", "application", "Comment", "1", "a"} –文中から検索するテキスト要素
  
set colList to {} –色情報を入れるリスト
  
  
  
tell application "Script Editor"
    
    
set aDoc to make new document
    
tell front document
      set aName to name
      
–end tell
      
      
–tell document aName
      
–未コンパイル時のテキストを取得
      
set contents to "aaaaa"
      
set rexItem1 to (color of attribute runs)
      
set rexItem1 to contents of (item 1 of rexItem1)
      
      
set colList to {rexItem1}
      
      
      
–各種構文要素を含む文字を入れる
      
set contents to "1 + 1
set a to \"abc\"
tell application \"Finder\"
end tell
–Comment
"

      –追加する場合には、テキストを後ろに追加すること
      
      
try
        compile
      on error
        close without saving
        
return false
      end try
      
      
set rex1 to attribute runs
      
set rex2 to color of attribute runs
      
      
repeat with i in rexList
        set j to contents of i
        
set rC to 1
        
repeat with ii in rex1
          set jj to contents of ii
          
set jj to replaceText(jj, " ", "") of me –スペースを削除する
          
if j = jj then
            set the end of colList to contents of item rC of rex2
            
exit repeat –抜けていた
          end if
          
set rC to rC + 1
        end repeat
      end repeat
      
      
close without saving
    end tell
    
  end tell
  
  
–Script Editorの再表示
  
set aRes to setVisibleOfSpecifiedProcess("Script Editor", true) of me
  
  
–要素の重複検出
  
set aRes to detectDuplicationSimple(colList) of me
  
if aRes = false then
    return false
  else
    return colList
  end if
  
end getRexicalColorOfScriptEditor

–リスト中の重複検出
on detectDuplicationSimple(cList)
  copy cList to ccList
  
  
set j to length of ccList
  
  
repeat with i from 2 to j
    set first_item to item 1 of ccList
    
set ccList to rest of ccList
    
if first_item is in ccList then
      return false
    end if
  end repeat
  
  
return true
end detectDuplicationSimple

–指定プロセスの可視/不可視切り替え
on setVisibleOfSpecifiedProcess(aProc, aBoolean)
  tell application "System Events"
    if exists process aProc then
      set visible of process aProc to aBoolean
      
set resF to true
    else
      set resF to false
    end if
  end tell
  
return resF
end setVisibleOfSpecifiedProcess

–任意のデータから特定の文字列を置換
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
  
return origData
end replaceText

★Click Here to Open This Script 

Posted in Color OSA System | Tagged 10.11savvy 10.12savvy 10.13savvy Script Editor | 1 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

Post navigation

  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 13.6.5 AS系のバグ、一切直らず
  • CotEditorで2つの書類の行単位での差分検出
  • Apple純正マウス、キーボードのバッテリー残量取得
  • macOS 15, Sequoia
  • 初心者がつまづきやすい「log」コマンド
  • 指定のWordファイルをPDFに書き出す
  • ディスプレイをスリープ状態にして処理続行
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • メキシカンハットの描画
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • 2023年に書いた価値あるAppleScript
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • Numbersで選択範囲のセルの前後の空白を削除

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (207) 13.0savvy (168) 14.0savvy (118) 15.0savvy (95) CotEditor (64) Finder (51) iTunes (19) Keynote (115) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (19) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (72) Pages (53) 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
  • 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
  • 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年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