Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Line number support #21

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Chromatism/Chromatism.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
8FFEB27E183AD6740032C9FB /* JLObjectiveCTokenizer.m in Sources */ = {isa = PBXBuildFile; fileRef = 8FFEB27C183AD6740032C9FB /* JLObjectiveCTokenizer.m */; };
8FFEB283183AD8B70032C9FB /* JLTokenizer+Additions.h in Headers */ = {isa = PBXBuildFile; fileRef = 8FFEB281183AD8B70032C9FB /* JLTokenizer+Additions.h */; settings = {ATTRIBUTES = (Public, ); }; };
8FFEB284183AD8B70032C9FB /* JLTokenizer+Additions.m in Sources */ = {isa = PBXBuildFile; fileRef = 8FFEB282183AD8B70032C9FB /* JLTokenizer+Additions.m */; };
9E5EC9B719A735F900E12723 /* CYRLayoutManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E5EC9B519A735F900E12723 /* CYRLayoutManager.h */; };
9E5EC9B819A735F900E12723 /* CYRLayoutManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 9E5EC9B619A735F900E12723 /* CYRLayoutManager.m */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -91,6 +93,8 @@
8FFEB27C183AD6740032C9FB /* JLObjectiveCTokenizer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JLObjectiveCTokenizer.m; sourceTree = "<group>"; };
8FFEB281183AD8B70032C9FB /* JLTokenizer+Additions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JLTokenizer+Additions.h"; sourceTree = "<group>"; };
8FFEB282183AD8B70032C9FB /* JLTokenizer+Additions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JLTokenizer+Additions.m"; sourceTree = "<group>"; };
9E5EC9B519A735F900E12723 /* CYRLayoutManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CYRLayoutManager.h; sourceTree = "<group>"; };
9E5EC9B619A735F900E12723 /* CYRLayoutManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CYRLayoutManager.m; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -159,6 +163,7 @@
8F3AB9501781C1250023348A /* JLScope.m */,
8F3AB9571781C1250023348A /* JLTokenPattern.h */,
8F3AB9581781C1250023348A /* JLTokenPattern.m */,
9E5EC9B919A7360700E12723 /* CYRLayoutManager */,
8F3AB91E1781C0BA0023348A /* Supporting Files */,
);
path = Chromatism;
Expand Down Expand Up @@ -223,6 +228,15 @@
name = General;
sourceTree = "<group>";
};
9E5EC9B919A7360700E12723 /* CYRLayoutManager */ = {
isa = PBXGroup;
children = (
9E5EC9B519A735F900E12723 /* CYRLayoutManager.h */,
9E5EC9B619A735F900E12723 /* CYRLayoutManager.m */,
);
name = CYRLayoutManager;
sourceTree = "<group>";
};
/* End PBXGroup section */

/* Begin PBXHeadersBuildPhase section */
Expand All @@ -235,6 +249,7 @@
8FA0CB0F1795F41B00FF8EB1 /* JLTextView.h in Headers */,
8F54EF0E1781C776008C1609 /* Chromatism.h in Headers */,
8F54EF101781C788008C1609 /* Helpers.h in Headers */,
9E5EC9B719A735F900E12723 /* CYRLayoutManager.h in Headers */,
8FE2796517C3842900DD933A /* UIColor+Chromatism.h in Headers */,
8F54EF111781C788008C1609 /* JLScope.h in Headers */,
8FFEB27D183AD6740032C9FB /* JLObjectiveCTokenizer.h in Headers */,
Expand Down Expand Up @@ -328,6 +343,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
9E5EC9B819A735F900E12723 /* CYRLayoutManager.m in Sources */,
8F54EF241781CD87008C1609 /* JLTokenPattern.m in Sources */,
8FFEB27E183AD6740032C9FB /* JLObjectiveCTokenizer.m in Sources */,
8F9F6BC91822F09D00DE15A8 /* JLDiffTokenizer.m in Sources */,
Expand Down
49 changes: 49 additions & 0 deletions Chromatism/Chromatism/CYRLayoutManager.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//
// CYRLayoutManager.h
//
// Version 0.4.0
//
// Created by Illya Busigin on 01/05/2014.
// Copyright (c) 2014 Cyrillian, Inc.
//
// Distributed under MIT license.
// Get the latest version from here:
//
// https://github.com/illyabusigin/CYRTextView
// Original implementation taken from: https://github.com/alldritt/TextKit_LineNumbers
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Cyrillian, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import <UIKit/UIKit.h>

@interface CYRLayoutManager : NSLayoutManager

@property (nonatomic, strong) UIFont *lineNumberFont;
@property (nonatomic, strong) UIColor *lineNumberColor;
@property (nonatomic, strong) UIColor *selectedLineNumberColor;

@property (nonatomic, readonly) CGFloat gutterWidth;
@property (nonatomic, assign) NSRange selectedRange;

- (CGRect)paragraphRectForRange:(NSRange)range;

