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

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.