OptionParser 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1451 @@
1
+ # :title: Text::Format
2
+ #--
3
+ # Text::Format for Ruby
4
+ # Version 0.63
5
+ #
6
+ # Copyright (c) 2002 - 2003 Austin Ziegler
7
+ #
8
+ # $Id: format.rb,v 1.3 2003/09/18 02:47:39 austin Exp $
9
+ #
10
+ # This file is placed here by Jim Freeze on a temporary basis
11
+ # until Ara releases it as a gem 'text/format'.
12
+ #
13
+ # ==========================================================================
14
+ # Revision History ::
15
+ # YYYY.MM.DD Change ID Developer
16
+ # Description
17
+ # --------------------------------------------------------------------------
18
+ # 2002.10.18 Austin Ziegler
19
+ # Fixed a minor problem with tabs not being counted. Changed
20
+ # abbreviations from Hash to Array to better suit Ruby's
21
+ # capabilities. Fixed problems with the way that Array arguments
22
+ # are handled in calls to the major object types, excepting in
23
+ # Text::Format#expand and Text::Format#unexpand (these will
24
+ # probably need to be fixed).
25
+ # 2002.10.30 Austin Ziegler
26
+ # Fixed the ordering of the <=> for binary tests. Fixed
27
+ # Text::Format#expand and Text::Format#unexpand to handle array
28
+ # arguments better.
29
+ # 2003.01.24 Austin Ziegler
30
+ # Fixed a problem with Text::Format::RIGHT_FILL handling where a
31
+ # single word is larger than #columns. Removed Comparable
32
+ # capabilities (<=> doesn't make sense; == does). Added Symbol
33
+ # equivalents for the Hash initialization. Hash initialization has
34
+ # been modified so that values are set as follows (Symbols are
35
+ # highest priority; strings are middle; defaults are lowest):
36
+ # @columns = arg[:columns] || arg['columns'] || @columns
37
+ # Added #hard_margins, #split_rules, #hyphenator, and #split_words.
38
+ # 2003.02.07 Austin Ziegler
39
+ # Fixed the installer for proper case-sensitive handling.
40
+ # 2003.03.28 Austin Ziegler
41
+ # Added the ability for a hyphenator to receive the formatter
42
+ # object. Fixed a bug for strings matching /\A\s*\Z/ failing
43
+ # entirely. Fixed a test case failing under 1.6.8.
44
+ # 2003.04.04 Austin Ziegler
45
+ # Handle the case of hyphenators returning nil for first/rest.
46
+ # 2003.09.17 Austin Ziegler
47
+ # Fixed a problem where #paragraphs(" ") was raising
48
+ # NoMethodError.
49
+ #
50
+ # ==========================================================================
51
+ #++
52
+
53
+ module Text #:nodoc:
54
+ # = Introduction
55
+ #
56
+ # Text::Format provides the ability to nicely format fixed-width text with
57
+ # knowledge of the writeable space (number of columns), margins, and
58
+ # indentation settings.
59
+ #
60
+ # Copyright:: Copyright (c) 2002 - 2003 by Austin Ziegler
61
+ # Version:: 0.63
62
+ # Based On:: Perl
63
+ # Text::Format[http://search.cpan.org/author/GABOR/Text-Format0.52/lib/Text/Format.pm],
64
+ # Copyright (c) 1998 G�bor Egressy
65
+ # Licence:: Ruby's, Perl Artistic, or GPL version 2 (or later)
66
+ #
67
+ class Format
68
+ VERSION = '0.63'
69
+
70
+ # Local abbreviations. More can be added with Text::Format.abbreviations
71
+ ABBREV = [ 'Mr', 'Mrs', 'Ms', 'Jr', 'Sr' ]
72
+
73
+ # Formatting values
74
+ LEFT_ALIGN = 0
75
+ RIGHT_ALIGN = 1
76
+ RIGHT_FILL = 2
77
+ JUSTIFY = 3
78
+
79
+ # Word split modes (only applies when #hard_margins is true).
80
+ SPLIT_FIXED = 1
81
+ SPLIT_CONTINUATION = 2
82
+ SPLIT_HYPHENATION = 4
83
+ SPLIT_CONTINUATION_FIXED = SPLIT_CONTINUATION | SPLIT_FIXED
84
+ SPLIT_HYPHENATION_FIXED = SPLIT_HYPHENATION | SPLIT_FIXED
85
+ SPLIT_HYPHENATION_CONTINUATION = SPLIT_HYPHENATION | SPLIT_CONTINUATION
86
+ SPLIT_ALL = SPLIT_HYPHENATION | SPLIT_CONTINUATION | SPLIT_FIXED
87
+
88
+ # Words forcibly split by Text::Format will be stored as split words.
89
+ # This class represents a word forcibly split.
90
+ class SplitWord
91
+ # The word that was split.
92
+ attr_reader :word
93
+ # The first part of the word that was split.
94
+ attr_reader :first
95
+ # The remainder of the word that was split.
96
+ attr_reader :rest
97
+
98
+ def initialize(word, first, rest) #:nodoc:
99
+ @word = word
100
+ @first = first
101
+ @rest = rest
102
+ end
103
+ end
104
+
105
+ private
106
+ LEQ_RE = /[.?!]['"]?$/
107
+
108
+ def brk_re(i) #:nodoc:
109
+ %r/((?:\S+\s+){#{i}})(.+)/
110
+ end
111
+
112
+ def posint(p) #:nodoc:
113
+ p.to_i.abs
114
+ end
115
+
116
+ public
117
+ # Compares two Text::Format objects. All settings of the objects are
118
+ # compared *except* #hyphenator. Generated results (e.g., #split_words)
119
+ # are not compared, either.
120
+ def ==(o)
121
+ (@text == o.text) &&
122
+ (@columns == o.columns) &&
123
+ (@left_margin == o.left_margin) &&
124
+ (@right_margin == o.right_margin) &&
125
+ (@hard_margins == o.hard_margins) &&
126
+ (@split_rules == o.split_rules) &&
127
+ (@first_indent == o.first_indent) &&
128
+ (@body_indent == o.body_indent) &&
129
+ (@tag_text == o.tag_text) &&
130
+ (@tabstop == o.tabstop) &&
131
+ (@format_style == o.format_style) &&
132
+ (@extra_space == o.extra_space) &&
133
+ (@tag_paragraph == o.tag_paragraph) &&
134
+ (@nobreak == o.nobreak) &&
135
+ (@abbreviations == o.abbreviations) &&
136
+ (@nobreak_regex == o.nobreak_regex)
137
+ end
138
+
139
+ # The text to be manipulated. Note that value is optional, but if the
140
+ # formatting functions are called without values, this text is what will
141
+ # be formatted.
142
+ #
143
+ # *Default*:: <tt>[]</tt>
144
+ # <b>Used in</b>:: All methods
145
+ attr_accessor :text
146
+
147
+ # The total width of the format area. The margins, indentation, and text
148
+ # are formatted into this space.
149
+ #
150
+ # COLUMNS
151
+ # <-------------------------------------------------------------->
152
+ # <-----------><------><---------------------------><------------>
153
+ # left margin indent text is formatted into here right margin
154
+ #
155
+ # *Default*:: <tt>72</tt>
156
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
157
+ # <tt>#center</tt>
158
+ attr_reader :columns
159
+
160
+ # The total width of the format area. The margins, indentation, and text
161
+ # are formatted into this space. The value provided is silently
162
+ # converted to a positive integer.
163
+ #
164
+ # COLUMNS
165
+ # <-------------------------------------------------------------->
166
+ # <-----------><------><---------------------------><------------>
167
+ # left margin indent text is formatted into here right margin
168
+ #
169
+ # *Default*:: <tt>72</tt>
170
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
171
+ # <tt>#center</tt>
172
+ def columns=(c)
173
+ @columns = posint(c)
174
+ end
175
+
176
+ # The number of spaces used for the left margin.
177
+ #
178
+ # columns
179
+ # <-------------------------------------------------------------->
180
+ # <-----------><------><---------------------------><------------>
181
+ # LEFT MARGIN indent text is formatted into here right margin
182
+ #
183
+ # *Default*:: <tt>0</tt>
184
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
185
+ # <tt>#center</tt>
186
+ attr_reader :left_margin
187
+
188
+ # The number of spaces used for the left margin. The value provided is
189
+ # silently converted to a positive integer value.
190
+ #
191
+ # columns
192
+ # <-------------------------------------------------------------->
193
+ # <-----------><------><---------------------------><------------>
194
+ # LEFT MARGIN indent text is formatted into here right margin
195
+ #
196
+ # *Default*:: <tt>0</tt>
197
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
198
+ # <tt>#center</tt>
199
+ def left_margin=(left)
200
+ @left_margin = posint(left)
201
+ end
202
+
203
+ # The number of spaces used for the right margin.
204
+ #
205
+ # columns
206
+ # <-------------------------------------------------------------->
207
+ # <-----------><------><---------------------------><------------>
208
+ # left margin indent text is formatted into here RIGHT MARGIN
209
+ #
210
+ # *Default*:: <tt>0</tt>
211
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
212
+ # <tt>#center</tt>
213
+ attr_reader :right_margin
214
+
215
+ # The number of spaces used for the right margin. The value provided is
216
+ # silently converted to a positive integer value.
217
+ #
218
+ # columns
219
+ # <-------------------------------------------------------------->
220
+ # <-----------><------><---------------------------><------------>
221
+ # left margin indent text is formatted into here RIGHT MARGIN
222
+ #
223
+ # *Default*:: <tt>0</tt>
224
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>,
225
+ # <tt>#center</tt>
226
+ def right_margin=(r)
227
+ @right_margin = posint(r)
228
+ end
229
+
230
+ # The number of spaces to indent the first line of a paragraph.
231
+ #
232
+ # columns
233
+ # <-------------------------------------------------------------->
234
+ # <-----------><------><---------------------------><------------>
235
+ # left margin INDENT text is formatted into here right margin
236
+ #
237
+ # *Default*:: <tt>4</tt>
238
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
239
+ attr_reader :first_indent
240
+
241
+ # The number of spaces to indent the first line of a paragraph. The
242
+ # value provided is silently converted to a positive integer value.
243
+ #
244
+ # columns
245
+ # <-------------------------------------------------------------->
246
+ # <-----------><------><---------------------------><------------>
247
+ # left margin INDENT text is formatted into here right margin
248
+ #
249
+ # *Default*:: <tt>4</tt>
250
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
251
+ def first_indent=(f)
252
+ @first_indent = posint(f)
253
+ end
254
+
255
+ # The number of spaces to indent all lines after the first line of a
256
+ # paragraph.
257
+ #
258
+ # columns
259
+ # <-------------------------------------------------------------->
260
+ # <-----------><------><---------------------------><------------>
261
+ # left margin INDENT text is formatted into here right margin
262
+ #
263
+ # *Default*:: <tt>0</tt>
264
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
265
+ attr_reader :body_indent
266
+
267
+ # The number of spaces to indent all lines after the first line of
268
+ # a paragraph. The value provided is silently converted to a
269
+ # positive integer value.
270
+ #
271
+ # columns
272
+ # <-------------------------------------------------------------->
273
+ # <-----------><------><---------------------------><------------>
274
+ # left margin INDENT text is formatted into here right margin
275
+ #
276
+ # *Default*:: <tt>0</tt>
277
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
278
+ def body_indent=(b)
279
+ @body_indent = posint(b)
280
+ end
281
+
282
+ # Normally, words larger than the format area will be placed on a line
283
+ # by themselves. Setting this to +true+ will force words larger than the
284
+ # format area to be split into one or more "words" each at most the size
285
+ # of the format area. The first line and the original word will be
286
+ # placed into <tt>#split_words</tt>. Note that this will cause the
287
+ # output to look *similar* to a #format_style of JUSTIFY. (Lines will be
288
+ # filled as much as possible.)
289
+ #
290
+ # *Default*:: +false+
291
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
292
+ attr_accessor :hard_margins
293
+
294
+ # An array of words split during formatting if #hard_margins is set to
295
+ # +true+.
296
+ # #split_words << Text::Format::SplitWord.new(word, first, rest)
297
+ attr_reader :split_words
298
+
299
+ # The object responsible for hyphenating. It must respond to
300
+ # #hyphenate_to(word, size) or #hyphenate_to(word, size, formatter) and
301
+ # return an array of the word split into two parts; if there is a
302
+ # hyphenation mark to be applied, responsibility belongs to the
303
+ # hyphenator object. The size is the MAXIMUM size permitted, including
304
+ # any hyphenation marks. If the #hyphenate_to method has an arity of 3,
305
+ # the formatter will be provided to the method. This allows the
306
+ # hyphenator to make decisions about the hyphenation based on the
307
+ # formatting rules.
308
+ #
309
+ # *Default*:: +nil+
310
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
311
+ attr_reader :hyphenator
312
+
313
+ # The object responsible for hyphenating. It must respond to
314
+ # #hyphenate_to(word, size) and return an array of the word hyphenated
315
+ # into two parts. The size is the MAXIMUM size permitted, including any
316
+ # hyphenation marks.
317
+ #
318
+ # *Default*:: +nil+
319
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
320
+ def hyphenator=(h)
321
+ raise ArgumentError, "#{h.inspect} is not a valid hyphenator." unless h.respond_to?(:hyphenate_to)
322
+ arity = h.method(:hyphenate_to).arity
323
+ raise ArgumentError, "#{h.inspect} must have exactly two or three arguments." unless [2, 3].include?(arity)
324
+ @hyphenator = h
325
+ @hyphenator_arity = arity
326
+ end
327
+
328
+ # Specifies the split mode; used only when #hard_margins is set to
329
+ # +true+. Allowable values are:
330
+ # [+SPLIT_FIXED+] The word will be split at the number of
331
+ # characters needed, with no marking at all.
332
+ # repre
333
+ # senta
334
+ # ion
335
+ # [+SPLIT_CONTINUATION+] The word will be split at the number of
336
+ # characters needed, with a C-style continuation
337
+ # character. If a word is the only item on a
338
+ # line and it cannot be split into an
339
+ # appropriate size, SPLIT_FIXED will be used.
340
+ # repr\
341
+ # esen\
342
+ # tati\
343
+ # on
344
+ # [+SPLIT_HYPHENATION+] The word will be split according to the
345
+ # hyphenator specified in #hyphenator. If there
346
+ # is no #hyphenator specified, works like
347
+ # SPLIT_CONTINUATION. The example is using
348
+ # TeX::Hyphen. If a word is the only item on a
349
+ # line and it cannot be split into an
350
+ # appropriate size, SPLIT_CONTINUATION mode will
351
+ # be used.
352
+ # rep-
353
+ # re-
354
+ # sen-
355
+ # ta-
356
+ # tion
357
+ #
358
+ # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
359
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
360
+ attr_reader :split_rules
361
+
362
+ # Specifies the split mode; used only when #hard_margins is set to
363
+ # +true+. Allowable values are:
364
+ # [+SPLIT_FIXED+] The word will be split at the number of
365
+ # characters needed, with no marking at all.
366
+ # repre
367
+ # senta
368
+ # ion
369
+ # [+SPLIT_CONTINUATION+] The word will be split at the number of
370
+ # characters needed, with a C-style continuation
371
+ # character.
372
+ # repr\
373
+ # esen\
374
+ # tati\
375
+ # on
376
+ # [+SPLIT_HYPHENATION+] The word will be split according to the
377
+ # hyphenator specified in #hyphenator. If there
378
+ # is no #hyphenator specified, works like
379
+ # SPLIT_CONTINUATION. The example is using
380
+ # TeX::Hyphen as the #hyphenator.
381
+ # rep-
382
+ # re-
383
+ # sen-
384
+ # ta-
385
+ # tion
386
+ #
387
+ # These values can be bitwise ORed together (e.g., <tt>SPLIT_FIXED |
388
+ # SPLIT_CONTINUATION</tt>) to provide fallback split methods. In the
389
+ # example given, an attempt will be made to split the word using the
390
+ # rules of SPLIT_CONTINUATION; if there is not enough room, the word
391
+ # will be split with the rules of SPLIT_FIXED. These combinations are
392
+ # also available as the following values:
393
+ # * +SPLIT_CONTINUATION_FIXED+
394
+ # * +SPLIT_HYPHENATION_FIXED+
395
+ # * +SPLIT_HYPHENATION_CONTINUATION+
396
+ # * +SPLIT_ALL+
397
+ #
398
+ # *Default*:: <tt>Text::Format::SPLIT_FIXED</tt>
399
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
400
+ def split_rules=(s)
401
+ raise ArgumentError, "Invalid value provided for split_rules." if ((s < SPLIT_FIXED) || (s > SPLIT_ALL))
402
+ @split_rules = s
403
+ end
404
+
405
+ # Indicates whether sentence terminators should be followed by a single
406
+ # space (+false+), or two spaces (+true+).
407
+ #
408
+ # *Default*:: +false+
409
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
410
+ attr_accessor :extra_space
411
+
412
+ # Defines the current abbreviations as an array. This is only used if
413
+ # extra_space is turned on.
414
+ #
415
+ # If one is abbreviating "President" as "Pres." (abbreviations =
416
+ # ["Pres"]), then the results of formatting will be as illustrated in
417
+ # the table below:
418
+ #
419
+ # extra_space | include? | !include?
420
+ # true | Pres. Lincoln | Pres. Lincoln
421
+ # false | Pres. Lincoln | Pres. Lincoln
422
+ #
423
+ # *Default*:: <tt>{}</tt>
424
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
425
+ attr_accessor :abbreviations
426
+
427
+ # Indicates whether the formatting of paragraphs should be done with
428
+ # tagged paragraphs. Useful only with <tt>#tag_text</tt>.
429
+ #
430
+ # *Default*:: +false+
431
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
432
+ attr_accessor :tag_paragraph
433
+
434
+ # The array of text to be placed before each paragraph when
435
+ # <tt>#tag_paragraph</tt> is +true+. When <tt>#format()</tt> is called,
436
+ # only the first element of the array is used. When <tt>#paragraphs</tt>
437
+ # is called, then each entry in the array will be used once, with
438
+ # corresponding paragraphs. If the tag elements are exhausted before the
439
+ # text is exhausted, then the remaining paragraphs will not be tagged.
440
+ # Regardless of indentation settings, a blank line will be inserted
441
+ # between all paragraphs when <tt>#tag_paragraph</tt> is +true+.
442
+ #
443
+ # *Default*:: <tt>[]</tt>
444
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
445
+ attr_accessor :tag_text
446
+
447
+ # Indicates whether or not the non-breaking space feature should be
448
+ # used.
449
+ #
450
+ # *Default*:: +false+
451
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
452
+ attr_accessor :nobreak
453
+
454
+ # A hash which holds the regular expressions on which spaces should not
455
+ # be broken. The hash is set up such that the key is the first word and
456
+ # the value is the second word.
457
+ #
458
+ # For example, if +nobreak_regex+ contains the following hash:
459
+ #
460
+ # { '^Mrs?\.$' => '\S+$', '^\S+$' => '^(?:S|J)r\.$'}
461
+ #
462
+ # Then "Mr. Jones", "Mrs. Jones", and "Jones Jr." would not be broken.
463
+ # If this simple matching algorithm indicates that there should not be a
464
+ # break at the current end of line, then a backtrack is done until there
465
+ # are two words on which line breaking is permitted. If two such words
466
+ # are not found, then the end of the line will be broken *regardless*.
467
+ # If there is a single word on the current line, then no backtrack is
468
+ # done and the word is stuck on the end.
469
+ #
470
+ # *Default*:: <tt>{}</tt>
471
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
472
+ attr_accessor :nobreak_regex
473
+
474
+ # Indicates the number of spaces that a single tab represents.
475
+ #
476
+ # *Default*:: <tt>8</tt>
477
+ # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
478
+ # <tt>#paragraphs</tt>
479
+ attr_reader :tabstop
480
+
481
+ # Indicates the number of spaces that a single tab represents.
482
+ #
483
+ # *Default*:: <tt>8</tt>
484
+ # <b>Used in</b>:: <tt>#expand</tt>, <tt>#unexpand</tt>,
485
+ # <tt>#paragraphs</tt>
486
+ def tabstop=(t)
487
+ @tabstop = posint(t)
488
+ end
489
+
490
+ # Specifies the format style. Allowable values are:
491
+ # [+LEFT_ALIGN+] Left justified, ragged right.
492
+ # |A paragraph that is|
493
+ # |left aligned.|
494
+ # [+RIGHT_ALIGN+] Right justified, ragged left.
495
+ # |A paragraph that is|
496
+ # | right aligned.|
497
+ # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
498
+ # spaces. (Essentially the same as +LEFT_ALIGN+ except
499
+ # that lines are padded on the right.)
500
+ # |A paragraph that is|
501
+ # |left aligned. |
502
+ # [+JUSTIFY+] Fully justified, words filled to width by spaces,
503
+ # except the last line.
504
+ # |A paragraph that|
505
+ # |is justified.|
506
+ #
507
+ # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
508
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
509
+ attr_reader :format_style
510
+
511
+ # Specifies the format style. Allowable values are:
512
+ # [+LEFT_ALIGN+] Left justified, ragged right.
513
+ # |A paragraph that is|
514
+ # |left aligned.|
515
+ # [+RIGHT_ALIGN+] Right justified, ragged left.
516
+ # |A paragraph that is|
517
+ # | right aligned.|
518
+ # [+RIGHT_FILL+] Left justified, right ragged, filled to width by
519
+ # spaces. (Essentially the same as +LEFT_ALIGN+ except
520
+ # that lines are padded on the right.)
521
+ # |A paragraph that is|
522
+ # |left aligned. |
523
+ # [+JUSTIFY+] Fully justified, words filled to width by spaces.
524
+ # |A paragraph that|
525
+ # |is justified.|
526
+ #
527
+ # *Default*:: <tt>Text::Format::LEFT_ALIGN</tt>
528
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
529
+ def format_style=(fs)
530
+ raise ArgumentError, "Invalid value provided for format_style." if ((fs < LEFT_ALIGN) || (fs > JUSTIFY))
531
+ @format_style = fs
532
+ end
533
+
534
+ # Indicates that the format style is left alignment.
535
+ #
536
+ # *Default*:: +true+
537
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
538
+ def left_align?
539
+ return @format_style == LEFT_ALIGN
540
+ end
541
+
542
+ # Indicates that the format style is right alignment.
543
+ #
544
+ # *Default*:: +false+
545
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
546
+ def right_align?
547
+ return @format_style == RIGHT_ALIGN
548
+ end
549
+
550
+ # Indicates that the format style is right fill.
551
+ #
552
+ # *Default*:: +false+
553
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
554
+ def right_fill?
555
+ return @format_style == RIGHT_FILL
556
+ end
557
+
558
+ # Indicates that the format style is full justification.
559
+ #
560
+ # *Default*:: +false+
561
+ # <b>Used in</b>:: <tt>#format</tt>, <tt>#paragraphs</tt>
562
+ def justify?
563
+ return @format_style == JUSTIFY
564
+ end
565
+
566
+ # The default implementation of #hyphenate_to implements
567
+ # SPLIT_CONTINUATION.
568
+ def hyphenate_to(word, size)
569
+ [word[0 .. (size - 2)] + "\\", word[(size - 1) .. -1]]
570
+ end
571
+
572
+ private
573
+ def __do_split_word(word, size) #:nodoc:
574
+ [word[0 .. (size - 1)], word[size .. -1]]
575
+ end
576
+
577
+ def __format(to_wrap) #:nodoc:
578
+ words = to_wrap.split(/\s+/).compact
579
+ words.shift if words[0].nil? or words[0].empty?
580
+ to_wrap = []
581
+
582
+ abbrev = false
583
+ width = @columns - @first_indent - @left_margin - @right_margin
584
+ indent_str = ' ' * @first_indent
585
+ first_line = true
586
+ line = words.shift
587
+ abbrev = __is_abbrev(line) unless line.nil? || line.empty?
588
+
589
+ while w = words.shift
590
+ if (w.size + line.size < (width - 1)) ||
591
+ ((line !~ LEQ_RE || abbrev) && (w.size + line.size < width))
592
+ line << " " if (line =~ LEQ_RE) && (not abbrev)
593
+ line << " #{w}"
594
+ else
595
+ line, w = __do_break(line, w) if @nobreak
596
+ line, w = __do_hyphenate(line, w, width) if @hard_margins
597
+ if w.index(/\s+/)
598
+ w, *w2 = w.split(/\s+/)
599
+ words.unshift(w2)
600
+ words.flatten!
601
+ end
602
+ to_wrap << __make_line(line, indent_str, width, w.nil?) unless line.nil?
603
+ if first_line
604
+ first_line = false
605
+ width = @columns - @body_indent - @left_margin - @right_margin
606
+ indent_str = ' ' * @body_indent
607
+ end
608
+ line = w
609
+ end
610
+
611
+ abbrev = __is_abbrev(w) unless w.nil?
612
+ end
613
+
614
+ loop do
615
+ break if line.nil? or line.empty?
616
+ line, w = __do_hyphenate(line, w, width) if @hard_margins
617
+ to_wrap << __make_line(line, indent_str, width, w.nil?)
618
+ line = w
619
+ end
620
+
621
+ if (@tag_paragraph && (to_wrap.size > 0)) then
622
+ clr = %r{`(\w+)'}.match([caller(1)].flatten[0])[1]
623
+ clr = "" if clr.nil?
624
+
625
+ if ((not @tag_text[0].nil?) && (@tag_cur.size < 1) &&
626
+ (clr != "__paragraphs")) then
627
+ @tag_cur = @tag_text[0]
628
+ end
629
+
630
+ fchar = /(\S)/.match(to_wrap[0])[1]
631
+ white = to_wrap[0].index(fchar)
632
+ if ((white - @left_margin - 1) > @tag_cur.size) then
633
+ white = @tag_cur.size + @left_margin
634
+ to_wrap[0].gsub!(/^ {#{white}}/, "#{' ' * @left_margin}#{@tag_cur}")
635
+ else
636
+ to_wrap.unshift("#{' ' * @left_margin}#{@tag_cur}\n")
637
+ end
638
+ end
639
+ to_wrap.join('')
640
+ end
641
+
642
+ # format lines in text into paragraphs with each element of @wrap a
643
+ # paragraph; uses Text::Format.format for the formatting
644
+ def __paragraphs(to_wrap) #:nodoc:
645
+ if ((@first_indent == @body_indent) || @tag_paragraph) then
646
+ p_end = "\n"
647
+ else
648
+ p_end = ''
649
+ end
650
+
651
+ cnt = 0
652
+ ret = []
653
+ to_wrap.each do |tw|
654
+ @tag_cur = @tag_text[cnt] if @tag_paragraph
655
+ @tag_cur = '' if @tag_cur.nil?
656
+ line = __format(tw)
657
+ ret << "#{line}#{p_end}" if (not line.nil?) && (line.size > 0)
658
+ cnt += 1
659
+ end
660
+
661
+ ret[-1].chomp! unless ret.empty?
662
+ ret.join('')
663
+ end
664
+
665
+ # center text using spaces on left side to pad it out empty lines
666
+ # are preserved
667
+ def __center(to_center) #:nodoc:
668
+ tabs = 0
669
+ width = @columns - @left_margin - @right_margin
670
+ centered = []
671
+ to_center.each do |tc|
672
+ s = tc.strip
673
+ tabs = s.count("\t")
674
+ tabs = 0 if tabs.nil?
675
+ ct = ((width - s.size - (tabs * @tabstop) + tabs) / 2)
676
+ ct = (width - @left_margin - @right_margin) - ct
677
+ centered << "#{s.rjust(ct)}\n"
678
+ end
679
+ centered.join('')
680
+ end
681
+
682
+ # expand tabs to spaces should be similar to Text::Tabs::expand
683
+ def __expand(to_expand) #:nodoc:
684
+ expanded = []
685
+ to_expand.split("\n").each { |te| expanded << te.gsub(/\t/, ' ' * @tabstop) }
686
+ expanded.join('')
687
+ end
688
+
689
+ def __unexpand(to_unexpand) #:nodoc:
690
+ unexpanded = []
691
+ to_unexpand.split("\n").each { |tu| unexpanded << tu.gsub(/ {#{@tabstop}}/, "\t") }
692
+ unexpanded.join('')
693
+ end
694
+
695
+ def __is_abbrev(word) #:nodoc:
696
+ # remove period if there is one.
697
+ w = word.gsub(/\.$/, '') unless word.nil?
698
+ return true if (!@extra_space || ABBREV.include?(w) || @abbreviations.include?(w))
699
+ false
700
+ end
701
+
702
+ def __make_line(line, indent, width, last = false) #:nodoc:
703
+ lmargin = " " * @left_margin
704
+ fill = " " * (width - line.size) if right_fill? && (line.size <= width)
705
+
706
+ if (justify? && ((not line.nil?) && (not line.empty?)) && line =~ /\S+\s+\S+/ && !last)
707
+ spaces = width - line.size
708
+ words = line.split(/(\s+)/)
709
+ ws = spaces / (words.size / 2)
710
+ spaces = spaces % (words.size / 2) if ws > 0
711
+ words.reverse.each do |rw|
712
+ next if (rw =~ /^\S/)
713
+ rw.sub!(/^/, " " * ws)
714
+ next unless (spaces > 0)
715
+ rw.sub!(/^/, " ")
716
+ spaces -= 1
717
+ end
718
+ line = words.join('')
719
+ end
720
+ line = "#{lmargin}#{indent}#{line}#{fill}\n" unless line.nil?
721
+ if right_align? && (not line.nil?)
722
+ line.sub(/^/, " " * (@columns - @right_margin - (line.size - 1)))
723
+ else
724
+ line
725
+ end
726
+ end
727
+
728
+ def __do_hyphenate(line, next_line, width) #:nodoc:
729
+ rline = line.dup rescue line
730
+ rnext = next_line.dup rescue next_line
731
+ loop do
732
+ if rline.size == width
733
+ break
734
+ elsif rline.size > width
735
+ words = rline.strip.split(/\s+/)
736
+ word = words[-1].dup
737
+ size = width - rline.size + word.size
738
+ if (size <= 0)
739
+ words[-1] = nil
740
+ rline = words.join(' ').strip
741
+ rnext = "#{word} #{rnext}".strip
742
+ next
743
+ end
744
+
745
+ first = rest = nil
746
+
747
+ if ((@split_rules & SPLIT_HYPHENATION) != 0)
748
+ if @hyphenator_arity == 2
749
+ first, rest = @hyphenator.hyphenate_to(word, size)
750
+ else
751
+ first, rest = @hyphenator.hyphenate_to(word, size, self)
752
+ end
753
+ end
754
+
755
+ if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
756
+ first, rest = self.hyphenate_to(word, size)
757
+ end
758
+
759
+ if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
760
+ first.nil? or @split_rules == SPLIT_FIXED
761
+ first, rest = __do_split_word(word, size)
762
+ end
763
+
764
+ if first.nil?
765
+ words[-1] = nil
766
+ rest = word
767
+ else
768
+ words[-1] = first
769
+ @split_words << SplitWord.new(word, first, rest)
770
+ end
771
+ rline = words.join(' ').strip
772
+ rnext = "#{rest} #{rnext}".strip
773
+ break
774
+ else
775
+ break if rnext.nil? or rnext.empty? or rline.nil? or rline.empty?
776
+ words = rnext.split(/\s+/)
777
+ word = words.shift
778
+ size = width - rline.size - 1
779
+
780
+ if (size <= 0)
781
+ rnext = "#{word} #{words.join(' ')}".strip
782
+ break
783
+ end
784
+
785
+ first = rest = nil
786
+
787
+ if ((@split_rules & SPLIT_HYPHENATION) != 0)
788
+ if @hyphenator_arity == 2
789
+ first, rest = @hyphenator.hyphenate_to(word, size)
790
+ else
791
+ first, rest = @hyphenator.hyphenate_to(word, size, self)
792
+ end
793
+ end
794
+
795
+ first, rest = self.hyphenate_to(word, size) if ((@split_rules & SPLIT_CONTINUATION) != 0) and first.nil?
796
+
797
+ first, rest = __do_split_word(word, size) if ((@split_rules & SPLIT_FIXED) != 0) and first.nil?
798
+
799
+ if (rline.size + (first ? first.size : 0)) < width
800
+ @split_words << SplitWord.new(word, first, rest)
801
+ rline = "#{rline} #{first}".strip
802
+ rnext = "#{rest} #{words.join(' ')}".strip
803
+ end
804
+ break
805
+ end
806
+ end
807
+ [rline, rnext]
808
+ end
809
+
810
+ def __do_break(line, next_line) #:nodoc:
811
+ no_brk = false
812
+ words = []
813
+ words = line.split(/\s+/) unless line.nil?
814
+ last_word = words[-1]
815
+
816
+ @nobreak_regex.each { |k, v| no_brk = ((last_word =~ /#{k}/) and (next_line =~ /#{v}/)) }
817
+
818
+ if no_brk && words.size > 1
819
+ i = words.size
820
+ while i > 0
821
+ no_brk = false
822
+ @nobreak_regex.each { |k, v| no_brk = ((words[i + 1] =~ /#{k}/) && (words[i] =~ /#{v}/)) }
823
+ i -= 1
824
+ break if not no_brk
825
+ end
826
+ if i > 0
827
+ l = brk_re(i).match(line)
828
+ line.sub!(brk_re(i), l[1])
829
+ next_line = "#{l[2]} #{next_line}"
830
+ line.sub!(/\s+$/, '')
831
+ end
832
+ end
833
+ [line, next_line]
834
+ end
835
+
836
+ def __create(arg = nil, &block) #:nodoc:
837
+ # Format::Text.new(text-to-wrap)
838
+ @text = arg unless arg.nil?
839
+ # Defaults
840
+ @columns = 72
841
+ @tabstop = 8
842
+ @first_indent = 4
843
+ @body_indent = 0
844
+ @format_style = LEFT_ALIGN
845
+ @left_margin = 0
846
+ @right_margin = 0
847
+ @extra_space = false
848
+ @text = Array.new if @text.nil?
849
+ @tag_paragraph = false
850
+ @tag_text = Array.new
851
+ @tag_cur = ""
852
+ @abbreviations = Array.new
853
+ @nobreak = false
854
+ @nobreak_regex = Hash.new
855
+ @split_words = Array.new
856
+ @hard_margins = false
857
+ @split_rules = SPLIT_FIXED
858
+ @hyphenator = self
859
+ @hyphenator_arity = self.method(:hyphenate_to).arity
860
+
861
+ instance_eval(&block) unless block.nil?
862
+ end
863
+
864
+ public
865
+ # Formats text into a nice paragraph format. The text is separated
866
+ # into words and then reassembled a word at a time using the settings
867
+ # of this Format object. If a word is larger than the number of
868
+ # columns available for formatting, then that word will appear on the
869
+ # line by itself.
870
+ #
871
+ # If +to_wrap+ is +nil+, then the value of <tt>#text</tt> will be
872
+ # worked on.
873
+ def format(to_wrap = nil)
874
+ to_wrap = @text if to_wrap.nil?
875
+ if to_wrap.class == Array
876
+ __format(to_wrap[0])
877
+ else
878
+ __format(to_wrap)
879
+ end
880
+ end
881
+
882
+ # Considers each element of text (provided or internal) as a paragraph.
883
+ # If <tt>#first_indent</tt> is the same as <tt>#body_indent</tt>, then
884
+ # paragraphs will be separated by a single empty line in the result;
885
+ # otherwise, the paragraphs will follow immediately after each other.
886
+ # Uses <tt>#format</tt> to do the heavy lifting.
887
+ def paragraphs(to_wrap = nil)
888
+ to_wrap = @text if to_wrap.nil?
889
+ __paragraphs([to_wrap].flatten)
890
+ end
891
+
892
+ # Centers the text, preserving empty lines and tabs.
893
+ def center(to_center = nil)
894
+ to_center = @text if to_center.nil?
895
+ __center([to_center].flatten)
896
+ end
897
+
898
+ # Replaces all tab characters in the text with <tt>#tabstop</tt> spaces.
899
+ def expand(to_expand = nil)
900
+ to_expand = @text if to_expand.nil?
901
+ if to_expand.class == Array
902
+ to_expand.collect { |te| __expand(te) }
903
+ else
904
+ __expand(to_expand)
905
+ end
906
+ end
907
+
908
+ # Replaces all occurrences of <tt>#tabstop</tt> consecutive spaces
909
+ # with a tab character.
910
+ def unexpand(to_unexpand = nil)
911
+ to_unexpand = @text if to_unexpand.nil?
912
+ if to_unexpand.class == Array
913
+ to_unexpand.collect { |te| v << __unexpand(te) }
914
+ else
915
+ __unexpand(to_unexpand)
916
+ end
917
+ end
918
+
919
+ # This constructor takes advantage of a technique for Ruby object
920
+ # construction introduced by Andy Hunt and Dave Thomas (see reference),
921
+ # where optional values are set using commands in a block.
922
+ #
923
+ # Text::Format.new {
924
+ # columns = 72
925
+ # left_margin = 0
926
+ # right_margin = 0
927
+ # first_indent = 4
928
+ # body_indent = 0
929
+ # format_style = Text::Format::LEFT_ALIGN
930
+ # extra_space = false
931
+ # abbreviations = {}
932
+ # tag_paragraph = false
933
+ # tag_text = []
934
+ # nobreak = false
935
+ # nobreak_regex = {}
936
+ # tabstop = 8
937
+ # text = nil
938
+ # }
939
+ #
940
+ # As shown above, +arg+ is optional. If +arg+ is specified and is a
941
+ # +String+, then arg is used as the default value of <tt>#text</tt>.
942
+ # Alternately, an existing Text::Format object can be used or a Hash can
943
+ # be used. With all forms, a block can be specified.
944
+ #
945
+ # *Reference*:: "Object Construction and Blocks"
946
+ # <http://www.pragmaticprogrammer.com/ruby/articles/insteval.html>
947
+ #
948
+ def initialize(arg = nil, &block)
949
+ case arg
950
+ when Text::Format
951
+ __create(arg.text) do
952
+ @columns = arg.columns
953
+ @tabstop = arg.tabstop
954
+ @first_indent = arg.first_indent
955
+ @body_indent = arg.body_indent
956
+ @format_style = arg.format_style
957
+ @left_margin = arg.left_margin
958
+ @right_margin = arg.right_margin
959
+ @extra_space = arg.extra_space
960
+ @tag_paragraph = arg.tag_paragraph
961
+ @tag_text = arg.tag_text
962
+ @abbreviations = arg.abbreviations
963
+ @nobreak = arg.nobreak
964
+ @nobreak_regex = arg.nobreak_regex
965
+ @text = arg.text
966
+ @hard_margins = arg.hard_margins
967
+ @split_words = arg.split_words
968
+ @split_rules = arg.split_rules
969
+ @hyphenator = arg.hyphenator
970
+ end
971
+ instance_eval(&block) unless block.nil?
972
+ when Hash
973
+ __create do
974
+ @columns = arg[:columns] || arg['columns'] || @columns
975
+ @tabstop = arg[:tabstop] || arg['tabstop'] || @tabstop
976
+ @first_indent = arg[:first_indent] || arg['first_indent'] || @first_indent
977
+ @body_indent = arg[:body_indent] || arg['body_indent'] || @body_indent
978
+ @format_style = arg[:format_style] || arg['format_style'] || @format_style
979
+ @left_margin = arg[:left_margin] || arg['left_margin'] || @left_margin
980
+ @right_margin = arg[:right_margin] || arg['right_margin'] || @right_margin
981
+ @extra_space = arg[:extra_space] || arg['extra_space'] || @extra_space
982
+ @text = arg[:text] || arg['text'] || @text
983
+ @tag_paragraph = arg[:tag_paragraph] || arg['tag_paragraph'] || @tag_paragraph
984
+ @tag_text = arg[:tag_text] || arg['tag_text'] || @tag_text
985
+ @abbreviations = arg[:abbreviations] || arg['abbreviations'] || @abbreviations
986
+ @nobreak = arg[:nobreak] || arg['nobreak'] || @nobreak
987
+ @nobreak_regex = arg[:nobreak_regex] || arg['nobreak_regex'] || @nobreak_regex
988
+ @hard_margins = arg[:hard_margins] || arg['hard_margins'] || @hard_margins
989
+ @split_rules = arg[:split_rules] || arg['split_rules'] || @split_rules
990
+ @hyphenator = arg[:hyphenator] || arg['hyphenator'] || @hyphenator
991
+ end
992
+ instance_eval(&block) unless block.nil?
993
+ when String
994
+ __create(arg, &block)
995
+ when NilClass
996
+ __create(&block)
997
+ else
998
+ raise TypeError
999
+ end
1000
+ end
1001
+ end
1002
+ end
1003
+
1004
+ if __FILE__ == $0
1005
+ require 'test/unit'
1006
+
1007
+ class TestText__Format < Test::Unit::TestCase #:nodoc:
1008
+ attr_accessor :format_o
1009
+
1010
+ GETTYSBURG = <<-'EOS'
1011
+ Four score and seven years ago our fathers brought forth on this
1012
+ continent a new nation, conceived in liberty and dedicated to the
1013
+ proposition that all men are created equal. Now we are engaged in
1014
+ a great civil war, testing whether that nation or any nation so
1015
+ conceived and so dedicated can long endure. We are met on a great
1016
+ battlefield of that war. We have come to dedicate a portion of
1017
+ that field as a final resting-place for those who here gave their
1018
+ lives that that nation might live. It is altogether fitting and
1019
+ proper that we should do this. But in a larger sense, we cannot
1020
+ dedicate, we cannot consecrate, we cannot hallow this ground.
1021
+ The brave men, living and dead who struggled here have consecrated
1022
+ it far above our poor power to add or detract. The world will
1023
+ little note nor long remember what we say here, but it can never
1024
+ forget what they did here. It is for us the living rather to be
1025
+ dedicated here to the unfinished work which they who fought here
1026
+ have thus far so nobly advanced. It is rather for us to be here
1027
+ dedicated to the great task remaining before us--that from these
1028
+ honored dead we take increased devotion to that cause for which
1029
+ they gave the last full measure of devotion--that we here highly
1030
+ resolve that these dead shall not have died in vain, that this
1031
+ nation under God shall have a new birth of freedom, and that
1032
+ government of the people, by the people, for the people shall
1033
+ not perish from the earth.
1034
+
1035
+ -- Pres. Abraham Lincoln, 19 November 1863
1036
+ EOS
1037
+
1038
+ FIVE_COL = "Four \nscore\nand s\neven \nyears\nago o\nur fa\nthers\nbroug\nht fo\nrth o\nn thi\ns con\ntinen\nt a n\new na\ntion,\nconce\nived \nin li\nberty\nand d\nedica\nted t\no the\npropo\nsitio\nn tha\nt all\nmen a\nre cr\neated\nequal\n. Now\nwe ar\ne eng\naged \nin a \ngreat\ncivil\nwar, \ntesti\nng wh\nether\nthat \nnatio\nn or \nany n\nation\nso co\nnceiv\ned an\nd so \ndedic\nated \ncan l\nong e\nndure\n. We \nare m\net on\na gre\nat ba\nttlef\nield \nof th\nat wa\nr. We\nhave \ncome \nto de\ndicat\ne a p\nortio\nn of \nthat \nfield\nas a \nfinal\nresti\nng-pl\nace f\nor th\nose w\nho he\nre ga\nve th\neir l\nives \nthat \nthat \nnatio\nn mig\nht li\nve. I\nt is \naltog\nether\nfitti\nng an\nd pro\nper t\nhat w\ne sho\nuld d\no thi\ns. Bu\nt in \na lar\nger s\nense,\nwe ca\nnnot \ndedic\nate, \nwe ca\nnnot \nconse\ncrate\n, we \ncanno\nt hal\nlow t\nhis g\nround\n. The\nbrave\nmen, \nlivin\ng and\ndead \nwho s\ntrugg\nled h\nere h\nave c\nonsec\nrated\nit fa\nr abo\nve ou\nr poo\nr pow\ner to\nadd o\nr det\nract.\nThe w\norld \nwill \nlittl\ne not\ne nor\nlong \nremem\nber w\nhat w\ne say\nhere,\nbut i\nt can\nnever\nforge\nt wha\nt the\ny did\nhere.\nIt is\nfor u\ns the\nlivin\ng rat\nher t\no be \ndedic\nated \nhere \nto th\ne unf\ninish\ned wo\nrk wh\nich t\nhey w\nho fo\nught \nhere \nhave \nthus \nfar s\no nob\nly ad\nvance\nd. It\nis ra\nther \nfor u\ns to \nbe he\nre de\ndicat\ned to\nthe g\nreat \ntask \nremai\nning \nbefor\ne us-\n-that\nfrom \nthese\nhonor\ned de\nad we\ntake \nincre\nased \ndevot\nion t\no tha\nt cau\nse fo\nr whi\nch th\ney ga\nve th\ne las\nt ful\nl mea\nsure \nof de\nvotio\nn--th\nat we\nhere \nhighl\ny res\nolve \nthat \nthese\ndead \nshall\nnot h\nave d\nied i\nn vai\nn, th\nat th\nis na\ntion \nunder\nGod s\nhall \nhave \na new\nbirth\nof fr\needom\n, and\nthat \ngover\nnment\nof th\ne peo\nple, \nby th\ne peo\nple, \nfor t\nhe pe\nople \nshall\nnot p\nerish\nfrom \nthe e\narth.\n-- Pr\nes. A\nbraha\nm Lin\ncoln,\n19 No\nvembe\nr 186\n3 \n"
1039
+
1040
+ FIVE_CNT = "Four \nscore\nand \nseven\nyears\nago \nour \nfath\\\ners \nbrou\\\nght \nforth\non t\\\nhis \ncont\\\ninent\na new\nnati\\\non, \nconc\\\neived\nin l\\\niber\\\nty a\\\nnd d\\\nedic\\\nated \nto t\\\nhe p\\\nropo\\\nsiti\\\non t\\\nhat \nall \nmen \nare \ncrea\\\nted \nequa\\\nl. N\\\now we\nare \nenga\\\nged \nin a \ngreat\ncivil\nwar, \ntest\\\ning \nwhet\\\nher \nthat \nnati\\\non or\nany \nnati\\\non so\nconc\\\neived\nand \nso d\\\nedic\\\nated \ncan \nlong \nendu\\\nre. \nWe a\\\nre m\\\net on\na gr\\\neat \nbatt\\\nlefi\\\neld \nof t\\\nhat \nwar. \nWe h\\\nave \ncome \nto d\\\nedic\\\nate a\nport\\\nion \nof t\\\nhat \nfield\nas a \nfinal\nrest\\\ning-\\\nplace\nfor \nthose\nwho \nhere \ngave \ntheir\nlives\nthat \nthat \nnati\\\non m\\\night \nlive.\nIt is\nalto\\\ngeth\\\ner f\\\nitti\\\nng a\\\nnd p\\\nroper\nthat \nwe s\\\nhould\ndo t\\\nhis. \nBut \nin a \nlarg\\\ner s\\\nense,\nwe c\\\nannot\ndedi\\\ncate,\nwe c\\\nannot\ncons\\\necra\\\nte, \nwe c\\\nannot\nhall\\\now t\\\nhis \ngrou\\\nnd. \nThe \nbrave\nmen, \nlivi\\\nng a\\\nnd d\\\nead \nwho \nstru\\\nggled\nhere \nhave \ncons\\\necra\\\nted \nit f\\\nar a\\\nbove \nour \npoor \npower\nto a\\\ndd or\ndetr\\\nact. \nThe \nworld\nwill \nlitt\\\nle n\\\note \nnor \nlong \nreme\\\nmber \nwhat \nwe s\\\nay h\\\nere, \nbut \nit c\\\nan n\\\never \nforg\\\net w\\\nhat \nthey \ndid \nhere.\nIt is\nfor \nus t\\\nhe l\\\niving\nrath\\\ner to\nbe d\\\nedic\\\nated \nhere \nto t\\\nhe u\\\nnfin\\\nished\nwork \nwhich\nthey \nwho \nfoug\\\nht h\\\nere \nhave \nthus \nfar \nso n\\\nobly \nadva\\\nnced.\nIt is\nrath\\\ner f\\\nor us\nto be\nhere \ndedi\\\ncated\nto t\\\nhe g\\\nreat \ntask \nrema\\\nining\nbefo\\\nre u\\\ns--t\\\nhat \nfrom \nthese\nhono\\\nred \ndead \nwe t\\\nake \nincr\\\neased\ndevo\\\ntion \nto t\\\nhat \ncause\nfor \nwhich\nthey \ngave \nthe \nlast \nfull \nmeas\\\nure \nof d\\\nevot\\\nion-\\\n-that\nwe h\\\nere \nhigh\\\nly r\\\nesol\\\nve t\\\nhat \nthese\ndead \nshall\nnot \nhave \ndied \nin v\\\nain, \nthat \nthis \nnati\\\non u\\\nnder \nGod \nshall\nhave \na new\nbirth\nof f\\\nreed\\\nom, \nand \nthat \ngove\\\nrnme\\\nnt of\nthe \npeop\\\nle, \nby t\\\nhe p\\\neopl\\\ne, f\\\nor t\\\nhe p\\\neople\nshall\nnot \nperi\\\nsh f\\\nrom \nthe \neart\\\nh. --\nPres.\nAbra\\\nham \nLinc\\\noln, \n19 N\\\novem\\\nber \n1863 \n"
1041
+
1042
+ # Tests both abbreviations and abbreviations=
1043
+ def test_abbreviations
1044
+ abbr = [" Pres. Abraham Lincoln\n", " Pres. Abraham Lincoln\n"]
1045
+ assert_nothing_raised { @format_o = Text::Format.new }
1046
+ assert_equal([], @format_o.abbreviations)
1047
+ assert_nothing_raised { @format_o.abbreviations = [ 'foo', 'bar' ] }
1048
+ assert_equal([ 'foo', 'bar' ], @format_o.abbreviations)
1049
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
1050
+ assert_nothing_raised { @format_o.extra_space = true }
1051
+ assert_equal(abbr[1], @format_o.format(abbr[0]))
1052
+ assert_nothing_raised { @format_o.abbreviations = [ "Pres" ] }
1053
+ assert_equal([ "Pres" ], @format_o.abbreviations)
1054
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
1055
+ assert_nothing_raised { @format_o.extra_space = false }
1056
+ assert_equal(abbr[0], @format_o.format(abbr[0]))
1057
+ end
1058
+
1059
+ # Tests both body_indent and body_indent=
1060
+ def test_body_indent
1061
+ assert_nothing_raised { @format_o = Text::Format.new }
1062
+ assert_equal(0, @format_o.body_indent)
1063
+ assert_nothing_raised { @format_o.body_indent = 7 }
1064
+ assert_equal(7, @format_o.body_indent)
1065
+ assert_nothing_raised { @format_o.body_indent = -3 }
1066
+ assert_equal(3, @format_o.body_indent)
1067
+ assert_nothing_raised { @format_o.body_indent = "9" }
1068
+ assert_equal(9, @format_o.body_indent)
1069
+ assert_nothing_raised { @format_o.body_indent = "-2" }
1070
+ assert_equal(2, @format_o.body_indent)
1071
+ assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[1])
1072
+ end
1073
+
1074
+ # Tests both columns and columns=
1075
+ def test_columns
1076
+ assert_nothing_raised { @format_o = Text::Format.new }
1077
+ assert_equal(72, @format_o.columns)
1078
+ assert_nothing_raised { @format_o.columns = 7 }
1079
+ assert_equal(7, @format_o.columns)
1080
+ assert_nothing_raised { @format_o.columns = -3 }
1081
+ assert_equal(3, @format_o.columns)
1082
+ assert_nothing_raised { @format_o.columns = "9" }
1083
+ assert_equal(9, @format_o.columns)
1084
+ assert_nothing_raised { @format_o.columns = "-2" }
1085
+ assert_equal(2, @format_o.columns)
1086
+ assert_nothing_raised { @format_o.columns = 40 }
1087
+ assert_equal(40, @format_o.columns)
1088
+ assert_match(/this continent$/,
1089
+ @format_o.format(GETTYSBURG).split("\n")[1])
1090
+ end
1091
+
1092
+ # Tests both extra_space and extra_space=
1093
+ def test_extra_space
1094
+ assert_nothing_raised { @format_o = Text::Format.new }
1095
+ assert(!@format_o.extra_space)
1096
+ assert_nothing_raised { @format_o.extra_space = true }
1097
+ assert(@format_o.extra_space)
1098
+ # The behaviour of extra_space is tested in test_abbreviations. There
1099
+ # is no need to reproduce it here.
1100
+ end
1101
+
1102
+ # Tests both first_indent and first_indent=
1103
+ def test_first_indent
1104
+ assert_nothing_raised { @format_o = Text::Format.new }
1105
+ assert_equal(4, @format_o.first_indent)
1106
+ assert_nothing_raised { @format_o.first_indent = 7 }
1107
+ assert_equal(7, @format_o.first_indent)
1108
+ assert_nothing_raised { @format_o.first_indent = -3 }
1109
+ assert_equal(3, @format_o.first_indent)
1110
+ assert_nothing_raised { @format_o.first_indent = "9" }
1111
+ assert_equal(9, @format_o.first_indent)
1112
+ assert_nothing_raised { @format_o.first_indent = "-2" }
1113
+ assert_equal(2, @format_o.first_indent)
1114
+ assert_match(/^ [^ ]/, @format_o.format(GETTYSBURG).split("\n")[0])
1115
+ end
1116
+
1117
+ def test_format_style
1118
+ assert_nothing_raised { @format_o = Text::Format.new }
1119
+ assert_equal(Text::Format::LEFT_ALIGN, @format_o.format_style)
1120
+ assert_match(/^November 1863$/,
1121
+ @format_o.format(GETTYSBURG).split("\n")[-1])
1122
+ assert_nothing_raised {
1123
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
1124
+ }
1125
+ assert_equal(Text::Format::RIGHT_ALIGN, @format_o.format_style)
1126
+ assert_match(/^ +November 1863$/,
1127
+ @format_o.format(GETTYSBURG).split("\n")[-1])
1128
+ assert_nothing_raised {
1129
+ @format_o.format_style = Text::Format::RIGHT_FILL
1130
+ }
1131
+ assert_equal(Text::Format::RIGHT_FILL, @format_o.format_style)
1132
+ assert_match(/^November 1863 +$/,
1133
+ @format_o.format(GETTYSBURG).split("\n")[-1])
1134
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
1135
+ assert_equal(Text::Format::JUSTIFY, @format_o.format_style)
1136
+ assert_match(/^of freedom, and that government of the people, by the people, for the$/,
1137
+ @format_o.format(GETTYSBURG).split("\n")[-3])
1138
+ assert_raises(ArgumentError) { @format_o.format_style = 33 }
1139
+ end
1140
+
1141
+ def test_tag_paragraph
1142
+ assert_nothing_raised { @format_o = Text::Format.new }
1143
+ assert(!@format_o.tag_paragraph)
1144
+ assert_nothing_raised { @format_o.tag_paragraph = true }
1145
+ assert(@format_o.tag_paragraph)
1146
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
1147
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
1148
+ end
1149
+
1150
+ def test_tag_text
1151
+ assert_nothing_raised { @format_o = Text::Format.new }
1152
+ assert_equal([], @format_o.tag_text)
1153
+ assert_equal(@format_o.format(GETTYSBURG),
1154
+ Text::Format.new.format(GETTYSBURG))
1155
+ assert_nothing_raised {
1156
+ @format_o.tag_paragraph = true
1157
+ @format_o.tag_text = ["Gettysburg Address", "---"]
1158
+ }
1159
+ assert_not_equal(@format_o.format(GETTYSBURG),
1160
+ Text::Format.new.format(GETTYSBURG))
1161
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG]),
1162
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG]))
1163
+ assert_not_equal(@format_o.paragraphs([GETTYSBURG, GETTYSBURG,
1164
+ GETTYSBURG]),
1165
+ Text::Format.new.paragraphs([GETTYSBURG, GETTYSBURG,
1166
+ GETTYSBURG]))
1167
+ end
1168
+
1169
+ def test_justify?
1170
+ assert_nothing_raised { @format_o = Text::Format.new }
1171
+ assert(!@format_o.justify?)
1172
+ assert_nothing_raised {
1173
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
1174
+ }
1175
+ assert(!@format_o.justify?)
1176
+ assert_nothing_raised {
1177
+ @format_o.format_style = Text::Format::RIGHT_FILL
1178
+ }
1179
+ assert(!@format_o.justify?)
1180
+ assert_nothing_raised {
1181
+ @format_o.format_style = Text::Format::JUSTIFY
1182
+ }
1183
+ assert(@format_o.justify?)
1184
+ # The format testing is done in test_format_style
1185
+ end
1186
+
1187
+ def test_left_align?
1188
+ assert_nothing_raised { @format_o = Text::Format.new }
1189
+ assert(@format_o.left_align?)
1190
+ assert_nothing_raised {
1191
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
1192
+ }
1193
+ assert(!@format_o.left_align?)
1194
+ assert_nothing_raised {
1195
+ @format_o.format_style = Text::Format::RIGHT_FILL
1196
+ }
1197
+ assert(!@format_o.left_align?)
1198
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
1199
+ assert(!@format_o.left_align?)
1200
+ # The format testing is done in test_format_style
1201
+ end
1202
+
1203
+ def test_left_margin
1204
+ assert_nothing_raised { @format_o = Text::Format.new }
1205
+ assert_equal(0, @format_o.left_margin)
1206
+ assert_nothing_raised { @format_o.left_margin = -3 }
1207
+ assert_equal(3, @format_o.left_margin)
1208
+ assert_nothing_raised { @format_o.left_margin = "9" }
1209
+ assert_equal(9, @format_o.left_margin)
1210
+ assert_nothing_raised { @format_o.left_margin = "-2" }
1211
+ assert_equal(2, @format_o.left_margin)
1212
+ assert_nothing_raised { @format_o.left_margin = 7 }
1213
+ assert_equal(7, @format_o.left_margin)
1214
+ assert_nothing_raised {
1215
+ ft = @format_o.format(GETTYSBURG).split("\n")
1216
+ assert_match(/^ {11}Four score/, ft[0])
1217
+ assert_match(/^ {7}November/, ft[-1])
1218
+ }
1219
+ end
1220
+
1221
+ def test_hard_margins
1222
+ assert_nothing_raised { @format_o = Text::Format.new }
1223
+ assert(!@format_o.hard_margins)
1224
+ assert_nothing_raised {
1225
+ @format_o.hard_margins = true
1226
+ @format_o.columns = 5
1227
+ @format_o.first_indent = 0
1228
+ @format_o.format_style = Text::Format::RIGHT_FILL
1229
+ }
1230
+ assert(@format_o.hard_margins)
1231
+ assert_equal(FIVE_COL, @format_o.format(GETTYSBURG))
1232
+ assert_nothing_raised {
1233
+ @format_o.split_rules |= Text::Format::SPLIT_CONTINUATION
1234
+ assert_equal(Text::Format::SPLIT_CONTINUATION_FIXED,
1235
+ @format_o.split_rules)
1236
+ }
1237
+ assert_equal(FIVE_CNT, @format_o.format(GETTYSBURG))
1238
+ end
1239
+
1240
+ # Tests both nobreak and nobreak_regex, since one is only useful
1241
+ # with the other.
1242
+ def test_nobreak
1243
+ assert_nothing_raised { @format_o = Text::Format.new }
1244
+ assert(!@format_o.nobreak)
1245
+ assert(@format_o.nobreak_regex.empty?)
1246
+ assert_nothing_raised {
1247
+ @format_o.nobreak = true
1248
+ @format_o.nobreak_regex = { '^this$' => '^continent$' }
1249
+ @format_o.columns = 77
1250
+ }
1251
+ assert(@format_o.nobreak)
1252
+ assert_equal({ '^this$' => '^continent$' }, @format_o.nobreak_regex)
1253
+ assert_match(/^this continent/,
1254
+ @format_o.format(GETTYSBURG).split("\n")[1])
1255
+ end
1256
+
1257
+ def test_right_align?
1258
+ assert_nothing_raised { @format_o = Text::Format.new }
1259
+ assert(!@format_o.right_align?)
1260
+ assert_nothing_raised {
1261
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
1262
+ }
1263
+ assert(@format_o.right_align?)
1264
+ assert_nothing_raised {
1265
+ @format_o.format_style = Text::Format::RIGHT_FILL
1266
+ }
1267
+ assert(!@format_o.right_align?)
1268
+ assert_nothing_raised { @format_o.format_style = Text::Format::JUSTIFY }
1269
+ assert(!@format_o.right_align?)
1270
+ # The format testing is done in test_format_style
1271
+ end
1272
+
1273
+ def test_right_fill?
1274
+ assert_nothing_raised { @format_o = Text::Format.new }
1275
+ assert(!@format_o.right_fill?)
1276
+ assert_nothing_raised {
1277
+ @format_o.format_style = Text::Format::RIGHT_ALIGN
1278
+ }
1279
+ assert(!@format_o.right_fill?)
1280
+ assert_nothing_raised {
1281
+ @format_o.format_style = Text::Format::RIGHT_FILL
1282
+ }
1283
+ assert(@format_o.right_fill?)
1284
+ assert_nothing_raised {
1285
+ @format_o.format_style = Text::Format::JUSTIFY
1286
+ }
1287
+ assert(!@format_o.right_fill?)
1288
+ # The format testing is done in test_format_style
1289
+ end
1290
+
1291
+ def test_right_margin
1292
+ assert_nothing_raised { @format_o = Text::Format.new }
1293
+ assert_equal(0, @format_o.right_margin)
1294
+ assert_nothing_raised { @format_o.right_margin = -3 }
1295
+ assert_equal(3, @format_o.right_margin)
1296
+ assert_nothing_raised { @format_o.right_margin = "9" }
1297
+ assert_equal(9, @format_o.right_margin)
1298
+ assert_nothing_raised { @format_o.right_margin = "-2" }
1299
+ assert_equal(2, @format_o.right_margin)
1300
+ assert_nothing_raised { @format_o.right_margin = 7 }
1301
+ assert_equal(7, @format_o.right_margin)
1302
+ assert_nothing_raised {
1303
+ ft = @format_o.format(GETTYSBURG).split("\n")
1304
+ assert_match(/^ {4}Four score.*forth on$/, ft[0])
1305
+ assert_match(/^November/, ft[-1])
1306
+ }
1307
+ end
1308
+
1309
+ def test_tabstop
1310
+ assert_nothing_raised { @format_o = Text::Format.new }
1311
+ assert_equal(8, @format_o.tabstop)
1312
+ assert_nothing_raised { @format_o.tabstop = 7 }
1313
+ assert_equal(7, @format_o.tabstop)
1314
+ assert_nothing_raised { @format_o.tabstop = -3 }
1315
+ assert_equal(3, @format_o.tabstop)
1316
+ assert_nothing_raised { @format_o.tabstop = "9" }
1317
+ assert_equal(9, @format_o.tabstop)
1318
+ assert_nothing_raised { @format_o.tabstop = "-2" }
1319
+ assert_equal(2, @format_o.tabstop)
1320
+ end
1321
+
1322
+ def test_text
1323
+ assert_nothing_raised { @format_o = Text::Format.new }
1324
+ assert_equal([], @format_o.text)
1325
+ assert_nothing_raised { @format_o.text = "Test Text" }
1326
+ assert_equal("Test Text", @format_o.text)
1327
+ assert_nothing_raised { @format_o.text = ["Line 1", "Line 2"] }
1328
+ assert_equal(["Line 1", "Line 2"], @format_o.text)
1329
+ end
1330
+
1331
+ def test_s_new
1332
+ # new(NilClass) { block }
1333
+ assert_nothing_raised do
1334
+ @format_o = Text::Format.new {
1335
+ self.text = "Test 1, 2, 3"
1336
+ }
1337
+ end
1338
+ assert_equal("Test 1, 2, 3", @format_o.text)
1339
+
1340
+ # new(Hash Symbols)
1341
+ assert_nothing_raised { @format_o = Text::Format.new(:columns => 72) }
1342
+ assert_equal(72, @format_o.columns)
1343
+
1344
+ # new(Hash String)
1345
+ assert_nothing_raised { @format_o = Text::Format.new('columns' => 72) }
1346
+ assert_equal(72, @format_o.columns)
1347
+
1348
+ # new(Hash) { block }
1349
+ assert_nothing_raised do
1350
+ @format_o = Text::Format.new('columns' => 80) {
1351
+ self.text = "Test 4, 5, 6"
1352
+ }
1353
+ end
1354
+ assert_equal("Test 4, 5, 6", @format_o.text)
1355
+ assert_equal(80, @format_o.columns)
1356
+
1357
+ # new(Text::Format)
1358
+ assert_nothing_raised do
1359
+ fo = Text::Format.new(@format_o)
1360
+ assert(fo == @format_o)
1361
+ end
1362
+
1363
+ # new(Text::Format) { block }
1364
+ assert_nothing_raised do
1365
+ fo = Text::Format.new(@format_o) { self.columns = 79 }
1366
+ assert(fo != @format_o)
1367
+ end
1368
+
1369
+ # new(String)
1370
+ assert_nothing_raised { @format_o = Text::Format.new("Test A, B, C") }
1371
+ assert_equal("Test A, B, C", @format_o.text)
1372
+
1373
+ # new(String) { block }
1374
+ assert_nothing_raised do
1375
+ @format_o = Text::Format.new("Test X, Y, Z") { self.columns = -5 }
1376
+ end
1377
+ assert_equal("Test X, Y, Z", @format_o.text)
1378
+ assert_equal(5, @format_o.columns)
1379
+ end
1380
+
1381
+ def test_center
1382
+ assert_nothing_raised { @format_o = Text::Format.new }
1383
+ assert_nothing_raised do
1384
+ ct = @format_o.center(GETTYSBURG.split("\n")).split("\n")
1385
+ assert_match(/^ Four score and seven years ago our fathers brought forth on this/, ct[0])
1386
+ assert_match(/^ not perish from the earth./, ct[-3])
1387
+ end
1388
+ end
1389
+
1390
+ def test_expand
1391
+ assert_nothing_raised { @format_o = Text::Format.new }
1392
+ assert_equal(" ", @format_o.expand("\t "))
1393
+ assert_nothing_raised { @format_o.tabstop = 4 }
1394
+ assert_equal(" ", @format_o.expand("\t "))
1395
+ end
1396
+
1397
+ def test_unexpand
1398
+ assert_nothing_raised { @format_o = Text::Format.new }
1399
+ assert_equal("\t ", @format_o.unexpand(" "))
1400
+ assert_nothing_raised { @format_o.tabstop = 4 }
1401
+ assert_equal("\t ", @format_o.unexpand(" "))
1402
+ end
1403
+
1404
+ def test_space_only
1405
+ assert_equal("", Text::Format.new.format(" "))
1406
+ assert_equal("", Text::Format.new.format("\n"))
1407
+ assert_equal("", Text::Format.new.format(" "))
1408
+ assert_equal("", Text::Format.new.format(" \n"))
1409
+ assert_equal("", Text::Format.new.paragraphs("\n"))
1410
+ assert_equal("", Text::Format.new.paragraphs(" "))
1411
+ assert_equal("", Text::Format.new.paragraphs(" "))
1412
+ assert_equal("", Text::Format.new.paragraphs(" \n"))
1413
+ assert_equal("", Text::Format.new.paragraphs(["\n"]))
1414
+ assert_equal("", Text::Format.new.paragraphs([" "]))
1415
+ assert_equal("", Text::Format.new.paragraphs([" "]))
1416
+ assert_equal("", Text::Format.new.paragraphs([" \n"]))
1417
+ end
1418
+
1419
+ def test_splendiferous
1420
+ h = nil
1421
+ test = "This is a splendiferous test"
1422
+ assert_nothing_raised { @format_o = Text::Format.new(:columns => 6, :left_margin => 0, :indent => 0, :first_indent => 0) }
1423
+ assert_match(/^splendiferous$/, @format_o.format(test))
1424
+ assert_nothing_raised { @format_o.hard_margins = true }
1425
+ assert_match(/^lendif$/, @format_o.format(test))
1426
+ assert_nothing_raised { h = Object.new }
1427
+ assert_nothing_raised do
1428
+ @format_o.split_rules = Text::Format::SPLIT_HYPHENATION
1429
+ class << h
1430
+ def hyphenate_to(word, size)
1431
+ return ["", word] if size < 2
1432
+ [word[0 ... size], word[size .. -1]]
1433
+ end
1434
+ end
1435
+ @format_o.hyphenator = h
1436
+ end
1437
+ assert_match(/^iferou$/, @format_o.format(test))
1438
+ assert_nothing_raised { h = Object.new }
1439
+ assert_nothing_raised do
1440
+ class << h
1441
+ def hyphenate_to(word, size, formatter)
1442
+ return ["", word] if word.size < formatter.columns
1443
+ [word[0 ... size], word[size .. -1]]
1444
+ end
1445
+ end
1446
+ @format_o.hyphenator = h
1447
+ end
1448
+ assert_match(/^ferous$/, @format_o.format(test))
1449
+ end
1450
+ end
1451
+ end