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

タグ: CotEditor

HexDump to BASIC

Posted on 1月 9 by Takaaki Naganoya

これも同じく、8bitコンピュータ時代のクロスアセンブラが出力していたダンプリストを、BASICのPOKE文に展開して出力するという、20〜30年前の仕様のテキスト変換を行うために作ったものです。

CotEditorでオープン中のダンプリストのテキストの変換対象行を選択しておいた状態で実行すると、変換したリストを新規書類に出力します。

AppleScript名:HexDump to BASIC.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/01/09
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

tell application "CotEditor"
  tell front document
    set aaSel to paragraphs of contents of selection
  end tell
end tell

set sNum to 100
set allText to ""
repeat with i in aaSel
  set tmpL to ""
  
  
set bList to words of i
  
set aStr to retOnLineBasicPoke(bList) of me
  
set allText to allText & ((sNum as string) & ": ") & aStr & return
  
set sNum to sNum + 1
end repeat

tell application "CotEditor"
  set newDoc to make new document
  
tell newDoc
    set contents of it to allText
  end tell
end tell

on retOnLineBasicPoke(aList)
  set addrStr to first item of aList
  
set aList to rest of aList
  
set aaList to items 1 thru 8 of aList
  
  
set aStr to "POKE #0, &" & addrStr & ", "
  
repeat with i in aaList
    set j to contents of i
    
set aStr to aStr & "&" & j & ", "
  end repeat
  
  
return text 1 thru -3 of aStr
end retOnLineBasicPoke

★Click Here to Open This Script 

(Visited 22 times, 1 visits today)
Posted in Text | Tagged 13.0savvy CotEditor | Leave a comment

Intel Hexa to BASIC

Posted on 1月 9 by Takaaki Naganoya

これ、8bitコンピュータ時代のクロスアセンブラが出力していたIntel Hexaフォーマットのダンプリスト(EPROMライター向けの出力フォーマットらしい)を、BASICのPOKE文に展開して出力するという、20〜30年前の仕様のテキスト変換を行うために作ったものです。

CotEditorでオープン中のIntel Hexaのテキストの変換対象行を選択しておいた状態で実行すると、変換したリストを新規書類に出力します。

汎用性は一切ないのですが、実際にさまざまな本を作る際に、こうした「ちょっとしたツール」を作るのと作らないのとでは生産性が段違いです。

ただ、元データと最終成果物を示すと途中のロジックをプログラム側で考えて出力してくれるといいのに、とは思います。

AppleScript名:Intel Hexa to BASIC.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/01/09
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "CotEditor"
  tell front document
    set aaSel to paragraphs of contents of selection
  end tell
end tell

set sNum to 100
set allText to ""
repeat with i in aaSel
  set tmpL to ""
  
set j to contents of i
  
set {addrStr, hexList} to procOneLine(j) of me
  
set aStr to retOnLineBasicPoke(addrStr, hexList) of me
  
set allText to allText & ((sNum as string) & " ") & aStr & return
  
set sNum to sNum + 1
end repeat

tell application "CotEditor"
  set newDoc to make new document
  
tell newDoc
    set contents of it to allText
  end tell
end tell

on retOnLineBasicPoke(addrStr, aList)
  set aStr to "POKE #0, &" & addrStr & ", "
  
repeat with i in aList
    set j to contents of i
    
set aStr to aStr & "&" & j & ", "
  end repeat
  
  
return text 1 thru -3 of aStr
end retOnLineBasicPoke

on procOneLine(a)
  set fChar to first character of a
  
if fChar is not equal to ":" then error
  
  
set byteC to text 2 thru 3 of a
  
set byteNum to retIntFromHexString(byteC) of me
  
  
set addrStr to text 4 thru 7 of a
  
  
set hList to {}
  
repeat with i from 10 to (10 + (2 * (byteNum – 1))) by 2
    set tmpStr to text i thru (i + 1) of a
    
set the end of hList to tmpStr
  end repeat
  
return {addrStr, hList}
end procOneLine

on retIntFromHexString(aHex as string)
  set {aRes, hexRes} to (current application’s NSScanner’s scannerWithString:aHex)’s scanHexInt:(reference)
  
if aRes = false then
    return "" –エラーの場合
  else
    return hexRes
  end if
end retIntFromHexString

★Click Here to Open This Script 

(Visited 20 times, 1 visits today)
Posted in Text | Tagged 13.0savvy CotEditor | Leave a comment

新発売:CotEditor Scripting Book with AppleScript

Posted on 12月 11, 2022 by Takaaki Naganoya

Piyomaru Software Booksの69冊目。「CotEditor Scripting Book with AppleScript」を発売しました。PDF 343ページ+サンプルScriptZipアーカイブ で構成されています。

→ 販売ページ

アプリケーションのすべてのScriptingをわかりやすく詳細にまとめた徹底解説シリーズの第5弾。

CotEditorは(起動、動作が)速い、うまい、フリー、と3拍子そろった、Macユーザー定番のテキストエディタです。

macOS専用に作られているため、その分、macOSならではの機能を活かす方向に全振りした作りになっています。

そんなCotEditorはもちろんAppleScriptに対応しており、さまざまな作業の部品としてCotEditorを利用したり、CotEditor自体の機能をAppleScriptで追加することもできます。macOS 12以降に対応。

■初級

・スクリプトエディタを起動しよう

スクリプトエディタを起動しよう!
スクリプトエディタのヘルプ
色設定を変えてみよう!
スクリプトを入力してみよう
スクリプトを保存しよう
スクリプトを実行しよう(1/3)
スクリプトを実行しよう(2/3)
セキュリティとプライバシー
プライバシーとセキュリティ(13.x以降)
セキュリティとプライバシー>プライバシー
プライバシーとセキュリティ(macOS 13)

・CotEditorを起動しよう

CotEditorを指定
CotEditor.appを起動
CotEditor.appを終了
CotEditorのAppleScript用語辞書の調べ方
メニュー項目や画面強制操作の調べ方
CotEditorの詳細仕様について

・CotEditor自体の情報を取得しよう

CotEditorの名前を取得
CotEditorのバージョンを取得
CotEditorのプロパティ項目と内容

・オープン中の書類へのアクセス

CotEditorでオープン中の書類へのアクセス
最前面の書類、ウインドウにアクセス
documentの属性情報にアクセス
windowの属性情報にアクセス
ウインドウ関連の操作で「できない」こと

・書類の選択部分へのアクセス

selection=選択中のテキスト
selection自体のプロパティ
selection内容のテキストの取得
selection内容の書き換え
selectionの作成

・書類のスクロールとジャンプ

書類のスクロール①
書類のスクロール②
書類の指定行にジャンプ
書類の乱数行にジャンプ

・ウインドウの操作

ウインドウの属性値へのアクセス
指定ウインドウを最前面に表示
指定ウインドウの表示状態を変更
指定ウインドウをズーム表示
参考:最前面のウインドウをフルスクリーン表示
指定ウインドウのサイズを変更

・CotEditor内蔵コンソールへの文字列出力

コンソールに文字列を出力

・内蔵/OS搭載スクリプトメニューからの操作

2つのScript Menu環境
CotEditor内蔵スクリプトメニュー
macOS搭載標準スクリプトメニュー
各スクリプトメニューの技術仕様

・AppleScriptからCotEditorを操作するパターン

■中級

・ファイルのオープン

ファイルを指定して書類をオープン
複数のファイルを指定して書類をオープン
コラム「CotEditorが使用するパス表現」

・ファイルの保存

書類を指定パスに保存
書類を新規作成して本文を設定して指定パスに保存
保存済み書類に変更が加わっていたら保存

・ファイルのクローズ

書類をクローズ(with saving)
書類をクローズ(without saving)
書類をクローズ(saving ask)
新規書類をクローズ

・各種文字操作(選択範囲の操作)

change case
change kana
change roman width
shift right
shift left
move line up
move line down
sort lines
delete duplicate line
comment out
uncomment
smarten quotes
straighten quotes
smarten dashes
normalize unicode

・各種文字操作(document全体の操作)

find(1/2)
find(2/2)
replace
string

・タブ、改行コードの取り扱い

改行コードの変更タブ幅の変更
文字コードの指定
convert
reinterpret

・書式つきテキスト対応機能

CotEditorの書式つきテキスト対応機能
書式つきテキスト機能にAppleScriptからアクセス

・AppleScript非対応機能を呼び出す

AppleScriptで操作可能な範囲
GUI Scripting:メニューなどを強制操作①
GUI Scripting:メニューなどを強制操作②
GUI Scripting:メニューへのアクセス
指定ウインドウを最前面に移動

・プリントアウト

CotEditorからの印刷出力(macOS 13)
AppleScriptによるプリントアウト
GUI Scriptingによるプリントアウト①
GUI Scriptingによるプリントアウト②
GUI Scriptingによるプリントアウト③
GUI Scriptingによるプリントアウト④
GUI Scriptingによるプリントアウト⑤

■上級

正規表現
正規表現が使えるAppleScriptコマンド
findコマンド+正規表現(GUI側との対応)
replaceコマンド+正規表現(GUI側との対応)
replace サンプル①
replace サンプル②
replace サンプル③
replace サンプル④

