How to get clang format for Xcode 8? - xcode

After Xcode update to version 8. The very useful Alcatraz PlugIn Manager is locked out and superb utilities like clang-format, or highlight selected word occurrences, or resize the font by use of a shortcut are gone.
How can I reenable clang-format to format my current source code file on save with a template .clang-format in any parent directory of the source file?

You could create a shell script that is added to Xcode 8 as a behavior: Xcode > Behaviors > +(to create new one) > Run script: (select file here), add shortcut like Cmd+Shift+S.
The script asks Xcode to save the current document. Then it extracts its filepath and calls clang-format to format that file in-place. Clang-format has to be available e.g. by using brew as the package manager to download it and having its path published for command line access. As usual the style guide used by clang-format must have the name .clang-format and must be in any parent folder of the source file.
Here is the script:
#!/bin/bash
CDP=$(osascript -e '
tell application "Xcode"
activate
tell application "System Events" to keystroke "s" using {command down}
--wait for Xcode to remove edited flag from filename
delay 0.3
set last_word_in_main_window to (word -1 of (get name of window 1))
set current_document to document 1 whose name ends with last_word_in_main_window
set current_document_path to path of current_document
--CDP is assigned last set value: current_document_path
end tell ')
LOGPATH=$(dirname "$0")
LOGNAME=formatWithClangLog.txt
echo "Filepath: ${CDP}" > ${LOGPATH}/${LOGNAME}
sleep 0.6 ### during save Xcode stops listening for file changes
/usr/local/bin/clang-format -style=file -i -sort-includes ${CDP} >> ${LOGPATH}/${LOGNAME} 2>&1
# EOF
Please exchange the path /usr/local/bin to the one where your clang-format executable resides.
Happy coding!

The mapbox/XcodeClangFormat extension looks like a promising way to get clang format working with Xcode8.
Due to the limitations of source editor extensions, unfortunately you can only specify one .clang-format file for all your projects. "Format on save" also is not available.

Found a viable solution in this blog - code-beautifier-in-xcode
Basically, we can have clang-format running as a service by automator and invoke it through Xcode whenever we need to format the code. Refer the blog for more details.

Unfortunately your little script often does not update the formatted file in Xcode because it stops listening to file updates when saving. Increasing the sleep durations in the script does not make it more reliable and introduces a lot of waiting time for the common file-save & file-format action.
What I did in your situation was to get my mac backup and restore macOS and Xcode to the last version where all the productivity plugins from Alcatraz work fine again. This boosted my productivity.

It looks like Alcatraz plug-ins get be back to work in Xcode 8+ when unsigning them. Because I am not in the situation to try that, I can only point you to that resource:
Examine the header Installation on that github page ClangFormat-Xcode.

Related

How do I make NeoVim my default text/code editor?

Is there a way to make NeoVim as default text/code editor (without any bad side effects) ?Trust me, I looked to lots of StackOverflow question/answers and tried a few things but nothing worked for me.
Note: I'm on macOS Big Sur (version 11.2.1). What I want is when I click on files to open in NeoVim.
--> For example, in ~/.zshrc (and added to ~/.bash_profile also just in case) I have:
Note: zsh is my default shell
alias nvim=$HOME/nvim-osx64/bin/nvim
export EDITOR="nvim"
export VISUAL="nvim"
When I do set in Terminal it shows:
EDITOR=nvim
VISUAL=nvim
And yes, I quit and started the terminal (I'm using iTerm2). I even reboot.
--> I will place my $PATH here just in case it has anything to do it that. When I do echo $PATH it shows:
--> And, just in case someone suggests:
I can't Select a File > Open With... and select NeoVim as default text editor, since that option doesn't show and I can't do Choose Other since I can't select NeoVim in that way.
If anyone needs more information, please say and I will edit the question with that info. Thanks!
Setting variables in the terminal will not affect the GUI file associations. To do that you have to change the OS's file associations.
Though it appears to be a small project and unsupported, I've had a good experience using duti. It's a wrapper around the Apple file extension API. The configuration did take me a minute to figure out. I'll post it if I can find it.
After a while I found the answer to my own question, here it is how you can set NeoVim in Mac as the default text editor. Now, you will be able click on files and opening them in NeoVim:
Some people recommended me to have a look at the follow links:
https://gist.github.com/Huluk/5117702
https://superuser.com/questions/139352/mac-os-x-how-to-open-vim-in-terminal-when-double-click-on-a-file
That didn't work for me but it served as a reference to look up related topics (automator + neovim).
After a while, I discover this blog:
https://blog.schembri.me/post/neovim-everywhere-on-macos/
Go and have a look at the blog, but here it is how you do it:
Launch Automator (Finder -> Applications -> Automator)
New Document -> Choose a type for your document: Application
In Actions search for Run AppleScript and drag that to where it says something like "Drag actions here..."
Delete the default example of AppleScript
Copy and Paste the code in the blog (where it says NeoVim.app) to where it previous had the default code
Save the new Automator app (save as aplicattion format). Save it in the Applications folder
Right-Click a file type you wish to open every time you click on them (e.g. .php file). Select Get Info or do cmd + i, it will open informations about that file. Scroll to wher it says Open With and select Other. Then just go to Aplicattions folder and select your new NeoVim "app".
Do the same to other file types if you wish.
You can now double click on your PHP files (or others if you did the same) and open them in NeoVim. Enjoy!
Note: You really need to do Right-Click, Get Info and look for Open With to change in all files with that extension. If you skip Get Info and just Right-Click + Open With, it will only work for that specific file...
This is the code from the blog:
on run {input, parameters}
set cmd to "nvim"
if input is not {} then
set filePath to POSIX path of input
set cmd to "nvim \"" & filePath & "\""
end if
tell application "iTerm"
create window with default profile
tell the current window
tell the current session to write text cmd
end tell
end tell
end run
This would open a new window even if you already had one open.
I change it so that it would open in a tab:
on run {input, parameters}
set cmd to "nvim"
if input is not {} then
set filePath to POSIX path of input
set cmd to "nvim \"" & filePath & "\""
end if
tell application "iTerm"
tell the current window
create tab with default profile
tell the current session to write text cmd
end tell
end tell
end run
Note: I'm using iTerm2. If you are using another Terminal Emulator, change where it says iTerm to the name of your terminal...
For anyone using Kitty on MacOS, I found a pretty simple way to accomplish this using the remote control feature.
First you need the following set in your kitty.conf:
allow_remote_control yes
listen_on unix:/tmp/mykitty
Using Automator like in #DGF's answer, I created an Application with the "Run Shell Script" action, and this is the script:
if [ -z "$(pgrep kitty)" ]
then
open /Applications/kitty.app
sleep 3 # allow ample time to startup and start listening
fi
/usr/local/bin/kitty # --to=unix:/tmp/mykitty-$(pgrep kitty) launch --type=os-window nvim "$#"
Save that as an application somewhere, and select it from "Open with"!
Note: to be honest, the logic to handle starting up kitty if it's not already running is a little flaky. But it seems to work great when kitty is already running, which of course it is most of the time for me. Also, it doesn't work at all if kitty is running but has no windows. :\
Choose nvim as the default application by means of a txt file sub-menu like here with Preview for PDFs:

Set Extended Attributes with AppleScript Objc

So I am looking for a way to set Mac specific extended attributes (specifically kMDItemWhereFroms) for a file (Image File, Jpg) using AppleScript or AppleScript-Objc.
There is a command line tool that will do this xattr -w kMDItemWhereFroms . The problem is that on the several machines that I have access to (10.12, 10.13, and 10.14) when you run this command as a do shell script from within an AppleScript it does not work, the metadata is not added to the file. If I set Script Debugger to debug mode, and go through the script step by step it will actually set the metadata, but since that is not the way I am running the script, it is more of an interesting fluke than anything else. I have tried running the command with both "com.apple.metadata:" included and not included with the shell script and that makes no difference.
I have tried running my script through SD, Script Editor and osascript, and they all fail to update the metadata. So I am thinking that this tool might be broken when called from an AppleScript.
I found setxattr but that looks like it only applies to C.
So my questions are
1. Is there a way to set the extended attributes of a file on MacOS using Aobjc? if not then
2. Is there a way to get setxattr to work with either version of AppleScript? Probably not so
3. Any ideas how I might be able to get the command line tool xattr -w kMDItemWhereFroms to work when using scripting?
This is more of an annoyance for me, I am just being stubborn with wanting the source of the file to show up in the "Where From" data in the Get Info window from the Finder. I already am setting some metadata for the file using exiftool. So it is more of an interesting problem for me, than a critical problem that I must try and solve now. Thanks!

Open an ipython notebook via double-click on osx

I've downloaded a couple of ipython notebooks, and I'd like to open them in browser tabs without navigating to the directory I've downloaded them to and running ipython notebook notebook_name.ipynb.
I realize this probably means I'm lazy, but it seems like a common use case to me. Am I missing something obvious?
Use Pineapple application for opening and working on your IPython/Jupyter notebooks. It is pretty cool.
Update:
Now there is nteract, which is a new jupyter-like Desktop app. After installing it, make it the default app for opening .ipynb files. Then just double-click any notebook to start it right away.
I have found a nice way using Automator (Oct. 2017; with information from here):
open Automator and create a new Application
to add Run Shell Script drag and drop it from the list; might need these settings Shell: /bin/bash and Pass input: as arguments
insert the code below; if necessary adjust the path to jupyter
Code
#!/bin/sh
variable="'$1'"
the_script='tell application "terminal" to do script "/usr/local/bin/jupyter notebook '
osascript -e "${the_script}${variable}\""
save the script as an application (!)
try to open a .ipynb file and change the default app to this newly created one.
notes
This will open a terminal and run the jupyter notebook command, such that you can interrupt and stop the notebook-server from there.
Also note that you cannot test the app like that in Automator, but need to add the Get Specified Finder Items and insert some test notebook there (just for testing purposes).
As pointed out in the comments, there are two more notes:
To avoid spamming your browser history with notebooks, you can start your notebooks in incognito/private mode: Run jupyter notebook in incognito window
If you want to run notebooks in one server and don't mind an extra tool, Sachit Nagpal has pointed out (thank you), that one could also use nbopen. To use this workflow just replace "/usr/local/bin/jupyter notebook ' with "nbopen '. Any other tool should work alike.
pip install nbopen.
open Automator, create new Application
Drag'n drop Run Shell Script
Change Pass input to as arguments
Copy/paste this script:
variable="'$1'"
the_script='tell application "terminal" to do script "nbopen '
osascript -e "${the_script}${variable}\""
Save the new application to Applications directory as nb_open
Right click any ipynb file and select "Open with > Other" and select the nb_open in the Applications folder. Don't forget to check "Always Open With".
Select an ipynb file, get info (command + i) > Open With (select nb_open if not selected already) > Click Change All.... Done.
The application posted here worked pretty well for me: http://bioequity.org/2013/11/16/ipynbviewer/
You also need to download iTerm2, as described on that page.
Note that this doesn't work if there are spaces in the filename, but you can modify it so that it works with spaces in the filename. Control-click on the iPyNbViewer.app and select "Show package contents". Edit the file Contents/Resources/Scripts/main.scpt. Change three instances of "POSIX path" to "quoted form of POSIX path". Now it will work with spaces in the filename.
To set all of your .ipynb files to open with the app, you'll need to Get Info (command-I) on one of the files and select the iPyNbViewer app to open all .ipynb files.
It would be great if this was the default behavior of double-clicking on an iPython notebook file...
I came up with a way of doing it on Ubuntu. (It works for me but I can take no responsibility). It's explained here. In a nutshell, you need to create a new MIME type, then write a script that works as the app that launches them:
#!/bin/bash
netstat -tln |grep "8902"
# if not found - equals to 1, start it
if [ $? -eq 1 ]
then
ipython notebook / --no-browser --port=8902 &
sleep .5
fi
xdg-open http://localhost:8902/notebooks$1
This always opens the notebook server on port 8902, but first checks whether there is already a server running, and, if so, uses it.
Then you can use ubuntu tweak to select your script as a default application for the MIME type "IPython Notebook" you just created.
Not very elegant, but worth it, in my opinion.
PyCharm now supports Jupyter ipynb files:
which is from the documentation https://www.jetbrains.com/help/pycharm/editing-jupyter-notebook-files.html.
But I think this feature is only available in the Professional version now; hopefully it will be added to the Community version in the future.
Look at this link.
Put a bash script in the folder where you keep your ipython notebooks and simply double click it to open up a notebook instance. From the link above, the bash script has just:
path=$0 # path is path to this file
cd ${path%/*.*} # clip off the file name to get directory path and cd
ipython notebook --pylab inline
Finally, you need to chmod u+x the script to make it executable and you're done.
I have used the command line application 'nbopen' and put it in a Platypus wrapper to get drag'n drop and double click opening on Macos. 'nbopen' is downloadable using 'pip'
It works well when used as described above by DanHickstein.
Only problem with my code is that it requires the full path to the nbopen command. I know I should be able to use 'which nbopen' somehow but can't get it to work.
Heres my Platypus code:
#!/bin/bash
# Opens ipynb files in a Jupyter Notebook
# echo $1
# $1 is the path of the dropped file
/Users/robw/anaconda/bin/nbopen $1
# Based on an idea from
# https://www.quora.com/Is-there-a-straightforward-way-to-open-an-IPython-Notebook-in-Windows-by-double-clicking

How to startup a Mac OS X application from command line?

"open -a" is not the answer wanted, because I want to debug the Mac OS X application automatically. This means it's better if someone can give the command line like [program] [args] format. So ltrace mechanism can make [program] as target for debugging and take [args] as input.
I have tried command line like "/Applications/Microsoft Office 2011/Microsoft PowerPoint.app/Contents/MacOS/Microsoft PowerPoint" /Users/poc.pptx, only Microsoft Point process started but the poc.pptx not opened.
After grepping the Microsoft Point with pptx file opened, it's something like: /Applications/Microsoft Office 2011/Microsoft PowerPoint.app/Contents/MacOS/Microsoft PowerPoint -psn_0_307275, there is no argument "poc.pptx".
I even manually use "gdb /Applications/Microsoft Office 2011/Microsoft PowerPoint.app/Contents/MacOS/Microsoft PowerPoint" and "set args /Users/poc.pptx", and then "r", the target application can not run with the certain file opened.
I am confused about this, so, is there someone can help me to solve this problem?
Thank you!
open -b com.microsoft.PowerPoint <filename> seems to work for me to open presentations from the command line.
Go to file directory and then type
open -a "Microsoft PowerPoint" <filename.ppt>
Here "Microsoft PowerPoint" is the name of power point application, please check name of power point if it is different in your application directory.
This is working perfectly fine on my MAC (OSX 10.8).
We can also give complete path instead of just file name.
open -a "Microsoft PowerPoint" <ppt file path>
This is also working fine.
I know this is a old question, but here is my 2ct anyway.
I add the applications I want to open through command line in /usr/local/bin as a symlink.
I never run into any problems, but as Ken stated it depends how a application handles arguments.
Example with Visual Studio:
First I check what makes the application start bij executing the file inside the App contents like:
$ /Applications/Visual\ Studio\ Code.app/Contents/MacOS/Electron
If that works, then I create the symlink as follows (ln -s <path-to-app> <path-to-symlink>):
$ ln -s /Applications/Visual\ Studio\ Code.app/Contents/MacOS/Electron /usr/local/bin/vs
After that I can start up Visual Studio with the current folder loaded as:
~/Development/SomeProject $ vs .
If PowerPoint is not opening a document passed as a command-line argument, then that's a reflection on how PowerPoint was coded. There's nothing anybody but Microsoft can do about that.
The OS does not normally use that technique to tell applications to open documents. Instead, it passes Apple Events to the application. Cocoa will, by default, accept command-line arguments and treat them similarly to such Apple Events, but apparently PowerPoint is overriding that default behavior.
If you want to debug or trace PowerPoint, I recommend that you do it in two steps. First, launch it without arguments under the debugger or trace program. Then, tell it to open a document. You can do that in the normal way, using the Finder and/or Dock, or you can use open -a .... Such a request to open a document will not launch a second instance of PowerPoint, it will deliver an event to the already-running PowerPoint which you are debugging/tracing. So, the result should be similar to what you seem to want.
Not sure if this will help you (depends on how you want to do your debugging), but you can use AppleScript from the command line, like this:
%osascript <<<EOD
tell application "Excel" to open "Users:xxx:Documents:sheet.xls"
EOD
When entered this way, your script can contain several lines, it does not have to be limited to a single one.

Perforce Checkout Macro for XCode4 [duplicate]

This question already has answers here:
xcode4 doesn't support Perforce?
(4 answers)
Closed 2 years ago.
I'd like to setup a macro in XCode 4 to checkout the current file from Perforce. How can I do this? I do not have perforce integrated with my project and do not wish to do so. This is pretty easy in Visual Studio but I don't know the XCode equivalent.
Just came across this at Perforce.com as their means of making this work. I tried it, and it's pretty good.
http://answers.perforce.com/articles/KB/2997
As per the comment, it works in Xcode 5 as well.
And now it's tested and working in Xcode 6!
EDIT:
If that doesn't work, and you're using OS X Mavericks, this guy fixed the script to keep working. Just make sure the script references p4 properly. I had to change it from /usr/local/bin/p4 to /usr/bin/p4.
http://forums.perforce.com/index.php?/topic/2830-xcode-501-x-mavericks-perforce-integration-not-working/#entry11319
Make sure that the 'p4' command line tool is installed in '/usr/local/bin/'.
Verify that your Perforce environment variables are configured correctly. I use a 'perforce.rc' file at the root of every client workspacewith the name of the client (P4CLIENT)and port (P4PORT). Don't forget about P4USER, P4PASSWD, P4CONFIG, etc...
Create the following script in your ~/bin folder and make sure the permissions are set so it is executable (755 should work).
Go to the Preferences in Xcode and select "behaviors".
Scroll down to "Unlock file"
Scroll down some more and select the checkbox next to "Run"
Choose "Choose Script..." and point it to the following script:
xcodeunlock.sh
#!/bin/bash
# Xcode4 doesn't setup the environment
source ~/.bashrc
# Delete the URL part from the file passed in
fn=${BASH_ARGV#file://localhost}
echo "fn=" $fn
if [ -a ${fn} ]; then
res=$(/usr/local/bin/p4 edit ${fn})
# TODO: Report the status back to the user in Xcode
# This output goes to the console.
echo $res
else
echo "FnF" ${fn}
fi
Once this is set up correctly, unlocking a file in Xcode should run this script and attempt to checkout the file. Unfortunately any output goes to '/var/log/system.log'. I'm not sure how to notify Xcode 4 of a failure in this script.
It's maddening trying to get XCode to work with Perforce. Here is a solution I came up with that is:
Quick to get set up
Easy to burn into your muscle-memory so you don't have to think to check files out
Doesn't require any mousing at all
One-time setup as follows:
Download and install the free "DTerm" app from Decimus Software.
Make sure you have the Perforce command-line utility installed. Type "p4" at a Terminal window prompt, and see if it recognizes this command. If not, you need to go to Perforce's website and find and download what they currently call "The Perforce Command-Line Client (P4)". There's no installer; just save it from your browser right into /usr/bin (or whatever) and do a chmod +x on it. For official setup notes, and if you need to do any custom environmental variable tricks, please see this tech note.
Once you've done this, let's say you are in XCode and you are viewing a source code file that you want to check out. Here's the rigamarole:
Have the file showing in the active XCode editor
Hit Shift Command Enter to get a DTerm window
Type p4 edit and then hit Shift Command V to paste in the filename of the active file, and hit return
Perforce checks the file out and DTerm shows you the status/errors.
Hit 'escape' to dismiss the DTerm window
Begin making your changes to the file in XCode. XCode may (erroneously) say that the file is read-only, because it's dumb and isn't aware that it's been made from read-only to read-write, so you have to hit Allow Editing. I didn't trust this at first and double-checked it a few times, but now I have blind faith that it's doing the right thing.
I haven't set this up in a while, so please let me know if you run into any glitches and I'll update my info here to make it as painless as possible. But otherwise, this is the best solution I've found.

Resources