]> git.lyx.org Git - lyx.git/blob - src/vspace.C
69fb9006b72fd8be7889ad42ce334841db13c3ef
[lyx.git] / src / vspace.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *      
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation "vspace.h"
15 #endif
16
17 #include <stdio.h>
18
19 #include "lyx_main.h"
20 #include "buffer.h"
21 #include "vspace.h"
22 #include "lyxrc.h"
23 #include "lyxtext.h"
24 #include "BufferView.h"
25 #include "support/lstrings.h"
26
27
28 namespace {
29
30 /*  length units
31  */
32
33 int const num_units = LyXLength::UNIT_NONE;
34
35 // I am not sure if "mu" should be possible to select (Lgb)
36 char const * unit_name[num_units] = { "sp", "pt", "bp", "dd",
37                                       "mm", "pc", "cc", "cm",
38                                       "in", "ex", "em", "mu",
39                                       "%",  "c%", "p%", "l%" };
40
41
42 /*  The following static items form a simple scanner for
43  *  length strings, used by isValid[Glue]Length.  See comments there.
44  */
45 double           number[4] = { 0, 0, 0, 0 };
46 LyXLength::UNIT unit[4]   = { LyXLength::UNIT_NONE,
47                               LyXLength::UNIT_NONE,
48                               LyXLength::UNIT_NONE,
49                               LyXLength::UNIT_NONE };
50 int number_index;
51 int unit_index;
52
53
54 inline
55 void lyx_advance(string & data, string::size_type n)
56 {
57         data.erase(0, n);
58 }
59
60
61 inline
62 bool isEndOfData(string const & data)
63 {
64         return frontStrip(data).empty();
65 }
66
67
68 char nextToken(string & data)
69 {
70         data = frontStrip(data);
71         if (data.empty())
72                 return '\0';
73         else if (data[0] == '+') {
74                 lyx_advance(data, 1);
75                 return '+';
76         } else if (prefixIs(data, "plus")) {
77                 lyx_advance(data, 4);
78                 return '+';
79         } else if (data[0] == '-') {
80                 lyx_advance(data, 1);
81                 return '-';
82         } else if (prefixIs(data, "minus")) {
83                 lyx_advance(data, 5);
84                 return '-';
85         } else {
86                 string::size_type i = data.find_first_not_of("0123456789.");
87
88                 if (i != 0) {
89                         if (number_index > 3) return 'E';
90
91                         string buffer;
92                 
93                         // we have found some number
94                         if (i == string::npos) {
95                                 buffer = data;
96                                 i = data.size() + 1;
97                         } else
98                                 buffer = data.substr(0, i);
99
100                         lyx_advance(data, i);
101
102                         if (isStrDbl(buffer)) {
103                                 number[number_index] = strToDbl(buffer);
104                                 ++number_index;
105                                 return 'n';
106                         } else return 'E';
107                 }
108                 
109                 i = data.find_first_not_of("abcdefghijklmnopqrstuvwxyz%");
110                 if (i != 0) {
111                         if (unit_index > 3) return 'E';
112
113                         string buffer;
114                 
115                         // we have found some alphabetical string
116                         if (i == string::npos) {
117                                 buffer = data;
118                                 i = data.size() + 1;
119                         } else
120                                 buffer = data.substr(0, i);
121
122                         // possibly we have "mmplus" string or similar
123                         if (buffer.size() > 5 && (buffer.substr(2,4) == string("plus") || buffer.substr(2,5) == string("minus"))) {
124                                 lyx_advance(data, 2);
125                                 unit[unit_index] = unitFromString(buffer.substr(0, 2));
126                         } else {
127                                 lyx_advance(data, i);
128                                 unit[unit_index] = unitFromString(buffer);
129                         }
130
131                         if (unit[unit_index] != LyXLength::UNIT_NONE) {
132                                 ++unit_index;
133                                 return 'u';
134                         } else return 'E';  // Error
135                 }
136                 return 'E';  // Error
137         }
138 }
139
140
141 struct LaTeXLength {
142         char const * pattern;
143         int  plus_val_index;
144         int  minus_val_index;
145         int  plus_uni_index;
146         int  minus_uni_index;
147 };
148
149
150 LaTeXLength table[] = {
151         { "nu",       0, 0, 0, 0 },
152         { "nu+nu",    2, 0, 2, 0 },
153         { "nu+nu-nu", 2, 3, 2, 3 },
154         { "nu+-nu",   2, 2, 2, 2 },
155         { "nu-nu",    0, 2, 0, 2 },
156         { "nu-nu+nu", 3, 2, 3, 2 },
157         { "nu-+nu",   2, 2, 2, 2 },
158         { "n+nu",     2, 0, 1, 0 },
159         { "n+n-nu",   2, 3, 1, 1 },
160         { "n+-nu",    2, 2, 1, 1 },
161         { "n-nu",     0, 2, 0, 1 },
162         { "n-n+nu",   3, 2, 1, 1 },
163         { "n-+nu",    2, 2, 1, 1 },
164         { "",         0, 0, 0, 0 }   // sentinel, must be empty
165 };
166
167 } // namespace anon
168
169 const char * stringFromUnit(int unit)
170 {
171         if (unit < 0 || unit >= num_units)
172                 return 0;
173         return unit_name[unit];
174 }
175
176
177 bool isValidGlueLength(string const & data, LyXGlueLength * result)
178 {
179         // This parser is table-driven.  First, it constructs a "pattern"
180         // that describes the sequence of tokens in "data".  For example,
181         // "n-nu" means: number, minus sign, number, unit.  As we go along,
182         // numbers and units are stored into static arrays.  Then, "pattern"
183         // is searched in the "table".  If it is found, the associated
184         // table entries tell us which number and unit should go where
185         // in the LyXLength structure.  Example: if "data" has the "pattern"
186         // "nu+nu-nu", the associated table entries are "2, 3, 2, 3".
187         // That means, "plus_val" is the second number that was seen
188         // in the input, "minus_val" is the third number, and "plus_uni"
189         // and "minus_uni" are the second and third units, respectively.
190         // ("val" and "uni" are always the first items seen in "data".)
191         // This is the most elegant solution I could find -- a straight-
192         // forward approach leads to very long, tedious code that would be
193         // much harder to understand and maintain. (AS)
194
195         if (data.empty())
196                 return true;
197         string buffer = frontStrip(data);
198
199         // To make isValidGlueLength recognize negative values as
200         // the first number this little hack is needed:
201         int val_sign = 1; // positive as default
202         switch (buffer[0]) {
203         case '-':
204                 lyx_advance(buffer, 1);
205                 val_sign = -1;
206                 break;
207         case '+':
208                 lyx_advance(buffer, 1);
209                 // fall through
210         default:
211                 // no action
212                 break;
213         }
214         // end of hack
215         
216         int  pattern_index = 0;
217         int  table_index = 0;
218         char pattern[20];
219
220         number_index = 1;
221         unit_index = 1;  // entries at index 0 are sentinels
222
223         // construct "pattern" from "data"
224         while (!isEndOfData (buffer)) {
225                 if (pattern_index > 20) return false;
226                 pattern[pattern_index] = nextToken (buffer);
227                 if (pattern[pattern_index] == 'E') return false;
228                 ++pattern_index;
229         }
230         pattern[pattern_index] = '\0';
231
232         // search "pattern" in "table"
233         table_index = 0;
234         while (compare(pattern, table[table_index].pattern)) {
235                 ++table_index;
236                 if (!*table[table_index].pattern)
237                         return false;
238         }
239         
240         // Get the values from the appropriate places.  If an index
241         // is zero, the corresponding array value is zero or UNIT_NONE,
242         // so we needn't check this.
243         if (result) {
244                 result->val_        = number[1] * val_sign;
245                 result->unit_       = unit[1];
246                 result->plus_val_   = number[table[table_index].plus_val_index];
247                 result->minus_val_  = number[table[table_index].minus_val_index];
248                 result->plus_unit_  = unit  [table[table_index].plus_uni_index];
249                 result->minus_unit_ = unit  [table[table_index].minus_uni_index];
250         }
251         return true;
252 }
253
254
255 bool isValidLength(string const & data, LyXLength * result)
256 {
257         /// This is a trimmed down version of isValidGlueLength.
258         /// The parser may seem overkill for lengths without
259         /// glue, but since we already have it, using it is
260         /// easier than writing something from scratch.
261         if (data.empty())
262                 return true;
263
264         string   buffer = data;
265         int      pattern_index = 0;
266         char     pattern[3];
267
268         // To make isValidLength recognize negative values
269         // this little hack is needed:
270         int val_sign = 1; // positive as default
271         switch (buffer[0]) {
272         case '-':
273                 lyx_advance(buffer, 1);
274                 val_sign = -1;
275                 break;
276         case '+':
277                 lyx_advance(buffer, 1);
278                 // fall through
279         default:
280                 // no action
281                 break;
282         }
283         // end of hack
284         
285         number_index = unit_index = 1;  // entries at index 0 are sentinels
286
287         // construct "pattern" from "data"
288         while (!isEndOfData (buffer)) {
289                 if (pattern_index > 2)
290                         return false;
291                 pattern[pattern_index] = nextToken (buffer);
292                 if (pattern[pattern_index] == 'E')
293                         return false;
294                 ++pattern_index;
295         }
296         pattern[pattern_index] = '\0';
297
298         // only the most basic pattern is accepted here
299         if (compare(pattern, "nu") != 0) return false;          
300         
301         // It _was_ a correct length string.
302         // Store away the values we found.
303         if (result) {
304                 result->val_  = number[1] * val_sign;
305                 result->unit_ = unit[1];
306         }
307         return true;
308 }
309
310
311
312
313 //
314 // LyXLength
315 //
316
317 LyXLength::LyXLength()
318         : val_(0), unit_(LyXLength::PT)
319 {}
320
321
322 LyXLength::LyXLength(double v, LyXLength::UNIT u)
323         : val_(v), unit_(u)
324 {}
325
326
327 LyXLength::LyXLength(string const & data)
328 {
329         LyXLength tmp;
330         
331         if (!isValidLength (data, &tmp))
332                 return; // should raise an exception
333
334         val_  = tmp.val_;
335         unit_ = tmp.unit_;
336 }
337
338
339 string const LyXLength::asString() const
340 {
341         ostringstream buffer;
342         buffer << val_ << unit_name[unit_]; // setw?
343         return buffer.str().c_str();
344 }
345
346
347 string const LyXLength::asLatexString() const
348 {
349         ostringstream buffer;
350         switch(unit_) {
351         case PW:
352         case PE:
353             buffer << abs(static_cast<int>(val_/100)) << "."
354                                 << abs(static_cast<int>(val_)%100) << "\\columnwidth";
355             break;
356         case PP:
357             buffer << abs(static_cast<int>(val_/100)) << "."
358                                 << abs(static_cast<int>(val_)%100) << "\\pagewidth";
359             break;
360         case PL:
361             buffer << abs(static_cast<int>(val_/100)) << "."
362                                 << abs(static_cast<int>(val_)%100) << "\\linewidth";
363             break;
364         default:
365             buffer << val_ << unit_name[unit_]; // setw?
366             break;
367         }
368         return buffer.str().c_str();
369 }
370
371
372 double LyXLength::value() const
373 {
374         return val_;
375 }
376
377
378 LyXLength::UNIT LyXLength::unit() const
379 {
380         return unit_;
381 }
382
383
384 bool operator==(LyXLength const & l1, LyXLength const & l2)
385 {
386         return l1.value() == l2.value() && l1.unit() == l2.unit();
387 }
388         
389
390 LyXLength::UNIT unitFromString (string const & data)
391 {
392         int i = 0;
393         while (i < num_units && data != unit_name[i])
394                 ++i;
395         return static_cast<LyXLength::UNIT>(i);
396 }
397
398
399
400 //
401 // LyXGlueLength
402 //
403
404
405 LyXGlueLength::LyXGlueLength(
406                         double v,  LyXLength::UNIT u,
407                         double pv, LyXLength::UNIT pu,
408                         double mv, LyXLength::UNIT mu)
409         : LyXLength(v, u),
410           plus_val_(pv),  minus_val_(mv),
411           plus_unit_(pu), minus_unit_(mu)
412 {}
413
414
415 LyXGlueLength::LyXGlueLength(string const & data)
416 {
417         LyXGlueLength tmp(0.0, PT);
418
419         // we should really raise exception here
420         if (!isValidGlueLength(data, &tmp))
421                 ;
422
423         val_        = tmp.val_;
424         unit_       = tmp.unit_;
425         plus_val_   = tmp.plus_val_;
426         plus_unit_  = tmp.plus_unit_;
427         minus_val_  = tmp.minus_val_;
428         minus_unit_ = tmp.minus_unit_;
429 }
430
431
432 string const LyXGlueLength::asString() const
433 {
434         ostringstream buffer;
435
436         if (plus_val_ != 0.0)
437                 if (minus_val_ != 0.0)
438                         if (unit_ == plus_unit_ && unit_ == minus_unit_)
439                                 if (plus_val_ == minus_val_)
440                                         buffer << val_ << "+-"
441                                                << plus_val_ << unit_name[unit_];
442                                 else
443                                         buffer << val_
444                                                << '+' << plus_val_
445                                                << '-' << minus_val_
446                                                << unit_name[unit_];
447                         else
448                                 if (plus_unit_ == minus_unit_
449                                     && plus_val_ == minus_val_)
450                                         buffer << val_ << unit_name[unit_]
451                                                << "+-" << plus_val_
452                                                << unit_name[plus_unit_];
453         
454                                 else
455                                         buffer << val_ << unit_name[unit_]
456                                                << '+' << plus_val_
457                                                << unit_name[plus_unit_]
458                                                << '-' << minus_val_
459                                                << unit_name[minus_unit_];
460                 else
461                         if (unit_ == plus_unit_)
462                                 buffer << val_ << '+' << plus_val_
463                                        << unit_name[unit_];
464                         else
465                                 buffer << val_ << unit_name[unit_]
466                                        << '+' << plus_val_
467                                        << unit_name[plus_unit_];
468         
469         else
470                 if (minus_val_ != 0.0)
471                         if (unit_ == minus_unit_)
472                                 buffer << val_ << '-' << minus_val_
473                                        << unit_name[unit_];
474         
475                         else
476                                 buffer << val_ << unit_name[unit_]
477                                        << '-' << minus_val_
478                                        << unit_name[minus_unit_];
479                 else
480                         buffer << val_ << unit_name[unit_];
481
482         return buffer.str().c_str();
483 }
484
485
486 string const LyXGlueLength::asLatexString() const
487 {
488         ostringstream buffer;
489
490         if (plus_val_ != 0.0)
491                 if (minus_val_ != 0.0)
492                         buffer << val_ << unit_name[unit_]
493                                << " plus "
494                                << plus_val_ << unit_name[plus_unit_]
495                                << " minus "
496                                << minus_val_ << unit_name[minus_unit_];
497                 else
498                         buffer << val_ << unit_name[unit_]
499                                << " plus "
500                                << plus_val_ << unit_name[plus_unit_];
501         else
502                 if (minus_val_ != 0.0)
503                         buffer << val_ << unit_name[unit_]
504                                << " minus "
505                                << minus_val_ << unit_name[minus_unit_];
506                 else
507                         buffer << val_ << unit_name[unit_];
508
509         return buffer.str().c_str();
510 }
511
512
513 double LyXGlueLength::plusValue() const
514 {
515         return plus_val_;
516 }
517
518
519 LyXLength::UNIT LyXGlueLength::plusUnit() const
520 {
521         return plus_unit_;
522 }
523
524
525 double LyXGlueLength::minusValue() const
526 {
527         return minus_val_;
528 }
529
530
531 LyXLength::UNIT LyXGlueLength::minusUnit() const
532 {
533         return minus_unit_;
534 }
535
536
537 bool operator==(LyXGlueLength const & l1, LyXGlueLength const & l2)
538 {
539         return l1.value() == l2.value()
540                 && l1.unit() == l2.unit()
541                 && l1.plusValue() == l2.plusValue()
542                 && l1.plusUnit() == l2.plusUnit()
543                 && l1.minusValue() == l2.minusValue()
544                 && l1.minusUnit() == l2.minusUnit();
545 }
546
547
548
549
550 //
551 //  VSpace class
552 //
553
554 VSpace::VSpace()
555         : kind_(NONE), len_(0.0, LyXLength::PT), keep_(false)
556 {}
557
558
559 VSpace::VSpace(vspace_kind k)
560         : kind_(k), len_(0.0, LyXLength::PT), keep_(false)
561 {}
562
563
564 VSpace::VSpace(LyXGlueLength l)
565         : kind_(LENGTH), len_(l), keep_(false)
566 {}
567
568
569 VSpace::VSpace(double v, LyXLength::UNIT u)
570         : kind_(LENGTH), len_(v, u), keep_(false)
571 {}
572
573
574 VSpace::VSpace(string const & data)
575         : kind_(NONE), len_(0.0, LyXLength::PT), keep_(false)
576 {
577         if (data.empty())
578                 return;
579         double value;
580         string input  = strip(data);
581
582         string::size_type const length = input.length();
583
584         if (length > 1 && input[length-1] == '*') {
585                 keep_ = true;
586                 input.erase(length - 1);
587         }
588
589         if      (prefixIs (input, "defskip"))    kind_ = DEFSKIP;
590         else if (prefixIs (input, "smallskip"))  kind_ = SMALLSKIP;
591         else if (prefixIs (input, "medskip"))    kind_ = MEDSKIP;
592         else if (prefixIs (input, "bigskip"))    kind_ = BIGSKIP;
593         else if (prefixIs (input, "vfill"))      kind_ = VFILL;
594         else if (isValidGlueLength(input, &len_)) kind_ = LENGTH;
595         else if (sscanf(input.c_str(), "%lf", &value) == 1) {
596                 // This last one is for reading old .lyx files
597                 // without units in added_space_top/bottom.
598                 // Let unit default to centimeters here.
599                 kind_ = LENGTH;
600                 len_  = LyXGlueLength(value, LyXLength::CM);
601         }
602 }
603
604
605 VSpace::vspace_kind VSpace::kind() const
606 {
607         return kind_;
608 }
609
610
611 LyXGlueLength VSpace::length() const
612 {
613         return len_;
614 }
615
616
617 bool VSpace::keep() const
618 {
619         return keep_;
620 }
621
622
623 void VSpace::setKeep(bool val)
624 {
625         keep_ = val;
626 }
627
628
629 bool VSpace::operator==(VSpace const & other) const
630 {
631         if (kind_ != other.kind_)
632                 return false;
633
634         if (kind_ != LENGTH)
635                 return this->keep_ == other.keep_;
636
637         if (len_ != other.len_)
638                 return false;
639
640         return keep_ == other.keep_;
641 }
642
643
644 string const VSpace::asLyXCommand() const
645 {
646         string result;
647         switch (kind_) {
648         case NONE:      break;
649         case DEFSKIP:   result = "defskip";      break;
650         case SMALLSKIP: result = "smallskip";    break;
651         case MEDSKIP:   result = "medskip";      break;
652         case BIGSKIP:   result = "bigskip";      break;
653         case VFILL:     result = "vfill";        break;
654         case LENGTH:    result = len_.asString(); break;
655         }
656         if (keep_ && kind_ != NONE && kind_ != DEFSKIP)
657                 result += '*';
658         return result;
659 }
660
661
662 string const VSpace::asLatexCommand(BufferParams const & params) const
663 {
664         switch (kind_) {
665         case NONE:      return string();
666         case DEFSKIP:
667                 return params.getDefSkip().asLatexCommand(params);
668         case SMALLSKIP: return keep_ ? "\\vspace*{\\smallskipamount}"
669                                 : "\\smallskip{}";
670         case MEDSKIP:   return keep_ ? "\\vspace*{\\medskipamount}"
671                                 : "\\medskip{}";
672         case BIGSKIP:   return keep_ ? "\\vspace*{\\bigskipamount}"
673                                 : "\\bigskip{}";
674         case VFILL:     return keep_ ? "\\vspace*{\\fill}"
675                                 : "\\vfill{}";
676         case LENGTH:    return keep_ ? "\\vspace*{" + len_.asLatexString() + '}'
677                                 : "\\vspace{" + len_.asLatexString() + '}';
678         }
679         return string();  // should never be reached
680 }
681
682
683 int VSpace::inPixels(BufferView * bv) const
684 {
685         // Height of a normal line in pixels (zoom factor considered)
686         int height = bv->text->defaultHeight(); // [pixels]
687         int skip  = 0;
688         int width = bv->workWidth();
689
690         if (kind_ == DEFSKIP)
691                 skip = bv->buffer()->params.getDefSkip().inPixels(bv);
692
693         return inPixels(height, skip, width);
694 }
695
696
697 int VSpace::inPixels(int default_height, int default_skip, int default_width)
698         const
699 {
700         // Height of a normal line in pixels (zoom factor considered)
701         int height = default_height; // [pixels]
702         
703         // Zoom factor specified by user in percent
704         double const zoom = lyxrc.zoom / 100.0; // [percent]
705
706         // DPI setting for monitor: pixels/inch
707         double const dpi = lyxrc.dpi; // screen resolution [pixels/inch]
708
709         // We want the result in pixels
710         double result;
711         double value;
712
713         switch (kind_) {
714         case NONE:
715                 return 0;
716
717         case DEFSKIP:
718                 return default_skip;
719
720                 // This is how the skips are normally defined by
721                 // LateX.  But there should be some way to change
722                 // this per document.
723         case SMALLSKIP: return height / 4;
724         case MEDSKIP:   return height / 2;
725         case BIGSKIP:   return height;
726         case VFILL:     return 3 * height;
727                 // leave space for the vfill symbol
728         case LENGTH:
729                 // Pixel values are scaled so that the ratio
730                 // between lengths and font sizes on the screen
731                 // is the same as on paper.
732
733                 // we don't care about sign of value, we
734                 // display negative space with text too
735                 result = 0.0;
736                 value  = len_.value();
737                 int val_sign = value < 0.0 ? -1 : 1;
738                 
739                 switch (len_.unit()) {
740                 case LyXLength::SP:
741                         // Scaled point: sp = 1/65536 pt
742                         result = zoom * dpi * value
743                                 / (72.27 * 65536); // 4736286.7
744                         break;
745                 case LyXLength::PT:
746                         // Point: 1 pt = 1/72.27 inch
747                         result = zoom * dpi * value
748                                 / 72.27; // 72.27
749                         break;
750                 case LyXLength::BP:
751                         // Big point: 1 bp = 1/72 inch
752                         result = zoom * dpi * value
753                                 / 72; // 72
754                         break;
755                 case LyXLength::DD:
756                         // Didot: 1157dd = 1238 pt?
757                         result = zoom * dpi * value
758                                 / (72.27 / (0.376 * 2.845)); // 67.559735
759                         break;
760                 case LyXLength::MM:
761                         // Millimeter: 1 mm = 1/25.4 inch
762                         result = zoom * dpi * value
763                                 / 25.4; // 25.4
764                         break;
765                 case LyXLength::PC:
766                         // Pica: 1 pc = 12 pt
767                         result = zoom * dpi * value
768                                 / (72.27 / 12); // 6.0225
769                         break;
770                 case LyXLength::CC:
771                         // Cicero: 1 cc = 12 dd
772                         result = zoom * dpi * value
773                                 / (72.27 / (12 * 0.376 * 2.845)); // 5.6299779
774                         break;
775                 case LyXLength::CM:
776                         // Centimeter: 1 cm = 1/2.54 inch
777                         result = zoom * dpi * value
778                                 / 2.54; // 2.54
779                         break;
780                 case LyXLength::IN:
781                         // Inch
782                         result = zoom * dpi * value;
783                         break;
784                 case LyXLength::EX:
785                         // Ex: The height of an "x"
786                         result = zoom * value * height / 2; // what to / width?
787                         break;
788                 case LyXLength::EM: // what to / width?
789                         // Em: The width of an "m"
790                         result = zoom * value * height / 2; // Why 2?
791                         break;
792                 case LyXLength::MU: // This is probably only allowed in
793                         // math mode
794                         result = zoom * value * height;
795                         break;
796                 case LyXLength::PW: // Always % of workarea
797                 case LyXLength::PE:
798                 case LyXLength::PP:
799                 case LyXLength::PL:
800                         result = value * default_width / 100;
801                         break;
802                 case LyXLength::UNIT_NONE:
803                         result = 0;  // this cannot happen
804                         break;
805                 }
806                 return static_cast<int>(result * val_sign + 0.5);
807         }
808         return 0; // never reached
809 }