・オープン時に縦/横書きを強制できる書類仕様

xattrコマンドで強制的に縦書き表示

・文字数のカウント

CotEditorの文字数カウント機能
AppleScriptの文字カウント

・内蔵スクリプトメニューの独自仕様

フォルダ階層構造がそのまま反映される
内蔵スクリプトメニューの独自機能
メニュー上の並び順を指定
メニュー上の区切りセパレータ表示指定
キーボードショートカットの指定
Scriptをメニューに出さない(非表示設定)

・CotEditorのAppleScript関連機能のバグ(v4.4.2)
・高度なサンプル集

AppleScriptで操作可能な範囲
最前面のウィンドウをフルスクリーン表示(1/2)
最前面のウィンドウをフルスクリーン表示(2/2)
選択範囲のテキストをhexdump(1/2)
選択範囲のテキストをhexdump(2/2)
選択範囲のカンマ区切りテキストをNumbersへ(1/2)
選択範囲のカンマ区切りテキストをNumbersへ(2/2)
選択範囲のテキストの文字比率グラフを表示(1/8)
選択範囲のテキストの使用文字比率のグラフ表示(2/8)
選択範囲のテキストの使用文字比率のグラフ表示(3/8)
選択範囲のテキストの使用文字比率のグラフ表示(4/8)
選択範囲のテキストの使用文字比率のグラフ表示(5/8)
選択範囲のテキストの使用文字比率のグラフ表示(6/8)
選択範囲のテキストの使用文字比率のグラフ表示(7/8)
選択範囲のテキストの使用文字比率のグラフ表示(8/8)

・便利な他のプログラムや周辺機器

さまざまなAppleScript呼び出しプログラムから操作①(1/2)
さまざまなAppleScript呼び出しプログラムから操作①(2/2)
さまざまなAppleScript呼び出しプログラムから操作②
さまざまなAppleScript呼び出しプログラムから操作③
さまざまなAppleScript呼び出しプログラムから操作④

■資料集

・CotEditorのAppleScript用語辞書解説
・CotEditorのAppleScript用語の変遷
・CotEditor&AppleScript Q&A
・AppleScript mini Reference
・macOS搭載 AppleScript関連ドキュメント
・AppleScript関連の情報源
・macOSバージョンとAppleScriptの動向
・AppleScript予約語一覧
・サードパーティ製FrameworkやAppleScript Librariesを呼ぶ
・エラーコード表

(Visited 49 times, 1 visits today)
Posted in Books news | Tagged 12.0savvy 13.0savvy CotEditor | Leave a comment

CotEditor v4.4.1+macOS 13の組み合わせで発生している問題

Posted on 11月 18, 2022 by Takaaki Naganoya

CotEditor v4.4.1+macOS 13.1 Betaの組みわせで発生しているAppleScriptの問題について書いておきます。

CotEditorの内蔵スクリプトメニューから呼び出すAppleScriptは、実行プログラムがosascriptで、macOS標準搭載のスクリプトメニューと部品は同じですが、挙動や制約条件が異なります。

macOS 13+CotEditorの内蔵スクリプトメニューから呼び出すAppleScriptで、「path to me」を実行したらエラーになる現象に直面しています。

AppleScript名:mepath_without_block.scpt
set mePath to POSIX path of (path to me)
display dialog mePath as string

★Click Here to Open This Script 

ただし、解決策はすぐに見つかって、tellブロックでpath to meを囲ってあげることです。tell current applicationで囲ってあげるのが一番手っ取り早いところ。using terms from scripting additionsも使えそうです。

AppleScript名:mepath.scpt
tell current application
  set mePath to POSIX path of (path to me)
end tell
display dialog mePath as string

★Click Here to Open This Script 

(Visited 37 times, 1 visits today)
Posted in news | Tagged 13.0savvy CotEditor | Leave a comment

macOS 12.6.1、組み込みAppleScript実行環境の「script objectで分離したハンドラが呼べない」問題が解消?

Posted on 10月 12, 2022 by Takaaki Naganoya

macOS 12.6.1がアップデートして12.6.1になるというわけのわからないバージョン番号の採番ルールが展開されている今日このごろ。

macOS 12の初期において、Shortcuts.appやCotEditor内部のAppleScript実行環境において、script objectで論理分割した中にあるハンドラを呼べない という問題が確認されました。ただし、macOS 12.6.1で気づいたということであって、もう少し前のバージョンでこの変更が加わっていた可能性もあります。

ハンドラ呼び出しの範囲がscript objectを超えられないというわけで、CotEditor PowerPackの作成時に大幅にScriptを書き換える必要があって手間がかかった記憶があります。

AppleScript基礎テクニック集25巻にて「CotEditorのメニューScriptとShortcuts.appでは対策が必要」と書こうとして、念のために実際にmacOS 12.6.1の上でCotEditor v4.3.6で確認したところ、動きました。Shortcuts.appでも同様にscript object内部のハンドラを外部から呼び出せるようになっていました。

# 慌てて、書籍の方を書き換えました

各プログラム側で何かそんなマイナーな問題への対策を行ったような雰囲気はなかったので、OS側の実行モジュール(osascript?)で対策を行ったような雰囲気があります。ただ、Appleがリリースノートを一切出さないので、確認のしようがありません(ものすごく不信感しかないので、リリースノートは出してほしいなー。まさか、詳細なリリースノートを出さないことで、クラッカーへの情報流出を防止できている、とか現状を肯定的に捉えているのだろうか)。

(Visited 30 times, 1 visits today)
Posted in Bug | Tagged 12.0savvy CotEditor Shortcuts Shortcuts Events | Leave a comment

新発売:AppleScript実践的テクニック集(1)GUI Scripting

Posted on 10月 10, 2022 by Takaaki Naganoya

Piyomaru Software Booksの60冊目。GUIアプリケーションを強引に動かす「GUI Scripting」について動作原理から気をつけるべき点、実戦レベルのScriptで注意している点やサンプルなどをまとめた「AppleScript実践的テクニック集(1)GUI Scripting」を発売しました。本文283ページとなっています。

→ 販売ページ

「AppleScript実践的テクニック集」とは、従来の「基礎テクニック集」の枠組みでは収まりきらないテーマを扱う新シリーズです。基礎テクニック集は32ページ前後のコンパクトな構成にするために、いろいろ省略した部分もありましたが、この枠組みに入り切らないテーマを別枠でご紹介することにしたものです。

ページ数の上限をとくに設けず、徹底的に情報を入れる設計です。それでいて、「基礎テクニック集」ゆずりの図や表を多用した構成はそのままです。

使い所さえ間違えなければ強力な武器になるGUI Scriptingについて、動作原理からノウハウ、注意すべきポイントや実戦レベルのScriptで気をつけていること、さまざまな「ありがちな処理」のサンプルなどを紹介する1冊です。

■GUI Scripting (UI Element Scripting)とは?

AS用語辞書にすべての機能は掲載されていません①
AS用語辞書にすべての機能は掲載されていません②
AppleScript非対応機能を呼ぶGUI Scripting
GUI Scriptingとは?
GUI ScriptingはSystem Eventsごしに操作
操作対象のアプリケーション①
操作対象のアプリケーション②

■AppleScript非対応機能を操作する

KeynoteでASから利用できない機能を呼ぶ
GUIアプリケーションの挙動確認が欠かせません
メニュー項目操作の実例
実行結果のリストアップ①
実行結果のリストアップ②

■GUI Scriptingの実行を許可する

デフォルト状態だとGUI Scriptingは無効
AppleScript実行アプリケーションを登録
設定するとGUI Scriptingが有効に
スクリプトメニューも登録必須
資料:macOS上のAppleScript実行環境①
資料:macOS上のAppleScript実行環境②

■GUI部品への参照を求める方法

メニュー項目:メニューを頂点としたツリー
ウィンドウ上のオブジェクト:ウィンドウが基準
簡単なGUI部品の求め方

■GUI Scriptingでやりたい特徴的な操作

GUI Scriptingの有効チェック
属性値の取得(properties)
属性値の取得(AX-attributes)
GUI部品のクリック
指定座標のクリック
参考資料:GUI Scriptingの座標系
ポップアップメニューの項目選択
キー入力操作
項目選択
コンテクストメニューの表示
スクロール操作
ファイル保存/書き出し
自分で発生させたモーダルなダイアログのクリック
ドラッグ&ドロップ操作
日本語IMの文字入力モード取得/設定

■マウスカーソルの強制移動&強制クリック

マウスカーソルを移動させる必要性
マウスカーソルの強制移動とクリック

■実戦レベルのAppleScriptにおけるGUI Scripting解説

指定フォルダ以下のPagesなどをPDF出力して連結
実際のメインScript部分
generatePDFLibの当該箇所
本プログラムが環境の影響を受けた点
参考資料:デスクトップの表示/非表示切り替え

■Accessibility Inspectorの使い方

Xcodeに入っているGUI部品探索ツール
Accessibility Inspectorの画面構成①
Accessibility Inspectorの画面構成②
プロセス一覧から対象を選択してInspection
指定プロセスのGUI部品の追跡中の画面表示
GUI部品の追跡ポーズ中の画面表示

