[comp.sys.next] printf method for Text object

lane@sumex-aim.stanford.edu (Christopher Lane) (07/19/90)

I've an application where I wanted to use 'printf' to a Text object in a
ScrollView that I created with Interface builder.  I wanted to do so from
numerous methods (it was a debugging log) so I didn't want to have to code
'buffered printf' everywhere I needed it.

I came up with the following solution that others may find useful.  In my code
it is a method of my Application and messages an outlet, but I've recast it
here as a method of a specialization of the Text object, for simplicity:

#import <appkit/Text.h>

#define BUFFERSIZE 512

@interface MyText:Text { }

- (int) printf:(const char *) format, ...;

@end

@implementation MyText

- (int) printf:(const char *) format, ...
{
	int result, length = [self textLength];
	char buffer[BUFFERSIZE];
	va_list	ap;

	va_start(ap, format);
	result = vsprintf(buffer, format, ap);
	va_end(ap);

	[[self setSel:length :length] replaceSel:buffer];
	[[self scrollSelToVisible] display];

	return result;
}

@end

Using this, you can do arbitrary printf style output to a Text object:

	[text printf:"The date is %s.\n", ctime(time(0))];

The 'setSel::' and 'textLength' calls can probably be optimized out (just done
on Text initialization) if you're always writing to the end of the Text object
from your other routines that access it.  Comments/suggestions welcome,

- Christopher
-------