Seth B
Seth B

Reputation: 1056

macOS change text when you copy it to clipboard

I have some text

blah blah blah
this is a new line
blah blah blah

I want to be able to copy the above text, and when I paste it, I want it to look like this

blah blah blah<br>this is a new line<br>blah blah blah

How do you do this in macOS? Automation? Applescript?

Upvotes: 2

Views: 1491

Answers (3)

CJK
CJK

Reputation: 6092

You will probably want to create an Automator Service workflow, to which you can then bind a keyboard shortcut via System Preferences. In the workflow, you can insert a Run AppleScript action, or a Run Shell Script action. Delete any existing sample code, and insert one of the following (depending on which action you opt for):

AppleScript:

on run {input}
    set my text item delimiters to "<br>"
    return the input's paragraphs as text
end run

Shell Script passing input to stdin:

input="$(</dev/stdin)"
printf "${input//$'\n'/<br>}"

You'll want to tick the checkbox called Output replaces selected text. To choose what the workflow should receive, decide which out of two scenarios you envisage activating this service:

  1. If the service should operate on text that you've highlighted, which then gets replaced by the modified output, choose Workflow receives: text

  2. If the service should operate on text that is stored on the clipboard, which then gets inserted into the document you're presently working on, choose Workflow receives: no input. Additionally, insert the action called Get Contents of Clipboard above the Run AppleScript or Run Shell Script action.

Save your service as whatever you would like it to appear as in the service menu. Assign a keyboard shortcut (such as V) through System Preferences.

Upvotes: 2

Chino22
Chino22

Reputation: 165

another one :

set theText to "blah blah blah
this is a new line
blah blah blah"

set curTID to AppleScript's text item delimiters
set theText to every paragraph of theText
set AppleScript's text item delimiters to "<br>"
set theText to theText as text
set AppleScript's text item delimiters to curTID

return theText

Upvotes: 2

user3439894
user3439894

Reputation: 7555

The following example AppleScript code shows a way to manipulate the text how you've shown it in your OP:

set theText to "blah blah blah
this is a new line
blah blah blah"

set curTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to {linefeed, return}
set theText to text items of theText
set AppleScript's text item delimiters to "<br>"
set theText to theText as text
set AppleScript's text item delimiters to curTID

return theText

Result:
"blah blah blah<br>this is a new line<br>blah blah blah"

You can incorporate this into a Run AppleScript action in an Automator Service/Quick Action, if that is what you desire.

Upvotes: 1

Related Questions