■OSやアプリケーションのアップデートに備える

OSアップデートごとにGUI構成は変わる
GUI Scripting処理部分だけをサブルーチンに分離
GUI Scripting処理部分をライブラリに分離
OSアップデートの影響を受けにくい構造に

■GUI Scriptingの信頼性は?

GUI Scriptingの信頼性は?
一般的な信頼性の計測方法
経験に基づく傾向と対策
GUI Scriptingで直面した問題とその解決策
指定した処理の終了前に次の処理が行われる
同じ名前のプロセスが存在していると名称衝突①
同じ名前のプロセスが存在していると名称衝突②

■GUI Scriptingサンプル集

指定のアプリケーションの全メニュータイトルを取得
選択中のテキストを取得
選択中のテキストを書き換え
Safariの最前面のウィンドウへの参照を得る
GUI部品への参照から所属するアプリケーション名を取得
Dockに登録されているアイコンの情報を取得
Keynoteで選択中のテキストを縦書きに
CotEditorで最前面のウィンドウを縦書きに

■GUI Scripting資料集

click【クリック】コマンド
key code【キーコード】コマンド
keystroke【キーストローク】コマンド
perform【パフォーム】コマンド
select【セレクト】コマンド
application【アプリケーション】クラス
action【アクション】クラス
application process【アプリケーションプロセス】クラス
attribute【アトリビュート】クラス
browser【ブラウザ】クラス
busy indicator【ビジーインディケータ】クラス
button【ボタン】クラス
checkbox【チェックボックス】クラス
color well【カラーウェル】クラス
column【カラム】クラス
combo box【コンボボックス】クラス
desk accessory process【デスクアクセサリプロセス】クラス
drawer【ドロワー】クラス
group【グループ】クラス
grow area【グローエリア】クラス
image【イメージ】クラス
incrementor【インクリメンタ】クラス
list【リスト】クラス
menu【メニュー】クラス
menu bar【メニューバー】クラス
menu bar item【メニューバーアイテム】クラス
menu button 【メニューボタン】クラス
menu item 【メニューアイテム】クラス
outline 【アウトライン】クラス
pop over 【ポップオーバー】クラス
pop up button 【ポップアップボタン】クラス
process 【プロセス】クラス
progress indicator 【プログレスインジケータ】クラス
radio button 【ラジオボタン】クラス
radio group【ラジオグループ】クラス
relevance indicator【レレベンスインジケータ】クラス
row【ロー】クラス
scroll area【スクロールエリア】クラス
scroll bar 【スクロールバー】クラス
sheet 【シート】クラス
slider【スライダ】クラス
splitter【スプリッタ】クラス
splitter group【スプリッタグループ】クラス
static text【スタティックテキスト】クラス
tab group【タブグループ】クラス
table【テーブル】クラス
text area【テキストエリア】クラス
text field【テキストフィールド】クラス
toolbar【ツールバー】クラス
UI element【ユーアイエレメント】クラス
value indicator【バリューインディケータ】クラス
window【ウインドウ】クラス

■AppleScript資料集

macOSバージョンとAppleScriptの動向
macOSとAppleScriptの要素技術史
各macOSごとのAppleScript解説
macOS内AppleScript補助ツールの歴史
System EventsのAppleScript用語辞書変更点
AppleScript 各ランタイム環境情報
AppleScript予約語一覧
AppleScriptのエラーコード
あとがき
奥付

(Visited 28 times, 1 visits today)
Posted in Books GUI Scripting news PRODUCTS | Tagged 12.0savvy CotEditor Keynote System Events TextEdit | Leave a comment

CotEditor v4.1.2でAppleScript系の機能を追加

Posted on 2月 22, 2022 by Takaaki Naganoya

オープンソース開発されているフリーのテキストエディタ「CotEditor」v4.1.2において、AppleScript系の機能が追加されています。

・DocumentオブジェクトのhasBOM属性

has BOM (boolean, r/o) : Is the file encoding of the document has BOM (byte order mark)?

・convertコマンドのBOMオプション

convert v : Convert the document text to new encoding.
convert document : The document to convert encoding.
[lossy boolean] : Allows lossy conversion?
[BOM boolean] : Has the new encoding a BOM (byte order mark)?
to text : The new encoding, either in localized encoding name or an IANA charset name.
→ boolean : Did the convertion succeed?

・新設のjumpコマンド

jump v : Move the caret to the specified location. At least, either one of a parameter is required.
jump document : The document to move.
to line integer : The number of the line to go. If a negative value is provided, the line is counted from the end of the document.
[column integer] : The location in the line to jump. If a negative value is provided, the column is counted from the end of the line.

こんなサンプル書類があったとして、

AppleScriptのdocumentオブジェクトの文字データを取得してダンプしてみても、

--No BOM
{"E3", "81", "B4", "E3", "82", "88", "E3", "81", "BE", "E3", "82", "8B", "E3", "82", "BD", "E3", "83", "95", "E3", "83", "88", "E3", "82", "A6", "E3", "82", "A7", "E3", "82", "A2", "0A", "61", "62", "63", "64", "E9", "AB", "98", "E5", "B3", "B6", "E5", "B1", "8B", "65", "66", "67", "68", "69", "0A", "0A"}

--with BOM
{"E3", "81", "B4", "E3", "82", "88", "E3", "81", "BE", "E3", "82", "8B", "E3", "82", "BD", "E3", "83", "95", "E3", "83", "88", "E3", "82", "A6", "E3", "82", "A7", "E3", "82", "A2", "0A", "61", "62", "63", "64", "E9", "AB", "98", "E5", "B3", "B6", "E5", "B1", "8B", "65", "66", "67", "68", "69", "0A", "0A"}

この状態ではhasBOM属性値で差があっても、内部データでは差が出ません。これをファイルに書き込んで、ファイル内容についてチェックを行うと、

--No BOM
0000000 81e3 e3b4 8882 81e3 e3be 8b82 82e3 e3bd
0000010 9583 83e3 e388 a682 82e3 e3a7 a282 610a
0000020 6362 e964 98ab b3e5 e5b6 8bb1 6665 6867
0000030 0a69 000a                              
0000033

--With BOM
0000000 bbef e3bf b481 82e3 e388 be81 82e3 e38b
0000010 bd82 83e3 e395 8883 82e3 e3a6 a782 82e3
0000020 0aa2 6261 6463 abe9 e598 b6b3 b1e5 658b
0000030 6766 6968 0a0a                         
0000036

のように、差を検出できます。

(Visited 71 times, 1 visits today)
Posted in news Object control Text | Tagged 10.15savvy 11.0savvy 12.0savvy CotEditor | Leave a comment

CotEditorで選択範囲の行頭にある数字をリナンバーする v1

Posted on 1月 2, 2022 by Takaaki Naganoya

CotEditorでオープン中の最前面の書類の選択範囲のテキストを行ごとにチェックし、行頭に存在する数字を、それらのうちの最小値を検出しつつ、指定のステップ数でリナンバー(番号振り直し)を行うAppleScriptです。

さまざまな項目の整理のために、テキストの先頭に仮想的なノンブル(ページ番号的なもの、ソート順を指定するための番号)を振っています。この番号ではじまるテキストをもとにFinder上でフォルダ整理をしており、項目の前後関係を入れ替えると…前後関係を明示するために、番号を振り直す必要が出てくるわけです。

# Numbers上やExcel上で行うと、余計な書体スタイルなどが入ってきて邪魔なので、テキストエディタ上で行うことが多いです

その番号の振り直しを行うAppleScriptです。macOS 12.2beta+CotEditor v4.0.9で動作確認を行っています。


▲選択範囲内の行頭の番号を振り直す。ちなみに、表示例はボツになった本の企画

本来は「行頭にある数字」を指示する必要があるものの、まだうまく機能していません。桁数でなんとなく判別しているだけです。


▲フォント作者の方々の合意を得られなさそうで流れた企画「同人フォントソムリエ」

AppleScript名:選択範囲の行頭にある数字をリナンバーする v1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/01/02
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

property NSMutableArray : a reference to current application’s NSMutableArray

property myNumStep : 1000

tell application "CotEditor"
  tell front document
    set aSel to contents of selection
    
set aSelList to paragraphs of aSel
  end tell
end tell

–範囲指定がない場合
if length of aSelList = 0 then
  display dialog "Error: No Selection" buttons {"OK"} default button 1 with icon 2
  
return
end if

–過大な範囲指定チェック
if length of aSelList > 1000 then
  set bRes to button returned of (display dialog "選択範囲が1000行を超えています。処理に時間がかかることが予想されますが、実行しますか?")
end if

–行頭の数字部分のみ取得して、数字の最小値を取得する
set topNumList to getNumbersAtLineBegennings(aSelList) of me
set minNum to calcIntMinAsStr(topNumList) of me

–行頭部分の数字部分のみリナンバー
set bRes to renumberNumsAtLineBegennings(aSelList, minNum as integer, myNumStep) of me

–1D Arrayを改行コードをデリミタに指定しつつテキスト化
set outStr to retDelimedText(bRes, return) of me