@end
227 changes: 227 additions & 0 deletions Chromatism/Chromatism/CYRLayoutManager.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
//
// CYRLayoutManager.h
//
// Version 0.4.0
//
// Created by Illya Busigin on 01/05/2014.
// Copyright (c) 2014 Cyrillian, Inc.
//
// Distributed under MIT license.
// Get the latest version from here:
//
// https://github.com/illyabusigin/CYRTextView
// Original implementation taken from: https://github.com/alldritt/TextKit_LineNumbers
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Cyrillian, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import "CYRLayoutManager.h"

static CGFloat kMinimumGutterWidth = 30.f;

@interface CYRLayoutManager ()

@property (nonatomic, assign) CGFloat gutterWidth;
@property (nonatomic, assign) UIEdgeInsets lineAreaInset;

@property (nonatomic) NSUInteger lastParaLocation;
@property (nonatomic) NSUInteger lastParaNumber;

@end

@implementation CYRLayoutManager

#pragma mark - Initialization & Setup

- (instancetype)init
{
self = [super init];

if (self)
{
[self _commonSetup];
}

return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];

if (self)
{
[self _commonSetup];
}

return self;
}

- (void)_commonSetup
{
self.gutterWidth = kMinimumGutterWidth;
self.selectedRange = NSMakeRange(0, 0);

self.lineAreaInset = UIEdgeInsetsMake(0, 10, 0, 4);
self.lineNumberColor = [UIColor grayColor];
self.lineNumberFont = [UIFont systemFontOfSize:10.0f];
self.selectedLineNumberColor = [UIColor colorWithWhite:0.9 alpha:1];
}


#pragma mark - Convenience

- (CGRect)paragraphRectForRange:(NSRange)range
{
range = [self.textStorage.string paragraphRangeForRange:range];
range = [self glyphRangeForCharacterRange:range actualCharacterRange:NULL];

CGRect startRect = [self lineFragmentRectForGlyphAtIndex:range.location effectiveRange:NULL];
CGRect endRect = [self lineFragmentRectForGlyphAtIndex:range.location + range.length - 1 effectiveRange:NULL];

CGRect paragraphRectForRange = CGRectUnion(startRect, endRect);
paragraphRectForRange = CGRectOffset(paragraphRectForRange, _gutterWidth, 8);

return paragraphRectForRange;
}

- (NSUInteger) _paraNumberForRange:(NSRange) charRange
{
// NSString does not provide a means of efficiently determining the paragraph number of a range of text. This code
// attempts to optimize what would normally be a series linear searches by keeping track of the last paragraph number
// found and uses that as the starting point for next paragraph number search. This works (mostly) because we
// are generally asked for continguous increasing sequences of paragraph numbers. Also, this code is called in the
// course of drawing a pagefull of text, and so even when moving back, the number of paragraphs to search for is
// relativly low, even in really long bodies of text.
//
// This all falls down when the user edits the text, and can potentially invalidate the cached paragraph number which
// causes a (potentially lengthy) search from the beginning of the string.

if (charRange.location == self.lastParaLocation)
return self.lastParaNumber;
else if (charRange.location < self.lastParaLocation)
{
// We need to look backwards from the last known paragraph for the new paragraph range. This generally happens
// when the text in the UITextView scrolls downward, revaling paragraphs before/above the ones previously drawn.

NSString* s = self.textStorage.string;
__block NSUInteger paraNumber = self.lastParaNumber;

[s enumerateSubstringsInRange:NSMakeRange(charRange.location, self.lastParaLocation - charRange.location)
options:NSStringEnumerationByParagraphs |
NSStringEnumerationSubstringNotRequired |
NSStringEnumerationReverse
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
if (enclosingRange.location <= charRange.location) {
*stop = YES;
}
--paraNumber;
}];

self.lastParaLocation = charRange.location;
self.lastParaNumber = paraNumber;

return paraNumber;
}
else
{
// We need to look forward from the last known paragraph for the new paragraph range. This generally happens
// when the text in the UITextView scrolls upwards, revealing paragraphs that follow the ones previously drawn.

NSString* s = self.textStorage.string;
__block NSUInteger paraNumber = self.lastParaNumber;

[s enumerateSubstringsInRange:NSMakeRange(self.lastParaLocation, charRange.location - self.lastParaLocation)
options:NSStringEnumerationByParagraphs | NSStringEnumerationSubstringNotRequired
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
if (enclosingRange.location >= charRange.location) {
*stop = YES;
}
++paraNumber;
}];

self.lastParaLocation = charRange.location;
self.lastParaNumber = paraNumber;

return paraNumber;
}
}


#pragma mark - Layouting

- (void)processEditingForTextStorage:(NSTextStorage *)textStorage edited:(NSTextStorageEditActions)editMask range:(NSRange)newCharRange changeInLength:(NSInteger)delta invalidatedRange:(NSRange)invalidatedCharRange
{
[super processEditingForTextStorage:textStorage edited:editMask range:newCharRange changeInLength:delta invalidatedRange:invalidatedCharRange];

if (invalidatedCharRange.location < self.lastParaLocation)
{
// When the backing store is edited ahead the cached paragraph location, invalidate the cache and force a complete
// recalculation. We cannot be much smarter than this because we don't know how many paragraphs have been deleted
// since the text has already been removed from the backing store.
self.lastParaLocation = 0;
self.lastParaNumber = 0;
}
}


