How do i get the range of the current paragraph in a NSTextView where the cussor stayed there? - cocoa

Now i need to change the alignment of a paragraph in a nstextview without select it ,so i need to know the range of the current range of the paragraph?

I have a subclass of NSTextView so you need to access textStorage and selectedRange different than [self textStorage] and [self selectedRange].
NSTextStorage *textStorage = [self textStorage];
NSString *string = [textStorage string];
NSUInteger editEnd = [self selectedRange].location;
NSUInteger editStart = editEnd-[textStorage editedRange].length;
NSUInteger maxLength = [string length];
while (editStart > 0) {
unichar theChr = [string characterAtIndex:editStart-1];
if( theChr == '\n' || theChr == '\r' ) {
break;
}
--editStart;
}
while (editEnd < maxLength) {
unichar theChr = [string characterAtIndex:editEnd];
if( theChr == '\n' || theChr == '\r' ) {
break;
}
++editEnd;
}
NSRange paragraphRange = NSMakeRange(editStart, editEnd-editStart);

Here's a shortcut:
NSRange paragraphRange = [textView.textStorage.string paragraphRangeForRange: [textView selectedRange]];

First, get the range where the cursor stayed through [textView selectedRange]
Then you can get the line range through - (NSRange)lineRangeForRange:(NSRange)range of [textView string]
Here is a example code:
NSRange sel = [textView selectedRange];
NSString *viewContent = [textView string];
NSRange lineRange = [viewContent lineRangeForRange:NSMakeRange(sel.location,0)];
detail in there.
How to get the selected line range of NSTextView?

Related

NSTextView indentation

