]> git.lyx.org Git - lyx.git/blob - src/Counters.cpp
First version of separate translation machinery for strings that go into
[lyx.git] / src / Counters.cpp
1 /**
2  * \file Counters.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Martin Vermeer
8  * \author André Pönitz
9  * \author Richard Heck (roman numerals)
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "Counters.h"
17 #include "Layout.h"
18 #include "Lexer.h"
19
20 #include "support/convert.h"
21 #include "support/debug.h"
22 #include "support/gettext.h"
23 #include "support/lassert.h"
24 #include "support/lstrings.h"
25
26 #include <algorithm>
27 #include <sstream>
28
29 using namespace std;
30 using namespace lyx::support;
31
32 namespace lyx {
33
34
35 Counter::Counter()
36 {
37         reset();
38 }
39
40
41 Counter::Counter(docstring const & mc, docstring const & ls,  
42                 docstring const & lsa)
43         : master_(mc), labelstring_(ls), labelstringappendix_(lsa)
44 {
45         reset();
46 }
47
48
49 bool Counter::read(Lexer & lex)
50 {
51         enum {
52                 CT_WITHIN = 1,
53                 CT_LABELSTRING,
54                 CT_LABELSTRING_APPENDIX,
55                 CT_PRETTYFORMAT,
56                 CT_END
57         };
58
59         LexerKeyword counterTags[] = {
60                 { "end", CT_END },
61                 { "labelstring", CT_LABELSTRING },
62                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
63                 { "prettyformat", CT_PRETTYFORMAT },
64                 { "within", CT_WITHIN }
65         };
66
67         lex.pushTable(counterTags);
68
69         bool getout = false;
70         while (!getout && lex.isOK()) {
71                 int le = lex.lex();
72                 switch (le) {
73                         case Lexer::LEX_UNDEF:
74                                 lex.printError("Unknown counter tag `$$Token'");
75                                 continue;
76                         default: 
77                                 break;
78                 }
79                 switch (le) {
80                         case CT_WITHIN:
81                                 lex.next();
82                                 master_ = lex.getDocString();
83                                 if (master_ == "none")
84                                         master_.erase();
85                                 break;
86                         case CT_PRETTYFORMAT:
87                                 lex.next();
88                                 prettyformat_ = lex.getDocString();
89                                 break;
90                         case CT_LABELSTRING:
91                                 lex.next();
92                                 labelstring_ = lex.getDocString();
93                                 labelstringappendix_ = labelstring_;
94                                 break;
95                         case CT_LABELSTRING_APPENDIX:
96                                 lex.next();
97                                 labelstringappendix_ = lex.getDocString();
98                                 break;
99                         case CT_END:
100                                 getout = true;
101                                 break;
102                 }
103         }
104
105         // Here if have a full counter if getout == true
106         if (!getout)
107                 LYXERR0("No End tag found for counter!");
108         lex.popTable();
109         return getout;
110 }
111
112 void Counter::set(int v)
113 {
114         value_ = v;
115 }
116
117
118 void Counter::addto(int v)
119 {
120         value_ += v;
121 }
122
123
124 int Counter::value() const
125 {
126         return value_;
127 }
128
129
130 void Counter::step()
131 {
132         ++value_;
133 }
134
135
136 void Counter::reset()
137 {
138         value_ = 0;
139 }
140
141
142 docstring const & Counter::master() const
143 {
144         return master_;
145 }
146
147
148 bool Counter::checkAndRemoveMaster(docstring const & cnt)
149 {
150         if (master_ != cnt)
151                 return false;
152         master_ = docstring();
153         return true;
154 }
155
156
157 docstring const & Counter::labelString(bool in_appendix) const
158 {
159         return in_appendix ? labelstringappendix_ : labelstring_;
160 }
161
162
163 Counter::StringMap & Counter::flatLabelStrings(bool in_appendix) const
164 {
165         return in_appendix ? flatlabelstringappendix_ : flatlabelstring_;
166 }
167
168
169 Counters::Counters() : appendix_(false), subfloat_(false)
170 {
171         layout_stack_.push_back(0);
172         counter_stack_.push_back(from_ascii(""));
173 }
174
175
176 void Counters::newCounter(docstring const & newc,
177                           docstring const & masterc, 
178                           docstring const & ls,
179                           docstring const & lsa)
180 {
181         if (!masterc.empty() && !hasCounter(masterc)) {
182                 lyxerr << "Master counter does not exist: "
183                        << to_utf8(masterc)
184                        << endl;
185                 return;
186         }
187         counterList_[newc] = Counter(masterc, ls, lsa);
188 }
189
190
191 bool Counters::hasCounter(docstring const & c) const
192 {
193         return counterList_.find(c) != counterList_.end();
194 }
195
196
197 bool Counters::read(Lexer & lex, docstring const & name, bool makenew)
198 {
199         if (hasCounter(name)) {
200                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
201                 return counterList_[name].read(lex);
202         }
203
204         LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
205         Counter cnt;
206         bool success = cnt.read(lex);
207         // if makenew is false, we will just discard what we read
208         if (success && makenew)
209                 counterList_[name] = cnt;
210         else if (!success)
211                 LYXERR0("Error reading counter `" << name << "'!");
212         return success;
213 }
214
215
216 void Counters::set(docstring const & ctr, int const val)
217 {
218         CounterList::iterator const it = counterList_.find(ctr);
219         if (it == counterList_.end()) {
220                 lyxerr << "set: Counter does not exist: "
221                        << to_utf8(ctr) << endl;
222                 return;
223         }
224         it->second.set(val);
225 }
226
227
228 void Counters::addto(docstring const & ctr, int const val)
229 {
230         CounterList::iterator const it = counterList_.find(ctr);
231         if (it == counterList_.end()) {
232                 lyxerr << "addto: Counter does not exist: "
233                        << to_utf8(ctr) << endl;
234                 return;
235         }
236         it->second.addto(val);
237 }
238
239
240 int Counters::value(docstring const & ctr) const
241 {
242         CounterList::const_iterator const cit = counterList_.find(ctr);
243         if (cit == counterList_.end()) {
244                 lyxerr << "value: Counter does not exist: "
245                        << to_utf8(ctr) << endl;
246                 return 0;
247         }
248         return cit->second.value();
249 }
250
251
252 void Counters::step(docstring const & ctr, UpdateType utype)
253 {
254         CounterList::iterator it = counterList_.find(ctr);
255         if (it == counterList_.end()) {
256                 lyxerr << "step: Counter does not exist: "
257                        << to_utf8(ctr) << endl;
258                 return;
259         }
260
261         it->second.step();
262         if (utype == OutputUpdate) {
263                 LASSERT(!counter_stack_.empty(), /* */);
264                 counter_stack_.pop_back();
265                 counter_stack_.push_back(ctr);
266         }
267         it = counterList_.begin();
268         CounterList::iterator const end = counterList_.end();
269         for (; it != end; ++it) {
270                 if (it->second.master() == ctr) {
271                         it->second.reset();
272                 }
273         }
274 }
275
276
277 void Counters::reset()
278 {
279         appendix_ = false;
280         subfloat_ = false;
281         current_float_.erase();
282         CounterList::iterator it = counterList_.begin();
283         CounterList::iterator const end = counterList_.end();
284         for (; it != end; ++it)
285                 it->second.reset();
286         counter_stack_.clear();
287         counter_stack_.push_back(from_ascii(""));
288         layout_stack_.clear();
289         layout_stack_.push_back(0);
290 }
291
292
293 void Counters::reset(docstring const & match)
294 {
295         LASSERT(!match.empty(), /**/);
296
297         CounterList::iterator it = counterList_.begin();
298         CounterList::iterator end = counterList_.end();
299         for (; it != end; ++it) {
300                 if (it->first.find(match) != string::npos)
301                         it->second.reset();
302         }
303 }
304
305
306 bool Counters::remove(docstring const & cnt)
307 {
308         bool retval = counterList_.erase(cnt);
309         if (!retval)
310                 return false;
311         CounterList::iterator it = counterList_.begin();
312         CounterList::iterator end = counterList_.end();
313         for (; it != end; ++it) {
314                 if (it->second.checkAndRemoveMaster(cnt))
315                         LYXERR(Debug::TCLASS, "Removed master counter `" +
316                                         to_utf8(cnt) + "' from counter: " + to_utf8(it->first));
317         }
318         return retval;
319 }
320
321
322 void Counters::copy(Counters & from, Counters & to, docstring const & match)
323 {
324         CounterList::iterator it = counterList_.begin();
325         CounterList::iterator end = counterList_.end();
326         for (; it != end; ++it) {
327                 if (it->first.find(match) != string::npos || match == "") {
328                         to.set(it->first, from.value(it->first));
329                 }
330         }
331 }
332
333
334 namespace {
335
336 char loweralphaCounter(int const n)
337 {
338         if (n < 1 || n > 26)
339                 return '?';
340         return 'a' + n - 1;
341 }
342
343
344 char alphaCounter(int const n)
345 {
346         if (n < 1 || n > 26)
347                 return '?';
348         return 'A' + n - 1;
349 }
350
351
352 char hebrewCounter(int const n)
353 {
354         static const char hebrew[22] = {
355                 '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8',
356                 '\xe9', '\xeb', '\xec', '\xee', '\xf0', '\xf1', '\xf2', '\xf4', '\xf6',
357                 '\xf7', '\xf8', '\xf9', '\xfa'
358         };
359
360         if (n < 1 || n > 22)
361                 return '?';
362         return hebrew[n - 1];
363 }
364
365
366
367 // On the special cases, see http://mathworld.wolfram.com/RomanNumerals.html
368 // and for a list of roman numerals up to and including 3999, see 
369 // http://www.research.att.com/~njas/sequences/a006968.txt. (Thanks to Joost
370 // for this info.)
371 docstring const romanCounter(int const n)
372 {
373         static char const * const ones[9] = {
374                 "I",   "II",  "III", "IV", "V",
375                 "VI",  "VII", "VIII", "IX"
376         };
377         
378         static char const * const tens[9] = {
379                 "X", "XX", "XXX", "XL", "L",
380                 "LX", "LXX", "LXXX", "XC"
381         };
382         
383         static char const * const hunds[9] = {
384                 "C", "CC", "CCC", "CD", "D",
385                 "DC", "DCC", "DCCC", "CM"
386         };
387         
388         if (n > 1000 || n < 1) 
389                 return from_ascii("??");
390         
391         int val = n;
392         string roman;
393         switch (n) {
394         //special cases
395         case 900: 
396                 roman = "CM";
397                 break;
398         case 400:
399                 roman = "CD";
400                 break;
401         default:
402                 if (val >= 100) {
403                         int hundreds = val / 100;
404                         roman = hunds[hundreds - 1];
405                         val = val % 100;
406                 }
407                 if (val >= 10) {
408                         switch (val) {
409                         //special case
410                         case 90:
411                                 roman = roman + "XC";
412                                 val = 0; //skip next
413                                 break;
414                         default:
415                                 int tensnum = val / 10;
416                                 roman = roman + tens[tensnum - 1];
417                                 val = val % 10;
418                         } // end switch
419                 } // end tens
420                 if (val > 0)
421                         roman = roman + ones[val -1];
422         }
423         return from_ascii(roman);
424 }
425
426
427 docstring const lowerromanCounter(int const n)
428 {
429         return lowercase(romanCounter(n));
430 }
431
432 } // namespace anon
433
434
435 docstring Counters::labelItem(docstring const & ctr,
436                               docstring const & numbertype) const
437 {
438         CounterList::const_iterator const cit = counterList_.find(ctr);
439         if (cit == counterList_.end()) {
440                 lyxerr << "Counter "
441                        << to_utf8(ctr)
442                        << " does not exist." << endl;
443                 return docstring();
444         }
445
446         int val = cit->second.value();
447
448         if (numbertype == "hebrew")
449                 return docstring(1, hebrewCounter(val));
450
451         if (numbertype == "alph")
452                 return docstring(1, loweralphaCounter(val));
453
454         if (numbertype == "Alph")
455                 return docstring(1, alphaCounter(val));
456
457         if (numbertype == "roman")
458                 return lowerromanCounter(val);
459
460         if (numbertype == "Roman")
461                 return romanCounter(val);
462
463         return convert<docstring>(val);
464 }
465
466
467 docstring Counters::theCounter(docstring const & counter,
468                                string const & lang) const
469 {
470         CounterList::const_iterator it = counterList_.find(counter); 
471         if (it == counterList_.end())
472                 return from_ascii("#");
473         Counter const & ctr = it->second;
474         Counter::StringMap & sm = ctr.flatLabelStrings(appendix());
475         Counter::StringMap::iterator smit = sm.find(lang);
476         if (smit != sm.end())
477                 return counterLabel(smit->second, lang);
478
479         vector<docstring> callers;
480         docstring const & fls = flattenLabelString(counter, appendix(),
481                                                    lang, callers);
482         sm[lang] = fls;
483         return counterLabel(fls, lang);
484 }
485
486
487 docstring Counters::flattenLabelString(docstring const & counter, 
488                                        bool in_appendix,
489                                        string const & lang,
490                                        vector<docstring> & callers) const
491 {
492         docstring label;
493
494         if (find(callers.begin(), callers.end(), counter) != callers.end()) {
495                 // recursion detected
496                 lyxerr << "Warning: Recursion in label for counter `"
497                        << counter << "' detected"
498                        << endl;
499                 return from_ascii("??");
500         }
501                 
502         CounterList::const_iterator it = counterList_.find(counter); 
503         if (it == counterList_.end())
504                 return from_ascii("#");
505         Counter const & c = it->second;
506
507         docstring ls = translateIfPossible(c.labelString(in_appendix), lang);
508
509         callers.push_back(counter);
510         if (ls.empty()) {
511                 if (!c.master().empty())
512                         ls = flattenLabelString(c.master(), in_appendix, lang, callers) 
513                                 + from_ascii(".");
514                 callers.pop_back();
515                 return ls + from_ascii("\\arabic{") + counter + "}";
516         }
517
518         while (true) {
519                 //lyxerr << "ls=" << to_utf8(ls) << endl;
520                 size_t const i = ls.find(from_ascii("\\the"), 0);
521                 if (i == docstring::npos)
522                         break;
523                 size_t const j = i + 4;
524                 size_t k = j;
525                 while (k < ls.size() && lowercase(ls[k]) >= 'a' 
526                        && lowercase(ls[k]) <= 'z')
527                         ++k;
528                 docstring const newc = ls.substr(j, k - j);
529                 docstring const repl = flattenLabelString(newc, in_appendix,
530                                                           lang, callers);
531                 ls.replace(i, k - j + 4, repl);
532         }
533         callers.pop_back();
534
535         return ls;
536 }
537
538
539 docstring Counters::counterLabel(docstring const & format,
540                                  string const & lang) const
541 {
542         docstring label = format;
543
544         // FIXME: Using regexps would be better, but we compile boost without
545         // wide regexps currently.
546         docstring const the = from_ascii("\\the");
547         while (true) {
548                 //lyxerr << "label=" << label << endl;
549                 size_t const i = label.find(the, 0);
550                 if (i == docstring::npos)
551                         break;
552                 size_t const j = i + 4;
553                 size_t k = j;
554                 while (k < label.size() && lowercase(label[k]) >= 'a' 
555                        && lowercase(label[k]) <= 'z')
556                         ++k;
557                 docstring const newc(label, j, k - j);
558                 label.replace(i, k - i, theCounter(newc, lang));
559         }
560         while (true) {
561                 //lyxerr << "label=" << label << endl;
562
563                 size_t const i = label.find('\\', 0);
564                 if (i == docstring::npos)
565                         break;
566                 size_t const j = label.find('{', i + 1);
567                 if (j == docstring::npos)
568                         break;
569                 size_t const k = label.find('}', j + 1);
570                 if (k == docstring::npos)
571                         break;
572                 docstring const numbertype(label, i + 1, j - i - 1);
573                 docstring const counter(label, j + 1, k - j - 1);
574                 label.replace(i, k + 1 - i, labelItem(counter, numbertype));
575         }
576         //lyxerr << "DONE! label=" << label << endl;
577         return label;
578 }
579
580
581 docstring Counters::prettyCounter(docstring const & name,
582                                string const & lang) const
583 {
584         CounterList::const_iterator it = counterList_.find(name); 
585         if (it == counterList_.end())
586                 return from_ascii("#");
587         Counter const & ctr = it->second;
588
589         docstring const value = theCounter(name, lang);
590         docstring const & format = ctr.prettyFormat();
591         if (format.empty())
592                 return value;
593         return subst(format, from_ascii("##"), value);
594 }
595
596
597 docstring Counters::currentCounter() const
598
599         LASSERT(!counter_stack_.empty(), /* */);
600         return counter_stack_.back(); 
601 }
602
603
604 void Counters::setActiveLayout(Layout const & lay)
605 {
606         LASSERT(!layout_stack_.empty(), return);
607         Layout const * const lastlay = layout_stack_.back();
608         // we want to check whether the layout has changed and, if so,
609         // whether we are coming out of or going into an environment.
610         if (!lastlay) { 
611                 layout_stack_.pop_back();
612                 layout_stack_.push_back(&lay);
613                 if (lay.isEnvironment())
614                         beginEnvironment();
615         } else if (lastlay->name() != lay.name()) {
616                 layout_stack_.pop_back();
617                 layout_stack_.push_back(&lay);
618                 if (lastlay->isEnvironment()) {
619                         // we are coming out of an environment
620                         // LYXERR0("Out: " << lastlay->name());
621                         endEnvironment();
622                 }
623                 if (lay.isEnvironment()) {
624                         // we are going into a new environment
625                         // LYXERR0("In: " << lay.name());
626                         beginEnvironment();
627                 }
628         } 
629 }
630
631
632 void Counters::beginEnvironment()
633 {
634         counter_stack_.push_back(counter_stack_.back());
635 }
636
637
638 void Counters::endEnvironment()
639 {
640         LASSERT(!counter_stack_.empty(), return);
641         counter_stack_.pop_back();
642 }
643
644
645 } // namespace lyx