]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
Load local textclass in addTextClass(), reload local layout correctly in LFUN_TEXTCLA...
[lyx.git] / src / TextClass.cpp
1 /**
2  * \file TextClass.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 Jean-Marc Lasgouttes
8  * \author Angus Leeming
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "TextClass.h"
18
19 #include "Color.h"
20 #include "Counters.h"
21 #include "Floating.h"
22 #include "FloatList.h"
23 #include "Layout.h"
24 #include "Lexer.h"
25 #include "Font.h"
26
27 #include "frontends/alert.h"
28
29 #include "support/debug.h"
30 #include "support/ExceptionMessage.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
35 #include "support/os.h"
36
37 #include <sstream>
38
39 using namespace std;
40 using namespace lyx::support;
41
42 namespace lyx {
43
44 namespace {
45
46 class LayoutNamesEqual : public unary_function<LayoutPtr, bool> {
47 public:
48         LayoutNamesEqual(docstring const & name)
49                 : name_(name)
50         {}
51         bool operator()(LayoutPtr const & c) const
52         {
53                 return c->name() == name_;
54         }
55 private:
56         docstring name_;
57 };
58
59
60 int const FORMAT = 6;
61
62
63 bool layout2layout(FileName const & filename, FileName const & tempfile)
64 {
65         FileName const script = libFileSearch("scripts", "layout2layout.py");
66         if (script.empty()) {
67                 lyxerr << "Could not find layout conversion "
68                           "script layout2layout.py." << endl;
69                 return false;
70         }
71
72         ostringstream command;
73         command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
74                 << ' ' << quoteName(filename.toFilesystemEncoding())
75                 << ' ' << quoteName(tempfile.toFilesystemEncoding());
76         string const command_str = command.str();
77
78         LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
79
80         cmd_ret const ret =
81                 runCommand(command_str);
82         if (ret.first != 0) {
83                 lyxerr << "Could not run layout conversion "
84                           "script layout2layout.py." << endl;
85                 return false;
86         }
87         return true;
88 }
89
90
91 std::string translateRT(TextClass::ReadType rt) 
92 {
93         switch (rt) {
94         case TextClass::BASECLASS:
95                 return "textclass";
96         case TextClass::MERGE:
97                 return "input file";
98         case TextClass::MODULE:
99                 return "module file";
100         }
101         // shutup warning
102         return string();
103 }
104
105 } // namespace anon
106
107
108 TextClass::TextClass(string const & fn, string const & cln,
109                            string const & desc, bool texClassAvail )
110         : name_(fn), latexname_(cln), description_(desc),
111           floatlist_(new FloatList), counters_(new Counters),
112           texClassAvail_(texClassAvail)
113 {
114         modular_ = false;
115         outputType_ = LATEX;
116         columns_ = 1;
117         sides_ = OneSide;
118         secnumdepth_ = 3;
119         tocdepth_ = 3;
120         pagestyle_ = "default";
121         defaultfont_ = sane_font;
122         opt_fontsize_ = "10|11|12";
123         opt_pagestyle_ = "empty|plain|headings|fancy";
124         titletype_ = TITLE_COMMAND_AFTER;
125         titlename_ = "maketitle";
126         loaded_ = false;
127         // a hack to make this available for translation
128         // i'm sure there must be a better way (rgh)
129         _("PlainLayout");
130 }
131
132
133 docstring const TextClass::emptylayout_ = from_ascii("PlainLayout");
134
135
136 InsetLayout TextClass::empty_insetlayout_;
137
138
139 bool TextClass::isTeXClassAvailable() const
140 {
141         return texClassAvail_;
142 }
143
144
145 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
146 {
147         LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
148         if (!lay.read(lexrc, *this)) {
149                 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
150                 return false;
151         }
152         // Resolve fonts
153         lay.resfont = lay.font;
154         lay.resfont.realize(defaultfont());
155         lay.reslabelfont = lay.labelfont;
156         lay.reslabelfont.realize(defaultfont());
157         return true; // no errors
158 }
159
160
161 enum TextClassTags {
162         TC_OUTPUTTYPE = 1,
163         TC_INPUT,
164         TC_STYLE,
165         TC_DEFAULTSTYLE,
166         TC_INSETLAYOUT,
167         TC_ENVIRONMENT,
168         TC_NOSTYLE,
169         TC_COLUMNS,
170         TC_SIDES,
171         TC_PAGESTYLE,
172         TC_DEFAULTFONT,
173         TC_SECNUMDEPTH,
174         TC_TOCDEPTH,
175         TC_CLASSOPTIONS,
176         TC_PREAMBLE,
177         TC_PROVIDES,
178         TC_REQUIRES,
179         TC_LEFTMARGIN,
180         TC_RIGHTMARGIN,
181         TC_FLOAT,
182         TC_COUNTER,
183         TC_NOFLOAT,
184         TC_TITLELATEXNAME,
185         TC_TITLELATEXTYPE,
186         TC_FORMAT
187 };
188
189
190 // Reads a textclass structure from file.
191 bool TextClass::read(FileName const & filename, ReadType rt)
192 {
193         if (!filename.isReadableFile()) {
194                 lyxerr << "Cannot read layout file `" << filename << "'."
195                        << endl;
196                 return false;
197         }
198
199         keyword_item textClassTags[] = {
200                 { "classoptions",    TC_CLASSOPTIONS },
201                 { "columns",         TC_COLUMNS },
202                 { "counter",         TC_COUNTER },
203                 { "defaultfont",     TC_DEFAULTFONT },
204                 { "defaultstyle",    TC_DEFAULTSTYLE },
205                 { "environment",     TC_ENVIRONMENT },
206                 { "float",           TC_FLOAT },
207                 { "format",          TC_FORMAT },
208                 { "input",           TC_INPUT },
209                 { "insetlayout",     TC_INSETLAYOUT },
210                 { "leftmargin",      TC_LEFTMARGIN },
211                 { "nofloat",         TC_NOFLOAT },
212                 { "nostyle",         TC_NOSTYLE },
213                 { "outputtype",      TC_OUTPUTTYPE },
214                 { "pagestyle",       TC_PAGESTYLE },
215                 { "preamble",        TC_PREAMBLE },
216                 { "provides",        TC_PROVIDES },
217                 { "requires",        TC_REQUIRES },
218                 { "rightmargin",     TC_RIGHTMARGIN },
219                 { "secnumdepth",     TC_SECNUMDEPTH },
220                 { "sides",           TC_SIDES },
221                 { "style",           TC_STYLE },
222                 { "titlelatexname",  TC_TITLELATEXNAME },
223                 { "titlelatextype",  TC_TITLELATEXTYPE },
224                 { "tocdepth",        TC_TOCDEPTH }
225         };
226
227         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
228                 to_utf8(makeDisplayPath(filename.absFilename())));
229
230         // Define the `empty' layout used in table cells, ert, etc. Note that 
231         // we do this before loading any layout file, so that classes can 
232         // override features of this layout if they should choose to do so.
233         if (rt == BASECLASS) {
234                 static char const * s = "Margin Static\n"
235                         "LatexType Paragraph\n"
236                         "LatexName dummy\n"
237                         "Align Block\n"
238                         "AlignPossible Left, Right, Center\n"
239                         "LabelType No_Label\n"
240                         "End";
241                 istringstream ss(s);
242                 Lexer lex(textClassTags, sizeof(textClassTags) / sizeof(textClassTags[0]));
243                 lex.setStream(ss);
244                 Layout lay;
245                 lay.setName(emptylayout_);
246                 if (!readStyle(lex, lay)) {
247                         // The only way this happens is because the hardcoded layout above
248                         // is wrong.
249                         BOOST_ASSERT(false);
250                 }
251                 layoutlist_.push_back(boost::shared_ptr<Layout>(new Layout(lay)));
252         }
253
254         Lexer lexrc(textClassTags,
255                 sizeof(textClassTags) / sizeof(textClassTags[0]));
256
257         lexrc.setFile(filename);
258         bool error = !lexrc.isOK();
259
260         // Format of files before the 'Format' tag was introduced
261         int format = 1;
262
263         // parsing
264         while (lexrc.isOK() && !error) {
265                 int le = lexrc.lex();
266
267                 switch (le) {
268                 case Lexer::LEX_FEOF:
269                         continue;
270
271                 case Lexer::LEX_UNDEF:
272                         lexrc.printError("Unknown TextClass tag `$$Token'");
273                         error = true;
274                         continue;
275
276                 default:
277                         break;
278                 }
279
280                 switch (static_cast<TextClassTags>(le)) {
281
282                 case TC_FORMAT:
283                         if (lexrc.next())
284                                 format = lexrc.getInteger();
285                         break;
286
287                 case TC_OUTPUTTYPE:   // output type definition
288                         readOutputType(lexrc);
289                         break;
290
291                 case TC_INPUT: // Include file
292                         if (lexrc.next()) {
293                                 string const inc = lexrc.getString();
294                                 FileName tmp = libFileSearch("layouts", inc,
295                                                             "layout");
296
297                                 if (tmp.empty()) {
298                                         lexrc.printError("Could not find input file: " + inc);
299                                         error = true;
300                                 } else if (!read(tmp, MERGE)) {
301                                         lexrc.printError("Error reading input"
302                                                          "file: " + tmp.absFilename());
303                                         error = true;
304                                 }
305                         }
306                         break;
307
308                 case TC_DEFAULTSTYLE:
309                         if (lexrc.next()) {
310                                 docstring const name = from_utf8(subst(lexrc.getString(),
311                                                           '_', ' '));
312                                 defaultlayout_ = name;
313                         }
314                         break;
315
316                 case TC_ENVIRONMENT:
317                 case TC_STYLE:
318                         if (lexrc.next()) {
319                                 docstring const name = from_utf8(subst(lexrc.getString(),
320                                                     '_', ' '));
321                                 if (name.empty()) {
322                                         string s = "Could not read name for style: `$$Token' "
323                                                 + lexrc.getString() + " is probably not valid UTF-8!";
324                                         lexrc.printError(s.c_str());
325                                         Layout lay;
326                                         //FIXME If we're just dropping this layout, do we really
327                                         //care whether there's an error?? Or should we just set
328                                         //error to true, since we couldn't even read the name?
329                                         error = !readStyle(lexrc, lay);
330                                 } else if (hasLayout(name)) {
331                                         Layout * lay = operator[](name).get();
332                                         error = !readStyle(lexrc, *lay);
333                                 } else {
334                                         Layout lay;
335                                         lay.setName(name);
336                                         if (le == TC_ENVIRONMENT)
337                                                 lay.is_environment = true;
338                                         error = !readStyle(lexrc, lay);
339                                         if (!error)
340                                                 layoutlist_.push_back(boost::shared_ptr<Layout>(new Layout(lay)));
341
342                                         if (defaultlayout_.empty()) {
343                                                 // We do not have a default layout yet, so we choose
344                                                 // the first layout we encounter.
345                                                 defaultlayout_ = name;
346                                         }
347                                 }
348                         }
349                         else {
350                                 //FIXME Should we also eat the style here? viz:
351                                 //Layout lay;
352                                 //readStyle(lexrc, lay);
353                                 //as above...
354                                 lexrc.printError("No name given for style: `$$Token'.");
355                                 error = true;
356                         }
357                         break;
358
359                 case TC_NOSTYLE:
360                         if (lexrc.next()) {
361                                 docstring const style = from_utf8(subst(lexrc.getString(),
362                                                      '_', ' '));
363                                 if (!deleteLayout(style))
364                                         lyxerr << "Cannot delete style `"
365                                                << to_utf8(style) << '\'' << endl;
366                         }
367                         break;
368
369                 case TC_COLUMNS:
370                         if (lexrc.next())
371                                 columns_ = lexrc.getInteger();
372                         break;
373
374                 case TC_SIDES:
375                         if (lexrc.next()) {
376                                 switch (lexrc.getInteger()) {
377                                 case 1: sides_ = OneSide; break;
378                                 case 2: sides_ = TwoSides; break;
379                                 default:
380                                         lyxerr << "Impossible number of page"
381                                                 " sides, setting to one."
382                                                << endl;
383                                         sides_ = OneSide;
384                                         break;
385                                 }
386                         }
387                         break;
388
389                 case TC_PAGESTYLE:
390                         lexrc.next();
391                         pagestyle_ = rtrim(lexrc.getString());
392                         break;
393
394                 case TC_DEFAULTFONT:
395                         defaultfont_ = lyxRead(lexrc);
396                         if (!defaultfont_.resolved()) {
397                                 lexrc.printError("Warning: defaultfont should "
398                                                  "be fully instantiated!");
399                                 defaultfont_.realize(sane_font);
400                         }
401                         break;
402
403                 case TC_SECNUMDEPTH:
404                         lexrc.next();
405                         secnumdepth_ = lexrc.getInteger();
406                         break;
407
408                 case TC_TOCDEPTH:
409                         lexrc.next();
410                         tocdepth_ = lexrc.getInteger();
411                         break;
412
413                 // First step to support options
414                 case TC_CLASSOPTIONS:
415                         readClassOptions(lexrc);
416                         break;
417
418                 case TC_PREAMBLE:
419                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
420                         break;
421
422                 case TC_PROVIDES: {
423                         lexrc.next();
424                         string const feature = lexrc.getString();
425                         lexrc.next();
426                         if (lexrc.getInteger())
427                                 provides_.insert(feature);
428                         else
429                                 provides_.erase(feature);
430                         break;
431                 }
432
433                 case TC_REQUIRES: {
434                         lexrc.eatLine();
435                         vector<string> const req 
436                                 = getVectorFromString(lexrc.getString());
437                         requires_.insert(req.begin(), req.end());
438                         break;
439                 }
440
441                 case TC_LEFTMARGIN:     // left margin type
442                         if (lexrc.next())
443                                 leftmargin_ = lexrc.getDocString();
444                         break;
445
446                 case TC_RIGHTMARGIN:    // right margin type
447                         if (lexrc.next())
448                                 rightmargin_ = lexrc.getDocString();
449                         break;
450
451                 case TC_INSETLAYOUT:
452                         if (lexrc.next()) {
453                                 InsetLayout il;
454                                 if (il.read(lexrc)) {
455                                         insetlayoutlist_[il.name()] = il;
456                                 }
457                                 // else there was an error, so forget it
458                         }
459                         break;
460
461                 case TC_FLOAT:
462                         readFloat(lexrc);
463                         break;
464
465                 case TC_COUNTER:
466                         readCounter(lexrc);
467                         break;
468
469                 case TC_TITLELATEXTYPE:
470                         readTitleType(lexrc);
471                         break;
472
473                 case TC_TITLELATEXNAME:
474                         if (lexrc.next())
475                                 titlename_ = lexrc.getString();
476                         break;
477
478                 case TC_NOFLOAT:
479                         if (lexrc.next()) {
480                                 string const nofloat = lexrc.getString();
481                                 floatlist_->erase(nofloat);
482                         }
483                         break;
484                 }
485
486                 //Note that this is triggered the first time through the loop unless
487                 //we hit a format tag.
488                 if (format != FORMAT)
489                         break;
490         }
491
492         if (format != FORMAT) {
493                 LYXERR(Debug::TCLASS, "Converting layout file from format "
494                                       << format << " to " << FORMAT);
495                 FileName const tempfile = FileName::tempName();
496                 error = !layout2layout(filename, tempfile);
497                 if (!error)
498                         error = read(tempfile, rt);
499                 tempfile.removeFile();
500                 return !error;
501         }
502
503         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
504                         to_utf8(makeDisplayPath(filename.absFilename())));
505
506         if (rt != BASECLASS) 
507                 return !error;
508
509         if (defaultlayout_.empty()) {
510                 lyxerr << "Error: Textclass '" << name_
511                                                 << "' is missing a defaultstyle." << endl;
512                 error = true;
513         }
514                 
515         //Try to erase "stdinsets" from the provides_ set. 
516         //The
517         //  Provides stdinsets 1
518         //declaration simply tells us that the standard insets have been
519         //defined. (It's found in stdinsets.inc but could also be used in
520         //user-defined files.) There isn't really any such package. So we
521         //might as well go ahead and erase it.
522         //If we do not succeed, then it was not there, which means that
523         //the textclass did not provide the definitions of the standard
524         //insets. So we need to try to load them.
525         int erased = provides_.erase("stdinsets");
526         if (!erased) {
527                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
528
529                 if (tmp.empty()) {
530                         throw ExceptionMessage(WarningException, _("Missing File"),
531                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
532                         error = true;
533                 } else if (!read(tmp, MERGE)) {
534                         throw ExceptionMessage(WarningException, _("Corrupt File"),
535                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
536                         error = true;
537                 }
538         }
539
540         min_toclevel_ = Layout::NOT_IN_TOC;
541         max_toclevel_ = Layout::NOT_IN_TOC;
542         for (size_t i = 0; i != layoutCount(); ++i) {
543                 int const toclevel = layout(i)->toclevel;
544                 if (toclevel != Layout::NOT_IN_TOC) {
545                         if (min_toclevel_ == Layout::NOT_IN_TOC)
546                                 min_toclevel_ = toclevel;
547                         else
548                                 min_toclevel_ = min(min_toclevel_, toclevel);
549                         max_toclevel_ = max(max_toclevel_, toclevel);
550                 }
551         }
552         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
553                 << ", maximum is " << max_toclevel_);
554
555         return !error;
556 }
557
558
559 void TextClass::readTitleType(Lexer & lexrc)
560 {
561         keyword_item titleTypeTags[] = {
562                 { "commandafter", TITLE_COMMAND_AFTER },
563                 { "environment", TITLE_ENVIRONMENT }
564         };
565
566         PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
567
568         int le = lexrc.lex();
569         switch (le) {
570         case Lexer::LEX_UNDEF:
571                 lexrc.printError("Unknown output type `$$Token'");
572                 return;
573         case TITLE_COMMAND_AFTER:
574         case TITLE_ENVIRONMENT:
575                 titletype_ = static_cast<TitleLatexType>(le);
576                 break;
577         default:
578                 lyxerr << "Unhandled value " << le
579                        << " in TextClass::readTitleType." << endl;
580
581                 break;
582         }
583 }
584
585
586 void TextClass::readOutputType(Lexer & lexrc)
587 {
588         keyword_item outputTypeTags[] = {
589                 { "docbook", DOCBOOK },
590                 { "latex", LATEX },
591                 { "literate", LITERATE }
592         };
593
594         PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
595
596         int le = lexrc.lex();
597         switch (le) {
598         case Lexer::LEX_UNDEF:
599                 lexrc.printError("Unknown output type `$$Token'");
600                 return;
601         case LATEX:
602         case DOCBOOK:
603         case LITERATE:
604                 outputType_ = static_cast<OutputType>(le);
605                 break;
606         default:
607                 lyxerr << "Unhandled value " << le
608                        << " in TextClass::readOutputType." << endl;
609
610                 break;
611         }
612 }
613
614
615 enum ClassOptionsTags {
616         CO_FONTSIZE = 1,
617         CO_PAGESTYLE,
618         CO_OTHER,
619         CO_HEADER,
620         CO_END
621 };
622
623
624 void TextClass::readClassOptions(Lexer & lexrc)
625 {
626         keyword_item classOptionsTags[] = {
627                 {"end", CO_END },
628                 {"fontsize", CO_FONTSIZE },
629                 {"header", CO_HEADER },
630                 {"other", CO_OTHER },
631                 {"pagestyle", CO_PAGESTYLE }
632         };
633
634         lexrc.pushTable(classOptionsTags, CO_END);
635         bool getout = false;
636         while (!getout && lexrc.isOK()) {
637                 int le = lexrc.lex();
638                 switch (le) {
639                 case Lexer::LEX_UNDEF:
640                         lexrc.printError("Unknown ClassOption tag `$$Token'");
641                         continue;
642                 default: break;
643                 }
644                 switch (static_cast<ClassOptionsTags>(le)) {
645                 case CO_FONTSIZE:
646                         lexrc.next();
647                         opt_fontsize_ = rtrim(lexrc.getString());
648                         break;
649                 case CO_PAGESTYLE:
650                         lexrc.next();
651                         opt_pagestyle_ = rtrim(lexrc.getString());
652                         break;
653                 case CO_OTHER:
654                         lexrc.next();
655                         options_ = lexrc.getString();
656                         break;
657                 case CO_HEADER:
658                         lexrc.next();
659                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
660                         break;
661                 case CO_END:
662                         getout = true;
663                         break;
664                 }
665         }
666         lexrc.popTable();
667 }
668
669
670 enum FloatTags {
671         FT_TYPE = 1,
672         FT_NAME,
673         FT_PLACEMENT,
674         FT_EXT,
675         FT_WITHIN,
676         FT_STYLE,
677         FT_LISTNAME,
678         FT_BUILTIN,
679         FT_END
680 };
681
682
683 void TextClass::readFloat(Lexer & lexrc)
684 {
685         keyword_item floatTags[] = {
686                 { "end", FT_END },
687                 { "extension", FT_EXT },
688                 { "guiname", FT_NAME },
689                 { "latexbuiltin", FT_BUILTIN },
690                 { "listname", FT_LISTNAME },
691                 { "numberwithin", FT_WITHIN },
692                 { "placement", FT_PLACEMENT },
693                 { "style", FT_STYLE },
694                 { "type", FT_TYPE }
695         };
696
697         lexrc.pushTable(floatTags, FT_END);
698
699         string type;
700         string placement;
701         string ext;
702         string within;
703         string style;
704         string name;
705         string listName;
706         bool builtin = false;
707
708         bool getout = false;
709         while (!getout && lexrc.isOK()) {
710                 int le = lexrc.lex();
711                 switch (le) {
712                 case Lexer::LEX_UNDEF:
713                         lexrc.printError("Unknown float tag `$$Token'");
714                         continue;
715                 default: break;
716                 }
717                 switch (static_cast<FloatTags>(le)) {
718                 case FT_TYPE:
719                         lexrc.next();
720                         type = lexrc.getString();
721                         if (floatlist_->typeExist(type)) {
722                                 Floating const & fl = floatlist_->getType(type);
723                                 placement = fl.placement();
724                                 ext = fl.ext();
725                                 within = fl.within();
726                                 style = fl.style();
727                                 name = fl.name();
728                                 listName = fl.listName();
729                                 builtin = fl.builtin();
730                         } 
731                         break;
732                 case FT_NAME:
733                         lexrc.next();
734                         name = lexrc.getString();
735                         break;
736                 case FT_PLACEMENT:
737                         lexrc.next();
738                         placement = lexrc.getString();
739                         break;
740                 case FT_EXT:
741                         lexrc.next();
742                         ext = lexrc.getString();
743                         break;
744                 case FT_WITHIN:
745                         lexrc.next();
746                         within = lexrc.getString();
747                         if (within == "none")
748                                 within.erase();
749                         break;
750                 case FT_STYLE:
751                         lexrc.next();
752                         style = lexrc.getString();
753                         break;
754                 case FT_LISTNAME:
755                         lexrc.next();
756                         listName = lexrc.getString();
757                         break;
758                 case FT_BUILTIN:
759                         lexrc.next();
760                         builtin = lexrc.getBool();
761                         break;
762                 case FT_END:
763                         getout = true;
764                         break;
765                 }
766         }
767
768         // Here if have a full float if getout == true
769         if (getout) {
770                 Floating fl(type, placement, ext, within,
771                             style, name, listName, builtin);
772                 floatlist_->newFloat(fl);
773                 // each float has its own counter
774                 counters_->newCounter(from_ascii(type), from_ascii(within), 
775                                       docstring(), docstring());
776         }
777
778         lexrc.popTable();
779 }
780
781
782 enum CounterTags {
783         CT_NAME = 1,
784         CT_WITHIN,
785         CT_LABELSTRING,
786         CT_LABELSTRING_APPENDIX,
787         CT_END
788 };
789
790
791 void TextClass::readCounter(Lexer & lexrc)
792 {
793         keyword_item counterTags[] = {
794                 { "end", CT_END },
795                 { "labelstring", CT_LABELSTRING },
796                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
797                 { "name", CT_NAME },
798                 { "within", CT_WITHIN }
799         };
800
801         lexrc.pushTable(counterTags, CT_END);
802
803         docstring name;
804         docstring within;
805         docstring labelstring;
806         docstring labelstring_appendix;
807
808         bool getout = false;
809         while (!getout && lexrc.isOK()) {
810                 int le = lexrc.lex();
811                 switch (le) {
812                 case Lexer::LEX_UNDEF:
813                         lexrc.printError("Unknown counter tag `$$Token'");
814                         continue;
815                 default: break;
816                 }
817                 switch (static_cast<CounterTags>(le)) {
818                 case CT_NAME:
819                         lexrc.next();
820                         name = lexrc.getDocString();
821                         if (counters_->hasCounter(name))
822                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
823                         else
824                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
825                         break;
826                 case CT_WITHIN:
827                         lexrc.next();
828                         within = lexrc.getDocString();
829                         if (within == "none")
830                                 within.erase();
831                         break;
832                 case CT_LABELSTRING:
833                         lexrc.next();
834                         labelstring = lexrc.getDocString();
835                         labelstring_appendix = labelstring;
836                         break;
837                 case CT_LABELSTRING_APPENDIX:
838                         lexrc.next();
839                         labelstring_appendix = lexrc.getDocString();
840                         break;
841                 case CT_END:
842                         getout = true;
843                         break;
844                 }
845         }
846
847         // Here if have a full counter if getout == true
848         if (getout)
849                 counters_->newCounter(name, within, 
850                                       labelstring, labelstring_appendix);
851
852         lexrc.popTable();
853 }
854
855
856 FontInfo const & TextClass::defaultfont() const
857 {
858         return defaultfont_;
859 }
860
861
862 docstring const & TextClass::leftmargin() const
863 {
864         return leftmargin_;
865 }
866
867
868 docstring const & TextClass::rightmargin() const
869 {
870         return rightmargin_;
871 }
872
873
874 bool TextClass::hasLayout(docstring const & n) const
875 {
876         docstring const name = n.empty() ? defaultLayoutName() : n;
877
878         return find_if(layoutlist_.begin(), layoutlist_.end(),
879                        LayoutNamesEqual(name))
880                 != layoutlist_.end();
881 }
882
883
884
885 LayoutPtr const & TextClass::operator[](docstring const & name) const
886 {
887         BOOST_ASSERT(!name.empty());
888
889         LayoutList::const_iterator cit =
890                 find_if(layoutlist_.begin(),
891                         layoutlist_.end(),
892                         LayoutNamesEqual(name));
893
894         if (cit == layoutlist_.end()) {
895                 lyxerr << "We failed to find the layout '" << to_utf8(name)
896                        << "' in the layout list. You MUST investigate!"
897                        << endl;
898                 for (LayoutList::const_iterator it = layoutlist_.begin();
899                          it != layoutlist_.end(); ++it)
900                         lyxerr  << " " << to_utf8(it->get()->name()) << endl;
901
902                 // we require the name to exist
903                 BOOST_ASSERT(false);
904         }
905
906         return *cit;
907 }
908
909
910 bool TextClass::deleteLayout(docstring const & name)
911 {
912         if (name == defaultLayoutName() || name == emptyLayoutName())
913                 return false;
914
915         LayoutList::iterator it =
916                 remove_if(layoutlist_.begin(), layoutlist_.end(),
917                           LayoutNamesEqual(name));
918
919         LayoutList::iterator end = layoutlist_.end();
920         bool const ret = (it != end);
921         layoutlist_.erase(it, end);
922         return ret;
923 }
924
925
926 // Load textclass info if not loaded yet
927 bool TextClass::load(string const & path) const
928 {
929         if (loaded_)
930                 return true;
931
932         // Read style-file, provided path is searched before the system ones
933         FileName layout_file;
934         if (!path.empty())
935                 layout_file = FileName(addName(path, name_ + ".layout"));
936         if (layout_file.empty() || !layout_file.exists())
937                 layout_file = libFileSearch("layouts", name_, "layout");
938         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
939
940         if (!loaded_) {
941                 lyxerr << "Error reading `"
942                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
943                        << "'\n(Check `" << name_
944                        << "')\nCheck your installation and "
945                         "try Options/Reconfigure..." << endl;
946         }
947
948         return loaded_;
949 }
950
951
952 FloatList & TextClass::floats()
953 {
954         return *floatlist_.get();
955 }
956
957
958 FloatList const & TextClass::floats() const
959 {
960         return *floatlist_.get();
961 }
962
963
964 Counters & TextClass::counters() const
965 {
966         return *counters_.get();
967 }
968
969
970 // Return the layout object of an inset given by name. If the name
971 // is not found as such, the part after the ':' is stripped off, and
972 // searched again. In this way, an error fallback can be provided:
973 // An erroneous 'CharStyle:badname' (e.g., after a documentclass switch)
974 // will invoke the layout object defined by name = 'CharStyle'.
975 // If that doesn't work either, an empty object returns (shouldn't
976 // happen).  -- Idea JMarc, comment MV
977 InsetLayout const & TextClass::insetLayout(docstring const & name) const 
978 {
979         docstring n = name;
980         while (!n.empty()) {
981                 if (insetlayoutlist_.count(n) > 0)
982                         return insetlayoutlist_[n];
983                 size_t i = n.find(':');
984                 if (i == string::npos)
985                         break;
986                 n = n.substr(0,i);
987         }
988         return empty_insetlayout_;
989 }
990
991
992 docstring const & TextClass::defaultLayoutName() const
993 {
994         // This really should come from the actual layout... (Lgb)
995         return defaultlayout_;
996 }
997
998
999 LayoutPtr const & TextClass::defaultLayout() const
1000 {
1001         return operator[](defaultLayoutName());
1002 }
1003
1004
1005 string const & TextClass::name() const
1006 {
1007         return name_;
1008 }
1009
1010
1011 string const & TextClass::latexname() const
1012 {
1013         // No buffer path information is needed here because on-demand layout files
1014         // have already been loaded, and no path is needed for system layouts.
1015         const_cast<TextClass*>(this)->load();
1016         return latexname_;
1017 }
1018
1019
1020 string const & TextClass::description() const
1021 {
1022         return description_;
1023 }
1024
1025
1026 string const & TextClass::opt_fontsize() const
1027 {
1028         return opt_fontsize_;
1029 }
1030
1031
1032 string const & TextClass::opt_pagestyle() const
1033 {
1034         return opt_pagestyle_;
1035 }
1036
1037
1038 string const & TextClass::options() const
1039 {
1040         return options_;
1041 }
1042
1043
1044 string const & TextClass::class_header() const
1045 {
1046         return class_header_;
1047 }
1048
1049
1050 string const & TextClass::pagestyle() const
1051 {
1052         return pagestyle_;
1053 }
1054
1055
1056 docstring const & TextClass::preamble() const
1057 {
1058         return preamble_;
1059 }
1060
1061
1062 PageSides TextClass::sides() const
1063 {
1064         return sides_;
1065 }
1066
1067
1068 int TextClass::secnumdepth() const
1069 {
1070         return secnumdepth_;
1071 }
1072
1073
1074 int TextClass::tocdepth() const
1075 {
1076         return tocdepth_;
1077 }
1078
1079
1080 OutputType TextClass::outputType() const
1081 {
1082         return outputType_;
1083 }
1084
1085
1086 bool TextClass::provides(string const & p) const
1087 {
1088         return provides_.find(p) != provides_.end();
1089 }
1090
1091
1092 unsigned int TextClass::columns() const
1093 {
1094         return columns_;
1095 }
1096
1097
1098 TitleLatexType TextClass::titletype() const
1099 {
1100         return titletype_;
1101 }
1102
1103
1104 string const & TextClass::titlename() const
1105 {
1106         return titlename_;
1107 }
1108
1109
1110 int TextClass::size() const
1111 {
1112         return layoutlist_.size();
1113 }
1114
1115
1116 int TextClass::min_toclevel() const
1117 {
1118         return min_toclevel_;
1119 }
1120
1121
1122 int TextClass::max_toclevel() const
1123 {
1124         return max_toclevel_;
1125 }
1126
1127
1128 bool TextClass::hasTocLevels() const
1129 {
1130         return min_toclevel_ != Layout::NOT_IN_TOC;
1131 }
1132
1133
1134 ostream & operator<<(ostream & os, PageSides p)
1135 {
1136         switch (p) {
1137         case OneSide:
1138                 os << '1';
1139                 break;
1140         case TwoSides:
1141                 os << '2';
1142                 break;
1143         }
1144         return os;
1145 }
1146
1147
1148 } // namespace lyx