Use highlighted file in Finder as Bash variable (Applescript, macOS 10.13) - bash

I want to set up an applet for archiving my files in non-standard formats (e.g. non .zip/.cpgz/.tar) with only the use of Applescript and the command line versions of each format's respective tool. The last thing I need to figure out is how to get the path of the currently highlighted file in Finder via Applescript, so that I can pipe it to bash.
I've searched around a bit and can't seem to find an answer to this via search engine, or this forum. I have found and still find that Apple's documentation has about a 40/60 chance of being too sparse and/or outdated, or even simply nonexistent for any given subject, so I opt not to use it when possible. Please don't just link to an Apple documentation page, Real-world examples are always appreciated.
The target platform is macOS 10.13.2, Automator 2.8, Applescript 2.7.

There is more then one way to do it and also depends on how may Finder items are selected. Here's an example if only one item is selected in Finder:
set theTarget to POSIX path of (application "Finder"'s selection as string)
Or, if the pathname has spaces, use:
set theTarget to quoted form of POSIX path of (application "Finder"'s selection as string)
Sans the shown examples, the other ways can depend on how/where it falls in the rest of your code and whether or not more then one item is selected in Finder, however this is a place to start.
BTW If you're doing this AppleScript from bash, not Script Editor where the other examples were run, then using osascript in bash to run the same example AppleScript code shown above, with a single item selected in Finder, it would be:
theTarget="$(osascript -e "POSIX path of (application \"Finder\"'s selection as string)")"
Or:
theTarget="$(osascript -e "quoted form of POSIX path of (application \"Finder\"'s selection as string)")"

Related

Customize word boundaries of Option-Delete (and other word related shortcuts) in macOS?

Is it possible to change the behavior of ⌥⌫ (option+delete) to include certain characters, like a period, as a word boundary?
For example, in some.variable, I would like ⌥⌫ to delete up to the period but it currently deletes the entire string. The screencast below shows the behavior using ⌥⇧←.
Screencast GIF
I've looked high and low for a solution to this issue since the Cocoa-era, as far as I can tell there isn't a way to customize the "Option-Delete" word-delimiter (word-boundary) list. In addition to my own experiments, I'm basing this conclusion largely on the enormous number of MacOS keybinding modifications that can be found at the following 3 URLs (from oldest to most recently updated):
Customizing the Cocoa Text System (circa 2006)
DefaultKeybinding.dict (circa 2016, some info previously at the URL "lri.me")
Keybindings -- BrettTerpstra.com (last updated 2018)
AFAIK, word-boundaries on MacOS default to whitespace and can't be changed. [This conclusion is invalid if there have been recent radical changes to MacOS text-input system].
It's no secret that many of the MacOS keyboard shortcuts are based upon eMacs-style 'keyboard-chording', as opposed to Vim-style 'modal-editing'. Indeed much of the Keybinding work cited above deals with remapping these chords. Vim of course is well-known for having a customizable delimiter list, it's the basis for differential word-movements between (for example) w, W and b and B (see vimhelp.org).
There have been a few extensions that have tried to bring 'Vim-style' editing to the MacOS, one of which is Karabiner. Karabiner (now re-written/updated to Karabiner-Elements) used to have a mode called "Ubiquitous_Vim". However without an OS-level 'hook' personal tests indicate that (for example) moving backwards via b and B works identically (i.e. there's no difference between a Vim word and a Vim WORD, see this StackOverflow post).
While I'm unable to find a way to modify the MacOS default 'word-boundary' list, if Vim-style editing does appeal to you, then you might try installing a project such as Vim-Anywhere, which enables you to 1. use a MacOS keyboard shortcut to open a Vim window whenever you need to enter text, and 2. will automatically copy your text to the MacOS System Clipboard when you close the Vim window. See this OSTechNix article: "How To Use Vim Editor To Input Text Anywhere" for more information.

Autogenerating terminal window screenshots from text/commands for documentation?

Ok, I hope that stackoverflow is the right place to ask this: I've searched high and wide and haven't come up with a good solution so far.
I'm writing a bunch of documentation for command-line and programming newbies, including nice screenshots of what they might see as they interact with a terminal window. I am thinking of doing this in something like restructuredtext so that I can keep it version controlled and multiformat (for later conversion to html, latex/pdf, etc). Is there any way that I can keep the commands/code/text/etc in a document for revision control, and yet still produce nice user-friendly screenshots in an automated way for inclusion in the final doc? Just as an example, perhaps in in my markup I had something like this (I'm not very familiar with restructuredtext directives yet, but they seem pretty powerful):
.. terminal:: ls_example.png
pre:
/Users/soneil/Documents/test% ls
post:
/Users/soneil/Documents/test% ls
testfile todo.txt
/Users/soneil/Documents/test%
and get two screenshots of terminal windows with the appropriate text in them. The trickier part would be ansi characters for things like editors:
.. terminal:: nano_example.png
pre:
/Users/soneil/Documents/test% ls
testfile todo.txt
/Users/soneil/Documents/test% nano todo.txt
post:
(Either the contents of test.txt right here [with or without editor decoration as well,
which could be faked if needed],
or let a script actually run the command and capture the output somehow)
Resulting in something like:
Pre: http://d.pr/i/a1JS
Post: http://d.pr/i/Edu4
(Sorry for the links, I guess I don't have enough reputation for images yet, nor do I have enough reputation to post more than two links).
I'm working on OSX now, but I'm not tied to the Terminal app (or even OSX, really). If I could specify the cols/rows of the windows as well that would be nice. Creative solutions involving programming, imagemagick, ttyrec, etc. welcome; I've even considered applescript interaction with Terminal.app but with minimal success. I am hoping to get something out the other end with ansi colors (e.g. views of top, htop) and preferably window chrome, so a raster format like png seems logical so far.
Whew! Thanks for your time-
Your idea of automatically generating screenshots is great, but if you actually do them as image files, it won’t be so great because people won’t be able to copy-and-paste from them.
What I’d suggest instead is to using AppleScript with the copy-as-formatted text feature in the Mavericks terminal to make rich-text copies of the terminal display, and convert that to HTML for including in your documents.
Here’s a ruby script:
#!/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby
command = '/bin/ls -G /'
clipboard = `osascript -e '
tell application "Terminal"
set newTab to do script
delay 0.1
do script "#{command}" in newTab
delay 0.1
activate newTab
-- ⌘-A select all
tell application "System Events" to keystroke "a" using command down
-- ⌘-C copy
tell application "System Events" to keystroke "c" using command down
delay 0.1
do script "exit" in newTab
end tell
get the clipboard as «class RTF »
'`
# this returns "«data RTF 7B5C…27D»"; need to strip out the hex data
hex_data = /[A-F0-9]{2,}/.match(clipboard).to_s
data = [hex_data].pack('H*')
converter = IO.popen('textutil -cat html -stdin -stdout', 'w+')
converter.puts data
converter.close_write
puts converter.gets(sep='')
It sends command to the terminal, copies the terminal contents, grabs the terminal contents from the clipboard, and converts it to HTML.
If you plop the output of that straight into a browser
you get a copy of your terminal, with fonts and colours preserved, all copy-and-pastable:
The output HTML can be a bit messy, but since it’s already data inside Ruby you can write code to clean it up. And if you still want the terminal frame around the terminal output, you can do that with CSS.
Hope this helps!

ctrl-r history search equivalent for R64/R GUI OS X Application [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Retrieving Variable Declaration
I would like some way to search through the history of commands sent to R for a running session. This can be done in Bash using ctrl-r history search, and I find it extremely useful.
Is there a shortcut key in the R GUI IDE that does this? I've looked through changelogs and done some google searching, and I can't find it.
If not, is there a way outside of the R GUI IDE to extract this information? Possibly by searching through some sort of .Rhistory file maybe?
How are other R users accessing command history?
In the R GUI there is is a discoverable side panel that appears to whichever side of the screen has the most space and it has the history entries displayed in a clickable manner. That panel is kbd-toggled with shift-cmd-H, and if opened that way will place the active cursor in an entry line. That line at the top of that panel accepts regex expressions that will limit the displayed lines to those that match. It's a bit confusing (to me anyway) that there are separate history files. The side panel like the R.app or R64.app uses a file named ".Rapp.history", while the regular history file that a Terminal R session would access has its expected name.
The icon that does the show/hide toggling is exposed to the toolbar item selection panel of the console, so I suspect it is exposed to AppleScript commands. I'm not a big user of AppleScript and that last part is a hunch more than a promise.
The MacOSX FAQ says R will accept Applescript delivered R commands.
What is available as a shortcut depends on what interface you are using. If you use the r terminal on windows (but not the GUI) then ctrl-r works like you describe.
One tool (though not as easy) that should work for all interfaces is to use the 'history' command. Y can type something like history(pat='plot') and the recent commands that included "plot" in them will be displayed and you can cut and paste to rerun the command of interest.

MacOSX Give alias/symlink label color but not original file

Hoi Stackoverflow,
i have a short question. Is it possible to set the label of an alias/symlink to a certain color without effecting other symlinks and the original file?
Lets say if have one main folder and different subgroups. Each subgroups contains symlinks to the files in the main folder.
I want know to color these symlinks according to some variables which is easily done with
osascript -e "tell application \"Finder\" to set label index of alias POSIX file \"$1\" to \"$2\""
Unfortunately this changes the label index of the main file as well as and the ones from all other symlinks to that particular file.
Thanks a lot in advance :-)

Manipulating text in XCode, moving one line

In emacs I have various functions to manipulate text. Now that I'm using xcode, I suppose I could make emacs my default editor, but I want to browse obj-c objects and such, so I'd rather just implement my most used text manipulation commands for xcode.
First on my list, I'd like a command that moves the text of the current line up/down one line, keeping the cursor on the current line.
In emacs this is:
(defun move-one-line-downward ()
"Move current line downward once."
(interactive)
(forward-line)
(transpose-lines 1)
(forward-line -1))
I'd be happiest if I could write a script in Python that would do the equivalent in XCode, but as far as I can tell, I need to talk to AppleScript to do this.
Can someone walk me through how to do this with XCode?
Xcode 4 has a new set of command for moving the line where the cursor is or the selected text with command + option + [ or ]
⌥⌘[ or ⌥⌘]
http://developer.apple.com/library/mac/#documentation/IDEs/Conceptual/xcode_help-command_shortcuts/MenuCommands/MenuCommands014.html
What you’re wanting to do can be achieved through Xcode’s “User Scripts”—and it helpfully comes with a pair of scripts that almost do what you want. (I’m using Xcode 3.2 here, but I think these were also there in 3.1)
Look in /Developer/Library/Xcode/User Scripts/; there are two applescripts there, Move Line Up.scpt and Move Line Down.scpt. Here’s what’s in Move Line Up:
(*
To edit this script, choose Save As... and save it in your home directory, then re-add it to the User Scripts list.
*)
using terms from application "Xcode"
tell first text document
set {startLine, endLine} to selected paragraph range
if startLine > 1 then
set theText to (paragraphs startLine through endLine)
set theText to (theText as string)
delete (paragraphs startLine through endLine)
make new paragraph at beginning of paragraph (startLine - 1) with data theText
set selected paragraph range to {startLine - 1, endLine - 1}
else
beep 1
end if
end tell
end using terms from
These almost do what you want, except they select the whole line afterwards; I’m no applescript expert, but you probably want to store the selected character range. Have a look at the Xcode scripting dictionary (in AppleScript Editor, File -> Open Dictionary -> Xcode) to find out the types of objects you can manipulate.
You can add your own scripts to Xcode with the “Edit User Scripts”menu item in the script menu; and assign shortcut keys to the scripts in that window also, by double-clicking in the right-hand column beside the entry for the script menu item.
You can also use shell scripts (perl, python, bash, whatever) in the User Scripts menu, but these process only the selection or the whole file, so might be a bit heavyweight for moving a single line up or down.
See all the docuemntation on User Scripts here: http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/XcodeWorkspace/310-User_Scrips/user_scripts.html
I hope this helps!
I think your question is more generic that Xcode/emacs. Most IDE can't do stuff that editors can do and vice versa.
What I do is to use Xcode for 'simple' stuff and compile/debug. When I want to do lot's of coding (hm ... text editing) I open multiple files in one Vim (no offense to emacs ... vim is my editor of choice) and use all the vim tricks available.
I follow the same process when I need to do lots of coding on Windows (Visual Studio). I have VS opened just for compiling/debugging but I do most coding in separate Vim window.
I don't need to do any of that on Unix because I just open file in Vim and run Makefile from within Vim, jumping directly to errors and so on (:mak) ...
I'm sure that there are some extremely clever things to get Xcode do stuff that are already in Vim and Vim to do stuff that Xcode can do but I'm focusing on coding so not much time to play around.
Also, you can hook up emacs (or vi, or bbedit, or ed, I imagine) to xcode, so that they will talk to each other. When you tell xcode to open a file it will call emacsclient, etc. You can even get emacs to tell xcode where to put a breakpoint (I don't remember how, but I asked a question here a while back, and it works great)

Resources