#pragma mark - Drawing

- (void) drawBackgroundForGlyphRange:(NSRange)glyphsToShow atPoint:(CGPoint)origin
{
[super drawBackgroundForGlyphRange:glyphsToShow atPoint:origin];

// Draw line numbers. Note that the background for line number gutter is drawn by the LineNumberTextView class.

NSDictionary* atts = @{NSFontAttributeName : _lineNumberFont ,
NSForegroundColorAttributeName : _lineNumberColor};

[self enumerateLineFragmentsForGlyphRange:glyphsToShow
usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer *textContainer, NSRange glyphRange, BOOL *stop) {
NSRange charRange = [self characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
NSRange paraRange = [self.textStorage.string paragraphRangeForRange:charRange];

BOOL showCursorRect = NSLocationInRange(_selectedRange.location, paraRange);

if (showCursorRect)
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect cursorRect = CGRectMake(0, usedRect.origin.y + 8, _gutterWidth, usedRect.size.height);

CGContextSetFillColorWithColor(context, _selectedLineNumberColor.CGColor);
CGContextFillRect(context, cursorRect);
}

// Only draw line numbers for the paragraph's first line fragment. Subsequent fragments are wrapped portions of the paragraph and don't get the line number.
if (charRange.location == paraRange.location) {
CGRect gutterRect = CGRectOffset(CGRectMake(0, rect.origin.y, _gutterWidth, rect.size.height), origin.x, origin.y);
NSUInteger paraNumber = [self _paraNumberForRange:charRange];
NSString* ln = [NSString stringWithFormat:@"%ld", (unsigned long) paraNumber + 1];
CGSize size = [ln sizeWithAttributes:atts];

[ln drawInRect:CGRectOffset(gutterRect, CGRectGetWidth(gutterRect) - _lineAreaInset.right - size.width - _gutterWidth, (CGRectGetHeight(gutterRect) - size.height) / 2.0)
withAttributes:atts];
}

}];
}

@end
2 changes: 2 additions & 0 deletions Chromatism/Chromatism/Chromatism+Internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ FOUNDATION_EXPORT NSString *const JLTokenTypeProjectClassNames;
FOUNDATION_EXPORT NSString *const JLTokenTypeProjectMethodNames;
FOUNDATION_EXPORT NSString *const JLTokenTypeDiffAddition;
FOUNDATION_EXPORT NSString *const JLTokenTypeDiffDeletion;
FOUNDATION_EXPORT NSString *const JLGutterBackgroundColor;
FOUNDATION_EXPORT NSString *const JLGutterLineColor;

/// Used as attribute in NSAttributedStrings. You may subclass NSLayoutManager to use this attribute.
FOUNDATION_EXPORT NSString *const JLDiffColorAttributeName;
Expand Down
12 changes: 10 additions & 2 deletions Chromatism/Chromatism/Chromatism.m
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
NSString *const JLTokenTypeProjectMethodNames = @"project_method_names";
NSString *const JLTokenTypeProjectClassNames = @"project_class_names";

NSString *const JLGutterBackgroundColor = @"gutterBackgroundColor";
NSString *const JLGutterLineColor = @"gutterLineColor";

NSString *const JLTokenTypeDiffAddition = @"diff_addition";
NSString *const JLTokenTypeDiffDeletion = @"diff_deletion";
Expand Down Expand Up @@ -76,7 +78,10 @@ + (NSDictionary *)colorsForTheme:(JLTokenizerTheme)theme
JLTokenTypeProjectMethodNames : [UIColor colorWithRed:38.0/255 green:71.0/255 blue:75.0/255 alpha:1],

JLTokenTypeDiffAddition : [UIColor greenColor],
JLTokenTypeDiffDeletion : [UIColor redColor]
JLTokenTypeDiffDeletion : [UIColor redColor],

JLGutterBackgroundColor : [UIColor colorWithWhite:0.95 alpha:1],
JLGutterLineColor : [UIColor lightGrayColor]

};
break;
Expand All @@ -99,7 +104,10 @@ + (NSDictionary *)colorsForTheme:(JLTokenizerTheme)theme
JLTokenTypeProjectClassNames : [UIColor colorWithRed:131.0/255 green:192.0/255 blue:87.0/255 alpha:1],

JLTokenTypeDiffAddition : [UIColor greenColor],
JLTokenTypeDiffDeletion : [UIColor redColor]
JLTokenTypeDiffDeletion : [UIColor redColor],

JLGutterBackgroundColor : [UIColor colorWithRed:19.0/255.0 green:16.0/255.0 blue:26.0/255.0 alpha:1],
JLGutterLineColor : [UIColor lightGrayColor]

};
break;
Expand Down
4 changes: 4 additions & 0 deletions Chromatism/Chromatism/JLTextView.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,8 @@

@property (nonatomic, strong) JLTokenizer *syntaxTokenizer;
@property (nonatomic, assign) JLTokenizerTheme theme;

@property (nonatomic, assign) BOOL drawLineNumbers;
@property (nonatomic, assign) BOOL drawLineCursor;

@end
Loading