XCode: How to join two lines? - xcode

Say I have this:
CGColorSpaceRef space =
CGColorGetColorSpace(col.CGColor);
Is there a hotkey in XCode that lets me join these two lines together into:
CGColorSpaceRef space = CGColorGetColorSpace(col.CGColor);
?

Simplest method I have found: Position your cursor at the end of a line, then CTRL-SHIFT-RIGHT CTRL-SHIFT-LEFT SPACE.
There is no such function like the "J" command in VI.

Old question but I was looking for a way today, and ended up adding:
<key>JoinLines</key>
<dict>
<key>Join Current Line</key>
<string>moveDown:, moveToBeginningOfText:, deleteToBeginningOfLine:, deleteBackward:</string>
</dict>
In file:
/Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/IDETextKeyBindingSet.plist
(to be edited with sudo)
Then restart XCode, go to preferences -> Key Bindings, and assign some shortcut to "Join Current Line". Seems to work!

Xcode 13.2 added CTRL-J [Join paragraphs (Deletions)].

There's at least one extension for Xcode Source Editor that provides "Join Lines" command, available in AppStore: TextPlus. After installing and activating the extension, you can assign any shortcut to the corresponding "Join Lines" menu via Xcode > Preferences > Key Bindings.

Related

Xcode : How to use cmd + x to either cut a line or cut the selected text

Pressing cmd + x without selecting text in other IDEs, cuts the complete line. Same goes for cmd + c which copies, instead of cutting. Otherwise, if some text is selected, only that region is cut.
How do I do this in Xcode?
I added the following in the IDETextKeyBindingSet.plist to add cutting line and copying line functionality:
<key>My Custom Commands</key>
<dict>
<key>Cut Current Line</key>
<string>selectLine:, cut:</string>
<key>Copy Current Line</key>
<string>selectLine:, copy:</string>
</dict>
</dict>
But obviously binding these to cmd + x (or c) doesn't allow cutting/copying selected region. I understand I can set it to some other keybinding. But, as a force of habit, cmd + x (or c) suits better.
Is there any way to do this? Maybe an extension?

Is it possible to sort the Compile Sources list in the Build Phases section of an Xcode project?

I want to sort the files in the 'Compile Sources' section of my Xcode project according to their names. Is it possible?
Yes, you can reorder the Compile Sources section in Xcode, but not from the GUI - which is a shame considering that this is already version 6 of the IDE and they still haven't gotten around to this basic feature.
As A-Live said, you need to edit the project.pbxproj file within the yourproject.xcodeproj file. Use Finder to select the yourproject.xcodeproj file and then use the context menu to Show Package Contents. After that open the project.pbxproj file with a text editor.
Find the PBXSourcesBuildPhase section and copy everything between files = ( and ); into a new text file. Remove the leading tabs/spaces. Save that file somewhere on your disk. Open up a terminal and do this:
sort -bf -t " " -k 3 PBXSourcesBuildPhase.txt > PBXSourcesBuildPhase.sorted.txt
Open up the new PBXSourcesBuildPhase.sorted.txt file in your text editor, copy the sorted lines into the PBXSourcesBuildPhase section of your project.pbxproj (overwrite the lines that you previously copied) and save.
Now you should be able to see all the files sorted in the Compile Sources section in Xcode.
I've tested this in Xcode 6.0.1 with a small project (~150 source files) and had no problems.
Careful: you should make a backup of your project file (or better: use version control) before you try this. Just in case.
I reckon it is a shame that this is not possible.
as a workaround in most of situations, you can use the search filter on the right upper corner of the file list.
for example, I needed to add a compiler flag in many files which (fortunately) all started with the same prefix. to do so, as stated here, you have to double click on a file.
then, I filtered the files for the prefix, shift-clicked them in order to select them all, then released shift and double-clicked one of them. this way I was able to add the flag to all of the files at once
The accepted solution works fine, but it requires manual steps(open the project file, find the section for the target that you want etc.) so it is a little cumbersome and it can not be automated if you need to keep the section sorted each time you perform a build or commit.
I faced with the same problem and I created a ruby script to sort these sections. The script sorts the 'Compile Sources', 'Copy Bundle Resources’ and all the 'Copy files' sections under Build Phase for a specified or all the targets.
#!/usr/bin/env ruby
require 'xcodeproj'
require 'set'
project_file, target_name = ARGV
# open the project
project = Xcodeproj::Project.open(project_file)
# find the target
targets_to_sort = project.native_targets.select { |x| x.name == target_name || target_name.nil? }
phases_to_sort = [Xcodeproj::Project::Object::PBXSourcesBuildPhase, Xcodeproj::Project::Object::PBXCopyFilesBuildPhase, Xcodeproj::Project::Object::PBXResourcesBuildPhase]
targets_to_sort.each do |target|
puts "sorting files for target #{target.name}"
phases_to_sort.each do |phase_to_sort|
target.build_phases.select { |x| x.class == phase_to_sort }.each do |phase|
phase.files.sort! { |l, r| l.display_name <=> r.display_name }
end
end
end
puts 'saving project'
project.save
To sort all targets:
./sort_sources.rb MyProject.xcodeproj
Or to sort only one target:
./sort_sources.rb MyProject.xcodeproj My_Target
It requires the gem xcodeproj:
gem install xcodeproj
This is thoroughly answered, but I thought I'd share the Emacs command that sorted these in place for me. Navigate to project.pbxproj, mark all files under PBXSourcesBuildPhase, and use the command:
M-3 M-x sort-fields
...aka sorting the marked area by the 3rd column, which happens to be the filenames. C-x C-s and you're on your way.
You can reorder the entries of PBXSourcesBuildPhase section at the project.pbxproj, it worked for me but of course there's no guarantee in general for it to work. Don't forget to backup your backups first.