tell application "CotEditor"
  tell front document
    set contents of selection to outStr
  end tell
end tell

–行頭に入っている数字の文字のみリナンバー
–実際には行頭判定はまだ行えていない。行頭の番号と文の途中に出てくる数字の区別は「桁数」でのみ行っている
on renumberNumsAtLineBegennings(aSelList as list, firstNum as string, stepNum as number)
  set aDigit to length of firstNum –桁数
  
copy firstNum to aCount
  
  
set aRes to {}
  
  
repeat with i in aSelList
    set j to (contents of i) as string
    
set nRes to (getNumberCharsOnlyAtBegening(j) of me) as string
    
    
if nRes is not equal to "" then –InputとOutputが違った
      set n1Res to removeNumCharsOnly(j, aDigit) of me
      
set tmpNumStr to zeroPadding(aCount, aDigit) of me
      
set n1Res to tmpNumStr & n1Res
      
set aCount to aCount + stepNum
      
set the end of aRes to n1Res
    else
      set the end of aRes to j
    end if
  end repeat
  
  
return aRes
end renumberNumsAtLineBegennings

–1D Listの最小値を文字列で返す
on calcIntMinAsStr(aList as list)
  set nArray to (NSMutableArray’s arrayWithArray:aList)
  
set maxRes to (nArray’s valueForKeyPath:"@min.self")’s intValue()
  
return maxRes as string
end calcIntMinAsStr

–行頭に入っている数字の文字のみ抽出
on getNumbersAtLineBegennings(aSelList as list)
  set aRes to {}
  
repeat with i in aSelList
    set j to contents of i
    
set nRes to getNumberCharsOnlyAtBegening(j) of me
    
if nRes is not equal to "" then
      set the end of aRes to nRes
    end if
  end repeat
  
  
return aRes
end getNumbersAtLineBegennings

–数字のみ返す
on getNumberCharsOnlyAtBegening(aStr as string)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9]{4,}" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end getNumberCharsOnlyAtBegening

–数字のみ削除して返す
on removeNumCharsOnly(aStr as string, aDigit)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:("[0-9]{" & (aDigit as string) & ",}") withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end removeNumCharsOnly

–指定桁数で指定の数にゼロパディングして文字列を返す
on zeroPadding(aNum as number, aDigit as number)
  set aText to "00000000000" & (aNum as text)
  
set aLen to length of aText
  
set aRes to text (aLen – aDigit + 1) thru -1 of aText
  
return aRes
end zeroPadding

–1D Listを指定デリミタをはさみつつテキストに
on retDelimedText(aList as list, aDelim as string)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retDelimedText

★Click Here to Open This Script 

(Visited 155 times, 1 visits today)
Posted in regexp Text | Tagged 10.15savvy 11.0savvy 12.0savvy CotEditor | Leave a comment

CotEditorで最前面の書類の内容をすべて選択してコマンド実行

Posted on 8月 13, 2021 by Takaaki Naganoya

CotEditorでオープン中の最前面の書類の内容をすべて選択してコマンド(半角→全角 文字変換)を実行するAppleScriptです。

データ処理内容の確認のためにCotEditor上で処理したときに「あれ? 書類の内容を全選択する処理って書いたことなかったわ〜」と気づいて、慌てて書きました。

AppleScript名:最前面のドキュメント内を全選択して全角変換.scpt
tell application "CotEditor"
  tell front document
    set tLen to length
    
set aRange to {0, tLen}
    
set range of selection to aRange
    
change roman width selection to full
  end tell
end tell

★Click Here to Open This Script 

(Visited 71 times, 1 visits today)
Posted in Text | Tagged 10.15savvy 11.0savvy 12.0savvy CotEditor | Leave a comment

CotEditor Script Pack v3の一般向け配布を開始

Posted on 7月 8, 2021 by Takaaki Naganoya

macOS用テキストエディタ「CotEditor」の機能強化AppleScript集「Script Pack v3」の配布を開始しました。

→ 配布ページ

Script Packは従来バージョン同様に、機能強化ユーティリティScript集の「PowerPack」および、AppleScriptによる基礎的なCotEditorの操作を解説した「Basic Pack」から構成されています。macOS 10.15.xおよび11.x+CotEditor v4.xとの組み合わせで利用することを想定しています。M1 Mac上でも動作確認ずみです。

PowerPack v3では、CotEditor上で編集中のテキストの文字種別を集計してグラフ表示させたり、編集中のテキストで使われている単語をもとにタグクラウド表示を行うなど、従来では把握しにくかったテキストの傾向をビジュアル表示する機能を追加しています。

外部アプリケーションを使わずにCSVデータのプレビュー(100行までの制限あり)、Markdownテキストのプレビューを行えるなど、CotEditorの動作速度を損うことなく大幅な機能追加を行なっています。

(Visited 311 times, 2 visits today)
Posted in news PRODUCTS | Tagged 10.15savvy 11.0savvy CotEditor | Leave a comment

CotEditor強化Script集「PowerPack v3」の解説本を発売

Posted on 7月 7, 2021 by Takaaki Naganoya

電子書籍の新刊を出しました。「機能強化AppleScript集 CotEditor用 PowerPack 取扱説明書」ページ数:191ページ、フォーマット:PDF+Zipアーカイブ(PowerPack、BasicPack)となっています。

→ 販売ページ
→ お試し版書籍ダウンロード

「CotEditor」は、Github上のオープンソース・プロジェクトで公開されているmacOS用の高機能テキストエディタです。本書は、そのCotEditorに便利で強力な機能を追加できるAppleScript集「PowerPack v3」の取扱説明書です。

本書にはPowerPack v3(ソース編集可能版)+Basic Packが含まれています。現在準備中の一般配布版のPowerPack v3は内容が見られません。ただ実行するだけです。

新たにリリースしたPowerPackバージョン3では、グラフ表示やタグクラウド表示などの「ド派手な機能」を追加。Markdown書類のプレビューやCSVデータの表プレビュー、タブ区切りテキストによるKeynote書類の生成、ミュージック.appのトラックへの歌詞データの書き込みなど、AppleScriptによる高度な処理を手軽にご堪能いただけます。

→ 書籍サポートページ

(Visited 177 times, 1 visits today)
Posted in Books PRODUCTS | Tagged 10.15savvy 11.0savvy CotEditor | 1 Comment

CotEditorのScript集、PowerPack & Basic Packを近日中にv3.0にアップデート

Posted on 5月 30, 2021 by Takaaki Naganoya

CotEditorの強化用AppleScript集、PowerPackを近日中にv3.0にアップデートします。また、同時にこのPowerPackの使い方を詳細に説明したドキュメントをBooth上で電子ブックとして販売します。

今回の目玉は、グラフ表示。

AppleScriptによって、CotEditorで編集中の最前面のドキュメントの文字種別を分析して、アニメーションしつつグラフ表示します。文章書きがとっても気にする、漢字、ひらがな、カタカナなどの文字種別の使用比率をグラフ化。

AppleScriptでワードクラウド表示。AppleScriptで記述した世界最小(自称)の簡易日本語形態素解析プログラム「easyJParse」を組み込んで、簡易的にワードクラウドを組み立てて表示します。文章内容の傾向を客観的に把握するための表示です。

AppleScriptだけでMarkdownのプレビュー表示を行います。

さらに、AppleScriptでCSVのプレビュー表示も。小規模なデータならその場でダイアログ上でプレビュー表示を、大きなデータはNumbersに渡してそちらで表示させるという寸法です。

(Visited 72 times, 1 visits today)
Posted in Books PRODUCTS | Tagged 10.15savvy 11.0savvy CotEditor | Leave a comment

CotEditorの各Windowで選択しておいた内容を座標でソートして結合

Posted on 2月 11, 2021 by Takaaki Naganoya

CotEditorでオープン中の複数のウィンドウから、各ウィンドウ(書類)の選択範囲を取得し、各ウィンドウの画面上の位置情報をもとに、その順番(Y座標、X座標)にテキストを組み合わせて新規書類を作成するAppleScriptです。


▲DEMO


▲Live Coding

当初、ウィンドウの重ね合わせ順(windowのindex)も考慮していたのですが、実際にためしてみたところ、重ね合わせ順を使うのは無駄だったので、機能を外しました。

AppleScript名:CotEditorの各Windowで選択しておいた内容を重ね合わせ順と座標でソートして結合.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/02/10
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set wList to {}

tell application "CotEditor"
  set wCount to count (every window whose visible is true)
  
if wCount < 2 then return
  
  
repeat with i from 1 to wCount
    tell window i
      set tmpBounds to bounds
      
      
set tmpProp to properties
    end tell
    
    
set tmpDoc to document of tmpProp
    
tell tmpDoc
      set aCon to contents of selection
    end tell
    
    
set tmpX to item 1 of tmpBounds
    
set tmpY to item 2 of tmpBounds
    
set tmpRec to {winIndex:i, winX:tmpX, winY:tmpY, selText:aCon}
    
    
set the end of wList to tmpRec
    
  end repeat
  
end tell

