Script Editor

[スクリプトエディタ用]クリップボードでHTML(失敗作)


【スクリプトエディタで開く】 |

HTML4AppleScript.Copy.applescript
ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004スクリプトメニュー用
005スクリプトエディタの前面ドキュメントで
006投稿用のHTMLを生成する
007
008v0 テスト中 
009v0.1 コピーボタンにCSS追加
010v1 20250420 特に治すところも無くなったのでこれでOKにする
011
012com.cocolog-nifty.quicktimer.icefloe *)
013----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
014use AppleScript version "2.8"
015use framework "Foundation"
016use framework "AppKit"
017use scripting additions
018global argFileName
019property refMe : a reference to current application
020
021set appFileManager to refMe's NSFileManager's defaultManager()
022
023##########################################
024###起動時に削除するフォルダ
025##########################################
026set ocidDirPathURL to appFileManager's temporaryDirectory()
027###ディレクトリ
028set appFileManager to refMe's NSFileManager's defaultManager()
029set ocidTempDirURL to appFileManager's temporaryDirectory()
030set ocidUUID to refMe's NSUUID's alloc()'s init()
031set ocidUUIDString to ocidUUID's UUIDString
032set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(true)
033
034####アクセス権777で作成
035set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
036ocidAttrDict's setValue:511 forKey:(refMe's NSFilePosixPermissions)
037appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:ocidAttrDict |error|:(reference)
038
039
040##########################################
041###ファイル名とパス
042##########################################
043tell application "Script Editor"
044   tell front document
045      tell application "System Events"
046         key code 0 using command down
047         delay 0.2
048         key code 8 using command down
049         delay 0.2
050         key code 0 using control down
051      end tell
052   end tell
053end tell
054
055
056tell application "Script Editor"
057   tell front document
058      set strScriptFileName to name as text
059      set strScriptSource to contents as text
060   end tell
061end tell
062set argFileName to strScriptFileName as text
063###中間ファイルの名前は全部日付
064set strTime to doGetDateNo("yyyyMMddhhmmss") as text
065####ファイル名
066set strHtmlFileName to ("" & strScriptFileName & ".html") as text
067set strTextFileName to ("" & strScriptFileName & ".txt") as text
068###HTMLへのURL
069set ocidFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strHtmlFileName) isDirectory:false
070set ocidTextFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strTextFileName) isDirectory:false
071##########################################
072###HTML Entity
073##########################################
074set recordEntityMap to {|&|:"&amp;", |<|:"&lt;", |>|:"&gt;", |"|:"&quot;", |'|:"&apos;", |=|:"&#x3D;", |+|:"&#x2B;", |\\|:"&bsol;", |$|:"&#36;", |\||:"&#124;"} as record
075set ocidEntityMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordEntityMap)
076set ocidAllKeys to ocidEntityMap's allKeys()
077set ocidTextToEncode to refMe's NSMutableString's alloc()'s init()
078ocidTextToEncode's setString:(strScriptSource)
079repeat with itemAllKey in ocidAllKeys
080   ##キーの値を取り出して
081   set ocidMapValue to (ocidEntityMap's valueForKey:itemAllKey)
082   ##置換
083   set ocidEncodedText to (ocidTextToEncode's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
084   ##次の変換に備える
085   set ocidTextToEncode to ocidEncodedText
086end repeat
087###
088set ocidTextToEncode to (ocidTextToEncode's stringByReplacingOccurrencesOfString:("\t") withString:("    "))
089set ocidTextToEncode to (ocidTextToEncode's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
090
091###
092set strSetPattern to ("\\u00A0") as text
093set ocidOption to (refMe's NSRegularExpressionAnchorsMatchLines)
094set listResponse to (refMe's NSRegularExpression's regularExpressionWithPattern:(strSetPattern) options:(ocidOption) |error|:(reference))
095set appRegex to (item 1 of listResponse)
096set ocidLegth to ocidTextToEncode's |length|()
097set ocidRange to refMe's NSRange's NSMakeRange(0, ocidLegth)
098set ocidTextToEncode to (appRegex's stringByReplacingMatchesInString:(ocidTextToEncode) options:0 range:(ocidRange) withTemplate:(" "))
099
100set strEncodedText to ocidTextToEncode as text
101
102
103##########################################
104###コピーボタン
105##########################################
106
107###HTMLのエレメントID用のランダム番号5
108set num5Digit to random number from 10000 to 99999
109#このランダム値でクラス名を決める
110set strDivClassName to ("sourcecode" & num5Digit & "")
111###JAVAASCRIPT整形
112set strJsText to ("<script>const elmentButtonCopy" & num5Digit & " = document.getElementById('buttonCopy" & num5Digit & "');const elmentInputText" & num5Digit & " = document.getElementById('inputText" & num5Digit & "');elmentButtonCopy" & num5Digit & ".addEventListener('click', () => {const strInputTextValue = elmentInputText" & num5Digit & ".value;return navigator.clipboard.writeText(strInputTextValue);})</script>") as text
113set strCopyHTML to ("<textarea id=\"inputText" & num5Digit & "\" type=\"text\" hidden readonly>" & strEncodedText & "</textarea>") as text
114###ボタン用CSS
115set strCopyBottonCSS to ("#buttonCopy" & num5Digit & "{background-color:#569cd6;border:none;color:white;padding:15px32px;text-align:center;text-decoration:none;display:inline-block;font-size:16px;margin:4px2px;cursor:pointer;border-radius:10px;}") as text
116###出来上がり
117set strCopyLinkText to (strCopyHTML & "<button id=\"buttonCopy" & num5Digit & "\" style=\"display: inline-block;border:none;padding: 7px 14px;background-color: #fdb200;color: white;text-decoration: none;border-radius: 6px;font-weight: bold;text-align: center;transition: background 0.3s;font-size:16px;\"  onmousedown=\"this.style.transform='translateY(2px)'; this.style.boxShadow='inset 0 2px 4px rgba(0,0,0,0.2)'\" onmouseup=\"this.style.transform='none'; this.style.boxShadow='none'\" onmouseleave=\"this.style.transform='none'; this.style.boxShadow='none'\">【クリップボードへコピー】</button>" & strJsText) as text
118set strJsLinkText to ("<span class=\"javascript_botton\">" & strCopyLinkText & "</span>") as text
119
120##########################################
121###スクリプトリンクの作成
122##########################################
123set ocidScriptSource to refMe's NSString's stringWithString:(strScriptSource)
124##キャラクタセットを指定
125set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
126###ペーストボードの内容をキャラクタセットで変換
127set ocidTextEncodeAS to ocidScriptSource's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
128###可変テキストに格納しておく
129set ocidEncodedText to refMe's NSMutableString's alloc()'s init()
130ocidEncodedText's setString:(ocidTextEncodeAS)
131########   置換 %エンコードの追加処理
132###置換レコード
133set recordPercentMap to {|+|:"%2B", |=|:"%3D", |&|:"%26", |$|:"%24"} as record
134###ディクショナリにして
135set ocidPercentMap to refMe's NSDictionary's alloc()'s initWithDictionary:(recordPercentMap)
136###キーの一覧を取り出します
137set ocidAllKeys to ocidPercentMap's allKeys()
138###取り出したキー一覧を順番に処理
139repeat with itemAllKey in ocidAllKeys
140   ##キーの値を取り出して
141   set ocidMapValue to (ocidPercentMap's valueForKey:itemAllKey)
142   ##置換
143   set ocidEncodedText to (ocidEncodedText's stringByReplacingOccurrencesOfString:(itemAllKey) withString:(ocidMapValue))
144   ##次の変換に備える
145   set ocidTextToEncode to ocidEncodedText
146end repeat
147###
148set strSetPattern to ("\\u00A0") as text
149set ocidOption to (refMe's NSRegularExpressionAnchorsMatchLines)
150set listResponse to (refMe's NSRegularExpression's regularExpressionWithPattern:(strSetPattern) options:(ocidOption) |error|:(reference))
151set appRegex to (item 1 of listResponse)
152set ocidLegth to ocidTextToEncode's |length|()
153set ocidRange to refMe's NSRange's NSMakeRange(0, ocidLegth)
154set ocidTextToEncode to (appRegex's stringByReplacingMatchesInString:(ocidTextToEncode) options:0 range:(ocidRange) withTemplate:(" "))
155
156
157set strEncodedText to ocidTextToEncode as text
158###
159set ocidURLComponents to refMe's NSURLComponents's alloc()'s init()
160ocidURLComponents's setScheme:("applescript")
161ocidURLComponents's setHost:("com.apple.scripteditor")
162##クエリー部
163set ocidQueryItems to refMe's NSMutableArray's alloc()'s init()
164ocidQueryItems's addObject:(refMe's NSURLQueryItem's alloc()'s initWithName:("action") value:("new"))
165ocidQueryItems's addObject:(refMe's NSURLQueryItem's alloc()'s initWithName:("name") value:(strScriptFileName))
166#ocidQueryItems's addObject:(refMe's NSURLQueryItem's alloc()'s initWithName:("script") value:(ocidScriptSource))
167##クエリーをセットする
168ocidURLComponents's setQueryItems:(ocidQueryItems)
169##URLに戻して テキストにしておく
170set ocidOpenURL to ocidURLComponents's |URL|()
171set strURL to ocidOpenURL's absoluteString() as text
172log strURL
173set strSetStyle to ("display: inline-block;padding: 7px 14px;background-color: #fdb200;color: white;text-decoration: none;border-radius: 6px;font-weight: bold;text-align: center;transition: background 0.3s;") as text
174
175
176set strAsLinkText to "<span class=\"openscript\"><a href=\"" & strURL & "&script=" & strEncodedText & "\" title=\"Open in Script Editor\" class=\"open-script-editor\" style=\"" & strSetStyle & "\">【スクリプトエディタで開く】</a></span>" as text
177set strLinkBotton to ("<p class=\"script-copy-botton\">" & strAsLinkText & "  |  " & strJsLinkText & "</p>") as text
178
179
180
181
182##########################################
183###ペーストボード
184##########################################
185####ペーストボード宣言
186set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
187####中に格納されているデータタイプを取得
188set ocidPastBoardTypeArray to ocidPasteboard's types
189log ocidPastBoardTypeArray as list
190
191
192if (ocidPastBoardTypeArray's containsObject:"public.rtf") is true then
193   ###ペーストボードの内容をタイプ指定で受け取るdataForTypeで受け取る
194   set ocidPublicRTF to ocidPasteboard's dataForType:(refMe's NSPasteboardTypeRTF)
195   ###NSAttributedStringに変換して
196   set ocidAttributedString to refMe's NSAttributedString's alloc()'s initWithRTF:(ocidPublicRTF) documentAttributes:(missing value)
197   ###文字数を数えてレンジを生成
198   set numStringLenge to ocidAttributedString's |length|() as integer
199   set ocidRange to refMe's NSMakeRange(0, numStringLenge)
200   ####オプション指定
201   set ocidAttributedDict to refMe's NSDictionary's dictionaryWithObject:(refMe's NSHTMLTextDocumentType) forKey:(refMe's NSDocumentTypeDocumentAttribute)
202   ##オプション指定でHTMLデータに変換
203   set listAttributedString to ocidAttributedString's dataFromRange:(ocidRange) documentAttributes:(ocidAttributedDict) |error|:(reference)
204   set ocidHTMLDATA to item 1 of listAttributedString
205   ###HTMLデータをHTMLテキストに戻して
206   set ocidPublicHTML to refMe's NSString's alloc()'s initWithData:(ocidHTMLDATA) encoding:(refMe's NSUTF8StringEncoding)
207   #
208   set ocidPublicHTML to (ocidPublicHTML's stringByReplacingOccurrencesOfString:("\n\n") withString:("\n"))
209   set ocidPublicHTML to (ocidPublicHTML's stringByReplacingOccurrencesOfString:("\r\r") withString:("\r"))
210   
211   set ocidPublicHTML to (ocidPublicHTML's stringByReplacingOccurrencesOfString:("</head>\n<body>") withString:("<div id=\"" & strDivClassName & "\">" & strLinkBotton & "<table>"))
212   
213   
214   #############
215   #
216   set ocidPublicHTML to doMakePostHTML(ocidPublicHTML, strDivClassName)
217   #############
218   #
219   set ocidPublicHTML to doReplacingString(ocidPublicHTML)
220   
221   #############
222   #
223   set ocidPublicHTML to doAddCss(ocidPublicHTML, num5Digit)
224   
225   ###ファイルに書き込む
226   ocidPublicHTML's writeToURL:(ocidFilePathURL) atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
227else
228   return "HTMLに変換出来ません"
229end if
230
231###HTML表示で開く
232tell application "TextEdit"
233   open (ocidFilePathURL as alias)
234end tell
235
236###拡張子をtxtにしたソース閲覧用のファイルを作る
237appFileManager's copyItemAtURL:(ocidFilePathURL) toURL:(ocidTextFilePathURL) |error|:(reference)
238###ソーステキストで開く
239tell application "TextEdit"
240   open (ocidTextFilePathURL as alias)
241end tell
242
243
244to doAddCss(argHTMLString, argNum5Digit)
245   
246   set strCSS to ("<hr><style type=\"text/css\">#sourcecode" & argNum5Digit & " div{margin: 5px;padding: 10px;max-width: 680px;}#sourcecode" & argNum5Digit & " table {border-spacing: 0;caption-side: top;}#sourcecode" & argNum5Digit & " table thead th {border: solid 1px #666666;padding: .5ch 1ch;border-block-width: 1px 1px;border-inline-width: 1px 0;-webkit-user-select: none;user-select: none;font-weight: normal;font-size: 10pt;&:first-of-type {border-start-start-radius: .5em}&:last-of-type {border-start-end-radius: .5em;border-inline-end-width: 1px}} #sourcecode" & argNum5Digit & " table tbody th {border-spacing: 0;border-top: none;border-bottom: solid 1px #666666;border-left: solid 1px #666666;border-right: solid 1px #666666;padding: .5ch 1ch;font-weight: normal;border-block-width: 1px 0;border-inline-width: 1px 0;-webkit-user-select: none;user-select: none;font-size: 10pt;}#sourcecode" & argNum5Digit & " table tbody td {max-width: 580px;word-wrap: break-word;border-spacing: 0;border-top: none;border-bottom: solid 1px #666666;border-left: solid 1px #666666;border-right: solid 1px #666666;padding-left: .5ch;padding-right: 1ch;border-block-width: 1px 0;border-inline-width: 1px 0;&:last-of-type {border-inline-end-width: 1px}}#sourcecode" & argNum5Digit & " table tbody td span {font-size: 12pt;line-height: 14pt;}kind_string {font-size: 0.75em;}.date_string {font-size: 0.5em;}#sourcecode" & argNum5Digit & " table tfoot th {border: solid 1px #666666;padding: .5ch 1ch;-webkit-user-select: none;user-select: none;font-weight: normal;&:first-of-type {border-end-start-radius: .5em}&:last-of-type {border-end-end-radius: .5em;border-inline-end-width: 1px}}</style>") as text
247   
248   set ocidReturnString to refMe's NSMutableString's alloc()'s init()
249   ocidReturnString's setString:(strCSS)
250   ocidReturnString's appendString:(argHTMLString)
251   #
252   (*
253   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("<table>") withString:("<table><thead><tr><th>行番号</th><th>ソース</th></tr></thead><tbody>"))
254   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("</table>") withString:("</tbody><tfoot><tr><th colspan=\"2\"></a></th></tr></tfoot></table>"))
255*)
256   
257   return ocidReturnString
258end doAddCss
259
260##########################################
261###日付時間番号
262##########################################
263to doGetDateNo(strDateFormat)
264   ####日付情報の取得
265   set ocidDate to refMe's NSDate's |date|()
266   ###日付のフォーマットを定義
267   set ocidNSDateFormatter to refMe's NSDateFormatter's alloc()'s init()
268   ocidNSDateFormatter's setLocale:(refMe's NSLocale's localeWithLocaleIdentifier:"en_US")
269   ocidNSDateFormatter's setDateFormat:(strDateFormat)
270   ###日付情報にフォーマットを適応
271   set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:(ocidDate)
272   ###テキストに確定させて
273   set strDateAndTime to ocidDateAndTime as text
274   ###戻す
275   return strDateAndTime
276end doGetDateNo
277
278
279to doReplacingString(argHTMLString)
280   
281   set ocidLineArray to argHTMLString's componentsSeparatedByString:("\n")
282   
283   set ocidReturnArray to refMe's NSMutableArray's alloc()'s init()
284   set numCntArray to ocidLineArray's |count|()
285   set numLineNO to 1 as number
286   repeat with itemIntNo from 0 to (numCntArray - 1) by 1
287      set itemLineSting to (ocidLineArray's objectAtIndex:(itemIntNo))
288      set boolPreFix to (itemLineSting's hasPrefix:("td.p"))
289      if boolPreFix is true then
290         set numLength to itemLineSting's |length|()
291         set ocidRange to refMe's NSRange's NSMakeRange(0, numLength)
292         set strRefPattern to ("(?:margin:\\s*[^;]+;\\s*|text-indent:\\s*[^;]+;\\s*)") as text
293         set ocidRefPattern to (refMe's NSString's stringWithString:(strRefPattern))
294         
295         set listResponse to (refMe's NSRegularExpression's regularExpressionWithPattern:(ocidRefPattern) options:(0) |error|:(reference))
296         set appRegex to (item 1 of listResponse)
297         set ocidLineString to (appRegex's stringByReplacingMatchesInString:(itemLineSting) options:0 range:(ocidRange) withTemplate:(""))
298      else
299         set ocidLineString to itemLineSting
300      end if
301      ##
302      set boolPreFix to (ocidLineString's hasPrefix:("<p "))
303      if boolPreFix is true then
304         set strLineNO to doZeroPad(numLineNO, 3) as text
305         set ocidLineString to (ocidLineString's stringByReplacingOccurrencesOfString:("<p ") withString:("<tr><td class=\"lineno\">" & strLineNO & "</td><td "))
306         set numLineNO to (numLineNO + 1) as integer
307      end if
308      set boolMeta to (ocidLineString's hasPrefix:("<meta"))
309      if boolMeta is false then
310         (ocidReturnArray's addObject:(ocidLineString))
311      end if
312      
313   end repeat
314   
315   set ocidReturnString to ocidReturnArray's componentsJoinedByString:("\n")
316   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("\n\n") withString:("\n"))
317   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("\n\n") withString:("\n"))
318   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("</script></span></td></tr>") withString:("</script></span></p>"))
319   #
320   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("<table>") withString:("<table><caption>" & argFileName & "</caption><colgroup><col title=\"LineNo\"></col><col title=\"Source\"></col></colgroup><thead><tr><th title=\"lineNo\" class=\"lineNo\" scope=\"col\"></th><th title=\"Source\" class=\"Source\" scope=\"col\">ソース</th></tr></thead><tbody>"))
321   
322   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("</table>") withString:("</tbody><tfoot><tr><th title=\"テーブルの終わり\" colspan=\"2\" scope=\"row\"><a href=\"https://quicktimer.cocolog-nifty.com/icefloe/2025/04/post-b26aa5.html\" target=\"_blank\">AppleScriptで生成しました</a></th></tr></tfoot></table>"))
323   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("table {margin: 0;padding: 0;width: 100%;} ") withString:("table {margin: 0;padding: 0;width: 100%;} "))
324   set ocidReturnString to (ocidReturnString's stringByReplacingOccurrencesOfString:("th {margin: 0;padding: 0;}") withString:("th {margin: 0;padding: 0;}"))
325   
326   
327   
328   return ocidReturnString
329   
330end doReplacingString
331
332
333to doMakePostHTML(argHTMLString, argDivClassName)
334   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">") withString:(""))
335   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("<html>\n<head>") withString:(""))
336   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("<title></title>") withString:(""))
337   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("</body>\n</html>") withString:("</table></div><hr>"))
338   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("\t") withString:("&nbsp;&nbsp;&nbsp;"))
339   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("</p>") withString:("</td></tr>"))
340   
341   #日本語の場合
342   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("<style type=\"text/css\">") withString:("<style type=\"text/css\">#" & argDivClassName & " table tr:nth-child(odd) { background-color: #f9f9f9; }#" & argDivClassName & " table tr:nth-child(even) {background-color: #ffffff;}#" & argDivClassName & " table {margin: 0;padding: 0;width: 100%;} #" & argDivClassName & " td, #" & argDivClassName & " th {margin: 0;padding: 0;}"))
343   
344   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("#sourcecode44530 td.p") withString:("#" & argDivClassName & " td.p"))
345   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("</style>") withString:("td.lineno{width:36px;font: 10px monospace; color: #707070;-webkit-user-select: none;user-select: none;}#" & argDivClassName & " td {text-indent: 0 !important;}#" & argDivClassName & " span {text-indent: 0 !important;}</style>"))
346   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:(";font-family: system-ui, -apple-system, BlinkMacSystemFont,sans-serif;") withString:(";font-family: system-ui, -apple-system, BlinkMacSystemFont,sans-serif;"))
347   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:(";font-family: system-ui, -apple-system, BlinkMacSystemFont,sans-serif;") withString:(";font-family: system-ui, -apple-system, BlinkMacSystemFont,sans-serif;"))
348   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("#sourcecode44530 span.s") withString:("#" & argDivClassName & " #sourcecode44530 span.s"))
349   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("<span class=\"Apple-tab-span\">") withString:(""))
350   set argHTMLString to (argHTMLString's stringByReplacingOccurrencesOfString:("&nbsp;</span>") withString:("&nbsp;"))
351   
352   
353   return argHTMLString
354   
355   
356end doMakePostHTML
357
358
359###doZeroPad(, 桁数)
360to doZeroPad(numZero, numDigits2Pad)
361   set theZeroDig to "" as text
362   repeat (numDigits2Pad - 1) times
363      set theZeroDig to (theZeroDig & "0") as text
364   end repeat
365   set theZeroMax to 1
366   set theZeroMax to (theZeroMax & theZeroDig) as text
367   if numZero < theZeroMax then
368      return text -numDigits2Pad through -1 of (theZeroDig & numZero)
369   else
370      return numZero as text
371   end if
372end doZeroPad
AppleScriptで生成しました

| | コメント (0)

[Script Editor]新規SCPTファイルを作成する

新規Scptを作成.scpt

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013
014#テキスト
015set strFileName to ("SOME.scpt") as text
016set strScptFilePath to ("~/Desktop/" & strFileName & "") as text
017set ocidScptFilePathStr to refMe's NSString's stringWithString:(strScptFilePath)
018set ocidScptFilePath to ocidScptFilePathStr's stringByStandardizingPath()
019set strScptFilePath to ocidScptFilePath as text
020set aliasScptFilePath to (POSIX file strScptFilePath) as «class furl»
021
022
023set strScript to "#!/usr/bin/env osascript\rset strText to \"SOME DAY SOME WHERE\"\r"
024
025tell application "Script Editor"
026  set refActivDoc to make new document with properties {contents:strScript, description:"FOR DEMO"}
027  tell refActivDoc
028    compile
029    save as "com.apple.applescript.script" in aliasScptFilePath
030  end tell
031  tell front document
032    set strFinderComment to contents
033  end tell
034  close refActivDoc saving no
035end tell
AppleScriptで生成しました

|

スクリプトをターミナルで実行するv2(bash等にも対応)



ダウンロード - applescriptscpt2opentearmv2.zip



スクリプトをターミナルで実行する.workflow.scpt

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# workflow用
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010use scripting additions
011property refMe : a reference to current application
012
013on run {argListAliasFilePath}
014  
015  repeat with itemAliasFilePath in argListAliasFilePath
016    ###入力パス
017    set strFilePath to (POSIX path of itemAliasFilePath) as text
018    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
019    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
020    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath))
021    #
022    set ocidExtensionName to ocidFilePathURL's pathExtension()
023    set strExtensionName to ocidExtensionName's lowercaseString() as text
024    
025    #種類によって分岐
026    if (strExtensionName as text) is "scpt" then
027      set strCommandText to ("/usr/bin/osascript \"" & strFilePath & "\"") as text
028      log doOpenTermScript(strCommandText)
029    else if (strExtensionName as text) is "applescript" then
030      set strCommandText to ("/usr/bin/osascript \"" & strFilePath & "\"") as text
031      log doOpenTermScript(strCommandText)
032    else if (strExtensionName as text) is "bash" then
033      set strCommandText to ("/bin/bash -c '\"" & strFilePath & "\"'") as text
034      log doOpenTermScript(strCommandText)
035    else
036      log doOpenTermScript("\"" & strFilePath & "\"")
037    end if
038  end repeat
039  
040end run
041
042###ターミナルで実行する
043to doOpenTermScript(argCommandText)
044  set strCommandText to argCommandText as text
045  tell application "Terminal"
046    launch
047    activate
048    set refNewWindow to (do script "\n\n")
049    delay 0.5
050    do script strCommandText in refNewWindow
051  end tell
052end doOpenTermScript
AppleScriptで生成しました

