TweetFollow Us on Twitter

Spaced Out

Volume Number: 18 (2002)
Issue Number: 12
Column Tag: Mac OS X

Spaced Out

Adding Paragraph Spacing to the Cocoa Text System

by Andrew C. Stone

One of my favorite Cocoa demos is to make a full featured word processor application in 5 minutes - complete with rulers, tabs, embedded graphics, line spacing, kerning, ligatures, baseline, colors, multi-font, automatic spell checking and more - (see http://www.stone.com/The_Cocoa_Files/Arise_Aqua_.html). Cocoa's powerful text system is a collection of classes that can meet almost any text need, and I highly recommend reading the documentation for these classes:,NSText and NSTextView (the display classes), NSTextStorage and NSAttributedString (how rich strings store all the attributes of unicode text), NSLayoutManager (manages an NSTextStorage and set of NSTextContainers which display in an NSTextView) and playing with the sample Text layout application available in the Developer distribution in /Developer/Examples/AppKit/TextSizingExample.

These full featured classes are getting more powerful with each major system release. In Mac OS X 10.2, a feature which was previously defined in the API was implemented in NSParagraphStyle:

ParagraphSpacing

- (float)paragraphSpacing

Returns the space added at the end of the paragraph to separate it from the following paragraph. This value is always nonnegative.

See Also: - lineSpacing - setParagraphSpacing: (NSMutableParagraphStyle)

Paragraph spacing is the additional distance between paragraphs (that is, whenever a <RETURN> appears in the text). This amount is in points (72 per inch) and by default is 0. It's added to any additional line spacing that applies to that paragraph style.

But, although the implementation is there, the interface is not. The ruler, which comes for free with NXTextView, and which contains controls for alignment, line spacing, and tabs, currently lacks any control for setting the paragraph spacing. This article will show you how to add a custom control to the standard text system ruler.


Figure 1: The standard text ruler in Mac OS X 10.2 doesn't have a paragraph spacing control.

Just using simple subclasses of NSTextView and NSLayoutManager, our page layout and web authoring application Create(R) can flow text through any size containers, place rich text along any path, apply neon and custom pattern effects to any text, and place text outside or inside of any path. Once Jaguar shipped, we could easily add paragraph spacing to our text - if we could figure out a way to add a new control to the ruler that automatically attaches itself to any NSTextView in an NSScrollView.

Like everything with Cocoa - if it's hard it's wrong. So finding an easy solution with modular application is the always the goal of any Cocoa programming challenge.

Our design imperatives include:

  • make it simple

  • make it small so it doesn't get in the way

  • make it a modular nib file

The solution has 3 parts - a user interface built in InterfaceBuilder, the create/update code in an NSLayoutManager subclass, and code in an NSTextView subclass which actually sets the spacing and maintains the undo stack.

So, I chose to make the narrowest UI possible - using the P symbol for paragraph and an NSStepper:


Figure 2: Create(R) adds a paragraph spacer next to the line spacing tools - P

The first problem is how do we get at the ruler to install the new device? It's owned by NSLayoutManager, which provides a method that returns this ruler view - so that seems like the most appropriate place to instantiate and update our own user interface addition which can set the paragraph spacing:

- (NSView *)rulerAccessoryViewForTextView:(NSTextView *)aTextView 
paragraphStyle:(NSParagraphStyle *)paraStyle ruler:(NSRulerView *)aRulerView enabled:(BOOL)flag

Returns the accessory NSView for aRulerView. This accessory contains tab wells, text alignment buttons, and so on. paraStyle is used to set the state of the controls in the accessory NSView; it must not be nil. If flag is YES the accessory view is enabled and accepts mouse and keyboard events; if NO it's disabled.

This method is invoked automatically by the NSTextView object using the layout manager. You should rarely need to invoke it, but you can override it to customize ruler support.

Let's Just Face it

We'll use InterfaceBuilder to create the interface and even the stub files for our new class, ParagraphSpacer:

    1. Launch Interface Builder

    2. File -> New..., Cocoa, "Empty", Click "New"

    3. Save this as "ParagraphSpacer.nib" in your project directory - also add it to your project when asked.

    4. Double-click the "File's Owner" icon in the folio window - NSObject will be selected in the Classes tab

    5. Control-Click NSObject and select "Create Subclass" - name it "ParagraphSpacer"

    6. Add two outlets: stepper and containerView by Control-Clicking ParagraphSpacer and choose "Add Outlet to ParagraphSpacer".

    7. Control-click ParagraphSpacer and choose "Create Files for Paragraph Spacer" - add these to your project

    8. Choose "Instances" tab, select "File's Owner", Info-> Custom Class, select "ParagraphSpacer"

    9. From the Tab icon on the Palette, drag a "Custom View" into the folio window

    10. Set the view's size with , Info -> Size, 26 wide by 28 tall

    11. Drag in "System Font Text", select all, delete, type P, Info -> Size 10 wide by 17 tall, locate on left

    12. Drag in an NSStepper from Slider Icon tab on Palette, adjust location as needed

    13. Connect the File's owner to the two instance variables - the stepper, and the view which holds the stepper and the static P text.

    14. Save ParagraphSpacer.nib

ParagraphSpacer

A very simple class which just returns its two instance variables.We need these to install the view into the Ruler view hierarchy and set the value of the stepper during updates:

/* ParagraphSpacer */
#import <Cocoa/Cocoa.h>
@interface ParagraphSpacer : NSObject
{
    IBOutlet id containerView;
    IBOutlet NSStepper *stepper;
}
- (NSStepper *)stepper;
- (NSView *)containerView;
@end
#import "ParagraphSpacer.h"
@implementation ParagraphSpacer
- (id) init {
    self = [super init];
    if (![NSBundle loadNibNamed:@"ParagraphSpacer.nib" owner:self])
   NSLog(@"couldn't load ParagraphSpacer\n");
        
        
    return self;
}
- (NSStepper *)stepper; {
    return stepper;
}
- (NSView *)containerView; {
    return containerView;
}
@end

SDLayoutManager

We just need to add one method to our NSLayoutManager subclass. Note that we call [super rulerAccessoryViewForTextView: ... ] to get the standard ruler provided for us, then we check to see if we have already initialized the paragraph spacer, and if not, proceed to create it, find it's proper position in the ruler and install it. We'll travel down the view hierarchy, looking at the subviews of each view. When we find a view with several subviews, then we know we're in the right place. When we find the view that starts far to the left, ie, not the tab well, but the NSBox which surrounds the alignment and line spacing controls, we'll place our control right next to it. We just have to hope that the ruler doesn't change drastically - if it does, it will probably have more controls in it, and our layout may be wrong.

Each time this method gets called, we'll set the target of the stepper to be the current text view with an action of changeParagraphSpacing:, and update the value of the stepper so that it sends the target the right value when incrementing or decrementing.

@interface SDLayoutManager : NSLayoutManager
{
  @private
    NSStepper *_paragraphStepper;
}
@implementation SDLayoutManager
- (NSView *)rulerAccessoryViewForTextView:(NSTextView *)view paragraphStyle:(NSParagraphStyle *)style 
ruler:(NSRulerView *)ruler enabled:(BOOL)isEnabled {

    NSView *accessory = [super rulerAccessoryViewForTextView:view paragraphStyle:style ruler:ruler 
    enabled:isEnabled];
    
    if (!_paragraphStepper) {
        ParagraphSpacer *spacer = [[ParagraphSpacer allocWithZone:[self zone]] init];
        NSView *viewToAdd = [spacer containerView];
        NSArray *subviews = [accessory subviews];
        NSView *viewToAddTo = accessory;
        unsigned int i, count = [subviews count];
        NSRect viewRect = [viewToAdd bounds];
        
        if (count == 1) {
            viewToAddTo = [subviews objectAtIndex:0];
            subviews = [[subviews objectAtIndex:0] subviews];
            count = [subviews count];
        }
        
        _paragraphStepper = [spacer stepper];
        
        for (i = 0; i < count; i++) {
            NSView *v = [subviews objectAtIndex:i];
            NSRect r = [v frame];
            if (r.origin.x < 10.0) {   // it's the box containing the left controls)
                viewRect.origin.x = r.origin.x + r.size.width;
                viewRect.origin.y = 0.0;
                [viewToAdd setFrame:viewRect];
                [viewToAddTo addSubview:viewToAdd];
            }
        }
    }
    [_paragraphStepper setDoubleValue:style? [style paragraphSpacing] : 0.0];
    [_paragraphStepper setTarget:view];
    [_paragraphStepper setAction:@selector(changeParagraphSpacing:)];
    
    return accessory;
}
@end

SDTextView

If you don't want to subclass NSTextView, you could instead add the changeParagraphSpacing: method to a category of NSTextView. This is not the case with the NSLayoutManager subclass, because we need to call super's implementation of rulerAccessoryViewForTextView:paragraphStyle:ruler:enabled:.

The main reason we place this code in NSTextView or a subclass is so we get the free automatic undo associated with Text. To do that, we alert the text system that there will be changes in a certain range with shouldChangeTextInRange: replacementString: with a replacement string of "nil" , which means other attributes are changing, but not any characters. Then, we walk over text paragraph style by paragraph style, setting the paragraph spacing to the value determined by the stepper (up or down a point from the first style in the selection). Note that if there are no paragraph attributes, one is added.

Finally, we alert the text that we are done changing it with didChangeText, and we add a custom action name so the menu will say "Undo Paragraph Spacing" and "Redo Paragraph Spacing".

@interface SDTextView: NSTextView
{}
@end
@implementation SDTextView
- (void)changeParagraphSpacing:(id)sender {
    double value = [sender doubleValue];
    NSRange range = [self rangeForUserParagraphAttributeChange];
    if (range.length > 0) {
        NSRange remainingRange = range;
        NSTextStorage *storage = [self textStorage];
        [self shouldChangeTextInRange:range replacementString:nil];
        while (remainingRange.length > 0) {
                NSRange effectiveRange;
                NSParagraphStyle *para = [storage attribute:NSParagraphStyleAttributeName 
                atIndex:remainingRange.location longestEffectiveRange:&effectiveRange 
                inRange:remainingRange];
        
                if (para == nil) {
                    para = [[[NSMutableParagraphStyle alloc] init] autorelease];
                    [para setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
                } else para = [[para mutableCopyWithZone:[self zone]]autorelease];
                
                [para setParagraphSpacing:value];
                [storage addAttribute:NSParagraphStyleAttributeName value:para range:remainingRange];
    
                if (NSMaxRange(effectiveRange) < NSMaxRange(remainingRange)) {
                    remainingRange.length = NSMaxRange(remainingRange) - NSMaxRange(effectiveRange);
                    remainingRange.location = NSMaxRange(effectiveRange);
                } else {
                    break;
                }
        }
            [self didChangeText];
            [[self undoManager] setActionName:NSLocalizedStringFromTable(@"Paragraph Spacing",
            @"Muktinath",@"change of space between paragraphs")];
    
    }
}
@end

All Together Now

Your final task is just to be sure you create your text system with the special SDLayoutManager. If you have a shared text editor, it might look something like this:

static NSTextView *newEditor(TextArea *self) {
    SDTextView *tv;
    NSTextContainer *tc;
    // This method returns an NSTextView whose SDLayoutManager has a refcount of 1.  It is 
    the caller's responsibility to release the SDLayoutManager.  This function is only for the use of
    the following method.
    
    SDLayoutManager *lm = [[SDLayoutManager allocWithZone:NULL] init];
    tv = [[SDTextView allocWithZone:NULL] initWithFrame:NSMakeRect(0.0, 0.0, 100.0, 100.0) 
    textContainer:nil];
    
    tc = [[NSTextContainer allocWithZone:NULL] initWithContainerSize:NSMakeSize(1.0e6, 1.0e6)];
    [lm addTextContainer:tc];
    [tc release];
     
    [tc setTextView:tv];
    [tv release];
    return tv;
}


Figure 3: The new text ruler with paragraph spacing stepper installed.

Conclusion

The Cocoa text system just keeps getting better. And sometimes there are features that are still hidden from the user interface, such as paragraph spacing in Jaguar 10.2. With a little Cocoa magic, it's easy to install your own custom controls and add more functionality to the standard text object.


Andrew Stone, CEO of Stone Design, www.stone.com, has been the principal architect of several solar houses and over a dozen Cocoa applications shipping for Mac OS X.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.