–座標値をもとにソートして選択テキストを返す
set sWList to sortRecListByLabel(wList, {"winY", "winX"}, {true, true}) of me
set anArray to current application’s NSArray’s arrayWithArray:sWList
set vList to (anArray’s valueForKey:"selText") as list
set jointStr to retArrowText(vList, return) of me

–CotEditor上で指定テキストでドキュメントを新規作成
makeNewCotEditorDoc(jointStr) of me

–リストを指定デリミタを追加しつつテキスト化
on retArrowText(aList, aDelim)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retArrowText

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as list, ascendF as list)
  set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
set aCount to length of aLabelStr
  
set sortDescArray to current application’s NSMutableArray’s new()
  
repeat with i from 1 to aCount
    set aLabel to (item i of aLabelStr)
    
set aKey to (item i of ascendF)
    
set sortDesc to (current application’s NSSortDescriptor’s alloc()’s initWithKey:aLabel ascending:aKey)
    (
sortDescArray’s addObject:sortDesc)
  end repeat
  
  
return (aArray’s sortedArrayUsingDescriptors:sortDescArray) as list
end sortRecListByLabel

–指定テキストでCotEditorの新規書類を作成
on makeNewCotEditorDoc(aCon)
  tell application "CotEditor"
    activate
    
set newDoc to make new document
    
tell newDoc
      set contents to aCon
    end tell
  end tell
end makeNewCotEditorDoc

★Click Here to Open This Script 

(Visited 44 times, 1 visits today)
Posted in list Record | Tagged 10.14savvy 10.15savvy 11.0savvy CotEditor | Leave a comment

CotEditor v3.9.7でAppleScriptコマンドを追加

Posted on 10月 23, 2020 by Takaaki Naganoya

CotEditor v3.9.7(macOS 10.1510.13以降対応)でAppleScript用語辞書にコマンドが追加されていました。

document中のselectionに対して処理を行うもので、英語のダブルクォート/シングルクォートをワープロ的なクォート開始文字とクォート終了文字に置き換えます。


▲smarten quotes実行前


▲smarten quotes実行後


▲straighten quotes実行前


▲straighten quotes実行後

AppleScript名:smarten quotes
tell application "CotEditor"
  tell front document
    smarten quotes selection
  end tell
end tell

★Click Here to Open This Script 

AppleScript名:straighten quotes
tell application "CotEditor"
  tell front document
    straighten quotes selection
  end tell
end tell

★Click Here to Open This Script 


▲smarten quotes実行前


▲smarten quotes実行後

(Visited 51 times, 1 visits today)
Posted in news | Tagged 10.15savvy 11.0savvy CotEditor | Leave a comment

AppleScriptでリアルタイムキースキャンを行いCotEditor書類上にカーソル描画

Posted on 10月 4, 2020 by Takaaki Naganoya

Modifier Keyのリアルタイムキースキャンを行なって、CotEditor書類上に文字でカーソル描画するAppleScriptです。30 x 30 の文字数のテキストを作成し、CotEditor書類に随時転送することで書き換えています。

AppleScriptでキースキャンといえば、Script/Applet起動時にoptionやcontrolなどのmodifier keys(装飾キー)が押されているかどうかを確認して、動作内容を変更するような用途でした。AppleScriptでGUIを作るのが大変だとか、AppleScriptで気軽にGUIを呼び出せない時代には、割と使われてきた手段です。

そんな中、macOS 10.10以降でCocoaの機能が気軽に利用できるようになってきたことで、Cocoaのキースキャン機能が利用できるようになりました。前述のModifier KeysのスキャンはmacOS側のセキュリティ機構でも問題視していないようで、気軽に使えそうです。ちなみに、SHIFTキーの左右は区別できません。

先日Pixelmator Proで「もぐら叩きゲーム」を作った際にも、このModifier Keysのスキャンは利用しましたが、実際にどの程度使い物になるのか確認しておきたいと考え、AppleScriptからの操作が高速なアプリケーションで試してみることにしてみました。

CotEditorにテキストで描画した画面を転送し、毎回テキスト内容をすべて書き換えることで本格的なゲームの用途に使えるのではないかと考えました。自分ではほとんどゲームを作ったこともないので、別にゲームを量産するつもりはありませんが……。テトリスぐらいならCotEditorのメニューから呼び出すAppleScript内で実行できそうな感じがします。

→ 冗談半分でAppleScriptで作られたTetrisを探してみたら、見つかりました

CotEditorでなくても、他のエディタでも同様の操作はできると思います。

AppleScript名:KeyScan TEST v3.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/10/03
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit" — for NSEvent
use scripting additions

–Initialize
set curPosX to 1
set curPosY to 1
set curMax to 30

set rText to ""
repeat curMax times
  set rText to rText & "🛑"
end repeat

tell application "CotEditor"
  write to console "Real-time Keyscan test with Modifier Keys
  [ Control ]    : Move Left
  [ Shift ]    : Move Right
  [ Option ]    : Move Up
  [ Command ]  : Move Down

  [ Caps Lock ]  : Quit this script"
  
  
make new document
  
activate
end tell

–Main Loop
repeat
  set leftF to my checkModifier:"control"
  
set rightF to my checkModifier:"shift"
  
set upF to my checkModifier:"option"
  
set downF to my checkModifier:"command"
  
  
set quitF to my checkModifier:"caps"
  
  
if quitF = true then return
  
  
if leftF = true then
    if curPosX > 1 then
      set curPosX to curPosX – 1
    end if
  else if rightF = true then
    if curPosX ≤ curMax then
      set curPosX to curPosX + 1
    end if
  end if
  
  
if upF = true then
    if curPosY > 1 then
      set curPosY to curPosY – 1
    end if
  else if downF = true then
    if curPosY < curMax then
      set curPosY to curPosY + 1
    end if
  end if
  
  
  
–make display text
  
set aText to ""
  
repeat with i from 1 to curMax + 1
    if i = curPosX then
      set aText to aText & "🛑"
    else
      set aText to aText & "㍳"
    end if
  end repeat
  
  
  
set bText to ""
  
repeat with y from 1 to curMax
    if y = curPosY then
      set bText to bText & rText & return
    else
      set bText to bText & aText & return
    end if
  end repeat
  
  
my displayText(bText)
  
end repeat

–テキスト画面描画
on displayText(aText)
  tell application "CotEditor"
    tell front document
      set contents to aText
    end tell
  end tell
end displayText

–複数同時検出に対応
on checkModifier:keyName
  if keyName = "option" then
    set theMask to current application’s NSAlternateKeyMask as integer
  else if keyName = "control" then
    set theMask to current application’s NSControlKeyMask as integer
  else if keyName = "command" then
    set theMask to current application’s NSCommandKeyMask as integer
  else if keyName = "shift" then
    set theMask to current application’s NSShiftKeyMask as integer
  else if keyName = "caps" then
    set theMask to current application’s NSEventModifierFlagCapsLock as integer
  else if keyName = "num" then
    set theMask to current application’s NSEventModifierFlagNumericPad as integer
  else if keyName = "help" then
    set theMask to current application’s NSEventModifierFlagHelp as integer
  else if keyName = "fn" then
    set theMask to current application’s NSEventModifierFlagFunction as integer
  else
    return false
  end if
  
  
set theFlag to current application’s NSEvent’s modifierFlags() as integer
  
if ((theFlag div theMask) mod 2) = 0 then
    return false
  else
    return true
  end if
end checkModifier:

★Click Here to Open This Script 

(Visited 127 times, 1 visits today)
Posted in System | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy CotEditor NSEvent | Leave a comment

CotEditor上で選択中のJavaScriptのrecord in listをASのオブジェクトに変換

Posted on 6月 29, 2020 by Takaaki Naganoya

CotEditorの最前面のドキュメントで選択中の、JavaScriptのrecord in listをAppleScriptのオブジェクトに変換するAppleScriptです。

こんな風にJavaScriptのプログラム中のrecord in listを選択しておいてScriptを実行すると、

AppleScriptのオブジェクトに変換します。

AppleScript名:CotEditor上で選択中のJavaScriptのrecord in listをASのオブジェクトに変換.scpt
— Created 2015-07-20 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "CotEditor"
  tell front document
    set jsonText to contents of selection
  end tell
end tell

set a to repChar(jsonText, "[", "{") of me
set b to repChar(a, "]", "}") of me
set c to repChar(b, string id 10, "") of me
set d to repChar(c, tab, "") of me

try
  set e to run script d
  
set f to convToStr(e) of textKit
  
  
tell application "CotEditor"
    make new document
    
tell front document
      set contents to f
    end tell
  end tell
on error erM
  display dialog erM
  
end try

–文字置換
on repChar(origText as string, targChar as string, repChar as string)
  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

–リストでもレコードでもなんでも文字列化して返すキット
script textKit
  
  
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") or (aClass = "boolean") 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 

(Visited 53 times, 1 visits today)
Posted in list Record Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy CotEditor | Leave a comment

AppleScriptを実行中のランタイムプログラム名を取得する

Posted on 1月 18, 2020 by Takaaki Naganoya

AppleScriptのランタイムプログラム名を取得するAppleScriptです。AppleScript自身が「何によって」実行されているか、その実行プログラム名を取得するものです。

AppleScriptには何種類かランタイム環境が存在し、ランタイム環境ごとに若干の動作が変わってくることが知られています。

