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