File: WrapString.m

package info (click to toggle)
psychtoolbox-3 3.0.9%2Bsvn2579.dfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 63,408 kB
  • sloc: ansic: 73,310; cpp: 11,139; objc: 3,129; sh: 1,669; python: 382; php: 272; makefile: 172; java: 113
file content (66 lines) | stat: -rw-r--r-- 2,154 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function wrappedString=WrapString(string,maxLineLength)
% wrappedString=WrapString(string,[maxLineLength])
% 
% Wraps text by changing spaces into linebreaks '\n', making each line as
% long as possible without exceeding maxLineLength (default 74
% characters). WrapString does not break words, even if you have a word
% that exceeds maxLineLength. The returned "wrappedString" is identical to
% the supplied "string" except for the conversion of some spaces into
% linebreaks. Besides making the text look pretty, wrapping the text will
% make the printout narrow enough that it can be sent by email and
% received as sent, not made hard to read by mindless breaking of every
% line.
% 
% Note that this schemes is based on counting characters, not pixels, so
% it will give a fairly even right margin only for monospaced fonts, not
% proportionally spaced fonts. The more general solution would be based on
% counting pixels, not characters, using either Screen 'TextWidth' or
% TextBounds.

% 6/30/02 dgp Wrote it.
% 10/2/02 dgp Make it clear that maxLineLength is in characters, not pixels.
% 09/20/09 mk Improve argument handling as per suggestion of Peter April.

if nargin>2 || nargout>1 %#ok<OR2>
	error('Usage: wrappedString=WrapString(string,[maxLineLength])\n');
end

if nargin<2
    maxLineLength=[];
end

if isempty(maxLineLength) | isnan(maxLineLength) %#ok<OR2>
	maxLineLength=74;
end

eol=sprintf('\n');
wrapped='';
while length(string)>maxLineLength
	l=min([findstr(eol,char(string)) length(string)+1]);
	if l<maxLineLength
		% line is already short enough
		[wrapped,string]=onewrap(wrapped,string,l);
	else
		s=findstr(' ',char(string));
		n=find(s<maxLineLength);
		if ~isempty(n)
			% ignore spaces before the furthest one before maxLineLength
			s=s(max(n):end);
		end
		% break at nearest space, linebreak, or end.
		s=sort([s l]);
		[wrapped,string]=onewrap(wrapped,string,s(1));
	end
end
wrappedString=[wrapped string];
return

function [wrapped,string]=onewrap(wrapped,string,n)
if n>length(string)
	wrapped=[wrapped string];
	string=[];
	return
end
wrapped=[wrapped string(1:n-1) sprintf('\n')];
string=string(n+1:end);
return