ランタイム環境ごとにどこが違うといえば、Finderからのselectionを取得できるとかできないとか(AppleScript Studioがこれに該当。もうありませんけれども)、GUI Scriptingの権限の認証を得られるとか得られないとか。ウィンドウを動的に生成して表示したときに最前面に表示できるとかできないとか(Script Menuがこれに該当)。明示的にメインスレッドで実行する機能がないとか(Script Debuggerがこれに該当)。そういうところです(ほかにもあるかもしれない)。

過去に作ったAppleScriptを確認していたところ、プロセス名を取得するだけの使えないプログラムだと思っていたものが、実は「ランタイムプログラムのプログラム名」を取得できるというスゲーものであることを再発見しました。

ながらく、ランタイムプログラム名をAppleScript側から取得する必要性を感じていたため、この機会に調べてみることに。プログラム自体は些細な(↓)ものです。

AppleScript名:ランタイム環境名の表示
— Created 2015-09-08 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set procInfo to current application’s NSProcessInfo’s processInfo()
set aName to procInfo’s processName() as string
display dialog aName

★Click Here to Open This Script 

Script Editor上で実行


–> “Script Editor”

Script Debugger上で実行


–> “Script Debugger”

ASObjC Explorer 4上で実行


–> “ASObjC Explorer 4”

Automator上で実行


–> “Automator”
これには驚きました。特別のランタイムプログラムが使われているのか、それとも単に親プロセスとしてのAutomatorが返ってきているのかは不明ですが、識別できるということには意義がありそうです。

Script Menu上で実行


–> “osascript”
これは、よく知られていることなのでとくに驚きはありません。テストを実施したのはmacOS 10.14.6上で、Script Menuは「スクリプトメニュー」という別アプリケーション(/System/Library/CoreServices/ にある)に変更になったOSバージョンですが、ランタイムにosascriptを使い続けていることを確認することになりました(それ以前のOSと挙動が同じなのでそうだと思っていましたけれども)。

Folder Action上で実行




–> “osascript”
Folder Actionは、macOS標準搭載のフォルダ監視機能です。監視対象のフォルダにファイルが追加されたり、移動されたり、フォルダそのものがオープンしたりするとその対象ファイル/フォルダで指定のAppleScriptを実行します。よく、ドラッグ&ドロップで処理を受け付けたり、ネットワーク経由でファイルを受信した場合にAppleScriptを実行するような使われ方をします。
Folder Action Disptcherが実行しているとばかり思っていたのですが、実際に確認したらosascriptでした。ちなみに、Folder ActionはmacOS 10.11でフルに書き換えられてそれ以前とは別物になっています。以前は数秒に一度対象フォルダをチェックする方式でしたが、10.11以降はFSEventsを利用して随時監視対象フォルダへの変更を受け付けます。

Switch Control上で実行



–> “osascript”
障害者向けの機能としてmacOSに標準装備されている、フローティングパレットからAppleScriptを呼び出せる機能である「Switch Control」。手を使わずに操作したり、他のコントローラで操作するような標準的ではない使い方をサポートするための機構ですが、普通に普通の人が使っても役立ちます。 
Switch ControlでAppleScriptを実行する場合のランタイムプログラムはosascriptです。

CotEditor上で実行


–> “osascript”
これは、CotEditorのソースを読んで確認してありました。ここだけ割と手抜き実装ですが、それでも複数のOSA言語に対応できたりと機能的には悪くはありません。むしろ、osascript側のランタイム環境が他の環境よりも一段落ちることに問題が、、、、GUI Scriptingの権限を取得できないこととか、このCotEditorのメニューから実行するとREST APIが呼び出せないとか。同じosascript系でもScript Menuのほうが制約が少ないのは、おそらくアプリケーション自体に許可されている条件の違いによるものでしょう。

FileMaker Pro上でスクリプトステップ「AppleScriptを実行」を実行


–> “FileMaker Pro”
FileMaker Proはランタイムアプリケーションが廃止され、FileMaker Pro AdvancedもFileMaker Proに一本化されたので、v19以降はFileMaker Proは「FileMaker Pro」というランタイムのみでしょう。v19でもFileMaker Pro自体はSandbox化されていないため、微妙にセキュリティ上の制約が少ない=自由度の高いランタイム環境として残っていくことでしょう。

Script EditorからApplet書き出しして実行


–> “applet”
取得できたらいいなぐらいの気持ちで試してみたものの、これが識別できるのはうれしい誤算です。書き出したAppleScript Applet名は「Appletでランタイム名を取得」であったため、この「applet」というものとは異なります(ねんのため)。

AutomatorからApplet書き出しして実行


–> “Application Stub”
見たことのない名前が、、、、やっぱり、これも別ランタイムなんですね、、、、

Script DebuggerからApplet(Enhanced)で書き出しして実行


–> “FancyDroplet”
Appleの標準ランタイムとはあきらかに別物(Enhanced)なので、たぶん別の名前がついているだろうとは思っていましたが、そういう名前でしたか。名前が予想外だったので驚かされましたが、識別できることに意義があります。

Cocoa-AppleScript Appletを実行


–> “CocoaApplet”
Script Editor上で作成できる、通常のAppleScriptとXcode上で作成するCocoa-Applicationの中間的な性格を持つ「Cocoa-AppleScript Applet」でランタイムプログラム名を取得したらこうなりました。

もちろん、実行プログラム名はまったく別の「ランタイム名を表示するだけのCocoa-AppleScript Applet」というものです。

ショートカットで「AppleScriptを実行」アクションを実行


–> “MacHelper”

macOS 12で搭載されたショートカット.app(Shortcuts.app)および不可視プロセスのAppleScriptの補助専用アプリケーション「Shortcuts Events.app」上で、アクション「AppleScriptを実行」でAppleScriptを実行するときのランタイム名は、「MacHelper」です。意外なところで、ユーザーディレクトリ以下にインストールされたAppleScriptライブラリをこのMacHelper環境は認識します。

RedSweater Software「FastScripts」からAppleScriptを実行

red sweater softwareによるメニュー常駐型Script Menuソフトウェア「FastScripts」から実行したときのランタイム名は「FascScripts Script Runner」です。

Knurling Group「Service Station」からAppleScriptを実行

Knurling Groupによるコンテクストメニューのカスタマイズ・ソフトウェア「Service Station」から実行したときのランタイム名は「osascript」です。

ランタイム名が得られることで実現できること

これらのほか、各アプリケーション内でAppleScript呼び出し機能を有するもの(ファイルメーカー、Mail.appなど)でランタイムプログラム名を取得すると有益な情報が得られることでしょう。

これは、地球上にいる人類が観測衛星を打ち上げて「ここは銀河系だ」と観測できるぐらいすごいことなので、割と意義深いものです。実行中のAppleScriptが、「いま、何のプログラムによって自分自身が実行されている」かという情報を取得できます。

ランタイムプログラムの名称取得については、いくつかのAppleScript実行方法を試してみましたが、得られる名前に違いがないことを確認しています。

直接AppleScriptを動かす方法に加え、間接的にAppleScriptを動かす方法も試してみましたが、同じ結果が得られました。

つまり、動的にOSAScriptViewを生成して実行しようが、NSAppleScriptで実行しようが、AppleScriptの「run script」コマンドで実行しようが、取得されるランタイム名には差がありません。

これで、ランタイム環境のプロセスの親プロセスの情報が取得できると、Terminal.app上から起動したosascriptコマンドで呼び出したのか、Script Menu上から呼び出したのかという状況をAppleScript側で認識できることになることでしょう。

ランタイム環境を識別した上で、各環境で実行できない処理を行わないとか、ランタイム環境ごとに処理を分岐できるようになることでしょう。

ちょうど、Edama2さんと「ランタイム環境ごとに若干の挙動の違いが見られるし、利用できるCocoaの機能にも違いがあるから、ランタイム環境ごとに認識コードでも振ってみようか」などと相談していたので、渡りに船でした。

(Visited 111 times, 1 visits today)
Posted in OSA | Tagged 10.13savvy 10.14savvy 10.15savvy Automator CotEditor Script Debugger Script Editor | Leave a comment

choose multiple list lib

Posted on 12月 10, 2019 by Takaaki Naganoya

choose from listの複数リスト版。複数のポップアップメニューをダイアログ上で選択するUser Interfaceを提供する、「choose multiple list」AppleScriptライブラリです。macOS 10.13以降対応です。


▲選択リスト数は可変

–> Download chooseMultiList(To ~/Library/Script Libraries)

AppleScript name:sample 1.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use mulList : script "choose multiple list"

set selList to {{"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}, {"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}}
set tList to {"1st Segments", "2nd Segments"}

set aRes to choose multiple list selList main message "Select Items Demo" sub message "Select each selection. Same selection items *NOT* allowed" with title lists tList height 140 width 400 return type item contents without allow same items
–> {"Red", "Yellow"}

★Click Here to Open This Script 

AppleScript name:sample 2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use mulList : script "choose multiple list"

