]> git.lyx.org Git - lyx.git/blob - src/VSpace.cpp
Comment
[lyx.git] / src / VSpace.cpp
1 /**
2  * \file VSpace.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Matthias Ettrich
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "VSpace.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "support/gettext.h"
19 #include "Length.h"
20 #include "Text.h"
21 #include "TextMetrics.h" // for defaultRowHeight()
22
23 #include "support/convert.h"
24 #include "support/lstrings.h"
25
26 #include "support/lassert.h"
27
28 #include <cstring>
29
30 using namespace std;
31 using namespace lyx::support;
32
33
34 namespace lyx {
35
36 namespace {
37
38 /// used to return numeric values in parsing vspace
39 double number[4] = { 0, 0, 0, 0 };
40
41 /// used to return unit types in parsing vspace
42 Length::UNIT unit[4] = {
43         Length::UNIT_NONE,
44         Length::UNIT_NONE,
45         Length::UNIT_NONE,
46         Length::UNIT_NONE
47 };
48
49 /// the current position in the number array
50 int number_index;
51 /// the current position in the unit array
52 int unit_index;
53
54 /// skip n characters of input
55 inline void lyx_advance(string & data, size_t n)
56 {
57         data.erase(0, n);
58 }
59
60
61 /// return true when the input is at the end
62 inline bool isEndOfData(string const & data)
63 {
64         return ltrim(data).empty();
65 }
66
67
68 /**
69  * nextToken -  return the next token in the input
70  * @param data input string
71  * @return a char representing the type of token returned
72  *
73  * The possible return values are :
74  *      +       stretch indicator for glue length
75  *      -       shrink indicator for glue length
76  *      n       a numeric value (stored in number array)
77  *      u       a unit type (stored in unit array)
78  *      E       parse error
79  */
80 char nextToken(string & data)
81 {
82         data = ltrim(data);
83
84         if (data.empty())
85                 return '\0';
86
87         if (data[0] == '+') {
88                 lyx_advance(data, 1);
89                 return '+';
90         }
91
92         if (prefixIs(data, "plus")) {
93                 lyx_advance(data, 4);
94                 return '+';
95         }
96
97         if (data[0] == '-') {
98                 lyx_advance(data, 1);
99                 return '-';
100         }
101
102         if (prefixIs(data, "minus")) {
103                 lyx_advance(data, 5);
104                 return '-';
105         }
106
107         size_t i = data.find_first_not_of("0123456789.");
108
109         if (i != 0) {
110                 if (number_index > 3)
111                         return 'E';
112
113                 string buffer;
114
115                 // we have found some number
116                 if (i == string::npos) {
117                         buffer = data;
118                         i = data.size() + 1;
119                 } else {
120                         buffer = data.substr(0, i);
121                 }
122
123                 lyx_advance(data, i);
124
125                 if (isStrDbl(buffer)) {
126                         number[number_index] = convert<double>(buffer);
127                         ++number_index;
128                         return 'n';
129                 }
130                 return 'E';
131         }
132
133         i = data.find_first_not_of("abcdefghijklmnopqrstuvwxyz%");
134         if (i != 0) {
135                 if (unit_index > 3)
136                         return 'E';
137
138                 string buffer;
139
140                 // we have found some alphabetical string
141                 if (i == string::npos) {
142                         buffer = data;
143                         i = data.size() + 1;
144                 } else {
145                         buffer = data.substr(0, i);
146                 }
147
148                 // possibly we have "mmplus" string or similar
149                 if (buffer.size() > 5 &&
150                                 (buffer.substr(2, 4) == string("plus") ||
151                                  buffer.substr(2, 5) == string("minus")))
152                 {
153                         lyx_advance(data, 2);
154                         unit[unit_index] = unitFromString(buffer.substr(0, 2));
155                 } else {
156                         lyx_advance(data, i);
157                         unit[unit_index] = unitFromString(buffer);
158                 }
159
160                 if (unit[unit_index] != Length::UNIT_NONE) {
161                         ++unit_index;
162                         return 'u';
163                 }
164                 return 'E';  // Error
165         }
166         return 'E';  // Error
167 }
168
169
170 /// latex representation of a vspace
171 struct LaTeXLength {
172         char const * pattern;
173         int  plus_val_index;
174         int  minus_val_index;
175         int  plus_uni_index;
176         int  minus_uni_index;
177 };
178
179
180 /// the possible formats for a vspace string
181 LaTeXLength table[] = {
182         { "nu",       0, 0, 0, 0 },
183         { "nu+nu",    2, 0, 2, 0 },
184         { "nu+nu-nu", 2, 3, 2, 3 },
185         { "nu+-nu",   2, 2, 2, 2 },
186         { "nu-nu",    0, 2, 0, 2 },
187         { "nu-nu+nu", 3, 2, 3, 2 },
188         { "nu-+nu",   2, 2, 2, 2 },
189         { "n+nu",     2, 0, 1, 0 },
190         { "n+n-nu",   2, 3, 1, 1 },
191         { "n+-nu",    2, 2, 1, 1 },
192         { "n-nu",     0, 2, 0, 1 },
193         { "n-n+nu",   3, 2, 1, 1 },
194         { "n-+nu",    2, 2, 1, 1 },
195         { "",         0, 0, 0, 0 }   // sentinel, must be empty
196 };
197
198
199 } // namespace anon
200
201 const char * stringFromUnit(int unit)
202 {
203         if (unit < 0 || unit > num_units)
204                 return 0;
205         return unit_name[unit];
206 }
207
208
209 bool isValidGlueLength(string const & data, GlueLength * result)
210 {
211         // This parser is table-driven.  First, it constructs a "pattern"
212         // that describes the sequence of tokens in "data".  For example,
213         // "n-nu" means: number, minus sign, number, unit.  As we go along,
214         // numbers and units are stored into static arrays.  Then, "pattern"
215         // is searched in the "table".  If it is found, the associated
216         // table entries tell us which number and unit should go where
217         // in the Length structure.  Example: if "data" has the "pattern"
218         // "nu+nu-nu", the associated table entries are "2, 3, 2, 3".
219         // That means, "plus_val" is the second number that was seen
220         // in the input, "minus_val" is the third number, and "plus_uni"
221         // and "minus_uni" are the second and third units, respectively.
222         // ("val" and "uni" are always the first items seen in "data".)
223         // This is the most elegant solution I could find -- a straight-
224         // forward approach leads to very long, tedious code that would be
225         // much harder to understand and maintain. (AS)
226
227         if (data.empty())
228                 return true;
229         string buffer = ltrim(data);
230
231         // To make isValidGlueLength recognize negative values as
232         // the first number this little hack is needed:
233         int val_sign = 1; // positive as default
234         switch (buffer[0]) {
235         case '-':
236                 lyx_advance(buffer, 1);
237                 val_sign = -1;
238                 break;
239         case '+':
240                 lyx_advance(buffer, 1);
241                 break;
242         default:
243                 break;
244         }
245         // end of hack
246
247         number_index = unit_index = 1;  // entries at index 0 are sentinels
248
249         // construct "pattern" from "data"
250         size_t const pattern_max_size = 20;
251         string pattern;
252         while (!isEndOfData(buffer)) {
253                 if (pattern.size() > pattern_max_size)
254                         return false;
255                 char const c = nextToken(buffer);
256                 if (c == 'E')
257                         return false;
258                 pattern.push_back(c);
259         }
260
261         // search "pattern" in "table"
262         size_t table_index = 0;
263         while (pattern != table[table_index].pattern) {
264                 ++table_index;
265                 if (!*table[table_index].pattern)
266                         return false;
267         }
268
269         // Get the values from the appropriate places.  If an index
270         // is zero, the corresponding array value is zero or UNIT_NONE,
271         // so we needn't check this.
272         if (result) {
273                 result->len_.value  (number[1] * val_sign);
274                 result->len_.unit   (unit[1]);
275                 result->plus_.value (number[table[table_index].plus_val_index]);
276                 result->plus_.unit  (unit  [table[table_index].plus_uni_index]);
277                 result->minus_.value(number[table[table_index].minus_val_index]);
278                 result->minus_.unit (unit  [table[table_index].minus_uni_index]);
279         }
280         return true;
281 }
282
283
284 bool isValidLength(string const & data, Length * result)
285 {
286         // This is a trimmed down version of isValidGlueLength.
287         // The parser may seem overkill for lengths without
288         // glue, but since we already have it, using it is
289         // easier than writing something from scratch.
290         if (data.empty())
291                 return true;
292
293         string   buffer = data;
294         int      pattern_index = 0;
295         char     pattern[3];
296
297         // To make isValidLength recognize negative values
298         // this little hack is needed:
299         int val_sign = 1; // positive as default
300         switch (buffer[0]) {
301         case '-':
302                 lyx_advance(buffer, 1);
303                 val_sign = -1;
304                 break;
305         case '+':
306                 lyx_advance(buffer, 1);
307                 // fall through
308         default:
309                 // no action
310                 break;
311         }
312         // end of hack
313
314         number_index = unit_index = 1;  // entries at index 0 are sentinels
315
316         // construct "pattern" from "data"
317         while (!isEndOfData(buffer)) {
318                 if (pattern_index > 2)
319                         return false;
320                 pattern[pattern_index] = nextToken(buffer);
321                 if (pattern[pattern_index] == 'E')
322                         return false;
323                 ++pattern_index;
324         }
325         pattern[pattern_index] = '\0';
326
327         // only the most basic pattern is accepted here
328         if (strcmp(pattern, "nu") != 0)
329                 return false;
330
331         // It _was_ a correct length string.
332         // Store away the values we found.
333         if (result) {
334                 result->val_  = number[1] * val_sign;
335                 result->unit_ = unit[1];
336         }
337         return true;
338 }
339
340
341 //
342 //  VSpace class
343 //
344
345 VSpace::VSpace()
346         : kind_(DEFSKIP), len_(), keep_(false)
347 {}
348
349
350 VSpace::VSpace(VSpaceKind k)
351         : kind_(k), len_(), keep_(false)
352 {}
353
354
355 VSpace::VSpace(Length const & l)
356         : kind_(LENGTH), len_(l), keep_(false)
357 {}
358
359
360 VSpace::VSpace(GlueLength const & l)
361         : kind_(LENGTH), len_(l), keep_(false)
362 {}
363
364
365 VSpace::VSpace(string const & data)
366         : kind_(DEFSKIP), len_(), keep_(false)
367 {
368         if (data.empty())
369                 return;
370
371         string input = rtrim(data);
372
373         size_t const length = input.length();
374
375         if (length > 1 && input[length - 1] == '*') {
376                 keep_ = true;
377                 input.erase(length - 1);
378         }
379
380         if (prefixIs(input, "defskip"))
381                 kind_ = DEFSKIP;
382         else if (prefixIs(input, "smallskip"))
383                 kind_ = SMALLSKIP;
384         else if (prefixIs(input, "medskip"))
385                 kind_ = MEDSKIP;
386         else if (prefixIs(input, "bigskip"))
387                 kind_ = BIGSKIP;
388         else if (prefixIs(input, "vfill"))
389                 kind_ = VFILL;
390         else if (isValidGlueLength(input, &len_))
391                 kind_ = LENGTH;
392         else if (isStrDbl(input)) {
393                 // This last one is for reading old .lyx files
394                 // without units in added_space_top/bottom.
395                 // Let unit default to centimeters here.
396                 kind_ = LENGTH;
397                 len_  = GlueLength(Length(convert<double>(input), Length::CM));
398         }
399 }
400
401
402 bool VSpace::operator==(VSpace const & other) const
403 {
404         if (kind_ != other.kind_)
405                 return false;
406
407         if (kind_ != LENGTH)
408                 return this->keep_ == other.keep_;
409
410         if (len_ != other.len_)
411                 return false;
412
413         return keep_ == other.keep_;
414 }
415
416
417 string const VSpace::asLyXCommand() const
418 {
419         string result;
420         switch (kind_) {
421         case DEFSKIP:   result = "defskip";      break;
422         case SMALLSKIP: result = "smallskip";    break;
423         case MEDSKIP:   result = "medskip";      break;
424         case BIGSKIP:   result = "bigskip";      break;
425         case VFILL:     result = "vfill";        break;
426         case LENGTH:    result = len_.asString(); break;
427         }
428         if (keep_)
429                 result += '*';
430         return result;
431 }
432
433
434 string const VSpace::asLatexCommand(BufferParams const & params) const
435 {
436         switch (kind_) {
437         case DEFSKIP:
438                 return params.getDefSkip().asLatexCommand(params);
439
440         case SMALLSKIP:
441                 return keep_ ? "\\vspace*{\\smallskipamount}" : "\\smallskip{}";
442
443         case MEDSKIP:
444                 return keep_ ? "\\vspace*{\\medskipamount}" : "\\medskip{}";
445
446         case BIGSKIP:
447                 return keep_ ? "\\vspace*{\\bigskipamount}" : "\\bigskip{}";
448
449         case VFILL:
450                 return keep_ ? "\\vspace*{\\fill}" : "\\vfill{}";
451
452         case LENGTH:
453                 return keep_ ? "\\vspace*{" + len_.asLatexString() + '}'
454                         : "\\vspace{" + len_.asLatexString() + '}';
455
456         default:
457                 LASSERT(false, /**/);
458                 return string();
459         }
460 }
461
462
463 docstring const VSpace::asGUIName() const
464 {
465         docstring result;
466         switch (kind_) {
467         case DEFSKIP:
468                 result = _("Default skip");
469                 break;
470         case SMALLSKIP:
471                 result = _("Small skip");
472                 break;
473         case MEDSKIP:
474                 result = _("Medium skip");
475                 break;
476         case BIGSKIP:
477                 result = _("Big skip");
478                 break;
479         case VFILL:
480                 result = _("Vertical fill");
481                 break;
482         case LENGTH:
483                 result = from_ascii(len_.asString());
484                 break;
485         }
486         if (keep_)
487                 result += ", " + _("protected");
488         return result;
489 }
490
491
492 string VSpace::asHTMLLength() const 
493 {
494         string result;
495         switch (kind_) {
496                 case DEFSKIP:   result = "2ex"; break;
497                 case SMALLSKIP: result = "1ex"; break;
498                 case MEDSKIP:   result = "3ex"; break;
499                 case BIGSKIP:   result = "5ex"; break;
500                 case LENGTH: {
501                         Length tmp = len_.len();
502                         if (tmp.value() > 0)
503                                 result = tmp.asHTMLString();
504                 }
505                 case VFILL:     break;
506         }
507         return result;
508 }
509
510 int VSpace::inPixels(BufferView const & bv) const
511 {
512         // Height of a normal line in pixels (zoom factor considered)
513         int const default_height = defaultRowHeight();
514
515         switch (kind_) {
516
517         case DEFSKIP:
518                 return bv.buffer().params().getDefSkip().inPixels(bv);
519
520         // This is how the skips are normally defined by LateX.
521         // But there should be some way to change this per document.
522         case SMALLSKIP:
523                 return default_height / 4;
524
525         case MEDSKIP:
526                 return default_height / 2;
527
528         case BIGSKIP:
529                 return default_height;
530
531         case VFILL:
532                 // leave space for the vfill symbol
533                 return 3 * default_height;
534
535         case LENGTH:
536                 return len_.len().inPixels(bv.workWidth());
537
538         default:
539                 LASSERT(false, /**/);
540                 return 0;
541         }
542 }
543
544
545 } // namespace lyx