How to show the Persian numbers in applescript? - applescript

Actually I've a simple code that it shows the page number in English , is there anyway to show them out in Persian or Arabic numbers ?
my applescript is :
tell application "myApp"
if (count documents) > 0 then
set pageCount to count (pages of document 1)
repeat with pageNumber from 1 to pageCount
set thePage to page pageNumber of document 1
make new text imprint at end of imprints of thePage with properties {rich text:pageNumber as rich text, x position:36, y position:36, height:16, width:30}
end repeat
return pageCount
end if
end tell
the output is like this :
1,2,3,4,5
and I want to be like this :
۱,۲,۳,۴,۵

You set the page number as string, so you can write a routine that shows a persian number in string format of an integer value
tell application "myApp"
if (count documents) > 0 then
set pageCount to count (pages of document 1)
repeat with pageNumber from 1 to pageCount
set thePage to page pageNumber of document 1
make new text imprint at end of imprints of thePage with properties {rich text:my intToPersianString(pageNumber), x position:36, y position:36, height:16, width:30}
end repeat
return pageCount
end if
end tell
on intToPersianString(intValue)
set persianSymbols to "۰۱۲۳۴۵۶۷۸۹"
set output to {}
repeat with i in characters of (intValue as string)
set end of output to character ((i as integer) + 1) of persianSymbols
end repeat
return output as string
end intToPersianString

Related

Get text of selected field code in Microsoft Word using AppleScript