Determine OS X keyboard layout ("input source") in the terminal/a script?

I would like to determine the OS X keyboard layout (or "input source" as OS X calls it) from the terminal so that I can show it in places like the tmux status bar.
So I want to know if the current layout is "U.S." or "Swedish - Pro" for example.
Googling turns up nothing for me. Is this possible?
Note: #MarkSetchell deserves credit for coming up with the fundamental approach - where to [start to] look and what tools to use.
After further investigation and back and forth in the comments I thought I'd summarize the solution (as of OS X 10.9.1):
do shell script "defaults read ~/Library/Preferences/com.apple.HIToolbox.plist \\
AppleSelectedInputSources | \\
egrep -w 'KeyboardLayout Name' | sed -E 's/^.+ = \"?([^\"]+)\"?;$/\\1/'"
Note how \ is escaped as \\ for the benefit of AppleScript, which ensures that just \ reaches the shell. If you want to execute the same command directly from the shell (as one line), it would be:
defaults read ~/Library/Preferences/com.apple.HIToolbox.plist AppleSelectedInputSources | egrep -w 'KeyboardLayout Name' |sed -E 's/^.+ = \"?([^\"]+)\"?;$/\1/'
The currently selected keyboard layout is stored in the user-level file ~/Library/Preferences/com.apple.HIToolbox.plist, top-level key AppleSelectedInputSources, subkey KeyboardLayout Name.
defaults read ensures that the current settings are read (sadly, as of OSX 10.9, the otherwise superior /usr/libexec/PlistBuddy sees only a cached version, which may be out of sync).
Since defaults read cannot return an individual key's value, the value of interest must be extracted via egrep and sed - one caveat there is that defaults read conditionally uses double quotes around key names and string values, depending on whether they are a single word (without punctuation) or not.
Update:
Turns out that AppleScript itself can parse property lists, but it's a bit like pulling teeth.
Also, incredibly, the potentially-not-fully-current-values problem also affects AppleScript's parsing.
Below is an AppleScript handler that gets the current keyboard layout; it uses a do shell script-based workaround to ensure that the plist file is current, but otherwise uses AppleScript's property-list features, via the Property List Suite of application System Events.
Note: Obviously, the above shell-based approach is much shorter in this case, but the code below demonstrates general techniques for working with property lists.
# Example call.
set activeKbdLayout to my getActiveKeyboardLayout() # ->, e.g., "U.S."
on getActiveKeyboardLayout()
# Surprisingly, using POSIX-style paths (even with '~') works with
# the `property list file` type.
set plistPath to "~/Library/Preferences/com.apple.HIToolbox.plist"
# !! First, ensure that the plist cache is flushed and that the
# !! *.plist file contains the current value; simply executing
# !! `default read` against the file - even with a dummy
# !! key - does that.
try
do shell script "defaults read " & plistPath & " dummy"
end try
tell application "System Events"
repeat with pli in property list items of ¬
property list item "AppleSelectedInputSources" of ¬
property list file plistPath
# Look for (first) entry with key "KeyboardLayout Name" and return
# its value.
# Note: Not all entries may have a 'KeyboardLayout Name' key,
# so we must ignore errors.
try
return value of property list item "KeyboardLayout Name" of pli
end try
end repeat
end tell
end getActiveKeyboardLayout
Recently I had written a small console utility (https://github.com/myshov/xkbswitch-macosx) on Objective-C to do this. It's a lot faster than a script based solutions. It can to get the current input layout but also it can to set the given input layout.
To get a current layout:
$xkbswitch -ge
> US
To set a given layout:
$xkbswith -se Russian
I am not sure of this answer, but it may be worth checking out. If you look in file:
/Library/Preferences/com.apple.HIToolbox.plist
there is a variable called
AppleCurrentKeyboardLayoutSourceID
and mine is set to "British" and I am in Britain...
You can read the file in a script with:
defaults read /Library/Preferences/com.apple.HIToolbox.plist AppleEnabledInputSources
sample output below:
(
{
InputSourceKind = "Keyboard Layout";
"KeyboardLayout ID" = 2;
"KeyboardLayout Name" = British;
}
)
So, I guess your question can be simply answered using this:
#!/bin/bash
defaults read /Library/Preferences/com.apple.HIToolbox.plist AppleEnabledInputSources | grep -sq Swedish
[[ $? -eq 0 ]] && echo Swedish
This question led to the creation of the keyboardSwitcher CLI Tool:
https://github.com/Lutzifer/keyboardSwitcher
Though similar to the already mentioned https://github.com/myshov/xkbswitch-macosx this has additional features, e.g. the list of Layouts is not hardcoded and thus can also support third party layouts (e.g. Logitech) and supports installation via homebrew.
Figured out how to do it with AppleScript, assuming you have the menu bar input menu.
Run this in a terminal:
osascript -e 'tell application "System Events" to tell process "SystemUIServer" to get the value of the first menu bar item of menu bar 1 whose description is "text input"'
Works fine even if you only show the input menu as flag icons, without the input source name.
Mavericks will probably prompt you to allow access, the first time. In earlier versions of OS X I suspect you'll need to turn on support for assistive devices in your accessibility preferences.
I was searching for an answer to an issue I was having with the keyboard layout that lead me to this post. I found the solution for my problem here.
Resolved Issues
You might experience difficulty logging into your account because the keyboard layout may change unexpectedly at the
Login window. (40821875)
Workaround: Log in to your account, launch Terminal, and execute the
following command:
sudo rm -rf /var/db/securityagent/Library/Preferences/com.apple.HIToolbox.plist
This is an Apple official release note for Mojave

Editor or way to print plist in a clean way without Xcode

I need to share information from a plist with someone who is not technically inclined. Is there a common free editor that one can use to view plist info in a similar way in which it is presented in Xcode? Or is there a way to print it out?
In other words I would like to view the plist without all the xml-like mark up and without the use of Xcode.
Command-line options for viewing Plist files:
For viewing only: Use plutil -p, which prints the content of a property-list in JSON-like format (the format is meant for human consumption only).
Example (append | open -tf to view output in a text editor):
plutil -p ~/Library/Preferences/com.apple.sidebarlists.plist
Alternative: Use /usr/libexec/PlistBuddy -c print, which outputs in JavaScript-object-literal-like format:
Example:
/usr/libexec/PlistBuddy -c print ~/Library/Preferences/com.apple.airplay.plist
Caveat:
If the plist has properties containing binary data, PlistBuddy will include it in raw form (by contrast, non-binary properties in the same file are printed properly). If XML output is desired, add option -x.
Note that PlistBuddy:
can be used to extract properties selectively using :-separated, case-sensitive property paths; e.g., /usr/libexec/PlistBuddy -c 'print :favorites:ShowRemovable' ~/Library/Preferences/com.apple.sidebarlists.plist
is also capable of modifying Plist files from the command line (including, with limitations, importing from previously exported-to XML files).
See /usr/libexec/PlistBuddy -h for details.
The standalone "Property List Editor" is gone since Xcode 4, you can use Pref Setter which is free but last updated 4 years ago.
To save the contents without the xml tags see this example:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[#"~/Library/Preferences/loginwindow.plist" stringByExpandingTildeInPath]];
[[dict description] writeToURL:[NSURL fileURLWithPath:[#"~/Desktop/loginwindow.txt" stringByExpandingTildeInPath]] atomically:YES encoding:NSUTF8StringEncoding error:nil];
You can use visual studio code to open and edit Plist files.
Just need to install an extension in the visual studio code called Binary Plist:
Binary Plist
Publisher: David Nicolson
Marketplace Link: https://marketplace.visualstudio.com/items?itemName=dnicolson.binary-plist
There is a way to get the old Property List Editor working on Mac OS X Lion, if you don't want to use bloated XCode 4 for this.
There is a "Property List Editor" app as part of OS X (or there used to be, I'm away from my machine at the moment so can't check).
Failing that, you could write one in about half an hour!

vim on mac os X function key mapping not working

I have recently started using a Mac OS X Lion system and tried to use Vim in terminal. I previously had a .vimrc file in my Ubuntu system and had F2 and F5 keys mapped to pastetoggle and run python interpreter. Here are the two lines I have for it:
set pastetoggle=<F2>
map <buffer> <F5> :wa<CR>:!/usr/bin/env python % <CR>
It's working just fine in Ubuntu but no longer works in Mac. (The above two lines are in .vimrc under my home dir.) I have turned off the Mac specific functions in my preference so the function keys are not been used for things like volume. Right now pressing F5 seems to capitalize all letters until next word, and F2 seems to delete next line and insert O.....
Is there something else I need to do to have it working as expected?
In addition, I had been using solarized as my color scheme and tried to have the same color scheme now in Mac. It seems that the scheme command is being read from .vimrc, but the colors are stil the default colors. Even though the .vim/colors files are just the same as before. Is this a related error that I need to fix? Perhaps another setting file being read after my own? (I looked for _vimrc and .gvimrc, none exists.)
Thanks!
I finally got my function mappings working by resorting to adding mappings like this:
if has('mac') && ($TERM == 'xterm-256color' || $TERM == 'screen-256color')
map <Esc>OP <F1>
map <Esc>OQ <F2>
map <Esc>OR <F3>
map <Esc>OS <F4>
map <Esc>[16~ <F5>
map <Esc>[17~ <F6>
map <Esc>[18~ <F7>
map <Esc>[19~ <F8>
map <Esc>[20~ <F9>
map <Esc>[21~ <F10>
map <Esc>[23~ <F11>
map <Esc>[24~ <F12>
endif
Answers to these questions were helpful, if you need to verify that these escape sequences match your terminal's or set your own:
mapping function keys in vim
Binding special keys as vim shortcuts
It probably depends on terminal emulators behaving consistently (guffaw), but #Mark Carey's suggestion wasn't enough for me (I wish it was so simple). With iTerm2 on OS X, I'd already configured it for xterm-256color and tmux for screen-256color, and function mappings still wouldn't work. So the has('mac') might be unnecessary if these sequences from iTerm2 are xterm-compliant, I haven't checked yet so left it in my own config for now.
You might want some imap versions too. Note that you shouldn't use noremap variants since you do want these mappings to cascade (to trigger whatever you've mapped <Fx> to).
Regarding your colorscheme/solarized question - make sure you set up Terminal (or iTerm2, which I prefer) with the solarized profiles available in the full solarized distribution that you can download here: http://ethanschoonover.com/solarized/files/solarized.zip.
Then the only other issue you may run into is making sure you set your $TERM xterm-256color or screen-256color if you use screen or tmux.
You can take a look at my dotfiles for a working setup, but don't forget to setup your Terminal/iTerm color profiles as a first step.
see this answer: https://stackoverflow.com/a/10524999/210923
essentially changing my TERM type to xterm-256color allowed me to map the function keys properly.
I used the following in my vimrc to copy and paste
if &term =~ "xterm.*"
let &t_ti = &t_ti . "\e[?2004h"
let &t_te = "\e[?2004l" . &t_te
function XTermPasteBegin(ret)
set pastetoggle=<Esc>[201~
set paste
return a:ret
endfunction
map <expr> <Esc>[200~ XTermPasteBegin("i")
imap <expr> <Esc>[200~ XTermPasteBegin("")
cmap <Esc>[200~ <nop>
cmap <Esc>[201~ <nop>
endif
I got it from here https://stackoverflow.com/a/7053522

Resources