スクリプトをターミナルで実行するv2.scpt

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# ファイル選択から用
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010use scripting additions
011property refMe : a reference to current application
012
013set appFileManager to refMe's NSFileManager's defaultManager()
014###ダイアログ
015set strName to (name of current application) as text
016if strName is "osascript" then
017  tell application "SystemUIServer" to activate
018else
019  tell current application to activate
020end if
021tell application "Finder"
022  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
023end tell
024
025set listUTI to {"com.apple.applescript.text", "com.apple.applescript.script", "public.shell-script", "public.bash-script", "public.zsh-script"} as list
026set strMes to ("ファイルを選んでください") as text
027set strPrompt to ("ファイルを選んでください") as text
028
029tell application "SystemUIServer"
030  activate
031  set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDefaultLocation of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
032end tell
033
034repeat with itemAliasFilePath in listAliasFilePath
035  ###入力パス
036  set strFilePath to (POSIX path of itemAliasFilePath) as text
037  set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
038  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
039  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath))
040  #
041  set ocidExtensionName to ocidFilePathURL's pathExtension()
042  set strExtensionName to ocidExtensionName's lowercaseString() as text
043  
044  #種類によって分岐
045  if (strExtensionName as text) is "scpt" then
046    set strCommandText to ("/usr/bin/osascript \"" & strFilePath & "\"") as text
047    log doOpenTermScript(strCommandText)
048  else if (strExtensionName as text) is "applescript" then
049    set strCommandText to ("/usr/bin/osascript \"" & strFilePath & "\"") as text
050    log doOpenTermScript(strCommandText)
051  else if (strExtensionName as text) is "bash" then
052    set strCommandText to ("/bin/bash -c '\"" & strFilePath & "\"'") as text
053    log doOpenTermScript(strCommandText)
054  else
055    log doOpenTermScript("\"" & strFilePath & "\"")
056  end if
057end repeat
058
059
060
061###ターミナルで実行する
062to doOpenTermScript(argCommandText)
063  set strCommandText to argCommandText as text
064  tell application "Terminal"
065    launch
066    activate
067    set refNewWindow to (do script "\n\n")
068    delay 0.5
069    do script strCommandText in refNewWindow
070  end tell
071end doOpenTermScript
AppleScriptで生成しました

