Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get clang format for Xcode 8?

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?

like image 465
VisorZ Avatar asked Feb 07 '23 01:02

VisorZ


1 Answers

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!

like image 186
VisorZ Avatar answered Mar 09 '23 00:03

VisorZ