I'm making a Automator to jump from citation in Word to the reference software(Zotero). But I can't find a AppleScript to extract text of selected field code (the first step).
The field code in Word is
ADDIN ZOTERO_ITEM CSL_CITATION {"citationID":"AFUiwuqi","properties":{"formattedCitation":"[1]","plainCitation":"[1]","noteIndex":0},"citationItems":[{"id":9752,"uris":["http://zotero.org/users/6410528/items/YYTRWPHH"],"itemData":{"id":9752,"type":"article-journal","container-title":"Nature","DOI":"10.1038/s41586-019-1737-7","ISSN":"0028-0836, 1476-4687","issue":"7782","page":"324-329","title":"Controlled flight of a microrobot powered by soft artificial muscles","volume":"575","author":[{"family":"Chen","given":"Yufeng"},{"family":"Zhao","given":"Huichan"},{"family":"Mao","given":"Jie"},{"family":"Chirarattananon","given":"Pakpong"},{"family":"Helbling","given":"E. Farrell"},{"family":"Hyun","given":"Nak-seung Patrick"},{"family":"Clarke","given":"David R."},{"family":"Wood","given":"Robert J."}],"issued":{"date-parts":[["2019",11,14]]}}}],"schema":"https://github.com/citation-style-language/schema/raw/master/csl-citation.json"}
Here is the script process:
Extract text from selected field code in Word (This is the question)
Get the uris text(http://zotero.org/users/6410528/items/YYTRWPHH)
Get the item-codes (YYTRWPHH).
Open url (zotero://select/library/items?itemKey=YYTRWPHH)
Now I use VBA to extract field code text, see below. But in this way, the file will be changed. So I want to do this via AppleScript.
Sub GetFiledsCodes()
Dim myRange As Range, myCodes As String
Set myRange = Selection.Range
With myRange
If .Fields.Count = 0 Then
MsgBox "No Code!", vbInformation
Exit Sub
Else
.Fields.Update
.TextRetrievalMode.IncludeFieldCodes = True
.TextRetrievalMode.IncludeHiddenText = True
myCodes = .Text
myCodes = VBA.Replace(myCodes, Chr(19), "{")
myCodes = VBA.Replace(myCodes, Chr(21), "}")
.SetRange .End, .End
.InsertAfter myCodes
.Font.Name = "Times New Roman"
.Font.Size = 12
.Cut
End If
End With
End Sub
PS:
Here is my process in Automator(it can work but using VBA):
Run AppleScript
on run {input, parameters}
tell application "Microsoft Word" to activate
tell application "Microsoft Word"
run VB macro macro name "GetFiledsCodes"
delay 0.5
end tell
return input
end run
Get contents from clipboard
Extract URLs from Text
Filter Paragraphs begin with http://zotero.org/users/
Copy to Clipboard
Run AppleScript
set myStr to do shell script "pbpaste"
tell application "Zotero" to activate
set AppleScript's text item delimiters to "
"
set myList to every text item of myStr
set zoterocode to ""
set codes to ""
repeat with j from 1 to the length of myList
set itemValue to item j of myList
set zoterocode to (do shell script "sed -E 's#http://zotero.org/users/[0-9]+/items/##g' <<< " & itemValue)
if j = 1 then
set codes to zoterocode
else
set codes to codes & "," & zoterocode
end if
end repeat
tell application "System Events"
key code 18 using {command down, control down, option down}
delay 0.5
set collectionKey to do shell script "pbpaste"
if collectionKey = myStr then
set theurl to "zotero://select/library/items?itemKey=" & codes
else
set theurl to collectionKey & "/items?itemKey=" & codes
end if
open location theurl
end tell
That helps a lot. Okay, so this isn't a turnkey solution for your question but I don't think you really need that as you'd probably end up having to tell me more about how this app works than is really necessary. So this script focuses on your initial question about getting the field codes/result ranges from a merge document.
I put together a simple mail merge consisting of labels and a data file with 8 records, each of which have 5 fields: {"«LastName»", "«JobTitle»", "«Company»", "«City»", "«Web»"}. The latter is the key field.
Basically, the script runs through the data merge document and cycles first through its fields, then the web field, and finally the web addresses.
Based on your script, I can't really determine what you are doing with each address so it finishes by collecting just the final part of each address in a list. The obscure parts for me are the pbpastes, the codes and the whole System Events block. This area would need tweaking.
Incidentally, it's quite likely that you can avoid some of the shell scripts but I can't say how yet. Obviously the script has some redundancies and could be further refined but I think it demonstrates how to extract the information you need. Take a look at it and let me know what issues there are that need addressing.
tell application "Microsoft Word"
set d1 to document "cardo_labels.docx"
set fContents to {} -- list of mergefield
set fResRange to {} -- list of result range, i.e. field merge data
repeat with x from 1 to (count of fields of d1)
set fcs to content of field code of field x of d1 --> " MERGEFIELD LastName "
set frr to content of result range of field x of d1 --> "Smith"
if fcs is not " NEXT " then -- ignore «Next Record»
set end of fContents to fcs
set end of fResRange to frr
end if
end repeat
--> single record example
fContents --> {" MERGEFIELD LastName ", " MERGEFIELD JobTitle ", " MERGEFIELD Company ", " MERGEFIELD City ", " MERGEFIELD Web "}
fResRange --> {"Smith", "President", "Acme Screw & Gear", "Metz", "http://zotero.org/users/1234/items/smith-metz"}
-- NB when not displaying 'merged data', fResRange will appear thusly: {"«LastName»", "«JobTitle»", "«Company»", "«City»", "«Web»"}
set webList to {}
repeat with y from 1 to (count of fResRange)
if item y of fResRange begins with "http://zotero.org/users/" then
set end of webList to (item y of fResRange)
end if
end repeat
--> {"http://zotero.org/users/1234/items/smith-metz"}
--> {"http://zotero.org/users/1234/items/smith-metz", "http://zotero.org/users/4222/items/branson-metz", "http://zotero.org/users/3236/items/house-metz", "http://zotero.org/users/3342/items/kurtz-london", "http://zotero.org/users/12345/items/jones-london"}
set urlPiece to {}
set AppleScript's text item delimiters to "/"
repeat with z in webList
set end of urlPiece to last text item of z
end repeat
-- contents of z
--> "http://zotero.org/users/1234/items/smith-metz"
set AppleScript's text item delimiters to ""
urlPiece
--> {"smith-metz"}
--> {"smith-metz", "jones-saopaolo", "branson-metz", "house-metz", "kurtz-london", "jones-london"}
end tell
Thanks to ideas from #Mockman.
Combining with the selection, here is the way to extract text from selected field code via AppleScript:
tell application "Microsoft Word"
tell selection
set fcs to content of field code of field of text object
end tell
end tell
fcs

Applescript | Extracting highest integer and create numbers from 0 to highest integer

I have a script returning the following results:
https://XY.com/shop/General-Mad-Dog-Mattis-For-PrN
https://XY.com/search?q=mad%20dog&p=29
https://XY.com/search?q=mad%20dog&p=26
Now i need to find the highest integer (in this case &p=29) and create new strings from https://XY.com/search?q=mad%20dog&p=0 up to the highest found integer in this case https://XY.com/search?q=mad%20dog&p=29
So far i managed to extract the URL's needed with the following code:
set AllUrls to {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29", "https://XY.com/shop/General-Mad-Dog-Mattis-For-PrN"}
-- FILTER PAGING URLS
set PagingFilter to "&p="
set PagingUrls to {}
repeat with i from 1 to length of AllUrls
if item i of AllUrls contains PagingFilter then
set end of PagingUrls to item i of AllUrls
end if
end repeat
PagingUrls -- returns {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29"}
And a small Script to extract the last 2 Digits from the URLs:
set alphabet to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set myURLs to {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29"}
set the text item delimiters of AppleScript to ¬
{space} & characters of the alphabet & {".", "_"}
set a to text items of myURLs as text
get last word of a --> returns "21"
set numlist to {}
repeat with i from 1 to count of words in a
set this_item to word i of a
try
set this_item to this_item as number
set the end of numlist to this_item
end try
end repeat
numlist -- returns {26, 29}
This is another approach.
It splits the URLs with text item delimiters by delimiter &p=. If the delimiter exists, get the integer (the right side of the delimiter) and save it as maxValue if the current value is higher than the previous value.
Then use a loop to create the list of page URLs
set AllUrls to {"https://XY.com/search?q=mad%20dog&p=26", "https://XY.com/search?q=mad%20dog&p=29", "https://XY.com/shop/General-Mad-Dog-Mattis-For-PrN"}
set maxValue to 0
set baseURL to ""
set TID to text item delimiters
set text item delimiters to "&p="
repeat with anURL in AllUrls
set textItems to text items of anURL
if (count textItems) is 2 then
set currentValue to item 2 of textItems as integer
if currentValue > maxValue then set maxValue to currentValue
set baseURL to item 1 of textItems & "&p="
end if
end repeat
set text item delimiters to TID
set pageURLs to {}
repeat with i from 0 to maxValue
set end of pageURLs to baseURL & i
end repeat

Applescript that looks for specific text in a list of text items

I have many esoteric CDs whose track names are not always in CDDB. So I'm trying to write a an Applescript that will take a list of song titles that I copy from AllMusic and paste them as track names in iTunes. When copying a list of track names from AllMusic, the format is ALMOST always:
track #
Title
Composer
Track length
A link to Spotify or Amazon
This repeats for as many tracks as the album contains. I wrote the following Applescript which works when the above format does not change:
set tid to AppleScript's text item delimiters
set txt to the clipboard
set p to count paragraphs of (the clipboard)
set i to 2
tell application "iTunes"
activate
if selection is not {} then -- there ARE tracks selected...
set mySelection to selection
repeat with aTrack in mySelection
if i is less than p then
set AppleScript's text item delimiters to ASCII character 13 -- (a carriage return)
set newTxt to text items of txt -- not text of, text items of
set AppleScript's text item delimiters to tid -- restore text delimiters
set name of aTrack to item i of newTxt
set i to i + 5
end if
end repeat
end if
end tell
The problem is that sometimes there is one or two more or less categories (e.g. missing composer) which throws my script off. Ideally, there would be a way to have the script go through the list of text items, find track #1, paste in the very next text item, find track 2, paste in the very next text item, etc. Any ideas on how to accomplish this?
Thanks for any help.
Here is the altered code based on my comment below:
…I tried adding "set k to 1" at the top, changing "set i to i + 5" to "set i to i + 4", and adding:
if i is equal to k then
set i to i + 1
set k to k + 1
end if
at the end of the repeat loop. Then the script would jump by 4 paragraphs. If counter 'k' didn't match the paragraph it was looking at (e.g. if k was "2" and paragraph i was not "2", it must mean that it was a group of 5 paragraphs, so "i" would advance by one. Not good scripting, but it would probably work in most cases. The trouble was that I could never get "if i is equal to k" to return as true, even when it was. Here is the code in full:
set tid to AppleScript's text item delimiters
set txt to the clipboard
set p to count paragraphs of (the clipboard)
set k to 1
set i to 2
tell application "iTunes"
activate
if selection is not {} then -- there ARE tracks selected...
set mySelection to selection
repeat with aTrack in mySelection
if i is less than p then
set AppleScript's text item delimiters to ASCII character 13 -- (a carriage return)
set newTxt to text items of txt -- not text of, text items of
set AppleScript's text item delimiters to tid -- restore text delimiters
set name of aTrack to item i of newTxt
set i to i + 4
if i is equal to k then
set i to i + 1
set k to k + 1
end if
end if
end repeat
end if
end tell
Thanks for confirmation about the format. The main issue is that it is not an easy format ! So, the script must look what are the next tab or return sequence to determine what is what.
I made the script bellow which does what you need. I included many comments to make it clear (I hope !). The first rows explain what could be the 4 possible text formats that the script must handle for composer and link ( yes/no for each).
I have tested the script with the 4 formats all in sequence in the same text. You must add your iTunes routine, which can use the defined variables : TTrack, TComposer (could be empty), TArtist, TLength and TLink (could be empty).
I insert a comment where your iTunes routine must be added.
The script loops until all txt from clipboard has been used.
(* format of input text is made of :
track# <tab> title <return> composer <return> artist <return> track_length <tab> link <tab>
- title, artist and track_length are mandatory
- composer and link are optional
Therefore, there are 4 possible formats :
track# <tab> title <return> composer <return> artist <return> track_length <tab> link <tab> (= complete)
track# <tab> title <return> artist <return> track_length <tab> link <tab> ( = no composer)
track# <tab> title <return> composer <return> artist <return> track_length <tab> ( = no link)
track# <tab> title <return> artist <return> track_length <tab> ( = no link, no composer)
*)
set Ctab to ASCII character 9
set Creturn to ASCII character 13
set txt to the clipboard
repeat while length of txt > 1
set AppleScript's text item delimiters to Creturn
set Track_Title to text item 1 of txt -- the first item always contains Track# tab Title
set L to (length of Track_Title) + 1 -- L will be the ofset for next track
set T2 to text item 2 of txt -- the second item could be composer or artist
set T3 to text item 3 of txt -- the third item could be artist or (track_length tab link tab track# tab title)
if (offset of Ctab in T3) = 0 then -- the third item is artist
set TComposer to T2
set TArtist to T3
set L to L + (length of TComposer) + 1 + (length of TArtist) + 1
set NextT to text item 4 of txt -- NextT = (track_length tab link tab track# tab title) or (track_length tab track# tab title)
else -- the third item is (track_length tab link tab track# tab title) or (track_length tab track# tab title)
set TComposer to ""
set TArtist to T2
set L to L + (length of TArtist) + 1
set NextT to text item 3 of txt
end if
set AppleScript's text item delimiters to Ctab
set TTrack to text item 1 of Track_Title
set TTitle to text item 2 of Track_Title
set TLength to text item 1 of NextT
set L to L + (length of TLength) + 1
if (count of text items of NextT) is 4 then -- format is (track_length tab link tab track# tab title)
set TLink to text item 2 of NextT
set L to L + (length of TLink) + 1
else -- format is (track_length tab track# tab title)
set TLink to ""
end if
-- replace this dialog by your iTunes procedure !!!!!!
display dialog "track=" & TTrack & return & "title=" & TTitle & return & "composer=" & TComposer & return & "Artist=" & TArtist & return & "length=" & TLength & return & "Link=" & TLink & return & "L=" & L
if length of txt > (L + 1) then
set txt to text (L + 1) thru -1 of txt -- remove all current track from text
else
set txt to ""
end if
end repeat

Applescript timed out in iTunes

I wrote a simple applescript to automatically add files into iTunes and fill the metadata. When I run it directly from the editor it works but running it from iTunes and I will get "AppleEvent Timed Out".
Here's the code:
set mainFolder to choose folder
tell application "Finder"
-- Loop through all shows
set shows to every folder of mainFolder
repeat with show from 1 to count of shows
-- Set Show Name
set showName to name of item show of shows
-- Set Artist
display dialog "Who is the artist for " & showName & "?" default answer showName
set showArtist to the text returned of the result
-- Set Genre
display dialog "What is the genre for " & showName & "?" default answer ""
set showGenre to the text returned of the result
-- Loop through all season
set seasons to every folder in item show of shows
repeat with season from 1 to count of seasons
set seasonName to name of item season of seasons
-- Set Season Number
set seasonNumber to text 1 thru ((offset of "-" in seasonName) - 2) of seasonName as integer
-- Set Year
display dialog "What year was Season " & seasonNumber & " of " & showName & " in?" default answer "2012"
set showYear to the text returned of the result
-- Set Season Name
set seasonName to text ((offset of "-" in seasonName) + 2) thru ((offset of "." in seasonName) - 1) of seasonName as text
-- Set Total Episodes in Season
set totalEpisodes to count of every file in item season of seasons
-- Loop through all episodes
set episodes to every file in item season of seasons
repeat with episode from 1 to count of episodes
set episodeName to name of item episode of episodes
-- Set Episode Number
set episodeNumber to text 1 thru ((offset of "-" in episodeName) - 2) of episodeName as integer
-- Set Episode Name
set episodeName to text ((offset of "-" in episodeName) + 2) thru ((offset of "." in episodeName) - 1) of episodeName as text
tell application "iTunes"
set newAddition to (add (item episode of episodes as alias))
tell newAddition
set video kind to TV show
set name to episodeName
set album to seasonName
set track number to episodeNumber
set track count to totalEpisodes
set disc number to "1"
set disc count to "1"
set show to showName
set season number to seasonNumber
set episode number to episodeNumber
-- Manual Entries
set artist to showArtist
set genre to showGenre
set year to showYear
-- Change episode ID based on season and episode number
if (seasonNumber < 10) then
if (episodeNumber < 10) then
set episode ID to ("S0" & seasonNumber as text) & "E0" & episodeNumber as text
else
set episode ID to ("S0" & seasonNumber as text) & "E" & episodeNumber as text
end if
else
if (episodeNumber < 10) then
set episode ID to ("S" & seasonNumber as text) & "E0" & episodeNumber as text
else
set episode ID to ("S" & seasonNumber as text) & "E" & episodeNumber as text
end if
end if
end tell -- End newAddition
end tell -- End iTunes
end repeat -- End Episode Repeat
end repeat -- End Season Repeat
end repeat -- End Show Repeat
end tell -- End Finder Repeat
the code itself seems sound assuming you don't have any errors when calculating the offsets and different components of the file name. However I can see 2 possible sources of errors that may fix your problem.
First, you have your iTunes tell block of code inside your Finder tell block of code. Essentially you are telling the Finder to tell iTunes to do something. That is a source of possible errors. You should separate your tell blocks from each other. For example you have this...
tell application "Finder"
-- do something
tell application "iTunes"
-- do something
end tell
end tell
When you should have it like this...
tell application "Finder"
-- do something
end tell
tell application "iTunes"
-- do something
end tell
Second, you have a mistake in your "episode id" code with the parenthesis. For example this...
("S0" & seasonNumber as text)
Should be this...
"S0" & (seasonNumber as text)
As such I have separated out the iTunes stuff into a subroutine and fixed the parenthesis. Note that I haven't tested this code. I think I passed all of the proper variables to the subroutine but I can't be certain. I hope this helps.
set mainFolder to choose folder
tell application "Finder"
-- Loop through all shows
set shows to every folder of mainFolder
repeat with show from 1 to count of shows
-- Set Show Name
set showName to name of item show of shows
-- Set Artist
display dialog "Who is the artist for " & showName & "?" default answer showName
set showArtist to the text returned of the result
-- Set Genre
display dialog "What is the genre for " & showName & "?" default answer ""
set showGenre to the text returned of the result
-- Loop through all season
set seasons to every folder in item show of shows
repeat with season from 1 to count of seasons
set seasonName to name of item season of seasons
-- Set Season Number
set seasonNumber to text 1 thru ((offset of "-" in seasonName) - 2) of seasonName as integer
-- Set Year
display dialog "What year was Season " & seasonNumber & " of " & showName & " in?" default answer "2012"
set showYear to the text returned of the result
-- Set Season Name
set seasonName to text ((offset of "-" in seasonName) + 2) thru ((offset of "." in seasonName) - 1) of seasonName as text
-- Set Total Episodes in Season
set totalEpisodes to count of every file in item season of seasons
-- Loop through all episodes
set episodes to every file in item season of seasons
repeat with episode from 1 to count of episodes
set episodeName to name of item episode of episodes
-- Set Episode Number
set episodeNumber to text 1 thru ((offset of "-" in episodeName) - 2) of episodeName as integer
-- Set Episode Name
set episodeName to text ((offset of "-" in episodeName) + 2) thru ((offset of "." in episodeName) - 1) of episodeName as text
my addEpisodeToItunes((item episode of episodes) as alias, seasonName, seasonNumber, episodeName, episodeNumber, totalEpisodes, showName, showArtist, showGenre, showYear)
end repeat -- End Episode Repeat
end repeat -- End Season Repeat
end repeat -- End Show Repeat
end tell -- End Finder Repeat
on addEpisodeToItunes(theEpisode, seasonName, seasonNumber, episodeName, episodeNumber, totalEpisodes, showName, showArtist, showGenre, showYear)
tell application "iTunes"
set newAddition to add theEpisode
tell newAddition
set video kind to TV show
set name to episodeName
set album to seasonName
set track number to episodeNumber
set track count to totalEpisodes
set disc number to "1"
set disc count to "1"
set show to showName
set season number to seasonNumber
set episode number to episodeNumber
-- Manual Entries
set artist to showArtist
set genre to showGenre
set year to showYear
-- Change episode ID based on season and episode number
if (seasonNumber < 10) then
if (episodeNumber < 10) then
set episode ID to "S0" & (seasonNumber as text) & "E0" & (episodeNumber as text)
else
set episode ID to "S0" & (seasonNumber as text) & "E" & (episodeNumber as text)
end if
else
if (episodeNumber < 10) then
set episode ID to "S" & (seasonNumber as text) & "E0" & (episodeNumber as text)
else
set episode ID to "S" & (seasonNumber as text) & "E" & (episodeNumber as text)
end if
end if
end tell -- End newAddition
end tell -- End iTunes
end addEpisodeToItunes
Here is how I solved it:
Save as an app instead of a script.
I got the solution from here:
http://forums.ilounge.com/applescripts-itunes-mac/245120-need-help-add-tracks-files-via-applescript.html
I have no clue why it's doing that, I've tried using try-catch, timeout... still didn't work. It works as an app though?!

How to loop through all rows in Excel using Applescript?

I'm trying to loop through all rows in Excel and run some command on each row, but I can't figure out how!
I tried initially doing that in rb-appscript (the Ruby wrapper for AppleScript) but decided that I'd be better off trying to get it working first in Applescript before adding another DSL. Any tips? (the rb-appscript version would be nice, too, though not required).
Thanks!
The coordinates of a range is a string that you can create dynamically. The simplest way to loop through your rows would be something like this:
repeat with thisRow from 1 to 10
tell application "Microsoft Excel"
set theRange to "A:" & thisRow & "Z:" & thisRow
set theValue to (get value of range theRange) as list
-- do something with the row's data
end tell
end repeat
Update per comments: To get the number of rows needing calculation, I wrote a subroutine ages ago to help with this. Be sure you have some kind of "key" column that is consistently populated (in other words, there are no skipped cells). This currently takes into account a header row since all of my spreadsheets have them:
on GetItemCount(KeyColumn)
set RowNumber to 1
set theText to "cSyoyodylg" -- dummy value
tell application "Microsoft Excel"
repeat until theText is ""
set RowNumber to RowNumber + 1
set theRange to KeyColumn & RowNumber & ":" & KeyColumn & RowNumber
set dataRange to range theRange of sheet 1
set theText to (get value of range theRange)
end repeat
end tell
set rowCount to RowNumber - 1
return rowCount
end GetItemCount
To use simply do this:
set lastRow to GetItemCount("A") of me
repeat with thisRow from 2 to lastRow + 1
-- go attack Excel
end repeat

Resources