set selList to {{"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}, {"Red", "Blue", "Yellow", "Brown", "White", "Cyan", "Grey"}}
set tList to {"1st Segments", "2nd Segments"}

set aRes to choose multiple list selList main message "Select Items Demo" sub message "Select each selection. Same selection items allowed" with title lists tList height 140 width 400 return type item numbers with allow same items
–> {1, 1}

★Click Here to Open This Script 

テキストエディタ上でオープン中のテキストのdiff表示を行う場合のファイル選択のために作成したものです。


▲もっと汎用的に差分表示用の部品として活用するために、AppleScript用語辞書の添付が切実に望まれるApple製アプリケーション第1位のFileMerge

AppleScript名:CotEditor –> FileMergeでDiff表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/10
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions
use mulList : script "choose multiple list"

tell application "CotEditor"
  set dCount to count every document
  
if dCount < 2 then
    display dialog "A few documents…" with title "Error" buttons {"OK"} default button 1
    
return
  else if dCount = 2 then
    –オープン中の書類が2つある場合
    
set aPath to file of document 1
    
set bPath to file of document 2
    
    
set aPOSIX to POSIX path of aPath
    
set bPOSIX to POSIX path of bPath
  else
    –オープン中の書類が2つ以上存在している場合
    
set dList to {}
    
set adList to file of every document
    
    
repeat with i in adList
      set the end of dList to POSIX path of i
    end repeat
    
    
set selList to {dList, dList}
    
set tList to {"Document #1", "Document #2"}
    
    
set aRes to choose multiple list selList main message "Select two files to display diff" sub message "Select each file. Same selection items NOT allowed" with title lists tList height 140 width 700 return type item contents without allow same items
    
    
copy aRes to {aPOSIX, bPOSIX}
    
  end if
end tell

tell application "FileMerge" to activate
do shell script "/usr/bin/opendiff " & quoted form of aPOSIX & " " & quoted form of bPOSIX & " &"

★Click Here to Open This Script 

(Visited 122 times, 1 visits today)
Posted in dialog GUI list Script Libraries | Tagged 10.13savvy 10.14savvy 10.15savvy CotEditor FileMerge | Leave a comment

CotEditorのScript集、PowerPack & Basic Packをv2.0にアップデート

Posted on 10月 27, 2019 by Takaaki Naganoya

CotEditorの関連ScriptをまとめたScript Pack v2.0の配布を開始しました。無償、無保証、サポートなしで提供しています。CotEditor 3.8+macOS 10.14/10.15にて検証を行っています。

–> Download Page

基礎的なサンプルScriptの「Basic Pack」、強力なユーティリティScriptの「PowerPack」から構成され、今回アップデートしたのはPowerPackです。

PowerPackはCotEditorのScript Folder(~/Library/Application Scripts/com.coteditor.CotEditor)に入れればCotEditorのScript Menuに表示され、実行できるようになります。

Script Menuから実行すると、メニューバーにScript実行中のインジケーターが表示されます。

途中で停止したい場合には、⚙アイコンをクリックして表示されるメニューの×印ボタンをクリックすると、

実行がキャンセルされます。

さらに強化されたツールScript群:PowerPack

CotEditorのスクリプトメニューにインストールして使うためのScript群です。最大のアップデート内容は、メニュー内容の増加で見にくかった箇所を整理した点です。メニューにセパレータを入れて、おおまかな区分けを整理しています。v1.2で新規追加のScriptをわかりやすくしようと試みていましたが、メニュー内容が見にくくなったので廃止しました。


▲バージョンアップしてだんだんメニューが整理されてきました

アップデートしたものをご紹介いたします。

カウントレポート

「👀🔭🧼選択中のテキストの文字の種別ごとの構成比」を追加しました。長い文章の文字種判定を実行すると時間がかかるので、選択範囲のみ判定できるようにしたものです

🍎📜AppleScriptとして解釈


「📜AppleScript書類を読み込み、📄新規書類に展開」バンドル形式ではないAppleScript書類のソースコードを、CotEditorの新規書類に読み込みます
「📜🧼選択範囲をapplescript schemeの🌐URLに💙encodeして📄新規書類に展開」CotEditor上で編集中のAppleScriptの選択範囲をURLエンコードして、CotEditor新規書類に展開します

🧼🧼選択範囲を処理


「1️⃣2️⃣3️⃣行頭に番号を振る」選択中の行の先頭に連番を振ります
「🔄❎すべて❌伏せ字に」選択範囲の文字をすべて伏せ字にします
「🔄❎⚙️🇯🇵簡易日本語形態素解析📚してそれっぽく❌伏せ字に」選択範囲の日本語テキストを簡易形態素解析してそれっぽく伏せ字にします
「🔄❎⚙️🇬🇧英語簡易形態素解析📚してそれっぽく❌伏せ字に」同じく、選択範囲の英語のテキストをパースしてそれっぽく伏せ字にします(前置詞やbe動詞などを残してあとは伏せ字に)。まだ仕上がりがいまひとつです
「🔄✴️行頭にナカグロ(・)を入れる(箇条書き時の整形)」選択範囲の行頭にナカグロ(・)を入れます
「🔄✴️行頭のナカグロ(・)を削除する」行頭のナカグロ文字だけ削除します
「🔜⬇️行単位ソート(A→Z)」選択範囲の行を行単位で昇順ソートします
「🔙⬆️行単位ソート(Z→A)」選択範囲の行を行単位で逆順ソートします
「🔜🔃行単位で逆順に」選択範囲の行を行単位で現在と逆順に入れ替えます
「🔜🏞プロポーショナルフォントで🖥画面表示したピクセル数で行ソート」プロポーショナルフォントをオフスクリーン描画して、描画幅をもとにソートします
「🔄🎉行単位でランダム・シャッフル」行単位でシャッフルします

🈳青空文庫


「🈂️サンプル文章をオープン」同梱のサンプル文章「坊ちゃん」「こころ」「我輩は猫である」のうちのいずれかのテキストをオープンします

📝PDFから情報読み込み


「📝全ページの本文テキストを📗読み込む」指定のPDF本文テキストを新規書類に読み込みます
「📝指定ページの本文テキストを📗読み込む」指定のPDFの指定ページの本文テキストを新規書類に読み込みます
「🧾TOC(Table Of Contents)📗読み込み」指定のPDFのTOCテキストを新規書類に読み込みます
「🔗全ページの🌏URLリンクをまとめて📗新規書類に読み込む(http、https)」指定のPDFのURLリンクのうちプロトコルがhttp、httpsのURLを新規書類に読み込みます
「🔗全ページの🌏URLリンクをまとめて📗新規書類に読み込む(mailto)」指定のPDFのURLリンクのうちプロトコルがmailtoのURLを新規書類に読み込みます
「🔗全ページの🌏URLリンクをデコードして、それぞれ📗📗個別の📗📗新規書類に読み込む(applescript)」指定のPDFのURLリンクのうちプロトコルがapplescriptのURLをデコードして個別の新規書類に読み込みます
「🔗全ページの🌏URLリンクをデコードして、🧼選択語句を含むものをそれぞれ📗📗個別の📗📗新規書類に読み込む(applescript)」指定のPDFのURLリンクのうちプロトコルがapplescriptで、デコード内容にCotEditor上で選択中の語句を含むものを個別の新規書類に読み込みます

🎹iTunesまたはMusic


「🎹🖍現在の音楽トラックに歌詞として書き込む」CotEditorで選択範囲のテキストを、iTunes/Music上で選択中の音楽トラックの歌詞として書き込みます
「🎹👀現在の音楽トラックの歌詞を📗新規書類に読み込む」、iTunes/Music上で選択中の音楽トラックの歌詞をCotEditorの新規書類に読み込みます

🎲QRコード


「🎲💔QRコード画像をdecodeして📗新規書類に読み込み」QRコード画像をデコードして、CotEditorの新規書類に読み込みます
「🎲💙選択範囲をQRコードにencodeして🎆画像出力」CotEditor上で選択中のテキストをQRコードにエンコードしてデスクトップに画像出力します

🌇画像取り込み


「🔌💙base64 encodeして📃新規書類に読み込み」指定画像をbase64エンコードして新規書類に読み込みます
「)🔌💙base64 encodeして🏷img srcタグ🏷つきで📗新規書類に読み込み」指定画像をbase64エンコードして新規書類にimg srcタグつきで新規書類に読み込みます

📄⚙️ファイルの情報読み込み


「📄⚙️指定ファイルの🛍メタデータを📗新規書類に読み込み」指定ファイルのメタデータを新規書類に読み込みます

macOS 10.13上ではインストールできません

macOS 10.13上では配布中のZipファイルの展開時にエラーが出ることを確認していますが、macOS 10.13自体がバグの塊のようなバージョンなので、対処できるのかどうか、、、
–> DiskImageに入れて圧縮してみましたが、macOS 10.13上ではマウントしたDiskImageからのコピー時にエラーが出て(ファイル名をすべて変更しないと)コピー自体ができないようです

(Visited 278 times, 1 visits today)
Posted in System | Tagged 10.14savvy 10.15savvy CotEditor | 2 Comments

CotEditorの最前面のドキュメントの選択範囲を伏せ字に

Posted on 10月 22, 2019 by Takaaki Naganoya

CotEditorの最前面のドキュメントの選択範囲を、簡易形態素解析ルーチンeasyJparseを用いて、いい感じに伏せ字にするAppleScriptです。

–> Download makeSelectionToFuseji(Code-Signed AppleScript applet with libraries in its bundle, co-work with CotEditor)

easyJparseは日本語のコマンド解析用にでっちあげた作った超簡易形態素解析プログラムです。単語(形態素)ごとに分割しますが、品詞まではわかりません。コマンド解釈用ではあるものの、少し他の用途にも使えないかと思い、このような用途に使ってみました。

# 本Scriptは、CotEditor用のScript Pack v2.0に収録されています


▲CotEditorの選択範囲を伏せ字にする。形態素解析して単語化して、単語単位で伏せ字にするかの判断を実行

テキストエディタ上で伏せ字処理というのは、個人的によく使います。たいていは、オリジナルの文章に対して同様の分量の文章を作らなくてはならないようなケースで、文字数の感覚をつかむために使います。一種のダミーレイアウトのようなものです。

本スクリプトのような伏せ字処理については、ニーズがあるんだかないんだか不明なものですが、とりあえず掲載してみました。自分で使ってみたところ、たしかに面白いものの、実用性については未知数という印象です。

(minusList of parseSPD) に入れている語群は、どこかからか拾ってきたもののようではあるものの、すでに何か方向性を見失っているような気がしないではありません。

AppleScript名:選択範囲を伏せ字に(簡易形態素解析でそれっぽく).scptd
— Created 2018-09-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions
use jParser : script "easyJParse"

property NSArray : a reference to current application’s NSArray
property NSMutableSet : a reference to current application’s NSMutableSet
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

property fuesejiChar : "□"

script parseSPD
  property pList : {}
  
property p2List : {}
  
property oneLine : {}
  
property outStr : ""
  
property minusList : {}
end script

–伏せ字化しない助詞などの単語リスト。名詞だけを残すように整備。単語(形態素)単位で照合する
set (minusList of parseSPD) to {"", " ", "ー", "あ", "で", "も", "に", "と", "の", "は", "へ", "さ", "が", "せ", "か", "た", "だ", "だっ", "ば", "つ", "な", "い", "き", "お", "ら", "る", "れ", "なっ", "それ", "これ", "あれ", "どれ", "この", "どの", "あの", "その", "まで", "こと", "もの", "いつ", "いく", "たち", "ただ", "たい", "そう", "いる", "よう", "れる", "ない", "なら", "なる", "なけれ", "から", "する", "たら", "たり", "だけ", "って", "られ", "的", "化", "いくら", "そんな", "どんな", "あんな", "者", "陰", "時", "事", "こんな", "つれ", "けど", "ああ", "ある", "あっ", "あり", "しかし", "きっと", "すっかり", "例えば", "たとえば", "さっぱり", "たとえ", "だろう", "かつ", "ところ", "まるで", "だが", "全て", "すべて", "なり", "いい", "つれ", "つけ", "ながら", "せいぜい", "そうそう", "さらに", "もっと", "まだ", "なく", "し", "を", "て", "いけ", "行く", "また", "まま", "まぁ", "『", "』", "、", "。", "。。", "……。", "【", "】", "「", "」", "(", ")", "最近", "今度", "中", "チカチカ", "グラグラ", "ふわふわ", "少し", "ついで", "より", "っぽい", "ぐらい", "何", "とき", "ため", "そっくり", "そして", "やがて", "じきに", "すぐ", "今", "次", "できる", "出来る", "いや", "そう", "おそらく", "いえ", "らしい", "とも", "ほぼ", "つい", "もう", "きっかけ", "ころ", "頃", "早々", "そこ", "どこ", "なんか", "じゃ", "くれ", "ください", "こそ", "あいつ", "だれ", "誰", "おぼしき", "らしき", "らしい", "しか", "でき", "よっ", "確か", "どう", "こう", "そう", "ああ", "くる", "ざま", "ごとく", "きれ", "はず", "さらに", "さらなる", "更なる", "など", "ごと", "とても", "たく", "いう", "とっ", "いっ", "えっ", "おっ", "ここ", "そこ", "どこ", "なかっ", "ごく", "やる", "ゆい", "ふと", "たび", "ほど", "もた", "よし", "ぜひ", "いら", "よい", "ま", "み", "む", "め", "も", "や", "けれど", "だけど", "したがっ", "すごく", "そもそも", "ほしい", "なれる", "すぎ", "もふもふ", "モフモフ", "さん", "おと", "とー", "えっと", "け", "っけ", "なん", "よ", "ね", "しっくり", "くれる", "くれた", "なぜ", "まあ", "まぁ", "ん", "なんて", "!」"}

set (pList of parseSPD) to {}
set (p2List of parseSPD) to {}
set (oneLine of parseSPD) to {}
set (outStr of parseSPD) to {}

tell application "CotEditor"
  tell front document
    –選択部分が存在しているかどうかチェック
    
set aCon to contents of selection
    
if aCon = "" then return
    
    
set (pList of parseSPD) to paragraphs of aCon
  end tell
end tell

–伏せ字にする対象単語を、助詞などを消し込むことでピックアップ
repeat with i in (pList of parseSPD)
  if length of i > 1 then
    –簡易形態素解析
    
set tempList to parseJ(i) of jParser
    
    
–簡易形態素解析したリストと助詞などのリストの差分を計算
    
set cList to clacListDiff(tempList, (minusList of parseSPD)) of me
    
    
set (oneLine of parseSPD) to {}
    
repeat with ii in tempList
      set aLen to length of ii
      
if ii is in cList then
        –伏せ字化する場合
        
set bCon to multipleChar(fuesejiChar, aLen) of me
        
      else
        –そのまま出力する場合
        
set bCon to contents of ii
      end if
      
set the end of (oneLine of parseSPD) to bCon
    end repeat
    
    
–1つの文章ぶんの単語を連結
    
set cStr to retDelimedText((oneLine of parseSPD), "") of me
  else
    set cStr to ""
  end if
  
  
set the end of (p2List of parseSPD) to cStr
  
end repeat

–すべての文章を連結して配列からテキストに
set (outStr of parseSPD) to retDelimedText((p2List of parseSPD), return) of me

tell application "CotEditor"
  tell front document
    set contents of selection to (outStr of parseSPD)
  end tell
end tell

–指定文字を指定回数繰り返して連結して出力
on multipleChar(aChar as string, aLen as integer)
  set aList to {}
  
repeat aLen times
    set the end of aList to aChar
  end repeat
  
  
return retDelimedText(aList, "") of me
end multipleChar

–1D Listを要素間に指定デリミタをはさんで文字列化
on retDelimedText(aList as list, aDelim as string)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retDelimedText

–2つの1D Listの差分を計算
on clacListDiff(aList as list, bList as list)
  set aSet to NSMutableSet’s setWithArray:aList
  
set bSet to NSMutableSet’s setWithArray:bList
  
  
aSet’s minusSet:bSet –補集合
  
set aRes to aSet’s allObjects() as list
  
  
return aRes
end clacListDiff

★Click Here to Open This Script 

(Visited 141 times, 1 visits today)
Posted in list Natural Language Processing Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy CotEditor NSArray NSMutableSet NSSortDescriptor | 1 Comment

Post navigation

  • Older posts

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

Google Search

Popular posts

  • AppleScriptによるWebブラウザ自動操縦ガイド
  • ドラッグ&ドロップ機能の未来?
  • macOS 13, Ventura(継続更新)
  • Intel MacとApple Silicon Macの速度差〜画像処理
  • macOS 12.x上のAppleScriptのトラブルまとめ
  • マウスの右クリックメニューをカスタマイズするService Station
  • macOS 12.3 beta 5、ASの障害が解消される(?)
  • CotEditorで選択範囲の行頭にある数字をリナンバーする v1
  • PFiddlesoft UI Browserが製品終了に
  • SF Symbolsを名称で指定してPNG画像化
  • 不可視プロセスで表示したNSAlertを最前面に表示
  • 与えられた自然言語テキストから言語を推測して、指定の性別で、TTSキャラクタを自動選択して読み上げ
  • macOS 12.3 beta4、まだ直らないASまわりの障害
  • 新刊発売:AppleScriptによるWebブラウザ自動操縦ガイド
  • Safariで表示中のYouTubeムービーのサムネイル画像を取得
  • macOS 12のスクリプトエディタで、Context Menu機能にバグ
  • macOS 12.3上でFinder上で選択中のファイルをそのままオープンできない件
  • Pixelmator Pro v2.4.1で新機能追加+AppleScriptコマンド追加
  • SafariでブックマークされたURL一覧を取得
  • SkimのAppleScriptサポート機能にバグ

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1391) 10.14savvy (586) 10.15savvy (434) 11.0savvy (274) 12.0savvy (165) 13.0savvy (20) CotEditor (60) Finder (47) iTunes (19) Keynote (97) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (21) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (42) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (118) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSUUID (18) NSView (33) NSWorkspace (20) Numbers (55) Pages (35) Safari (40) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKWebView (22) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • 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
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • 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)
  • 未分類

アーカイブ

  • 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