ALL,
Apple documentation here talks about 3 function on setting indentation.
I did use them and I even called:
[attrs setValue: paragraphStyle forKey: NSParagraphStyleAttributeName];
[m_textView setTypingAttributes: attrs];
but unfortunately pressing Enter at the end of the text does not indent the cursor.
Below is a complete code:
paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setFirstLineHeadIndent: indent];
[paragraphStyle setHeadIndent: indent];
[storage addAttribute: NSParagraphStyleAttributeName value: paragraphStyle range: range];
if( range.length == 0 )
{
[attrs setValue: paragraphStyle forKey: NSParagraphStyleAttributeName];
[m_textView setTypingAttributes: attrs];
}
[paragraphStyle release];
It works when I have a selection in the text (range.length > 0), but when I try to set it, go to the end of the text and press Enter, cursor still goes to the column 1 (not indenting).
What am I missing?
I think it is called auto-indenting so I will add that tag as well. Please remove if I'm wrong.
TIA!
[EDIT]
Trying to add:
[m_textView setDefaultParagraphStyle:paragraphStyle];
does not do anything.
When there is no selection and I hit Enter at the end of the text, cursor still jump to the position at the beginning of the line.
[/EDIT]
[EDIT2]
I modified my code as follows:
if( style.HasLeftIndent() )
{
if( start == end && start == 0 )
range = NSMakeRange( 0, 1 );
else if( start == end && start == storage.string.length )
range = NSMakeRange( start - 1, start );
else if( start == end )
range = NSMakeRange( start, start + 1 );
paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setFirstLineHeadIndent: indent];
[paragraphStyle setHeadIndent: indent];
[storage addAttribute: NSParagraphStyleAttributeName value: paragraphStyle range: range];
if( /*start == -1 && end == -1*/range.length == 0 )
{
[attrs setValue: paragraphStyle forKey: NSParagraphStyleAttributeName];
[m_textView setDefaultParagraphStyle:paragraphStyle];
[m_textView setTypingAttributes: attrs];
}
[paragraphStyle release];
}
Now let's say my text contains following:
Big brown fox jumps over the lazy dog.\n
If I have my cursor sitting right after the dot and there is no selection the program crashes. It looks like the range variable is incorrect.
[/EDIT2]
[EDIT3]
My current code is:
if( start == end && start == 0 )
range = NSMakeRange( 0, 1 );
else if( start == end && start == storage.string.length )
range = NSMakeRange( start - 1, 1 );
else if( start == end )
range = NSMakeRange( start, 1 );
paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setFirstLineHeadIndent: indent];
[paragraphStyle setHeadIndent: indent];
[storage addAttribute: NSParagraphStyleAttributeName value: paragraphStyle range: range];
if( /*start == -1 && end == -1*/range.length > 1 )
{
[attrs setValue: paragraphStyle forKey: NSParagraphStyleAttributeName];
[m_textView setDefaultParagraphStyle:paragraphStyle];
[m_textView setTypingAttributes: attrs];
}
[paragraphStyle release];
[/EDIT3]
[EDIT4]
This is my latest code:
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithCapacity:5];
if( style.HasLeftIndent() )
{
if( start == end && start == 0 )
range = NSMakeRange( 0, 1 );
else if( start == end )
range = NSMakeRange( start - 1, 1 );
paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setFirstLineHeadIndent: indent];
[paragraphStyle setHeadIndent: indent];
[storage addAttribute: NSParagraphStyleAttributeName value: paragraphStyle range: range];
{
[attrs setValue: paragraphStyle forKey: NSParagraphStyleAttributeName];
[m_textView setDefaultParagraphStyle:paragraphStyle];
[m_textView setTypingAttributes: attrs];
}
[paragraphStyle release];
}
this code works if my cursor sits at the beginning of the paragraph.
However if I'm in the middle of itor in the end of there is no indentation.
The paragraph being the text after new-line symbol or Enter press.
What am I doing wrong?
[/EDIT4]
[EDIT5]
This is my last code:
if( style.HasLeftIndent() )
{
if( start == end && start == 0 )
range = NSMakeRange( start, start + 1 );
else
range = [[m_textView textStorage].string paragraphRangeForRange: NSMakeRange( end - 1, 1 )];
paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setFirstLineHeadIndent: indent];
[paragraphStyle setHeadIndent: indent];
[storage addAttribute: NSParagraphStyleAttributeName value: paragraphStyle range: range];
if( /*start == -1 && end == -1*/range.length == 0 )
{
[attrs setValue: paragraphStyle forKey: NSParagraphStyleAttributeName];
[m_textView setDefaultParagraphStyle:paragraphStyle];
[m_textView setTypingAttributes: attrs];
}
[paragraphStyle release];
}
It is almost perfect. The only thing missing is following:
Again my text is:
The brown fox jumps over the lazy dog.\n\n
There are 2 empty lines after the text. When my cursor is set on the top new new line this code indent the text on the first line. What I'd like is the text to stay non-indented, but the cursor jumps to the right, so that newly entered text becomes indented.
And the same should happen when my cursor at the second empty line.
[/EDIT5]
What am I missing?

sorting NSArray of NSStrings by match occurrence

