Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Keep your current source file open in Xcode after a run completes (a.k.a don't die in main.m)
#! /bin/sh
# On alternate invocations, this script
# saves the path of the source file currently open in Xcode
# and restores the file at that path in Xcode.
# By setting Xcode (in Behaviors) to run this script when "Run Starts"
# and when "Run Completes", you can prevent it from switching to main.m
# when a run finishes.
# See
# for a description of the problem and a bunch of solutions which don't work.
# We use the defaults system to save the source path.
# Change the domain to whatever you like.
# The first time this script is invoked, this call will return a "does not exist" error.
# The second time this script it invoked, this call will return the saved source path.
# We copy stderr to stdout so that we can read both results using a single call.
savedSourcePath=`defaults read $DOMAIN $KEY 2>&1`
if [[ "$savedSourcePath" == *"does not exist"* ]]; then
# read path of current source file out of Xcode
sourcePath="`osascript << EOT
tell application "Xcode"
set windowName to (name of first window)
set currentFileName to item 2 of (words of windowName)
set currentSourceDocument to first item of (source documents whose name ends with currentFileName)
set currentSourceFile to (file of currentSourceDocument)
set currentSourcePath to (POSIX path of currentSourceFile)
end tell
return currentSourcePath
# save current source path
defaults write $DOMAIN $KEY "$sourcePath"
# open saved source path in Xcode
open "$savedSourcePath"
# clear saved source path
defaults delete $DOMAIN $KEY

This comment has been minimized.

Copy link

@ddaddy ddaddy commented Feb 10, 2012

xcode 4.2 wont let me select this as a script to run. Any ideas why?


This comment has been minimized.

Copy link
Owner Author

@skeeet skeeet commented Feb 10, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment