I have a large amount of text broken into sections (using AppleScript delimiters) which mostly consist of several paragraphs. Each paragraph has a line return at the end of it. I would like to be able to remove the last line return after the last paragraph for each section, and I’m wondering how I can do this with AppleScript. In other words I would like the last character of each section to be the full stop at the end of the last paragraph.
I asked because I am accustomed to Pages in which there is an official definition of sections.
They are blocks of text separated by section breaks which are character id 4.
Starting from a document containing two section breaks, running the Shane’s code removed only the characters at the end of the document. The linefeeds preceding the section breaks weren’t removed.
So I tried to enhance the code and built :
set sectionBreak to character id 4
tell application "Pages" to tell document 1 to tell body text
# Do what Shane's script do
repeat while character -1 is in {return, linefeed}
delete character -1
end repeat
# Now treats the possible sections
set theChars to its characters
set i to count theChars
# loops while it remains a section break in the list theChars, aka while there is a section break before the current character
repeat while theChars contains sectionBreak
if theChars's item i ≠sectionBreak then
set i to i - 1
else
set theChars to items 1 thru i of theChars
repeat
if theChars's item -2 is in {return, linefeed} then
delete its character (i - 1) # delete the linebreak preceding sectionBreak
-- set item -2 of theChars to sectionBreak # we may get rid of that
set theChars to items 1 thru -2 of theChars
set i to i - 1
else
exit repeat
end if
end repeat
end if
end repeat
end tell
It’s probably not the most efficient code but at least it does the complete cleaning job.