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