How can I sort NSArray by search pattern matching?
So if for example I have a search pattern equal 'xd' and an array of values:
axd
bxd
xdd
gtxd
xdc
how can I get the output like below:
xdc
xdd
axd
bxd
gtxd
Thank you in advance.
Use NSArray's sortedArrayUsingFunction: with a function that orders first by the position of the search term, then by the strings' natural ordering.
NSInteger sorter(id arg1, id arg2, void *context)
{
NSString *searchTerm = (NSString *)context;
NSRange range1 = [arg1 rangeOfString:searchTerm];
NSRange range2 = [arg2 rangeOfString:searchTerm];
if (range1.location < range2.location)
return NSOrderedAscending;
if (range1.location > range2.location)
return NSOrderedDescending;
return [arg1 compare:arg2];
}
NSArray *array = [NSArray arrayWithObjects:#"axd", #"bxd", #"xdd", #"gtxd", #"xdc", nil];
NSArray *sortedArray = [array sortedArrayUsingFunction:sorter context:#"xd"];
This prints:
2011-02-15 01:33:49.642 GreatApp[78849:a0f] (
xdc,
xdd,
axd,
bxd,
gtxd
)
You can use NSArray's sortedArrayUsingFunction:context: method:
NSInteger occurenceSort(NSString* s1, NSString* s2, void *context)
{
NSRange range1 = [s1 rangeOfString:(NSString*)context];
NSRange range2 = [s2 rangeOfString:(NSString*)context];
if (range1.location < range2.location)
return NSOrderedAscending;
else if (range1.location > range2.location)
return NSOrderedDescending;
return NSOrderedSame;
}
...
NSString *stringToSearch = #"xd";
NSArray *sorterArray = [yourArray sortedArrayUsingFunction:occurenceSort context:stringToSearch];

optimize core-data fetchrequest

Dear Community.
I have some issues, where i have to compare digits in core data with decreased range.
here is a first part of code:
NSFetchRequest *requestDestinationWeBuy = [[[NSFetchRequest alloc] init] autorelease];
[requestDestinationWeBuy setEntity:[NSEntityDescription entityForName:#"DestinationsListWeBuy"
inManagedObjectContext:moc]];
NSError *error = nil;
[requestDestinationWeBuy setPredicate:
[NSPredicate predicateWithFormat:
#"carrier.name == %# and (country == %#) and (specific == %#) and (prefix == %#) and (enabled == YES) and ((rateSheet == %#) OR (rateSheet == %#))",
outCarrierName,
countryStr,
specificStr,
outCarrierPrefixStr,
outCarrierRateSheet,
#"Price table"]];
NSArray *destinationWeBuyList = nil;
//[requestDestinationWeBuy includesSubentities];
[requestDestinationWeBuy setResultType:NSManagedObjectIDResultType];
destinationWeBuyList = [moc executeFetchRequest:requestDestinationWeBuy error:&error];
if i didn't match first predicate, i have to cut last digit of code volume (it's a digits and send fetch request again.
int maxCodeDeep = 8;
if ([codeStr length] < maxCodeDeep) maxCodeDeep = [[NSNumber numberWithUnsignedInt:[codeStr length]] intValue] - 1;
NSRange codeStrRange = NSMakeRange(0,[codeStr length]);
NSString *changedCode = [NSString string];
BOOL huntingWasSuccess = NO;
for (NSUInteger codeDeep = 0; codeDeep < maxCodeDeep;codeDeep++)
{
codeStrRange.length = codeStrRange.length - 1;
changedCode = [codeStr substringWithRange:codeStrRange];
NSFetchRequest *compareCode = [[[NSFetchRequest alloc] init] autorelease];
[compareCode setEntity:[NSEntityDescription entityForName:#"CodesvsDestinationsList"
inManagedObjectContext:moc]];
NSString *codeRelationshipName = #"destinationsListWeBuy";
[compareCode setPredicate:[NSPredicate predicateWithFormat:#"(%K.carrier.name == %#) and ((code == %#) OR (originalCode == %#)) and (%K.prefix == %#) and (enabled == YES) and ((rateSheetID == %#) OR (rateSheetID == %#))",codeRelationshipName, outCarrierName,changedCode,changedCode, codeRelationshipName, outCarrierPrefixStr,outCarrierRateSheetID,#"65535"]];
//[compareCode includesSubentities];
//[compareCode includesPropertyValues];
[compareCode setResultType:NSManagedObjectIDResultType];
NSArray *codeAfterComparing = [moc executeFetchRequest:compareCode error:&error];
if ([codeAfterComparing count] == 0) {
NSLog(#"ROUTING: Compare was unsucceseful with parameters:%#",compareCode);
continue;
}
else {
destinationWeBuy = [[moc objectWithID:[codeAfterComparing lastObject]] valueForKey:codeRelationshipName];
NSLog(#"ROUTING: Compare was succeseful with parameters:%#\n and destination object:%#\n Carrier name is %# ",compareCode,destinationWeBuy,carrierName);
//destinationWeBuy = [destinationWeBuyObj objectID];
huntingWasSuccess = YES;
break;
}
}
Unfortunately, this is get a time and processor resources.
Some of latest WWDC recommendations is propose me to using #count, but i don't understand how i can using it in my case.
p.s. important note - i'm using a object, which i find, in next operations and parent object.
Try using subquery to narrow down your search area.Subquery NSExpression

Problem with NSNumber and plotting a graph with Core-Plot

I try to plot a Bar Chart with Core-Plot with an Array (content are NSIntegers) given one view before.
After transfering the Array in an NSInteger, i must convert it into a NSDecimalNumber, and in this process, my NSInteger (for example 45) becomes "60900224"...
Here's the code extract:
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{ NSInteger *values = [Werte objectAtIndex:index];
NSDecimalNumber *num = nil;
if ( [plot isKindOfClass:[CPBarPlot class]] ) {
switch ( fieldEnum ) {
case CPBarPlotFieldBarLocation:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
break;
case CPBarPlotFieldBarLength:
//num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:(index+1)*(index+1)];
num = [NSNumber numberWithInt:values];
if ( [plot.identifier isEqual:#"Bar Plot 2"] )
num = [num decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:#"10"]];
break;
}
}
return num;
}
Thanks for help!!
NSInteger is not an object type and can't be stored in an NSArray (which your Werte appears to be). You seem to be implicitly converting from a pointer to an integer.
Instead, you should always put NSNumber objects into the array, and then get NSInteger values out of those via integerValue:
NSInteger value = [[Werte objectAtIndex:index] integerValue];

Cocoa - Trim all leading whitespace from NSString

(have searched, but not been able to find a simple solution to this one either here, or in Cocoa docs)
Q. How can I trim all leading whitespace only from an NSString? (i.e. leaving any other whitespace intact.)
Unfortunately, for my purposes, NSString's stringByTrimmingCharactersInSet method works on both leading and trailing.
Mac OS X 10.4 compatibility needed, manual GC.
This creates an NSString category to do what you need. With this, you can call NSString *newString = [mystring stringByTrimmingLeadingWhitespace]; to get a copy minus leading whitespace. (Code is untested, may require some minor debugging.)
#interface NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace;
#end
#implementation NSString (trimLeadingWhitespace)
-(NSString*)stringByTrimmingLeadingWhitespace {
NSInteger i = 0;
while ((i < [self length])
&& [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[self characterAtIndex:i]]) {
i++;
}
return [self substringFromIndex:i];
}
#end
This is another solution using Regular Expressions (requires iOS 3.2):
NSRange range = [string rangeOfString:#"^\\s*" options:NSRegularExpressionSearch];
NSString *result = [string stringByReplacingCharactersInRange:range withString:#""];
And if you want to trim the trailing whitespaces only you can use #"\\s*$" instead.
This code is taking blanks.
NSString *trimmedText = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",trimmedText);
Here is a very efficient (uses CoreFoundation) way of doing it (Taken from kissxml):
- (NSString *)trimWhitespace {
NSMutableString *mStr = [self mutableCopy];
CFStringTrimWhitespace((CFMutableStringRef)mStr);
NSString *result = [mStr copy];
[mStr release];
return [result autorelease];
}
NSString *myText = #" foo ";
NSString *trimmedText = [myText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"old = [%#], trimmed = [%#]", myText, trimmedText);
Here's what I would do, and it doesn't involve categories!
NSString* outputString = inputString;
NSRange range = [inputString rangeOfCharacterFromSet: [NSCharacterSet whitespaceCharacterSet]
options:0];
if (range.location == 0)
outputString = [inputString substringFromIndex: range.location + range.length];
This is much less code.
I didn't really have much time to test this, and I'm not sure if 10.4 contains the UTF8String method for NSString, but here's how I'd do it:
NSString+Trimming.h
#import <Foundation/Foundation.h>
#interface NSString (Trimming)
-(NSString *) stringByTrimmingWhitespaceFromFront;
#end
NSString+Trimming.m
#import "NSString+Trimming.h"
#implementation NSString (Trimming)
-(NSString *) stringByTrimmingWhitespaceFromFront
{
const char *cStringValue = [self UTF8String];
int i;
for (i = 0; cStringValue[i] != '\0' && isspace(cStringValue[i]); i++);
return [self substringFromIndex:i];
}
#end
It may not be the most efficient way of doing this but it should work.
str = [str stringByReplacingOccurrencesOfString:#" " withString:#""];

Resources