|

AppleScriptをUTF8形式のテキストにするv2



ダウンロード - applescriptscpt2applescriptv2.workflow.zip



appleScriptをUTF8形式のテキストにするV2.workflow.scpt

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#workflow用
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "UniformTypeIdentifiers"
009use framework "AppKit"
010use scripting additions
011
012property refMe : a reference to current application
013###処理対象のファイルUTI1つ
014property listApplescriptUTI : {"com.apple.applescript.text", "com.apple.applescript.script"} as list
015
016on run {listAliasFilePath}
017  set appFileManager to refMe's NSFileManager's defaultManager()
018  repeat with itemAliasPath in listAliasFilePath
019    ###入力パス
020    set aliasFilePath to itemAliasPath as alias
021    set strFilePath to (POSIX path of aliasFilePath) as text
022    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
023    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
024    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath))
025    set aliasFilePath to (ocidFilePathURL's absoluteURL()) as alias
026    ###フォルダ除外
027    set listBool to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error| :(reference))
028    if (item 2 of listBool) = (refMe's NSNumber's numberWithBool:true) then
029      log "ディレクトリは処理しない"
030      exit repeat
031    end if
032    ###UTI取得
033    set listContentTypeKey to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error| :(reference))
034    set ocidContentType to (item 2 of listContentTypeKey)
035    set strUTI to (ocidContentType's identifier) as text
036    
037    
038    ###対象のUTIファイルタイプだけ処理する
039    if listApplescriptUTI contains strUTI then
040      tell application "Script Editor"
041        activate
042        open file aliasFilePath
043      end tell
044      tell application "Script Editor"
045        activate
046        tell front window
047          tell front document
048            set strFilePath to path as text
049            set boolmodified to modified
050            if boolmodified is true then
051              save
052            end if
053            set strContents to contents as text
054          end tell
055        end tell
056      end tell
057      tell application "Script Editor"
058        activate
059        tell front window
060          tell front document
061            close saving no
062          end tell
063        end tell
064      end tell
065      #シバン設定
066      set ocidScriptString to (refMe's NSMutableString's stringWithString:(strContents))
067      set ocidScriptString to (ocidScriptString's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
068      set ocidScriptString to (ocidScriptString's stringByReplacingOccurrencesOfString:("#!/usr/bin/env osascript") withString:("#!/usr/bin/env osascript"))
069      set ocidScriptString to (ocidScriptString's stringByReplacingOccurrencesOfString:("AppKit") withString:("AppKit"))
070      #Arrayにして1行目を調べる
071      set ocidScriptArray to (ocidScriptString's componentsSeparatedByString:("\n"))
072      set strFirstLine to ocidScriptArray's firstObject() as text
073      if strFirstLine is not "#!/usr/bin/env osascript" then
074        set ocidAddItem to (refMe's NSMutableString's stringWithString:("#!/usr/bin/env osascript"))
075        (ocidScriptArray's insertObject:(ocidAddItem) atIndex:(0))
076      end if
077      #テキストに戻す
078      set ocidScriptString to (ocidScriptArray's componentsJoinedByString:("\n"))
079      
080      #拡張子判定
081      set ocidExtensionName to ocidFilePathURL's pathExtension()
082      set strExtensionName to ocidExtensionName's lowercaseString() as text
083      if strExtensionName is "scpt" then
084        set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
085        set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("applescript"))
086        set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
087      else if strExtensionName is "applescript" then
088        set ocidSaveFilePathURL to ocidFilePathURL
089        set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
090      end if
091      
092      #
093      set boolDirExists to (appFileManager's fileExistsAtPath:(ocidSaveFilePath) isDirectory:(false))
094      if boolDirExists is true then
095        log "同名ファイルある"
096        set numCntNo to 1 as integer
097        repeat
098          set ocidBaseFilePath to ocidSaveFilePath's stringByDeletingPathExtension()
099          set ocidNewSaveFilePath to ocidBaseFilePath's mutableCopy()
100          set strNewExtension to ("@" & (numCntNo as text) & ".applescript") as text
101          (ocidNewSaveFilePath's appendString:(strNewExtension))
102          set boolDirExists to (appFileManager's fileExistsAtPath:(ocidNewSaveFilePath) isDirectory:(false))
103          if boolDirExists is false then
104            set ocidSaveFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidNewSaveFilePath) isDirectory:(false))
105            exit repeat
106          end if
107          set numCntNo to numCntNo + 1 as integer
108        end repeat
109      else if boolDirExists is false then
110        log "そのまま保存"
111      end if
112      
113      
114      set listDone to (ocidScriptString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
115      if (item 1 of listDone) is false then
116        log (item 2 of listDone)'s localizedDescription() as text
117        return "保存に失敗しました"
118      end if
119      set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
120      ###ターミナルで実行できるように755アクセス権にする
121      set ocidFileAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
122      # 777-->511 755-->493 700-->448 766-->502
123      (ocidFileAttrDict's setValue:(493) forKey:(refMe's NSFilePosixPermissions))
124      set listDone to (appFileManager's setAttributes:(ocidFileAttrDict) ofItemAtPath:(ocidSaveFilePath) |error| :(reference))
125    else
126      log "UTIが違えばは処理しない"
127    end if
128  end repeat
129  log "処理終了"
130end run
AppleScriptで生成しました

appleScriptをUTF8形式のテキストにするv2.scpt

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004#通常ダイアログからの実行用
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use scripting additions
009property refMe : a reference to current application
010
011property listApplescriptUTI : {"com.apple.applescript.text", "com.apple.applescript.script"} as list
012
013
014set strName to (name of current application) as text
015if strName is "osascript" then
016  tell application "SystemUIServer" to activate
017else
018  tell current application to activate
019end if
020tell application "Finder"
021  set aliasDefaultLocation to (path to desktop folder from user domain) as alias
022end tell
023set strMes to ("ファイルを選んでください") as text
024set strPrompt to ("Applescriptファイルを選んでください") as text
025tell application "SystemUIServer"
026  activate
027  ### ファイル選択時
028  set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDefaultLocation of type listApplescriptUTI with invisibles, multiple selections allowed and showing package contents) as list
029end tell
030
031set appFileManager to refMe's NSFileManager's defaultManager()
032
033repeat with itemAliasFilePath in listAliasFilePath
034  
035  set aliasFilePath to itemAliasFilePath as alias
036  set strFilePath to (POSIX path of aliasFilePath) as text
037  set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
038  set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
039  set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false))
040  #拡張子判定
041  set ocidExtensionName to ocidFilePathURL's pathExtension()
042  set strExtensionName to ocidExtensionName's lowercaseString() as text
043  if strExtensionName is "scpt" then
044    set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
045    set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("applescript"))
046    set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
047  else if strExtensionName is "applescript" then
048    set ocidSaveFilePathURL to ocidFilePathURL
049    set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
050  end if
051  #ファイルを開いて
052  tell application "Script Editor"
053    activate
054    open file aliasFilePath
055  end tell
056  #コンテンツ取得
057  tell application "Script Editor"
058    activate
059    tell front window
060      tell front document
061        set strFilePath to path as text
062        set boolmodified to modified
063        if boolmodified is true then
064          save
065        end if
066        set strContents to contents as text
067      end tell
068    end tell
069  end tell
070  #閉じる
071  tell application "Script Editor"
072    activate
073    tell front window
074      tell front document
075        close saving no
076      end tell
077    end tell
078  end tell
079  #シバン設定
080  set ocidScriptString to (refMe's NSMutableString's stringWithString:(strContents))
081  set ocidScriptString to (ocidScriptString's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
082  set ocidScriptString to (ocidScriptString's stringByReplacingOccurrencesOfString:("#!/usr/bin/env osascript") withString:("#!/usr/bin/env osascript"))
083  set ocidScriptString to (ocidScriptString's stringByReplacingOccurrencesOfString:("AppKit") withString:("AppKit"))
084  #Arrayにして1行目を調べる
085  set ocidScriptArray to (ocidScriptString's componentsSeparatedByString:("\n"))
086  set strFirstLine to ocidScriptArray's firstObject() as text
087  if strFirstLine is not "#!/usr/bin/env osascript" then
088    set ocidAddItem to (refMe's NSMutableString's stringWithString:("#!/usr/bin/env osascript"))
089    (ocidScriptArray's insertObject:(ocidAddItem) atIndex:(0))
090  end if
091  #テキストに戻す
092  set ocidScriptString to (ocidScriptArray's componentsJoinedByString:("\n"))
093  #
094  set boolDirExists to (appFileManager's fileExistsAtPath:(ocidSaveFilePath) isDirectory:(false))
095  if boolDirExists is true then
096    log "同名ファイルある"
097    set numCntNo to 1 as integer
098    repeat
099      set ocidBaseFilePath to ocidSaveFilePath's stringByDeletingPathExtension()
100      set ocidNewSaveFilePath to ocidBaseFilePath's mutableCopy()
101      set strNewExtension to ("@" & (numCntNo as text) & ".applescript") as text
102      (ocidNewSaveFilePath's appendString:(strNewExtension))
103      set boolDirExists to (appFileManager's fileExistsAtPath:(ocidNewSaveFilePath) isDirectory:(false))
104      if boolDirExists is false then
105        set ocidSaveFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidNewSaveFilePath) isDirectory:(false))
106        exit repeat
107      end if
108      set numCntNo to numCntNo + 1 as integer
109    end repeat
110  else if boolDirExists is false then
111    log "そのまま保存"
112  end if
113  
114  
115  set listDone to (ocidScriptString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference))
116  if (item 1 of listDone) is false then
117    log (item 2 of listDone)'s localizedDescription() as text
118    return "保存に失敗しました"
119  end if
120  set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
121  ###ターミナルで実行できるように755アクセス権にする
122  set ocidFileAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
123  # 777-->511 755-->493 700-->448 766-->502
124  (ocidFileAttrDict's setValue:(493) forKey:(refMe's NSFilePosixPermissions))
125  set listDone to (appFileManager's setAttributes:(ocidFileAttrDict) ofItemAtPath:(ocidSaveFilePath) |error| :(reference))
126  
127end repeat
AppleScriptで生成しました

|

スクリプトをアプリケーションで保存してもらう



でも用サンプルスクリプト入り

ダウンロード - script2save2app.zip



スクリプトをアプリケーションで保存.scpt

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004# 
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010property refMe : a reference to current application
011
012
013set aliasPathToMe to (path to me) as alias
014
015tell application "Finder"
016  set aliasContainerDir to (container of aliasPathToMe) as alias
017  set aliasScriptDirPath to (folder "Script" of folder aliasContainerDir) as alias
018  set listAliasFilePath to (entire contents of aliasScriptDirPath) as list
019end tell
020
021set strContainerDir to (POSIX path of aliasContainerDir) as text
022
023
024repeat with itemAliasFilePath in listAliasFilePath
025  tell application "Finder"
026    set strFileName to (name of itemAliasFilePath) as text
027  end tell
028  #拡張子をappに変更する
029  set strDelim to AppleScript's text item delimiters
030  set AppleScript's text item delimiters to "."
031  set listFileName to every text item of strFileName
032  copy "app" to last item of listFileName
033  set strAppFileName to listFileName as text
034  set AppleScript's text item delimiters to strDelim
035  #
036  set strSaveFilePath to ("" & strContainerDir & strAppFileName) as text
037  set aliasSavePath to (POSIX file strSaveFilePath) as «class furl»
038  
039  tell application "Script Editor"
040    open itemAliasFilePath
041    delay 1
042    tell document strFileName
043      save as "application" in aliasSavePath without run only and stay open
044    end tell
045    tell document strAppFileName
046      close saving no
047    end tell
048    
049    delay 1
050    
051  end tell
052end repeat
053
054tell application "Finder"
055  select file aliasSavePath
056end tell
057
058return "処理終了しました"
AppleScriptで生成しました

|

アクセシビリティにスクリプトメニューを追加する

スクリプトメニューから色々実行したい人は

この設定必須


202502191049361_1408x15462


Privacy_automation

"スクリプトメニュー.app" が
"'SystemUIServer.app"を制御するアクセスを要求しています。制御を許可すると、"SystemUIserver.
app"の書類やデータにアクセスしたり、そのアプリ内で操作を実行したりできるようになります。

202502191118301_520x552_20250219112701202502191118302_520x552

|

Script Editor ログの消去


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010
011property refMe : a reference to current application
012
013
014doClearLog()
015
016
017to doClearLog()
018  
019  tell application "Script Editor"
020    set listWindowName to (name of every window) as list
021  end tell
022  if listWindowName contains "ログの履歴" then
023    tell application "Script Editor"
024      tell application "System Events"
025        tell process "Script Editor"
026          tell window "ログの履歴"
027            try
028              ###activateできないWindowを前面に
029              perform action "AXRaise"
030              tell toolbar 1
031                tell button 1
032                  click
033                end tell
034              end tell
035            on error
036              keystroke "l" using {command down, option down}
037            end try
038          end tell
039        end tell
040      end tell
041    end tell
042  else
043    tell application "Script Editor"
044      tell application "System Events"
045        tell process "Script Editor"
046          keystroke "l" using {command down, option down}
047        end tell
048      end tell
049    end tell
050  end if
051  
052  tell application "Script Editor"
053    tell application "System Events"
054      tell process "Script Editor"
055        tell window "ログの履歴"
056          try
057            ###activateできないWindowを前面に
058            perform action "AXRaise"
059            tell toolbar 1
060              tell button 1
061                click
062              end tell
063            end tell
064          on error
065            keystroke "l" using {command down, option down}
066          end try
067        end tell
068      end tell
069    end tell
070  end tell
071  
072end doClearLog
AppleScriptで生成しました

|

[Script Editor]選択範囲をコメントにする

#行頭のコメント

AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# スクリプトメニュー用
004----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
005use AppleScript version "2.8"
006use framework "Foundation"
007use scripting additions
008
009#コメントの行頭接頭語
010set strPreFix to "#\t" as text
011
012#テキスト取得
013tell application "Script Editor"
014  tell front document
015    tell selection
016      set listRange to (character range) as list
017      set strGetText to contents as text
018    end tell
019  end tell
020end tell
021#エラー回避
022if strGetText is "" then
023  return "範囲を選択していません"
024end if
025#初期値
026set strOutputText to "" as text
027set strLineEndChar to "\r" as text
028#テキストをリストにして
029set strDelim to AppleScript's text item delimiters
030set AppleScript's text item delimiters to strLineEndChar
031set listSelectText to every text item of strGetText
032set AppleScript's text item delimiters to strDelim
033#リストの数
034set numCntList to (count of listSelectText) as integer
035#テキスト行だけ繰り返し
036repeat with itemNo from 1 to numCntList by 1
037  set strLineText to (item itemNo of listSelectText) as text
038  if itemNo = 1 then
039    #最初の行
040    set strOutputText to (strPreFix & strLineText & strLineEndChar) as text
041  else
042    #それ以外の行
043    set strOutputText to (strOutputText & strPreFix & strLineText & strLineEndChar) as text
044  end if
045end repeat
046
047#テキストを戻す
048tell application "Script Editor"
049  tell front document
050    tell selection
051      set contents to strOutputText as text
052    end tell
053  end tell
054end tell
AppleScriptで生成しました

(**)を使ったコメント
AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# スクリプトメニュー用
004----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
005use AppleScript version "2.8"
006use framework "Foundation"
007use scripting additions
008
009#テキスト取得
010tell application "Script Editor"
011  tell front document
012    tell selection
013      set listRange to (character range) as list
014      set strGetText to contents as text
015    end tell
016  end tell
017end tell
018#エラー回避
019if strGetText is "" then
020  return "範囲を選択していません"
021end if
022
023#初期値
024set strOutputText to "" as text
025set strLineEndChar to "\r" as text
026#テキストをリストにして
027set strDelim to AppleScript's text item delimiters
028set AppleScript's text item delimiters to strLineEndChar
029set listSelectText to every text item of strGetText
030set AppleScript's text item delimiters to strDelim
031
032
033##コメントの始まり
034copy "(*" to beginning of listSelectText
035##コメントの終わり
036copy "*)" to end of listSelectText
037
038#リストの数
039set numCntList to (count of listSelectText) as integer
040
041#テキスト行だけ繰り返し
042repeat with itemNo from 1 to numCntList by 1
043  set strLineText to (item itemNo of listSelectText) as text
044  if itemNo = 1 then
045    #最初の行
046    set strOutputText to (strLineText & strLineEndChar) as text
047  else if itemNo = numCntList then
048    #最後の行
049    set strOutputText to (strOutputText & strLineText) as text
050  else
051    #それ以外の行
052    set strOutputText to (strOutputText & strLineText & strLineEndChar) as text
053  end if
054end repeat
055
056#テキストを戻す
057tell application "Script Editor"
058  tell front document
059    tell selection
060      set contents to strOutputText as text
061    end tell
062  end tell
063end tell
AppleScriptで生成しました

|

スクリプトエディターの入力支援(Path to)


AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#
005#com.cocolog-nifty.quicktimer.icefloe
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use framework "AppKit"
010use scripting additions
011property refMe : a reference to current application
012
013
014set listChooser to {"me", "system folder", "system preferences", "startup disk", "#", "users folder", "shared documents", "home folder", "#", "trash", "temporary items", "#", "desktop", "documents folder", "downloads folder", "movies folder", "music folder", "pictures folder", "public folder", "sites folder", "#", "applications folder", "utilities folder", "#", "library folder", "application support", "keychain folder", "fonts", "favorites folder", "Folder Action scripts", "help", "preferences", "scripting additions folder", "scripts folder", "services folder", "startup items", "workflows folder"} as list
015
016###ダイアログを前面に出す
017set strName to (name of current application) as text
018if strName is "osascript" then
019  tell application "Finder" to activate
020else
021  tell current application to activate
022end if
023###
024set strTitle to ("選んでください") as text
025set strPrompt to ("選んだ項目で戻します") as text
026try
027  set objResponse to (choose from list listChooser with title strTitle with prompt strPrompt default items (item 1 of listChooser) OK button name "OK" cancel button name "キャンセル" with empty selection allowed without multiple selections allowed)
028on error
029  log "エラーしました"
030  return "エラーしました"
031end try
032log class of objResponse
033if (class of objResponse) is boolean then
034  return "キャンセルしましたA"
035else if (class of objResponse) is list then
036  if objResponse is {} then
037    return "キャンセルしましたB"
038  else
039    set strResponse to (item 1 of objResponse) as text
040  end if
041end if
042if strResponse is "#" then
043  tell application "Finder"
044    set aliasPathToMe to (path to me) as alias
045  end tell
046  run script aliasPathToMe with parameters "再実行"
047  
048else if strResponse is "" then
049  tell application "Finder"
050    set aliasPathToMe to (path to me) as alias
051  end tell
052  run script aliasPathToMe with parameters "再実行"
053  
054end if
055#
056set ocidResponse to refMe's NSString's stringWithString:(strResponse)
057set ocidResponse to ocidResponse's stringByReplacingOccurrencesOfString:("folder") withString:("")
058set ocidResponse to ocidResponse's stringByReplacingOccurrencesOfString:("items") withString:("")
059set ocidResponse to ocidResponse's capitalizedString()
060set ocidResponse to ocidResponse's stringByReplacingOccurrencesOfString:(" ") withString:("")
061set strDirName to ocidResponse as text
062#
063if strDirName is "Me" then
064  set strScriptText to ("set aliasPathToMe to (path to " & strResponse & ") as alias") as text
065  set strScriptText to (strScriptText & "\n") as text
066  set strScriptText to (strScriptText & "set strPathToMe to (posix path of  aliasPathToMe)as text") as text
067  set strScriptText to (strScriptText & "\n") as text
068  set strScriptText to (strScriptText & "set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)") as text
069  set strScriptText to (strScriptText & "\n") as text
070  set strScriptText to (strScriptText & "set ocidPathToMe  to ocidPathToMeStr's  stringByStandardizingPath()") as text
071  set strScriptText to (strScriptText & "\n") as text
072  set strScriptText to (strScriptText & "set ocidPathToMeURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe ) isDirectory:(true)") as text
073  set strScriptText to (strScriptText & "\n") as text
074  set strScriptText to (strScriptText & "set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent()") as text
075  set strScriptText to (strScriptText & "\n") as text
076else
077  set strScriptText to ("set alias" & strDirName & "DirPath to (path to " & strResponse & " from user domain) as alias") as text
078  set strScriptText to (strScriptText & "\n") as text
079  set strScriptText to (strScriptText & "set str" & strDirName & "DirPath to (posix path of alias" & strDirName & "DirPath)as text") as text
080  set strScriptText to (strScriptText & "\n") as text
081  set strScriptText to (strScriptText & "set ocid" & strDirName & "DirPathStr to refMe's NSString's stringWithString:(str" & strDirName & "DirPath)") as text
082  set strScriptText to (strScriptText & "\n") as text
083  set strScriptText to (strScriptText & "set ocid" & strDirName & "DirPath  to ocid" & strDirName & "DirPathStr's  stringByStandardizingPath()") as text
084  set strScriptText to (strScriptText & "\n") as text
085  set strScriptText to (strScriptText & "set ocid" & strDirName & "DirPathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocid" & strDirName & "DirPath ) isDirectory:(true)") as text
086  set strScriptText to (strScriptText & "\n") as text
087end if
088
089
090##############################
091#####ダイアログ
092##############################
093tell current application
094  set strName to name as text
095end tell
096if strName is "osascript" then
097  tell application "Finder"
098    activate
099  end tell
100else
101  tell current application
102    activate
103  end tell
104end if
105set strMes to "AppleScriptです"
106set aliasIconPath to (POSIX file "/System/Applications/Utilities/Script Editor.app/Contents/Resources/AppIcon.icns") as alias
107try
108  set recordResult to (display dialog strMes with title "戻り値です" default answer strScriptText buttons {"クリップボードにコピー", "終了", "再実行"} default button "再実行" cancel button "終了" giving up after 20 with icon aliasIconPath without hidden answer) as record
109on error
110  return "エラーしました"
111end try
112if (gave up of recordResult) is true then
113  return "時間切れです"
114end if
115##############################
116#####自分自身を再実行
117##############################
118if button returned of recordResult is "再実行" then
119  tell application "Finder"
120    set aliasPathToMe to (path to me) as alias
121  end tell
122  run script aliasPathToMe with parameters "再実行"
123end if
124##############################
125#####値のコピー
126##############################
127if button returned of recordResult is "クリップボードにコピー" then
128  try
129    set strText to text returned of recordResult as text
130    ####ペーストボード宣言
131    set appPasteboard to refMe's NSPasteboard's generalPasteboard()
132    set ocidText to (refMe's NSString's stringWithString:(strText))
133    appPasteboard's clearContents()
134    appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
135  on error
136    tell application "Finder"
137      set the clipboard to strText as text
138    end tell
139  end try
140end if
141
142
143return 0
AppleScriptで生成しました

|

新しいアプリケーション・スクリプトを作成する


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "Appkit"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application


##############################
#####スクリプトメニューから実行させない
##############################
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
    set aliasPathToMe to path to me as alias
    tell application "Script Editor"
      open aliasPathToMe
    end tell
return "中止しました"
  end tell
else
  tell current application
    activate
  end tell
end if

set strBundleID to ("com.apple.FontBook") as text
set strAppFileName to (strBundleID & ".app") as text

set strFilePath to ("~/Desktop/" & strAppFileName) as text


set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
set aliasFilePath to (ocidFilePathURL's absoluteURL()) as «class furl»


set strScript to ("#!/usr/bin/env osascript\n----+----1----+----2----+-----3----+----4----+----5----+----6----+----7\n#\n(*\nログイン項目登録用\n起動時に起動後『隠す』処理\nファイル>書き出す…からアプリケーションに書き出し\nログイン項目に登録する\n設定項目のバンドルIDは\nhttps://github.com/force4u/AppleScript/blob/main/Script%20Menu/Developer/Get/getAppBundleID.applescript\nを使って取得できます\n*)\n#com.cocolog-nifty.quicktimer.icefloe\n----+----1----+----2----+-----3----+----4----+----5----+----6----+----7\nuse AppleScript version \"2.8\"\nuse framework \"Foundation\"\nuse scripting additions\n###設定項目\nset strBundleID to (\"" & strBundleID & "\") as text\n###起動\ntell application id strBundleID\nlaunch\nend tell\ndelay 3\n###起動待ち 最大60回\nrepeat 60 times\ntell application id strBundleID\nactivate\nset boolFrontMost to frontmost as boolean\nend tell\nif boolFrontMost is true then\nexit repeat\nelse\ndelay 0.25\nend if\nend repeat\n###名前の取得\ntell application id strBundleID\nset strAppName to name as text\nend tell\n###隠す処理\ntell application \"System Events\"\ntell application process strAppName\nset visible to false\nend tell\nend tell") as text


tell application "Script Editor"
  
  make new document with properties {contents:strScript}
  tell front document
    activate
compile
  end tell
  save front document as "application" in aliasFilePath without run only, startup screen and stay open
  close front document saving no
end tell

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom