]> git.lyx.org Git - lyx.git/blob - src/buffer.C
679c9636ab503ffe4edb31716320fc4ab452f59d
[lyx.git] / src / buffer.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2000 The LyX Team.
8  *
9  *           This file is Copyright 1996-1999
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #include <config.h>
16
17 #include <fstream>
18 #include <iomanip>
19 #include <map>
20 #include <stack>
21 #include <list>
22
23 #include <cstdlib>
24 #include <cmath>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <utime.h>
28
29 #include <algorithm>
30
31 #ifdef HAVE_LOCALE
32 #include <locale>
33 #endif
34
35 #ifdef __GNUG__
36 #pragma implementation "buffer.h"
37 #endif
38
39 #include "buffer.h"
40 #include "bufferlist.h"
41 #include "lyx_main.h"
42 #include "lyx_gui_misc.h"
43 #include "LyXAction.h"
44 #include "lyxrc.h"
45 #include "lyxlex.h"
46 #include "tex-strings.h"
47 #include "layout.h"
48 #include "bufferview_funcs.h"
49 #include "lyxfont.h"
50 #include "version.h"
51 #include "mathed/formulamacro.h"
52 #include "insets/lyxinset.h"
53 #include "insets/inseterror.h"
54 #include "insets/insetlabel.h"
55 #include "insets/insetref.h"
56 #include "insets/inseturl.h"
57 #include "insets/insetinfo.h"
58 #include "insets/insetquotes.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetbib.h" 
61 #include "insets/insetcite.h" 
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h" 
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/figinset.h"
69 #include "insets/insettext.h"
70 #include "insets/insetert.h"
71 #include "insets/insetgraphics.h"
72 #include "insets/insetfoot.h"
73 #include "insets/insetmarginal.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insetlist.h"
77 #include "insets/insettabular.h"
78 #include "insets/insettheorem.h"
79 #include "insets/insetcaption.h"
80 #include "support/filetools.h"
81 #include "support/path.h"
82 #include "LaTeX.h"
83 #include "Chktex.h"
84 #include "LyXView.h"
85 #include "debug.h"
86 #include "LaTeXFeatures.h"
87 #include "support/syscall.h"
88 #include "support/lyxlib.h"
89 #include "support/FileInfo.h"
90 #include "support/lyxmanip.h"
91 #include "lyxtext.h"
92 #include "gettext.h"
93 #include "language.h"
94 #include "lyx_gui_misc.h"       // WarnReadonly()
95 #include "frontends/Dialogs.h"
96 #include "encoding.h"
97 #include "exporter.h"
98 #include "Lsstream.h"
99 #include "converter.h"
100
101 using std::stringstream;
102 using std::ostream;
103 using std::ofstream;
104 using std::ifstream;
105 using std::fstream;
106 using std::ios;
107 using std::setw;
108 using std::endl;
109 using std::pair;
110 using std::make_pair;
111 using std::vector;
112 using std::map;
113 using std::max;
114 using std::set;
115 using std::stack;
116 using std::list;
117
118 // all these externs should eventually be removed.
119 extern BufferList bufferlist;
120
121 extern LyXAction lyxaction;
122
123 namespace {
124
125 const int LYX_FORMAT = 218;
126
127 } // namespace anon
128
129 extern int tex_code_break_column;
130
131
132 Buffer::Buffer(string const & file, bool ronly)
133 {
134         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
135         filename = file;
136         filepath = OnlyPath(file);
137         paragraph = 0;
138         lyx_clean = true;
139         bak_clean = true;
140         dep_clean = 0;
141         read_only = ronly;
142         unnamed = false;
143         users = 0;
144         lyxvc.buffer(this);
145         if (read_only || (lyxrc.use_tempdir)) {
146                 tmppath = CreateBufferTmpDir();
147         } else tmppath.erase();
148 }
149
150
151 Buffer::~Buffer()
152 {
153         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
154         // here the buffer should take care that it is
155         // saved properly, before it goes into the void.
156
157         // make sure that views using this buffer
158         // forgets it.
159         if (users)
160                 users->buffer(0);
161         
162         if (!tmppath.empty()) {
163                 DestroyBufferTmpDir(tmppath);
164         }
165         
166         LyXParagraph * par = paragraph;
167         LyXParagraph * tmppar;
168 #ifndef NEW_INSETS
169         while (par) {
170                 tmppar = par->next_;
171                 delete par;
172                 par = tmppar;
173         }
174 #else
175         while (par) {
176                 tmppar = par->next();
177                 delete par;
178                 par = tmppar;
179         }
180 #endif
181         paragraph = 0;
182 }
183
184
185 string const Buffer::getLatexName(bool no_path) const
186 {
187         if (no_path)
188                 return OnlyFilename(ChangeExtension(MakeLatexName(filename), 
189                                                     ".tex"));
190         else
191                 return ChangeExtension(MakeLatexName(filename), 
192                                        ".tex"); 
193 }
194
195
196 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
197 {
198         string const filename = getLatexName(false);
199
200         if (filename.empty())
201                 return make_pair(Buffer::latexlog, string());
202
203         string path = OnlyPath(filename);
204
205         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
206                 path = tmppath;
207
208         string const fname = AddName(path,
209                                      OnlyFilename(ChangeExtension(filename,
210                                                                   ".log")));
211         string const bname =
212                 AddName(path, OnlyFilename(
213                         ChangeExtension(filename,
214                                         formats.Extension("literate") + ".out")));
215
216         // If no Latex log or Build log is newer, show Build log
217
218         FileInfo const f_fi(fname);
219         FileInfo const b_fi(bname);
220
221         if (b_fi.exist() &&
222             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
223                 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
224                 return make_pair(Buffer::buildlog, bname);
225         }
226         lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
227         return make_pair(Buffer::latexlog, fname);
228 }
229
230
231 void Buffer::setReadonly(bool flag)
232 {
233         if (read_only != flag) {
234                 read_only = flag; 
235                 updateTitles();
236                 users->owner()->getDialogs()->updateBufferDependent(false);
237         }
238         if (read_only) {
239                 WarnReadonly(filename);
240         }
241 }
242
243
244 bool Buffer::saveParamsAsDefaults() // const
245 {
246         string const fname = AddName(AddPath(user_lyxdir, "templates/"),
247                                "defaults.lyx");
248         Buffer defaults = Buffer(fname);
249         
250         // Use the current buffer's parameters as default
251         defaults.params = params;
252         
253         // add an empty paragraph. Is this enough?
254         defaults.paragraph = new LyXParagraph;
255
256         return defaults.writeFile(defaults.filename, false);
257 }
258
259
260 /// Update window titles of all users
261 // Should work on a list
262 void Buffer::updateTitles() const
263 {
264         if (users) users->owner()->updateWindowTitle();
265 }
266
267
268 /// Reset autosave timer of all users
269 // Should work on a list
270 void Buffer::resetAutosaveTimers() const
271 {
272         if (users) users->owner()->resetAutosaveTimer();
273 }
274
275
276 void Buffer::setFileName(string const & newfile)
277 {
278         filename = MakeAbsPath(newfile);
279         filepath = OnlyPath(filename);
280         setReadonly(IsFileWriteable(filename) == 0);
281         updateTitles();
282 }
283
284
285 // candidate for move to BufferView
286 // (at least some parts in the beginning of the func)
287 //
288 // Uwe C. Schroeder
289 // changed to be public and have one parameter
290 // if par = 0 normal behavior
291 // else insert behavior
292 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
293 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
294 {
295         int pos = 0;
296         char depth = 0; // signed or unsigned?
297 #ifndef NEW_INSETS
298         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
299         LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
300 #endif
301         bool the_end_read = false;
302
303         LyXParagraph * return_par = 0;
304         LyXFont font(LyXFont::ALL_INHERIT, params.language);
305         if (file_format < 216 && params.language->lang() == "hebrew")
306                 font.setLanguage(default_language);
307         // If we are inserting, we cheat and get a token in advance
308         bool has_token = false;
309         string pretoken;
310
311         if (!par) {
312                 par = new LyXParagraph;
313         } else {
314                 users->text->BreakParagraph(users);
315                 return_par = users->text->FirstParagraph();
316                 pos = 0;
317                 markDirty();
318                 // We don't want to adopt the parameters from the
319                 // document we insert, so we skip until the text begins:
320                 while (lex.IsOK()) {
321                         lex.nextToken();
322                         pretoken = lex.GetString();
323                         if (pretoken == "\\layout") {
324                                 has_token = true;
325                                 break;
326                         }
327                 }
328         }
329
330         while (lex.IsOK()) {
331                 if (has_token) {
332                         has_token = false;
333                 } else {
334                         lex.nextToken();
335                         pretoken = lex.GetString();
336                 }
337
338                 if (pretoken.empty()) continue;
339                 
340                 the_end_read =
341                         parseSingleLyXformat2Token(lex, par, return_par,
342                                                    pretoken, pos, depth,
343                                                    font
344 #ifndef NEW_INSETS
345                                                    , footnoteflag,
346                                                    footnotekind
347 #endif
348                                 );
349         }
350    
351         if (!return_par)
352                 return_par = par;
353
354         paragraph = return_par;
355         
356         return the_end_read;
357 }
358
359
360 // We'll remove this later. (Lgb)
361 namespace {
362
363 string last_inset_read;
364
365 } // anon
366
367
368 bool
369 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
370                                    LyXParagraph *& return_par,
371                                    string const & token, int & pos,
372                                    char & depth, LyXFont & font
373 #ifndef NEW_INSETS
374                                    , LyXParagraph::footnote_flag & footnoteflag,
375                                    LyXParagraph::footnote_kind & footnotekind
376 #endif
377         )
378 {
379         bool the_end_read = false;
380 #ifndef NO_PEXTRA_REALLY
381 #ifdef NEW_INSETS
382         // This is super temporary but is needed to get the compability
383         // mode for minipages work correctly together with new tabulars.
384         static int call_depth = 0;
385         ++call_depth;
386 #endif
387         bool checkminipage = false;
388         static LyXParagraph * minipar = 0;
389         static LyXParagraph * parBeforeMinipage = 0;
390 #endif
391         
392         if (token[0] != '\\') {
393                 for (string::const_iterator cit = token.begin();
394                      cit != token.end(); ++cit)
395                 {
396                         par->InsertChar(pos, (*cit), font);
397                         ++pos;
398                 }
399                 checkminipage = true;
400         } else if (token == "\\i") {
401                 Inset * inset = new InsetLatexAccent;
402                 inset->Read(this, lex);
403                 par->InsertInset(pos, inset, font);
404                 ++pos;
405         } else if (token == "\\layout") {
406 #ifndef NEW_INSETS
407                 if (!return_par) 
408                         return_par = par;
409                 else {
410                         par->fitToSize();
411                         par = new LyXParagraph(par);
412                 }
413                 pos = 0;
414                 lex.EatLine();
415                 string const layoutname = lex.GetString();
416                 pair<bool, LyXTextClass::LayoutList::size_type> pp
417                         = textclasslist.NumberOfLayout(params.textclass,
418                                                        layoutname);
419                 if (pp.first) {
420                         par->layout = pp.second;
421                 } else { // layout not found
422                         // use default layout "Standard" (0)
423                         par->layout = 0;
424                 }
425                 // Test whether the layout is obsolete.
426                 LyXLayout const & layout =
427                         textclasslist.Style(params.textclass,
428                                             par->layout); 
429                 if (!layout.obsoleted_by().empty())
430                         par->layout = 
431                                 textclasslist.NumberOfLayout(params.textclass, 
432                                                              layout.obsoleted_by()).second;
433                 par->footnoteflag = footnoteflag;
434                 par->footnotekind = footnotekind;
435                 par->params.depth(depth);
436                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
437                 if (file_format < 216 && params.language->lang() == "hebrew")
438                         font.setLanguage(default_language);
439 #else
440                 lex.EatLine();
441                 string const layoutname = lex.GetString();
442                 pair<bool, LyXTextClass::LayoutList::size_type> pp
443                         = textclasslist.NumberOfLayout(params.textclass,
444                                                        layoutname);
445
446 #ifdef USE_CAPTION
447                 // The is the compability reading of layout caption.
448                 // It can be removed in LyX version 1.3.0. (Lgb)
449                 if (compare_no_case(layoutname, "caption") == 0) {
450                         // We expect that the par we are now working on is
451                         // really inside a InsetText inside a InsetFloat.
452                         // We also know that captions can only be
453                         // one paragraph. (Lgb)
454                         
455                         // We should now read until the next "\layout"
456                         // is reached.
457                         // This is probably not good enough, what if the
458                         // caption is the last par in the document (Lgb)
459                         istream & ist = lex.getStream();
460                         stringstream ss;
461                         string line;
462                         int begin = 0;
463                         while (true) {
464                                 getline(ist, line);
465                                 if (prefixIs(line, "\\layout")) {
466                                         lex.pushToken(line);
467                                         break;
468                                 }
469                                 if (prefixIs(line, "\\begin_inset"))
470                                         ++begin;
471                                 if (prefixIs(line, "\\end_inset")) {
472                                         if (begin)
473                                                 --begin;
474                                         else {
475                                                 lex.pushToken(line);
476                                                 break;
477                                         }
478                                 }
479                                 
480                                 ss << line << '\n';
481                         }
482                         // Now we should have the whole layout in ss
483                         // we should now be able to give this to the
484                         // caption inset.
485                         ss << "\\end_inset\n";
486                         
487                         // This seems like a bug in stringstream.
488                         // We really should be able to use ss
489                         // directly. (Lgb)
490                         istringstream is(ss.str());
491                         LyXLex tmplex(0, 0);
492                         tmplex.setStream(is);
493                         Inset * inset = new InsetCaption;
494                         inset->Read(this, tmplex);
495                         par->InsertInset(pos, inset, font);
496                         ++pos;
497                 } else {
498 #endif
499                         if (!return_par)
500                                 return_par = par;
501                         else {
502                                 par->fitToSize();
503                                 par = new LyXParagraph(par);
504                         }
505                         pos = 0;
506                         if (pp.first) {
507                                 par->layout = pp.second;
508                         } else {
509                                 // layout not found
510                                 // use default layout "Standard" (0)
511                                 par->layout = 0;
512                         }
513                         // Test whether the layout is obsolete.
514                         LyXLayout const & layout =
515                                 textclasslist.Style(params.textclass,
516                                                     par->layout);
517                         if (!layout.obsoleted_by().empty())
518                                 par->layout = textclasslist
519                                         .NumberOfLayout(params.textclass,
520                                                         layout.obsoleted_by())
521                                         .second;
522                         par->params.depth(depth);
523                         font = LyXFont(LyXFont::ALL_INHERIT, params.language);
524                         if (file_format < 216
525                             && params.language->lang() == "hebrew")
526                                 font.setLanguage(default_language);
527 #if USE_CAPTION
528                 }
529 #endif
530 #endif
531 #ifndef NEW_INSETS
532         } else if (token == "\\end_float") {
533                 if (!return_par) 
534                         return_par = par;
535                 else {
536                         par->fitToSize();
537                         par = new LyXParagraph(par);
538                 }
539                 footnotekind = LyXParagraph::FOOTNOTE;
540                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
541                 pos = 0;
542                 lex.EatLine();
543                 par->layout = LYX_DUMMY_LAYOUT;
544                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
545                 if (file_format < 216 && params.language->lang() == "hebrew")
546                         font.setLanguage(default_language);
547         } else if (token == "\\begin_float") {
548                 int tmpret = lex.FindToken(string_footnotekinds);
549                 if (tmpret == -1) ++tmpret;
550                 if (tmpret != LYX_LAYOUT_DEFAULT) 
551                         footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
552                 if (footnotekind == LyXParagraph::FOOTNOTE
553                     || footnotekind == LyXParagraph::MARGIN)
554                         footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
555                 else 
556                         footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
557 #else
558         } else if (token == "\\begin_float") {
559                 // This is the compability reader. It can be removed in
560                 // LyX version 1.3.0. (Lgb)
561                 lex.next();
562                 string const tmptok = lex.GetString();
563                 //lyxerr << "old float: " << tmptok << endl;
564                 
565                 Inset * inset = 0;
566                 stringstream old_float;
567                 
568                 if (tmptok == "footnote") {
569                         inset = new InsetFoot;
570                 } else if (tmptok == "margin") {
571                         inset = new InsetMarginal;
572                 } else if (tmptok == "fig") {
573                         inset = new InsetFloat("figure");
574                         old_float << "placement htbp\n";
575                 } else if (tmptok == "tab") {
576                         inset = new InsetFloat("table");
577                         old_float << "placement htbp\n";
578                 } else if (tmptok == "alg") {
579                         inset = new InsetFloat("algorithm");
580                         old_float << "placement htbp\n";
581                 } else if (tmptok == "wide-fig") {
582                         InsetFloat * tmp = new InsetFloat("figure");
583                         tmp->wide(true);
584                         inset = tmp;
585                         old_float << "placement htbp\n";
586                 } else if (tmptok == "wide-tab") {
587                         InsetFloat * tmp = new InsetFloat("table");
588                         tmp->wide(true);
589                         inset = tmp;
590                         old_float << "placement htbp\n";
591                 }
592
593                 if (!inset) {
594                         --call_depth;
595                         return false; // no end read yet
596                 }
597                 
598                 old_float << "collapsed true\n";
599
600                 // Here we need to check for \end_deeper and handle that
601                 // before we do the footnote parsing.
602                 // This _is_ a hack! (Lgb)
603                 while (true) {
604                         lex.next();
605                         string const tmp = lex.GetString();
606                         if (tmp == "\\end_deeper") {
607                                 //lyxerr << "\\end_deeper caught!" << endl;
608                                 if (!depth) {
609                                         lex.printError("\\end_deeper: "
610                                                        "depth is already null");
611                                 } else
612                                         --depth;
613                                 
614                         } else {
615                                 old_float << tmp << ' ';
616                                 break;
617                         }
618                 }
619                 
620                 old_float << lex.getLongString("\\end_float")
621                           << "\n\\end_inset\n";
622                 //lyxerr << "Float Body:\n" << old_float.str() << endl;
623                 // That this does not work seems like a bug
624                 // in stringstream. (Lgb)
625                 istringstream istr(old_float.str());
626                 LyXLex nylex(0, 0);
627                 nylex.setStream(istr);
628                 inset->Read(this, nylex);
629                 par->InsertInset(pos, inset, font);
630                 ++pos;
631 #endif
632         } else if (token == "\\begin_deeper") {
633                 ++depth;
634         } else if (token == "\\end_deeper") {
635                 if (!depth) {
636                         lex.printError("\\end_deeper: "
637                                        "depth is already null");
638                 }
639                 else
640                         --depth;
641         } else if (token == "\\begin_preamble") {
642                 params.readPreamble(lex);
643         } else if (token == "\\textclass") {
644                 lex.EatLine();
645                 pair<bool, LyXTextClassList::size_type> pp = 
646                         textclasslist.NumberOfClass(lex.GetString());
647                 if (pp.first) {
648                         params.textclass = pp.second;
649                 } else {
650                         WriteAlert(string(_("Textclass error")), 
651                                 string(_("The document uses an unknown textclass \"")) + 
652                                 lex.GetString() + string("\"."),
653                                 string(_("LyX will not be able to produce output correctly.")));
654                         params.textclass = 0;
655                 }
656                 if (!textclasslist.Load(params.textclass)) {
657                                 // if the textclass wasn't loaded properly
658                                 // we need to either substitute another
659                                 // or stop loading the file.
660                                 // I can substitute but I don't see how I can
661                                 // stop loading... ideas??  ARRae980418
662                         WriteAlert(_("Textclass Loading Error!"),
663                                    string(_("Can't load textclass ")) +
664                                    textclasslist.NameOfClass(params.textclass),
665                                    _("-- substituting default"));
666                         params.textclass = 0;
667                 }
668         } else if (token == "\\options") {
669                 lex.EatLine();
670                 params.options = lex.GetString();
671         } else if (token == "\\language") {
672                 params.readLanguage(lex);    
673         } else if (token == "\\fontencoding") {
674                 lex.EatLine();
675         } else if (token == "\\inputencoding") {
676                 lex.EatLine();
677                 params.inputenc = lex.GetString();
678         } else if (token == "\\graphics") {
679                 params.readGraphicsDriver(lex);
680         } else if (token == "\\fontscheme") {
681                 lex.EatLine();
682                 params.fonts = lex.GetString();
683         } else if (token == "\\noindent") {
684                 par->params.noindent(true);
685         } else if (token == "\\fill_top") {
686                 par->params.spaceTop(VSpace(VSpace::VFILL));
687         } else if (token == "\\fill_bottom") {
688                 par->params.spaceBottom(VSpace(VSpace::VFILL));
689         } else if (token == "\\line_top") {
690                 par->params.lineTop(true);
691         } else if (token == "\\line_bottom") {
692                 par->params.lineBottom(true);
693         } else if (token == "\\pagebreak_top") {
694                 par->params.pagebreakTop(true);
695         } else if (token == "\\pagebreak_bottom") {
696                 par->params.pagebreakBottom(true);
697         } else if (token == "\\start_of_appendix") {
698                 par->params.startOfAppendix(true);
699         } else if (token == "\\paragraph_separation") {
700                 int tmpret = lex.FindToken(string_paragraph_separation);
701                 if (tmpret == -1) ++tmpret;
702                 if (tmpret != LYX_LAYOUT_DEFAULT) 
703                         params.paragraph_separation =
704                                 static_cast<BufferParams::PARSEP>(tmpret);
705         } else if (token == "\\defskip") {
706                 lex.nextToken();
707                 params.defskip = VSpace(lex.GetString());
708         } else if (token == "\\epsfig") { // obsolete
709                 // Indeed it is obsolete, but we HAVE to be backwards
710                 // compatible until 0.14, because otherwise all figures
711                 // in existing documents are irretrivably lost. (Asger)
712                 params.readGraphicsDriver(lex);
713         } else if (token == "\\quotes_language") {
714                 int tmpret = lex.FindToken(string_quotes_language);
715                 if (tmpret == -1) ++tmpret;
716                 if (tmpret != LYX_LAYOUT_DEFAULT) {
717                         InsetQuotes::quote_language tmpl = 
718                                 InsetQuotes::EnglishQ;
719                         switch (tmpret) {
720                         case 0:
721                                 tmpl = InsetQuotes::EnglishQ;
722                                 break;
723                         case 1:
724                                 tmpl = InsetQuotes::SwedishQ;
725                                 break;
726                         case 2:
727                                 tmpl = InsetQuotes::GermanQ;
728                                 break;
729                         case 3:
730                                 tmpl = InsetQuotes::PolishQ;
731                                 break;
732                         case 4:
733                                 tmpl = InsetQuotes::FrenchQ;
734                                 break;
735                         case 5:
736                                 tmpl = InsetQuotes::DanishQ;
737                                 break;  
738                         }
739                         params.quotes_language = tmpl;
740                 }
741         } else if (token == "\\quotes_times") {
742                 lex.nextToken();
743                 switch (lex.GetInteger()) {
744                 case 1: 
745                         params.quotes_times = InsetQuotes::SingleQ; 
746                         break;
747                 case 2: 
748                         params.quotes_times = InsetQuotes::DoubleQ; 
749                         break;
750                 }
751         } else if (token == "\\papersize") {
752                 int tmpret = lex.FindToken(string_papersize);
753                 if (tmpret == -1)
754                         ++tmpret;
755                 else
756                         params.papersize2 = tmpret;
757         } else if (token == "\\paperpackage") {
758                 int tmpret = lex.FindToken(string_paperpackages);
759                 if (tmpret == -1) {
760                         ++tmpret;
761                         params.paperpackage = BufferParams::PACKAGE_NONE;
762                 } else
763                         params.paperpackage = tmpret;
764         } else if (token == "\\use_geometry") {
765                 lex.nextToken();
766                 params.use_geometry = lex.GetInteger();
767         } else if (token == "\\use_amsmath") {
768                 lex.nextToken();
769                 params.use_amsmath = lex.GetInteger();
770         } else if (token == "\\paperorientation") {
771                 int tmpret = lex.FindToken(string_orientation);
772                 if (tmpret == -1) ++tmpret;
773                 if (tmpret != LYX_LAYOUT_DEFAULT) 
774                         params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
775         } else if (token == "\\paperwidth") {
776                 lex.next();
777                 params.paperwidth = lex.GetString();
778         } else if (token == "\\paperheight") {
779                 lex.next();
780                 params.paperheight = lex.GetString();
781         } else if (token == "\\leftmargin") {
782                 lex.next();
783                 params.leftmargin = lex.GetString();
784         } else if (token == "\\topmargin") {
785                 lex.next();
786                 params.topmargin = lex.GetString();
787         } else if (token == "\\rightmargin") {
788                 lex.next();
789                 params.rightmargin = lex.GetString();
790         } else if (token == "\\bottommargin") {
791                 lex.next();
792                 params.bottommargin = lex.GetString();
793         } else if (token == "\\headheight") {
794                 lex.next();
795                 params.headheight = lex.GetString();
796         } else if (token == "\\headsep") {
797                 lex.next();
798                 params.headsep = lex.GetString();
799         } else if (token == "\\footskip") {
800                 lex.next();
801                 params.footskip = lex.GetString();
802         } else if (token == "\\paperfontsize") {
803                 lex.nextToken();
804                 params.fontsize = strip(lex.GetString());
805         } else if (token == "\\papercolumns") {
806                 lex.nextToken();
807                 params.columns = lex.GetInteger();
808         } else if (token == "\\papersides") {
809                 lex.nextToken();
810                 switch (lex.GetInteger()) {
811                 default:
812                 case 1: params.sides = LyXTextClass::OneSide; break;
813                 case 2: params.sides = LyXTextClass::TwoSides; break;
814                 }
815         } else if (token == "\\paperpagestyle") {
816                 lex.nextToken();
817                 params.pagestyle = strip(lex.GetString());
818         } else if (token == "\\bullet") {
819                 lex.nextToken();
820                 int const index = lex.GetInteger();
821                 lex.nextToken();
822                 int temp_int = lex.GetInteger();
823                 params.user_defined_bullets[index].setFont(temp_int);
824                 params.temp_bullets[index].setFont(temp_int);
825                 lex.nextToken();
826                 temp_int = lex.GetInteger();
827                 params.user_defined_bullets[index].setCharacter(temp_int);
828                 params.temp_bullets[index].setCharacter(temp_int);
829                 lex.nextToken();
830                 temp_int = lex.GetInteger();
831                 params.user_defined_bullets[index].setSize(temp_int);
832                 params.temp_bullets[index].setSize(temp_int);
833                 lex.nextToken();
834                 string const temp_str = lex.GetString();
835                 if (temp_str != "\\end_bullet") {
836                                 // this element isn't really necessary for
837                                 // parsing but is easier for humans
838                                 // to understand bullets. Put it back and
839                                 // set a debug message?
840                         lex.printError("\\end_bullet expected, got" + temp_str);
841                                 //how can I put it back?
842                 }
843         } else if (token == "\\bulletLaTeX") {
844                 lex.nextToken();
845                 int const index = lex.GetInteger();
846                 lex.next();
847                 string temp_str = lex.GetString();
848                 string sum_str;
849                 while (temp_str != "\\end_bullet") {
850                                 // this loop structure is needed when user
851                                 // enters an empty string since the first
852                                 // thing returned will be the \\end_bullet
853                                 // OR
854                                 // if the LaTeX entry has spaces. Each element
855                                 // therefore needs to be read in turn
856                         sum_str += temp_str;
857                         lex.next();
858                         temp_str = lex.GetString();
859                 }
860                 params.user_defined_bullets[index].setText(sum_str);
861                 params.temp_bullets[index].setText(sum_str);
862         } else if (token == "\\secnumdepth") {
863                 lex.nextToken();
864                 params.secnumdepth = lex.GetInteger();
865         } else if (token == "\\tocdepth") {
866                 lex.nextToken();
867                 params.tocdepth = lex.GetInteger();
868         } else if (token == "\\spacing") {
869                 lex.next();
870                 string const tmp = strip(lex.GetString());
871                 Spacing::Space tmp_space = Spacing::Default;
872                 float tmp_val = 0.0;
873                 if (tmp == "single") {
874                         tmp_space = Spacing::Single;
875                 } else if (tmp == "onehalf") {
876                         tmp_space = Spacing::Onehalf;
877                 } else if (tmp == "double") {
878                         tmp_space = Spacing::Double;
879                 } else if (tmp == "other") {
880                         lex.next();
881                         tmp_space = Spacing::Other;
882                         tmp_val = lex.GetFloat();
883                 } else {
884                         lex.printError("Unknown spacing token: '$$Token'");
885                 }
886                 // Small hack so that files written with klyx will be
887                 // parsed correctly.
888                 if (return_par) {
889                         par->params.spacing(Spacing(tmp_space, tmp_val));
890                 } else {
891                         params.spacing.set(tmp_space, tmp_val);
892                 }
893         } else if (token == "\\paragraph_spacing") {
894                 lex.next();
895                 string const tmp = strip(lex.GetString());
896                 if (tmp == "single") {
897                         par->params.spacing(Spacing(Spacing::Single));
898                 } else if (tmp == "onehalf") {
899                         par->params.spacing(Spacing(Spacing::Onehalf));
900                 } else if (tmp == "double") {
901                         par->params.spacing(Spacing(Spacing::Double));
902                 } else if (tmp == "other") {
903                         lex.next();
904                         par->params.spacing(Spacing(Spacing::Other,
905                                          lex.GetFloat()));
906                 } else {
907                         lex.printError("Unknown spacing token: '$$Token'");
908                 }
909         } else if (token == "\\float_placement") {
910                 lex.nextToken();
911                 params.float_placement = lex.GetString();
912         } else if (token == "\\family") { 
913                 lex.next();
914                 font.setLyXFamily(lex.GetString());
915         } else if (token == "\\series") {
916                 lex.next();
917                 font.setLyXSeries(lex.GetString());
918         } else if (token == "\\shape") {
919                 lex.next();
920                 font.setLyXShape(lex.GetString());
921         } else if (token == "\\size") {
922                 lex.next();
923                 font.setLyXSize(lex.GetString());
924         } else if (token == "\\latex") {
925                 lex.next();
926                 string const tok = lex.GetString();
927                 // This is dirty, but gone with LyX3. (Asger)
928                 if (tok == "no_latex")
929                         font.setLatex(LyXFont::OFF);
930                 else if (tok == "latex")
931                         font.setLatex(LyXFont::ON);
932                 else if (tok == "default")
933                         font.setLatex(LyXFont::INHERIT);
934                 else
935                         lex.printError("Unknown LaTeX font flag "
936                                        "`$$Token'");
937         } else if (token == "\\lang") {
938                 lex.next();
939                 string const tok = lex.GetString();
940                 Language const * lang = languages.getLanguage(tok);
941                 if (lang) {
942                         font.setLanguage(lang);
943                 } else {
944                         font.setLanguage(params.language);
945                         lex.printError("Unknown language `$$Token'");
946                 }
947         } else if (token == "\\numeric") {
948                 lex.next();
949                 font.setNumber(font.setLyXMisc(lex.GetString()));
950         } else if (token == "\\emph") {
951                 lex.next();
952                 font.setEmph(font.setLyXMisc(lex.GetString()));
953         } else if (token == "\\bar") {
954                 lex.next();
955                 string const tok = lex.GetString();
956                 // This is dirty, but gone with LyX3. (Asger)
957                 if (tok == "under")
958                         font.setUnderbar(LyXFont::ON);
959                 else if (tok == "no")
960                         font.setUnderbar(LyXFont::OFF);
961                 else if (tok == "default")
962                         font.setUnderbar(LyXFont::INHERIT);
963                 else
964                         lex.printError("Unknown bar font flag "
965                                        "`$$Token'");
966         } else if (token == "\\noun") {
967                 lex.next();
968                 font.setNoun(font.setLyXMisc(lex.GetString()));
969         } else if (token == "\\color") {
970                 lex.next();
971                 font.setLyXColor(lex.GetString());
972         } else if (token == "\\align") {
973                 int tmpret = lex.FindToken(string_align);
974                 if (tmpret == -1) ++tmpret;
975                 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
976                         int const tmpret2 = int(pow(2.0, tmpret));
977                         //lyxerr << "Tmpret2 = " << tmpret2 << endl;
978                         par->params.align(LyXAlignment(tmpret2));
979                 }
980         } else if (token == "\\added_space_top") {
981                 lex.nextToken();
982                 par->params.spaceTop(VSpace(lex.GetString()));
983         } else if (token == "\\added_space_bottom") {
984                 lex.nextToken();
985                 par->params.spaceBottom(VSpace(lex.GetString()));
986 #ifndef NO_PEXTRA_REALLY
987         } else if (token == "\\pextra_type") {
988                 lex.nextToken();
989                 par->params.pextraType(lex.GetInteger());
990         } else if (token == "\\pextra_width") {
991                 lex.nextToken();
992                 par->params.pextraWidth(lex.GetString());
993         } else if (token == "\\pextra_widthp") {
994                 lex.nextToken();
995                 par->params.pextraWidthp(lex.GetString());
996         } else if (token == "\\pextra_alignment") {
997                 lex.nextToken();
998                 par->params.pextraAlignment(lex.GetInteger());
999         } else if (token == "\\pextra_hfill") {
1000                 lex.nextToken();
1001                 par->params.pextraHfill(lex.GetInteger());
1002         } else if (token == "\\pextra_start_minipage") {
1003                 lex.nextToken();
1004                 par->params.pextraStartMinipage(lex.GetInteger());
1005 #endif
1006         } else if (token == "\\labelwidthstring") {
1007                 lex.EatLine();
1008                 par->params.labelWidthString(lex.GetString());
1009                 // do not delete this token, it is still needed!
1010         } else if (token == "\\end_inset") {
1011                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1012                        << "Last inset read was: " << last_inset_read
1013                        << endl;
1014                 // Simply ignore this. The insets do not have
1015                 // to read this.
1016                 // But insets should read it, it is a part of
1017                 // the inset isn't it? Lgb.
1018         } else if (token == "\\begin_inset") {
1019                 readInset(lex, par, pos, font);
1020         } else if (token == "\\SpecialChar") {
1021                 LyXLayout const & layout =
1022                         textclasslist.Style(params.textclass, 
1023                                             par->GetLayout());
1024
1025                 // Insets don't make sense in a free-spacing context! ---Kayvan
1026                 if (layout.free_spacing) {
1027                         if (lex.IsOK()) {
1028                                 lex.next();
1029                                 string next_token = lex.GetString();
1030                                 if (next_token == "\\-") {
1031                                         par->InsertChar(pos, '-', font);
1032                                 } else if (next_token == "\\protected_separator"
1033                                         || next_token == "~") {
1034                                         par->InsertChar(pos, ' ', font);
1035                                 } else {
1036                                         lex.printError("Token `$$Token' "
1037                                                        "is in free space "
1038                                                        "paragraph layout!");
1039                                         --pos;
1040                                 }
1041                         }
1042                 } else {
1043                         Inset * inset = new InsetSpecialChar;
1044                         inset->Read(this, lex);
1045                         par->InsertInset(pos, inset, font);
1046                 }
1047                 ++pos;
1048         } else if (token == "\\newline") {
1049                 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
1050                 ++pos;
1051         } else if (token == "\\LyXTable") {
1052                 Inset * inset = new InsetTabular(*this);
1053                 inset->Read(this, lex);
1054                 par->InsertInset(pos, inset, font);
1055                 ++pos;
1056                 // because of OLD_TABULAR_READ where tabulars have been
1057                 // one paragraph.
1058                 checkminipage = true;
1059         } else if (token == "\\hfill") {
1060                 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
1061                 ++pos;
1062         } else if (token == "\\protected_separator") { // obsolete
1063                 // This is a backward compability thingie. (Lgb)
1064                 // Remove it later some time...introduced with fileformat
1065                 // 2.16. (Lgb)
1066                 LyXLayout const & layout =
1067                         textclasslist.Style(params.textclass, 
1068                                             par->GetLayout());
1069
1070                 if (layout.free_spacing) {
1071                         par->InsertChar(pos, ' ', font);
1072                 } else {
1073                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1074                         par->InsertInset(pos, inset, font);
1075                 }
1076                 ++pos;
1077         } else if (token == "\\bibitem") {  // ale970302
1078                 if (!par->bibkey) {
1079                         InsetCommandParams p("bibitem", "dummy");
1080                         par->bibkey = new InsetBibKey(p);
1081                 }
1082                 par->bibkey->Read(this, lex);                   
1083         } else if (token == "\\backslash") {
1084                 par->InsertChar(pos, '\\', font);
1085                 ++pos;
1086         } else if (token == "\\the_end") {
1087                 the_end_read = true;
1088                 minipar = parBeforeMinipage = 0;
1089         } else {
1090                 // This should be insurance for the future: (Asger)
1091                 lex.printError("Unknown token `$$Token'. "
1092                                "Inserting as text.");
1093                 string::const_iterator cit = token.begin();
1094                 string::const_iterator end = token.end();
1095                 for (; cit != end; ++cit) {
1096                         par->InsertChar(pos, (*cit), font);
1097                         ++pos;
1098                 }
1099         }
1100 #ifndef NO_PEXTRA_REALLY
1101         // now check if we have a minipage paragraph as at this
1102         // point we already read all the necessary data!
1103         // this cannot be done in layout because there we did
1104         // not read yet the paragraph PEXTRA-params (Jug)
1105         //
1106         // BEGIN pextra_minipage compability
1107         // This should be removed in 1.3.x (Lgb)
1108         
1109         // This compability code is not perfect. In a couple
1110         // of rand cases it fails. When the minipage par is
1111         // the first par in the document, and when there are
1112         // none or only one regular paragraphs after the
1113         // minipage. Currently I am not investing any effort
1114         // in fixing those cases.
1115
1116         //lyxerr << "Call depth: " << call_depth << endl;
1117         if (checkminipage && (call_depth == 1)) {
1118         checkminipage = false;
1119         if (minipar && (minipar != par) &&
1120             (par->params.pextraType()==LyXParagraph::PEXTRA_MINIPAGE))
1121         {
1122                 lyxerr << "minipages in a row" << endl;
1123                 if (par->params.pextraStartMinipage()) {
1124                         lyxerr << "start new minipage" << endl;
1125                         // minipages in a row
1126                         par->previous()->next(0);
1127                         par->previous(0);
1128                                 
1129                         LyXParagraph * tmp = minipar;
1130                         while (tmp) {
1131                                 tmp->params.pextraType(0);
1132                                 tmp->params.pextraWidth(string());
1133                                 tmp->params.pextraWidthp(string());
1134                                 tmp->params.pextraAlignment(0);
1135                                 tmp->params.pextraHfill(false);
1136                                 tmp->params.pextraStartMinipage(false);
1137                                 tmp = tmp->next();
1138                         }
1139                         // create a new paragraph to insert the
1140                         // minipages in the following case
1141                         if (par->params.pextraStartMinipage() &&
1142                             !par->params.pextraHfill())
1143                         {
1144                                 LyXParagraph * p = new LyXParagraph;
1145                                 p->layout = 0;
1146                                 p->previous(parBeforeMinipage);
1147                                 parBeforeMinipage->next(p);
1148                                 p->next(0);
1149                                 p->params.depth(parBeforeMinipage->params.depth());
1150                                 parBeforeMinipage = p;
1151                         }
1152                         InsetMinipage * mini = new InsetMinipage;
1153                         mini->pos(static_cast<InsetMinipage::Position>(par->params.pextraAlignment()));
1154                         mini->width(par->params.pextraWidth());
1155                         if (!par->params.pextraWidthp().empty()) {
1156                             lyxerr << "WP:" << mini->width() << endl;
1157                             mini->width(tostr(par->params.pextraWidthp())+"%");
1158                         }
1159                         mini->inset.par = par;
1160                         // Insert the minipage last in the
1161                         // previous paragraph.
1162                         if (par->params.pextraHfill()) {
1163                                 parBeforeMinipage->InsertChar
1164                                         (parBeforeMinipage->size(), LyXParagraph::META_HFILL);
1165                         }
1166                         parBeforeMinipage->InsertInset
1167                                 (parBeforeMinipage->size(), mini);
1168                                 
1169                         minipar = par;
1170                 } else {
1171                         lyxerr << "new minipage par" << endl;
1172                         //nothing to do just continue reading
1173                 }
1174                         
1175         } else if (minipar && (minipar != par)) {
1176                 lyxerr << "last minipage par read" << endl;
1177                 // The last paragraph read was not part of a
1178                 // minipage but the par linked list is...
1179                 // So we need to remove the last par from the
1180                 // rest
1181                 if (par->previous())
1182                         par->previous()->next(0);
1183                 par->previous(parBeforeMinipage);
1184                 parBeforeMinipage->next(par);
1185                 LyXParagraph * tmp = minipar;
1186                 while (tmp) {
1187                         tmp->params.pextraType(0);
1188                         tmp->params.pextraWidth(string());
1189                         tmp->params.pextraWidthp(string());
1190                         tmp->params.pextraAlignment(0);
1191                         tmp->params.pextraHfill(false);
1192                         tmp->params.pextraStartMinipage(false);
1193                         tmp = tmp->next();
1194                 }
1195                 depth = parBeforeMinipage->params.depth();
1196                 minipar = parBeforeMinipage = 0;
1197         } else if (!minipar &&
1198                    (par->params.pextraType() == LyXParagraph::PEXTRA_MINIPAGE))
1199         {
1200                 // par is the first paragraph in a minipage
1201                 lyxerr << "begin minipage" << endl;
1202                 // To minimize problems for
1203                 // the users we will insert
1204                 // the first minipage in
1205                 // a sequence of minipages
1206                 // in its own paragraph.
1207                 LyXParagraph * p = new LyXParagraph;
1208                 p->layout = 0;
1209                 p->previous(par->previous());
1210                 p->next(0);
1211                 p->params.depth(depth);
1212                 par->params.depth(0);
1213                 depth = 0;
1214                 if (par->previous())
1215                         par->previous()->next(p);
1216                 par->previous(0);
1217                 parBeforeMinipage = p;
1218                 minipar = par;
1219                 if (!return_par || (return_par == par))
1220                         return_par = p;
1221
1222                 InsetMinipage * mini = new InsetMinipage;
1223                 mini->pos(static_cast<InsetMinipage::Position>(minipar->params.pextraAlignment()));
1224                 mini->width(minipar->params.pextraWidth());
1225                 if (!par->params.pextraWidthp().empty()) {
1226                     lyxerr << "WP:" << mini->width() << endl;
1227                     mini->width(tostr(par->params.pextraWidthp())+"%");
1228                 }
1229                 mini->inset.par = minipar;
1230                         
1231                 // Insert the minipage last in the
1232                 // previous paragraph.
1233                 if (minipar->params.pextraHfill()) {
1234                         parBeforeMinipage->InsertChar
1235                                 (parBeforeMinipage->size(),LyXParagraph::META_HFILL);
1236                 }
1237                 parBeforeMinipage->InsertInset
1238                         (parBeforeMinipage->size(), mini);
1239         }
1240         }
1241         // End of pextra_minipage compability
1242 #endif
1243         --call_depth;
1244         return the_end_read;
1245 }
1246
1247
1248 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
1249                        int & pos, LyXFont & font)
1250 {
1251         // consistency check
1252         if (lex.GetString() != "\\begin_inset") {
1253                 lyxerr << "Buffer::readInset: Consistency check failed."
1254                        << endl;
1255         }
1256         
1257         Inset * inset = 0;
1258
1259         lex.next();
1260         string const tmptok = lex.GetString();
1261         last_inset_read = tmptok;
1262
1263         // test the different insets
1264         if (tmptok == "LatexCommand") {
1265                 InsetCommandParams inscmd;
1266                 inscmd.Read(lex);
1267
1268                 if (inscmd.getCmdName() == "cite") {
1269                         inset = new InsetCitation(inscmd);
1270                 } else if (inscmd.getCmdName() == "bibitem") {
1271                         lex.printError("Wrong place for bibitem");
1272                         inset = new InsetBibKey(inscmd);
1273                 } else if (inscmd.getCmdName() == "BibTeX") {
1274                         inset = new InsetBibtex(inscmd);
1275                 } else if (inscmd.getCmdName() == "index") {
1276                         inset = new InsetIndex(inscmd);
1277                 } else if (inscmd.getCmdName() == "include") {
1278                         inset = new InsetInclude(inscmd, *this);
1279                 } else if (inscmd.getCmdName() == "label") {
1280                         inset = new InsetLabel(inscmd);
1281                 } else if (inscmd.getCmdName() == "url"
1282                            || inscmd.getCmdName() == "htmlurl") {
1283                         inset = new InsetUrl(inscmd);
1284                 } else if (inscmd.getCmdName() == "ref"
1285                            || inscmd.getCmdName() == "pageref"
1286                            || inscmd.getCmdName() == "vref"
1287                            || inscmd.getCmdName() == "vpageref"
1288                            || inscmd.getCmdName() == "prettyref") {
1289                         if (!inscmd.getOptions().empty()
1290                             || !inscmd.getContents().empty()) {
1291                                 inset = new InsetRef(inscmd, *this);
1292                         }
1293                 } else if (inscmd.getCmdName() == "tableofcontents"
1294                            || inscmd.getCmdName() == "listofalgorithms"
1295                            || inscmd.getCmdName() == "listoffigures"
1296                            || inscmd.getCmdName() == "listoftables") {
1297                         inset = new InsetTOC(inscmd);
1298                 } else if (inscmd.getCmdName() == "printindex") {
1299                         inset = new InsetPrintIndex(inscmd);
1300                 } else if (inscmd.getCmdName() == "lyxparent") {
1301                         inset = new InsetParent(inscmd, *this);
1302                 }
1303         } else {
1304                 if (tmptok == "Quotes") {
1305                         inset = new InsetQuotes;
1306                 } else if (tmptok == "External") {
1307                         inset = new InsetExternal;
1308                 } else if (tmptok == "FormulaMacro") {
1309                         inset = new InsetFormulaMacro;
1310                 } else if (tmptok == "Formula") {
1311                         inset = new InsetFormula;
1312                 } else if (tmptok == "Figure") {
1313                         inset = new InsetFig(100, 100, *this);
1314                 } else if (tmptok == "Info") {
1315                         inset = new InsetInfo;
1316                 } else if (tmptok == "Include") {
1317                         InsetCommandParams p( "Include" );
1318                         inset = new InsetInclude(p, *this);
1319                 } else if (tmptok == "ERT") {
1320                         inset = new InsetERT;
1321                 } else if (tmptok == "Tabular") {
1322                         inset = new InsetTabular(*this);
1323                 } else if (tmptok == "Text") {
1324                         inset = new InsetText;
1325                 } else if (tmptok == "Foot") {
1326                         inset = new InsetFoot;
1327                 } else if (tmptok == "Marginal") {
1328                         inset = new InsetMarginal;
1329                 } else if (tmptok == "Minipage") {
1330                         inset = new InsetMinipage;
1331                 } else if (tmptok == "Float") {
1332                         lex.next();
1333                         string tmptok = lex.GetString();
1334                         inset = new InsetFloat(tmptok);
1335                 } else if (tmptok == "List") {
1336                         inset = new InsetList;
1337                 } else if (tmptok == "Theorem") {
1338                         inset = new InsetList;
1339                 } else if (tmptok == "Caption") {
1340                         inset = new InsetCaption;
1341                 } else if (tmptok == "GRAPHICS") {
1342                         inset = new InsetGraphics;
1343                 }
1344                 
1345                 if (inset) inset->Read(this, lex);
1346         }
1347         
1348         if (inset) {
1349                 par->InsertInset(pos, inset, font);
1350                 ++pos;
1351         }
1352 }
1353
1354
1355 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1356 {
1357         if (lex.IsOK()) {
1358                 lex.next();
1359                 string const token(lex.GetString());
1360                 if (token == "\\lyxformat") { // the first token _must_ be...
1361                         lex.EatLine();
1362                         string tmp_format = lex.GetString();
1363                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1364                         // if present remove ".," from string.
1365                         string::size_type dot = tmp_format.find_first_of(".,");
1366                         //lyxerr << "           dot found at " << dot << endl;
1367                         if (dot != string::npos)
1368                                 tmp_format.erase(dot, 1);
1369                         file_format = strToInt(tmp_format);
1370                         if (file_format == LYX_FORMAT) {
1371                                 // current format
1372                         } else if (file_format > LYX_FORMAT) {
1373                                 // future format
1374                                 WriteAlert(_("Warning!"),
1375                                            _("LyX file format is newer that what"),
1376                                            _("is supported in this LyX version. Expect some problems."));
1377                                 
1378                         } else if (file_format < LYX_FORMAT) {
1379                                 // old formats
1380                                 if (file_format < 200) {
1381                                         WriteAlert(_("ERROR!"),
1382                                                    _("Old LyX file format found. "
1383                                                      "Use LyX 0.10.x to read this!"));
1384                                         return false;
1385                                 }
1386                         }
1387                         bool the_end = readLyXformat2(lex, par);
1388                         setPaperStuff();
1389                         // the_end was added in 213
1390                         if (file_format < 213)
1391                                 the_end = true;
1392
1393                         if (!the_end)
1394                                 WriteAlert(_("Warning!"),
1395                                            _("Reading of document is not complete"),
1396                                            _("Maybe the document is truncated"));
1397                         return true;
1398                 } else { // "\\lyxformat" not found
1399                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1400                 }
1401         } else
1402                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1403         return false;
1404 }
1405                     
1406
1407
1408 // Should probably be moved to somewhere else: BufferView? LyXView?
1409 bool Buffer::save() const
1410 {
1411         // We don't need autosaves in the immediate future. (Asger)
1412         resetAutosaveTimers();
1413
1414         // make a backup
1415         string s;
1416         if (lyxrc.make_backup) {
1417                 s = fileName() + '~';
1418                 if (!lyxrc.backupdir_path.empty())
1419                         s = AddName(lyxrc.backupdir_path,
1420                                     subst(CleanupPath(s),'/','!'));
1421
1422                 // Rename is the wrong way of making a backup,
1423                 // this is the correct way.
1424                 /* truss cp fil fil2:
1425                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1426                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1427                    open("LyXVC.lyx", O_RDONLY)                     = 3
1428                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1429                    fstat(4, 0xEFFFF508)                            = 0
1430                    fstat(3, 0xEFFFF508)                            = 0
1431                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1432                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1433                    read(3, 0xEFFFD4A0, 8192)                       = 0
1434                    close(4)                                        = 0
1435                    close(3)                                        = 0
1436                    chmod("LyXVC3.lyx", 0100644)                    = 0
1437                    lseek(0, 0, SEEK_CUR)                           = 46440
1438                    _exit(0)
1439                 */
1440
1441                 // Should proabaly have some more error checking here.
1442                 // Should be cleaned up in 0.13, at least a bit.
1443                 // Doing it this way, also makes the inodes stay the same.
1444                 // This is still not a very good solution, in particular we
1445                 // might loose the owner of the backup.
1446                 FileInfo finfo(fileName());
1447                 if (finfo.exist()) {
1448                         mode_t fmode = finfo.getMode();
1449                         struct utimbuf times = {
1450                                 finfo.getAccessTime(),
1451                                 finfo.getModificationTime() };
1452
1453                         ifstream ifs(fileName().c_str());
1454                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1455                         if (ifs && ofs) {
1456                                 ofs << ifs.rdbuf();
1457                                 ifs.close();
1458                                 ofs.close();
1459                                 ::chmod(s.c_str(), fmode);
1460                                 
1461                                 if (::utime(s.c_str(), &times)) {
1462                                         lyxerr << "utime error." << endl;
1463                                 }
1464                         } else {
1465                                 lyxerr << "LyX was not able to make "
1466                                         "backupcopy. Beware." << endl;
1467                         }
1468                 }
1469         }
1470         
1471         if (writeFile(fileName(), false)) {
1472                 markLyxClean();
1473                 removeAutosaveFile(fileName());
1474         } else {
1475                 // Saving failed, so backup is not backup
1476                 if (lyxrc.make_backup) {
1477                         lyx::rename(s, fileName());
1478                 }
1479                 return false;
1480         }
1481         return true;
1482 }
1483
1484
1485 // Returns false if unsuccesful
1486 bool Buffer::writeFile(string const & fname, bool flag) const
1487 {
1488         // if flag is false writeFile will not create any GUI
1489         // warnings, only cerr.
1490         // Needed for autosave in background or panic save (Matthias 120496)
1491
1492         if (read_only && (fname == filename)) {
1493                 // Here we should come with a question if we should
1494                 // perform the write anyway.
1495                 if (flag)
1496                         lyxerr << _("Error! Document is read-only: ")
1497                                << fname << endl;
1498                 else
1499                         WriteAlert(_("Error! Document is read-only: "),
1500                                    fname);
1501                 return false;
1502         }
1503
1504         FileInfo finfo(fname);
1505         if (finfo.exist() && !finfo.writable()) {
1506                 // Here we should come with a question if we should
1507                 // try to do the save anyway. (i.e. do a chmod first)
1508                 if (flag)
1509                         lyxerr << _("Error! Cannot write file: ")
1510                                << fname << endl;
1511                 else
1512                         WriteFSAlert(_("Error! Cannot write file: "),
1513                                      fname);
1514                 return false;
1515         }
1516
1517         ofstream ofs(fname.c_str());
1518         if (!ofs) {
1519                 if (flag)
1520                         lyxerr << _("Error! Cannot open file: ")
1521                                << fname << endl;
1522                 else
1523                         WriteFSAlert(_("Error! Cannot open file: "),
1524                                      fname);
1525                 return false;
1526         }
1527
1528 #ifdef HAVE_LOCALE
1529         // Use the standard "C" locale for file output.
1530         ofs.imbue(std::locale::classic());
1531 #endif
1532
1533         // The top of the file should not be written by params.
1534
1535         // write out a comment in the top of the file
1536         ofs << '#' << LYX_DOCVERSION 
1537             << " created this file. For more info see http://www.lyx.org/\n"
1538             << "\\lyxformat " << LYX_FORMAT << "\n";
1539
1540         // now write out the buffer paramters.
1541         params.writeFile(ofs);
1542
1543         char footnoteflag = 0;
1544         char depth = 0;
1545
1546         // this will write out all the paragraphs
1547         // using recursive descent.
1548         paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1549
1550         // Write marker that shows file is complete
1551         ofs << "\n\\the_end" << endl;
1552
1553         ofs.close();
1554
1555         // how to check if close went ok?
1556         // Following is an attempt... (BE 20001011)
1557         
1558         // good() returns false if any error occured, including some
1559         //        formatting error.
1560         // bad()  returns true if something bad happened in the buffer,
1561         //        which should include file system full errors.
1562
1563         bool status = true;
1564         if (!ofs.good()) {
1565                 status = false;
1566 #if 0
1567                 if (ofs.bad()) {
1568                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1569                 } else {
1570                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1571                                << endl;
1572                 }
1573 #endif
1574         }
1575         
1576         return status;
1577 }
1578
1579
1580 string const Buffer::asciiParagraph(LyXParagraph const * par,
1581                                     unsigned int linelen) const
1582 {
1583         ostringstream buffer;
1584         LyXFont font1;
1585         LyXFont font2;
1586         Inset const * inset;
1587         char c;
1588 #ifndef NEW_INSETS
1589         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1590 #endif
1591         char depth = 0;
1592         int ltype = 0;
1593         int ltype_depth = 0;
1594         unsigned int currlinelen = 0;
1595         bool ref_printed = false;
1596
1597         int noparbreak = 0;
1598         int islatex = 0;
1599 #ifndef NEW_INSETS
1600         if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1601             !par->previous_
1602             || par->previous()->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
1603                 /* begins a footnote environment ? */ 
1604                 if (footnoteflag != par->footnoteflag) {
1605                         footnoteflag = par->footnoteflag;
1606                         if (footnoteflag) {
1607                                 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1608                                 if ((linelen > 0) &&
1609                                     ((currlinelen + j) > linelen)) {
1610                                         buffer << "\n";
1611                                         currlinelen = 0;
1612                                 }
1613                                 buffer << "(["
1614                                        << string_footnotekinds[par->footnotekind]
1615                                        << "] ";
1616                                 currlinelen += j;
1617                         }
1618                 }
1619 #else
1620                 if (!par->previous()) {
1621 #endif
1622                 /* begins or ends a deeper area ?*/ 
1623                 if (depth != par->params.depth()) {
1624                         if (par->params.depth() > depth) {
1625                                 while (par->params.depth() > depth) {
1626                                         ++depth;
1627                                 }
1628                         } else {
1629                                 while (par->params.depth() < depth) {
1630                                         --depth;
1631                                 }
1632                         }
1633                 }
1634                 
1635                 /* First write the layout */
1636                 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1637                 if (tmp == "Itemize") {
1638                         ltype = 1;
1639                         ltype_depth = depth + 1;
1640                 } else if (tmp == "Enumerate") {
1641                         ltype = 2;
1642                         ltype_depth = depth + 1;
1643                 } else if (strstr(tmp.c_str(), "ection")) {
1644                         ltype = 3;
1645                         ltype_depth = depth + 1;
1646                 } else if (strstr(tmp.c_str(), "aragraph")) {
1647                         ltype = 4;
1648                         ltype_depth = depth + 1;
1649                 } else if (tmp == "Description") {
1650                         ltype = 5;
1651                         ltype_depth = depth + 1;
1652                 } else if (tmp == "Abstract") {
1653                         ltype = 6;
1654                         ltype_depth = 0;
1655                 } else if (tmp == "Bibliography") {
1656                         ltype = 7;
1657                         ltype_depth = 0;
1658                 } else {
1659                         ltype = 0;
1660                         ltype_depth = 0;
1661                 }
1662                 
1663                 /* maybe some vertical spaces */ 
1664                 
1665                 /* the labelwidthstring used in lists */ 
1666                 
1667                 /* some lines? */ 
1668                 
1669                 /* some pagebreaks? */ 
1670                 
1671                 /* noindent ? */ 
1672                 
1673                 /* what about the alignment */ 
1674         } else {
1675 #ifndef NEW_INSETS
1676                 /* dummy layout, that means a footnote ended */ 
1677                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1678                 buffer << ") ";
1679                 noparbreak = 1;
1680 #else
1681                 lyxerr << "Should this ever happen?" << endl;
1682 #endif
1683         }
1684       
1685         font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1686         for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1687                 if (!i &&
1688 #ifndef NEW_INSETS
1689                     !footnoteflag &&
1690 #endif
1691                     !noparbreak) {
1692                         if (linelen > 0)
1693                                 buffer << "\n\n";
1694                         for (char j = 0; j < depth; ++j)
1695                                 buffer << "  ";
1696                         currlinelen = depth * 2;
1697                         switch (ltype) {
1698                         case 0: /* Standard */
1699                         case 4: /* (Sub)Paragraph */
1700                         case 5: /* Description */
1701                                 break;
1702                         case 6: /* Abstract */
1703                                 if (linelen > 0)
1704                                         buffer << "Abstract\n\n";
1705                                 else
1706                                         buffer << "Abstract: ";
1707                                 break;
1708                         case 7: /* Bibliography */
1709                                 if (!ref_printed) {
1710                                         if (linelen > 0)
1711                                                 buffer << "References\n\n";
1712                                         else
1713                                                 buffer << "References: ";
1714                                         ref_printed = true;
1715                                 }
1716                                 break;
1717                         default:
1718                                 buffer << par->params.labelString() << " ";
1719                                 break;
1720                         }
1721                         if (ltype_depth > depth) {
1722                                 for (char j = ltype_depth - 1; j > depth; --j)
1723                                         buffer << "  ";
1724                                 currlinelen += (ltype_depth-depth)*2;
1725                         }
1726                 }
1727                 font2 = par->GetFontSettings(params, i);
1728                 if (font1.latex() != font2.latex()) {
1729                         if (font2.latex() == LyXFont::OFF)
1730                                 islatex = 0;
1731                         else
1732                                 islatex = 1;
1733                 } else {
1734                         islatex = 0;
1735                 }
1736                 c = par->GetUChar(params, i);
1737                 if (islatex)
1738                         continue;
1739                 switch (c) {
1740                 case LyXParagraph::META_INSET:
1741                         if ((inset = par->GetInset(i))) {
1742                                 if (!inset->Ascii(this, buffer)) {
1743                                         string dummy;
1744                                         string s = rsplit(buffer.str().c_str(),
1745                                                           dummy, '\n');
1746                                         currlinelen += s.length();
1747                                 } else {
1748                                         // to be sure it breaks paragraph
1749                                         currlinelen += linelen;
1750                                 }
1751                         }
1752                         break;
1753                 case LyXParagraph::META_NEWLINE:
1754                         if (linelen > 0) {
1755                                 buffer << "\n";
1756                                 for (char j = 0; j < depth; ++j)
1757                                         buffer << "  ";
1758                         }
1759                         currlinelen = depth * 2;
1760                         if (ltype_depth > depth) {
1761                                 for (char j = ltype_depth;
1762                                     j > depth; --j)
1763                                         buffer << "  ";
1764                                 currlinelen += (ltype_depth - depth) * 2;
1765                         }
1766                         break;
1767                 case LyXParagraph::META_HFILL: 
1768                         buffer << "\t";
1769                         break;
1770                 case '\\':
1771                         buffer << "\\";
1772                         break;
1773                 default:
1774                         if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1775                             (c == ' ') && ((i + 2) < par->size()))
1776                         {
1777                                 buffer << "\n";
1778                                 for (char j = 0; j < depth; ++j)
1779                                         buffer << "  ";
1780                                 currlinelen = depth * 2;
1781                                 if (ltype_depth > depth) {
1782                                         for (char j = ltype_depth;
1783                                             j > depth; --j)
1784                                                 buffer << "  ";
1785                                         currlinelen += (ltype_depth-depth)*2;
1786                                 }
1787                         } else if (c != '\0')
1788                                 buffer << c;
1789                         else if (c == '\0')
1790                                 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1791                         ++currlinelen;
1792                         break;
1793                 }
1794         }
1795         return buffer.str().c_str();
1796 }
1797
1798
1799 void Buffer::writeFileAscii(string const & fname, int linelen) 
1800 {
1801         ofstream ofs(fname.c_str());
1802         if (!ofs) {
1803                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1804                 return;
1805         }
1806         writeFileAscii(ofs, linelen);
1807 }
1808
1809
1810 void Buffer::writeFileAscii(ostream & ofs, int linelen) 
1811 {
1812         LyXParagraph * par = paragraph;
1813         while (par) {
1814                 ofs << asciiParagraph(par, linelen);
1815                 par = par->next();
1816         }
1817         ofs << "\n";
1818 }
1819
1820 bool use_babel;
1821
1822 void Buffer::makeLaTeXFile(string const & fname, 
1823                            string const & original_path,
1824                            bool nice, bool only_body)
1825 {
1826         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1827         
1828         niceFile = nice; // this will be used by Insetincludes.
1829
1830         tex_code_break_column = lyxrc.ascii_linelen;
1831
1832         LyXTextClass const & tclass =
1833                 textclasslist.TextClass(params.textclass);
1834
1835         ofstream ofs(fname.c_str());
1836         if (!ofs) {
1837                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1838                 return;
1839         }
1840         
1841         // validate the buffer.
1842         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1843         LaTeXFeatures features(params, tclass.numLayouts());
1844         validate(features);
1845         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1846         
1847         texrow.reset();
1848         // The starting paragraph of the coming rows is the 
1849         // first paragraph of the document. (Asger)
1850         texrow.start(paragraph, 0);
1851
1852         if (!only_body && nice) {
1853                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1854                         "For more info, see http://www.lyx.org/.\n"
1855                         "%% Do not edit unless you really know what "
1856                         "you are doing.\n";
1857                 texrow.newline();
1858                 texrow.newline();
1859         }
1860         lyxerr.debug() << "lyx header finished" << endl;
1861         // There are a few differences between nice LaTeX and usual files:
1862         // usual is \batchmode and has a 
1863         // special input@path to allow the including of figures
1864         // with either \input or \includegraphics (what figinsets do).
1865         // batchmode is not set if there is a tex_code_break_column.
1866         // In this case somebody is interested in the generated LaTeX,
1867         // so this is OK. input@path is set when the actual parameter
1868         // original_path is set. This is done for usual tex-file, but not
1869         // for nice-latex-file. (Matthias 250696)
1870         if (!only_body) {
1871                 if (!nice){
1872                         // code for usual, NOT nice-latex-file
1873                         ofs << "\\batchmode\n"; // changed
1874                         // from \nonstopmode
1875                         texrow.newline();
1876                 }
1877                 if (!original_path.empty()) {
1878                         ofs << "\\makeatletter\n"
1879                             << "\\def\\input@path{{"
1880                             << original_path << "/}}\n"
1881                             << "\\makeatother\n";
1882                         texrow.newline();
1883                         texrow.newline();
1884                         texrow.newline();
1885                 }
1886                 
1887                 ofs << "\\documentclass";
1888                 
1889                 string options; // the document class options.
1890                 
1891                 if (tokenPos(tclass.opt_fontsize(),
1892                              '|', params.fontsize) >= 0) {
1893                         // only write if existing in list (and not default)
1894                         options += params.fontsize;
1895                         options += "pt,";
1896                 }
1897                 
1898                 
1899                 if (!params.use_geometry &&
1900                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1901                         switch (params.papersize) {
1902                         case BufferParams::PAPER_A4PAPER:
1903                                 options += "a4paper,";
1904                                 break;
1905                         case BufferParams::PAPER_USLETTER:
1906                                 options += "letterpaper,";
1907                                 break;
1908                         case BufferParams::PAPER_A5PAPER:
1909                                 options += "a5paper,";
1910                                 break;
1911                         case BufferParams::PAPER_B5PAPER:
1912                                 options += "b5paper,";
1913                                 break;
1914                         case BufferParams::PAPER_EXECUTIVEPAPER:
1915                                 options += "executivepaper,";
1916                                 break;
1917                         case BufferParams::PAPER_LEGALPAPER:
1918                                 options += "legalpaper,";
1919                                 break;
1920                         }
1921                 }
1922
1923                 // if needed
1924                 if (params.sides != tclass.sides()) {
1925                         switch (params.sides) {
1926                         case LyXTextClass::OneSide:
1927                                 options += "oneside,";
1928                                 break;
1929                         case LyXTextClass::TwoSides:
1930                                 options += "twoside,";
1931                                 break;
1932                         }
1933
1934                 }
1935
1936                 // if needed
1937                 if (params.columns != tclass.columns()) {
1938                         if (params.columns == 2)
1939                                 options += "twocolumn,";
1940                         else
1941                                 options += "onecolumn,";
1942                 }
1943
1944                 if (!params.use_geometry 
1945                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1946                         options += "landscape,";
1947                 
1948                 // language should be a parameter to \documentclass
1949                 use_babel = false;
1950                 string language_options;
1951                 if (params.language->babel() == "hebrew"
1952                     && default_language->babel() != "hebrew")
1953                          // This seems necessary
1954                         features.UsedLanguages.insert(default_language);
1955
1956                 if (lyxrc.language_use_babel ||
1957                     params.language->lang() != lyxrc.default_language ||
1958                     !features.UsedLanguages.empty()) {
1959                         use_babel = true;
1960                         for (LaTeXFeatures::LanguageList::const_iterator cit =
1961                                      features.UsedLanguages.begin();
1962                              cit != features.UsedLanguages.end(); ++cit)
1963                                 language_options += (*cit)->babel() + ',';
1964                         language_options += params.language->babel();
1965                         if (lyxrc.language_global_options)
1966                                 options += language_options + ',';
1967                 }
1968
1969                 // the user-defined options
1970                 if (!params.options.empty()) {
1971                         options += params.options + ',';
1972                 }
1973                 
1974                 if (!options.empty()){
1975                         options = strip(options, ',');
1976                         ofs << '[' << options << ']';
1977                 }
1978                 
1979                 ofs << '{'
1980                     << textclasslist.LatexnameOfClass(params.textclass)
1981                     << "}\n";
1982                 texrow.newline();
1983                 // end of \documentclass defs
1984                 
1985                 // font selection must be done before loading fontenc.sty
1986                 // The ae package is not needed when using OT1 font encoding.
1987                 if (params.fonts != "default" &&
1988                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1989                         ofs << "\\usepackage{" << params.fonts << "}\n";
1990                         texrow.newline();
1991                         if (params.fonts == "ae") {
1992                                 ofs << "\\usepackage{aecompl}\n";
1993                                 texrow.newline();
1994                         }
1995                 }
1996                 // this one is not per buffer
1997                 if (lyxrc.fontenc != "default") {
1998                         ofs << "\\usepackage[" << lyxrc.fontenc
1999                             << "]{fontenc}\n";
2000                         texrow.newline();
2001                 }
2002
2003                 if (params.inputenc == "auto") {
2004                         string const doc_encoding =
2005                                 params.language->encoding()->LatexName();
2006
2007                         // Create a list with all the input encodings used 
2008                         // in the document
2009                         set<string> encodings;
2010                         for (LaTeXFeatures::LanguageList::const_iterator it =
2011                                      features.UsedLanguages.begin();
2012                              it != features.UsedLanguages.end(); ++it)
2013                                 if ((*it)->encoding()->LatexName() != doc_encoding)
2014                                         encodings.insert((*it)->encoding()->LatexName());
2015
2016                         ofs << "\\usepackage[";
2017                         std::copy(encodings.begin(), encodings.end(),
2018                                   std::ostream_iterator<string>(ofs, ","));
2019                         ofs << doc_encoding << "]{inputenc}\n";
2020                         texrow.newline();
2021                 } else if (params.inputenc != "default") {
2022                         ofs << "\\usepackage[" << params.inputenc
2023                             << "]{inputenc}\n";
2024                         texrow.newline();
2025                 }
2026
2027                 // At the very beginning the text parameters.
2028                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2029                         switch (params.paperpackage) {
2030                         case BufferParams::PACKAGE_A4:
2031                                 ofs << "\\usepackage{a4}\n";
2032                                 texrow.newline();
2033                                 break;
2034                         case BufferParams::PACKAGE_A4WIDE:
2035                                 ofs << "\\usepackage{a4wide}\n";
2036                                 texrow.newline();
2037                                 break;
2038                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2039                                 ofs << "\\usepackage[widemargins]{a4}\n";
2040                                 texrow.newline();
2041                                 break;
2042                         }
2043                 }
2044                 if (params.use_geometry) {
2045                         ofs << "\\usepackage{geometry}\n";
2046                         texrow.newline();
2047                         ofs << "\\geometry{verbose";
2048                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2049                                 ofs << ",landscape";
2050                         switch (params.papersize2) {
2051                         case BufferParams::VM_PAPER_CUSTOM:
2052                                 if (!params.paperwidth.empty())
2053                                         ofs << ",paperwidth="
2054                                             << params.paperwidth;
2055                                 if (!params.paperheight.empty())
2056                                         ofs << ",paperheight="
2057                                             << params.paperheight;
2058                                 break;
2059                         case BufferParams::VM_PAPER_USLETTER:
2060                                 ofs << ",letterpaper";
2061                                 break;
2062                         case BufferParams::VM_PAPER_USLEGAL:
2063                                 ofs << ",legalpaper";
2064                                 break;
2065                         case BufferParams::VM_PAPER_USEXECUTIVE:
2066                                 ofs << ",executivepaper";
2067                                 break;
2068                         case BufferParams::VM_PAPER_A3:
2069                                 ofs << ",a3paper";
2070                                 break;
2071                         case BufferParams::VM_PAPER_A4:
2072                                 ofs << ",a4paper";
2073                                 break;
2074                         case BufferParams::VM_PAPER_A5:
2075                                 ofs << ",a5paper";
2076                                 break;
2077                         case BufferParams::VM_PAPER_B3:
2078                                 ofs << ",b3paper";
2079                                 break;
2080                         case BufferParams::VM_PAPER_B4:
2081                                 ofs << ",b4paper";
2082                                 break;
2083                         case BufferParams::VM_PAPER_B5:
2084                                 ofs << ",b5paper";
2085                                 break;
2086                         default:
2087                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2088                                 switch (lyxrc.default_papersize) {
2089                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2090                                 case BufferParams::PAPER_USLETTER:
2091                                         ofs << ",letterpaper";
2092                                         break;
2093                                 case BufferParams::PAPER_LEGALPAPER:
2094                                         ofs << ",legalpaper";
2095                                         break;
2096                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2097                                         ofs << ",executivepaper";
2098                                         break;
2099                                 case BufferParams::PAPER_A3PAPER:
2100                                         ofs << ",a3paper";
2101                                         break;
2102                                 case BufferParams::PAPER_A4PAPER:
2103                                         ofs << ",a4paper";
2104                                         break;
2105                                 case BufferParams::PAPER_A5PAPER:
2106                                         ofs << ",a5paper";
2107                                         break;
2108                                 case BufferParams::PAPER_B5PAPER:
2109                                         ofs << ",b5paper";
2110                                         break;
2111                                 }
2112                         }
2113                         if (!params.topmargin.empty())
2114                                 ofs << ",tmargin=" << params.topmargin;
2115                         if (!params.bottommargin.empty())
2116                                 ofs << ",bmargin=" << params.bottommargin;
2117                         if (!params.leftmargin.empty())
2118                                 ofs << ",lmargin=" << params.leftmargin;
2119                         if (!params.rightmargin.empty())
2120                                 ofs << ",rmargin=" << params.rightmargin;
2121                         if (!params.headheight.empty())
2122                                 ofs << ",headheight=" << params.headheight;
2123                         if (!params.headsep.empty())
2124                                 ofs << ",headsep=" << params.headsep;
2125                         if (!params.footskip.empty())
2126                                 ofs << ",footskip=" << params.footskip;
2127                         ofs << "}\n";
2128                         texrow.newline();
2129                 }
2130                 if (features.amsstyle
2131                     && !tclass.provides(LyXTextClass::amsmath)) {
2132                         ofs << "\\usepackage{amsmath}\n";
2133                         texrow.newline();
2134                 }
2135
2136                 if (tokenPos(tclass.opt_pagestyle(),
2137                              '|', params.pagestyle) >= 0) {
2138                         if (params.pagestyle == "fancy") {
2139                                 ofs << "\\usepackage{fancyhdr}\n";
2140                                 texrow.newline();
2141                         }
2142                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2143                         texrow.newline();
2144                 }
2145
2146                 // We try to load babel late, in case it interferes
2147                 // with other packages.
2148                 if (use_babel) {
2149                         string tmp = lyxrc.language_package;
2150                         if (!lyxrc.language_global_options
2151                             && tmp == "\\usepackage{babel}")
2152                                 tmp = "\\usepackage[" +
2153                                         language_options + "]{babel}";
2154                         ofs << tmp << "\n";
2155                         texrow.newline();
2156                 }
2157
2158                 if (params.secnumdepth != tclass.secnumdepth()) {
2159                         ofs << "\\setcounter{secnumdepth}{"
2160                             << params.secnumdepth
2161                             << "}\n";
2162                         texrow.newline();
2163                 }
2164                 if (params.tocdepth != tclass.tocdepth()) {
2165                         ofs << "\\setcounter{tocdepth}{"
2166                             << params.tocdepth
2167                             << "}\n";
2168                         texrow.newline();
2169                 }
2170                 
2171                 if (params.paragraph_separation) {
2172                         switch (params.defskip.kind()) {
2173                         case VSpace::SMALLSKIP: 
2174                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2175                                 break;
2176                         case VSpace::MEDSKIP:
2177                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2178                                 break;
2179                         case VSpace::BIGSKIP:
2180                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2181                                 break;
2182                         case VSpace::LENGTH:
2183                                 ofs << "\\setlength\\parskip{"
2184                                     << params.defskip.length().asLatexString()
2185                                     << "}\n";
2186                                 break;
2187                         default: // should never happen // Then delete it.
2188                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2189                                 break;
2190                         }
2191                         texrow.newline();
2192                         
2193                         ofs << "\\setlength\\parindent{0pt}\n";
2194                         texrow.newline();
2195                 }
2196
2197                 // Now insert the LyX specific LaTeX commands...
2198
2199                 // The optional packages;
2200                 string preamble(features.getPackages());
2201
2202                 // this might be useful...
2203                 preamble += "\n\\makeatletter\n";
2204
2205                 // Some macros LyX will need
2206                 string tmppreamble(features.getMacros());
2207
2208                 if (!tmppreamble.empty()) {
2209                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2210                                 "LyX specific LaTeX commands.\n"
2211                                 + tmppreamble + '\n';
2212                 }
2213
2214                 // the text class specific preamble 
2215                 tmppreamble = features.getTClassPreamble();
2216                 if (!tmppreamble.empty()) {
2217                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2218                                 "Textclass specific LaTeX commands.\n"
2219                                 + tmppreamble + '\n';
2220                 }
2221
2222                 /* the user-defined preamble */
2223                 if (!params.preamble.empty()) {
2224                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2225                                 "User specified LaTeX commands.\n"
2226                                 + params.preamble + '\n';
2227                 }
2228
2229                 preamble += "\\makeatother\n";
2230
2231                 // Itemize bullet settings need to be last in case the user
2232                 // defines their own bullets that use a package included
2233                 // in the user-defined preamble -- ARRae
2234                 // Actually it has to be done much later than that
2235                 // since some packages like frenchb make modifications
2236                 // at \begin{document} time -- JMarc 
2237                 string bullets_def;
2238                 for (int i = 0; i < 4; ++i) {
2239                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2240                                 if (bullets_def.empty())
2241                                         bullets_def="\\AtBeginDocument{\n";
2242                                 bullets_def += "  \\renewcommand{\\labelitemi";
2243                                 switch (i) {
2244                                 // `i' is one less than the item to modify
2245                                 case 0:
2246                                         break;
2247                                 case 1:
2248                                         bullets_def += 'i';
2249                                         break;
2250                                 case 2:
2251                                         bullets_def += "ii";
2252                                         break;
2253                                 case 3:
2254                                         bullets_def += 'v';
2255                                         break;
2256                                 }
2257                                 bullets_def += "}{" + 
2258                                   params.user_defined_bullets[i].getText() 
2259                                   + "}\n";
2260                         }
2261                 }
2262
2263                 if (!bullets_def.empty())
2264                   preamble += bullets_def + "}\n\n";
2265
2266                 for (int j = countChar(preamble, '\n'); j-- ;) {
2267                         texrow.newline();
2268                 }
2269
2270                 ofs << preamble;
2271
2272                 // make the body.
2273                 ofs << "\\begin{document}\n";
2274                 texrow.newline();
2275         } // only_body
2276         lyxerr.debug() << "preamble finished, now the body." << endl;
2277
2278         if (!lyxrc.language_auto_begin) {
2279                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2280                              params.language->babel())
2281                     << endl;
2282                 texrow.newline();
2283         }
2284         
2285         latexParagraphs(ofs, paragraph, 0, texrow);
2286
2287         // add this just in case after all the paragraphs
2288         ofs << endl;
2289         texrow.newline();
2290
2291         if (!lyxrc.language_auto_end) {
2292                 ofs << subst(lyxrc.language_command_end, "$$lang",
2293                              params.language->babel())
2294                     << endl;
2295                 texrow.newline();
2296         }
2297
2298         if (!only_body) {
2299                 ofs << "\\end{document}\n";
2300                 texrow.newline();
2301         
2302                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2303         } else {
2304                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2305                                      << endl;
2306         }
2307
2308         // Just to be sure. (Asger)
2309         texrow.newline();
2310
2311         // tex_code_break_column's value is used to decide
2312         // if we are in batchmode or not (within mathed_write()
2313         // in math_write.C) so we must set it to a non-zero
2314         // value when we leave otherwise we save incorrect .lyx files.
2315         tex_code_break_column = lyxrc.ascii_linelen;
2316
2317         ofs.close();
2318         if (ofs.fail()) {
2319                 lyxerr << "File was not closed properly." << endl;
2320         }
2321         
2322         lyxerr.debug() << "Finished making latex file." << endl;
2323 }
2324
2325
2326 //
2327 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2328 //
2329 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2330                              LyXParagraph * endpar, TexRow & texrow) const
2331 {
2332         bool was_title = false;
2333         bool already_title = false;
2334         std::ostringstream ftnote;
2335         TexRow ft_texrow;
2336         int ftcount = 0;
2337
2338         // if only_body
2339         while (par != endpar) {
2340 #ifndef NEW_INSETS
2341                 if (par->IsDummy())
2342                         lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2343                                              << endl;
2344 #endif
2345                 LyXLayout const & layout =
2346                         textclasslist.Style(params.textclass,
2347                                             par->layout);
2348             
2349                 if (layout.intitle) {
2350                         if (already_title) {
2351                                 lyxerr <<"Error in latexParagraphs: You"
2352                                         " should not mix title layouts"
2353                                         " with normal ones." << endl;
2354                         } else
2355                                 was_title = true;
2356                 } else if (was_title && !already_title) {
2357                         ofs << "\\maketitle\n";
2358                         texrow.newline();
2359                         already_title = true;
2360                         was_title = false;                  
2361                 }
2362                 // We are at depth 0 so we can just use
2363                 // ordinary \footnote{} generation
2364                 // flag this with ftcount
2365                 ftcount = -1;
2366                 if (layout.isEnvironment()
2367 #ifndef NEW_INSETS
2368                     || par->params.pextraType() != LyXParagraph::PEXTRA_NONE
2369 #endif
2370                         ) {
2371                         par = par->TeXEnvironment(this, params, ofs, texrow
2372 #ifndef NEW_INSETS
2373                                                   ,ftnote, ft_texrow, ftcount
2374 #endif
2375                                 );
2376                 } else {
2377                         par = par->TeXOnePar(this, params, ofs, texrow, false
2378 #ifndef NEW_INSETS
2379                                              ,
2380                                              ftnote, ft_texrow, ftcount
2381 #endif
2382                                 );
2383                 }
2384
2385                 // Write out what we've generated...
2386                 if (ftcount >= 1) {
2387                         if (ftcount > 1) {
2388                                 ofs << "\\addtocounter{footnote}{-"
2389                                     << ftcount - 1
2390                                     << '}';
2391                         }
2392                         ofs << ftnote.str();
2393                         texrow += ft_texrow;
2394
2395                         // The extra .c_str() is needed when we use
2396                         // lyxstring instead of the STL string class. 
2397                         ftnote.str(string().c_str());
2398                         ft_texrow.reset();
2399                         ftcount = 0;
2400                 }
2401         }
2402         // It might be that we only have a title in this document
2403         if (was_title && !already_title) {
2404                 ofs << "\\maketitle\n";
2405                 texrow.newline();
2406         }
2407 }
2408
2409
2410 bool Buffer::isLatex() const
2411 {
2412         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2413 }
2414
2415
2416 bool Buffer::isLinuxDoc() const
2417 {
2418         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2419 }
2420
2421
2422 bool Buffer::isLiterate() const
2423 {
2424         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2425 }
2426
2427
2428 bool Buffer::isDocBook() const
2429 {
2430         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2431 }
2432
2433
2434 bool Buffer::isSGML() const
2435 {
2436         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2437                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2438 }
2439
2440
2441 void Buffer::sgmlOpenTag(ostream & os, int depth,
2442                          string const & latexname) const
2443 {
2444         if (!latexname.empty() && latexname != "!-- --")
2445                 os << string(depth, ' ') << "<" << latexname << ">\n";
2446 }
2447
2448
2449 void Buffer::sgmlCloseTag(ostream & os, int depth,
2450                           string const & latexname) const
2451 {
2452         if (!latexname.empty() && latexname != "!-- --")
2453                 os << string(depth, ' ') << "</" << latexname << ">\n";
2454 }
2455
2456
2457 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2458 {
2459         ofstream ofs(fname.c_str());
2460
2461         if (!ofs) {
2462                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2463                 return;
2464         }
2465
2466         niceFile = nice; // this will be used by included files.
2467
2468         LyXTextClass const & tclass =
2469                 textclasslist.TextClass(params.textclass);
2470
2471         LaTeXFeatures features(params, tclass.numLayouts());
2472         validate(features);
2473
2474         texrow.reset();
2475
2476         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2477
2478         if (!body_only) {
2479                 string sgml_includedfiles=features.getIncludedFiles(fname);
2480
2481                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2482                         ofs << "<!doctype linuxdoc system>\n\n";
2483                 } else {
2484                         ofs << "<!doctype linuxdoc system [ "
2485                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2486                 }
2487
2488                 if (params.options.empty())
2489                         sgmlOpenTag(ofs, 0, top_element);
2490                 else {
2491                         string top = top_element;
2492                         top += " ";
2493                         top += params.options;
2494                         sgmlOpenTag(ofs, 0, top);
2495                 }
2496         }
2497
2498         ofs << "<!-- "  << LYX_DOCVERSION 
2499             << " created this file. For more info see http://www.lyx.org/"
2500             << " -->\n";
2501
2502         int depth = 0; // paragraph depth
2503         LyXParagraph * par = paragraph;
2504         string item_name;
2505         vector<string> environment_stack(5);
2506
2507         while (par) {
2508                 LyXLayout const & style =
2509                         textclasslist.Style(params.textclass,
2510                                             par->layout);
2511
2512                 // treat <toc> as a special case for compatibility with old code
2513                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2514                         Inset * inset = par->GetInset(0);
2515                         Inset::Code lyx_code = inset->LyxCode();
2516                         if (lyx_code == Inset::TOC_CODE){
2517                                 string const temp = "toc";
2518                                 sgmlOpenTag(ofs, depth, temp);
2519
2520 #ifndef NEW_INSETS
2521                                 par = par->next_;
2522                                 linuxDocHandleFootnote(ofs, par, depth);
2523 #else
2524                                 par = par->next();
2525 #endif
2526                                 continue;
2527                         }
2528                 }
2529
2530                 // environment tag closing
2531                 for (; depth > par->params.depth(); --depth) {
2532                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2533                         environment_stack[depth].erase();
2534                 }
2535
2536                 // write opening SGML tags
2537                 switch (style.latextype) {
2538                 case LATEX_PARAGRAPH:
2539                         if (depth == par->params.depth() 
2540                            && !environment_stack[depth].empty()) {
2541                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2542                                 environment_stack[depth].erase();
2543                                 if (depth) 
2544                                         --depth;
2545                                 else
2546                                         ofs << "</p>";
2547                         }
2548                         sgmlOpenTag(ofs, depth, style.latexname());
2549                         break;
2550
2551                 case LATEX_COMMAND:
2552                         if (depth!= 0)
2553                                 LinuxDocError(par, 0,
2554                                               _("Error : Wrong depth for"
2555                                                 " LatexType Command.\n"));
2556
2557                         if (!environment_stack[depth].empty()){
2558                                 sgmlCloseTag(ofs, depth,
2559                                              environment_stack[depth]);
2560                                 ofs << "</p>";
2561                         }
2562
2563                         environment_stack[depth].erase();
2564                         sgmlOpenTag(ofs, depth, style.latexname());
2565                         break;
2566
2567                 case LATEX_ENVIRONMENT:
2568                 case LATEX_ITEM_ENVIRONMENT:
2569                         if (depth == par->params.depth() 
2570                             && environment_stack[depth] != style.latexname()) {
2571                                 sgmlCloseTag(ofs, depth,
2572                                              environment_stack[depth]);
2573                                 environment_stack[depth].erase();
2574                         }
2575                         if (depth < par->params.depth()) {
2576                                depth = par->params.depth();
2577                                environment_stack[depth].erase();
2578                         }
2579                         if (environment_stack[depth] != style.latexname()) {
2580                                 if (depth == 0) {
2581                                         sgmlOpenTag(ofs, depth, "p");
2582                                 }
2583                                 sgmlOpenTag(ofs, depth, style.latexname());
2584
2585                                 if (environment_stack.size() == depth + 1)
2586                                         environment_stack.push_back("!-- --");
2587                                 environment_stack[depth] = style.latexname();
2588                         }
2589
2590                         if (style.latexparam() == "CDATA")
2591                                 ofs << "<![CDATA[";
2592
2593                         if (style.latextype == LATEX_ENVIRONMENT) break;
2594
2595                         if (style.labeltype == LABEL_MANUAL)
2596                                 item_name = "tag";
2597                         else
2598                                 item_name = "item";
2599
2600                         sgmlOpenTag(ofs, depth + 1, item_name);
2601                         break;
2602                 default:
2603                         sgmlOpenTag(ofs, depth, style.latexname());
2604                         break;
2605                 }
2606
2607 #ifndef NEW_INSETS
2608                 do {
2609                         SimpleLinuxDocOnePar(ofs, par, depth);
2610                         
2611                         par = par->next_;
2612                         linuxDocHandleFootnote(ofs, par, depth);
2613                 }
2614                 while(par && par->IsDummy());
2615 #else
2616                 SimpleLinuxDocOnePar(ofs, par, depth);
2617
2618                 par = par->next();
2619 #endif
2620
2621                 ofs << "\n";
2622                 // write closing SGML tags
2623                 switch (style.latextype) {
2624                 case LATEX_COMMAND:
2625                         break;
2626                 case LATEX_ENVIRONMENT:
2627                 case LATEX_ITEM_ENVIRONMENT:
2628                         if (style.latexparam() == "CDATA")
2629                                 ofs << "]]>";
2630                         break;
2631                 default:
2632                         sgmlCloseTag(ofs, depth, style.latexname());
2633                         break;
2634                 }
2635         }
2636    
2637         // Close open tags
2638         for (int i=depth; i >= 0; --i)
2639                 sgmlCloseTag(ofs, depth, environment_stack[i]);
2640
2641         if (!body_only) {
2642                 ofs << "\n\n";
2643                 sgmlCloseTag(ofs, 0, top_element);
2644         }
2645
2646         ofs.close();
2647         // How to check for successful close
2648 }
2649
2650
2651 #ifndef NEW_INSETS
2652 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2653                                     int depth)
2654 {
2655         string const tag = "footnote";
2656
2657         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2658                 sgmlOpenTag(os, depth + 1, tag);
2659                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2660                 sgmlCloseTag(os, depth + 1, tag);
2661                 par = par->next_;
2662         }
2663 }
2664 #endif
2665
2666
2667 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2668                                   int depth, int desc_on,
2669                                   LyXParagraph * & par)
2670 {
2671         LyXParagraph * tpar = par;
2672 #ifndef NEW_INSETS
2673         while (tpar
2674                && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2675                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2676                                                              "Caption").second))
2677                 tpar = tpar->next_;
2678 #else
2679         while (tpar
2680                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2681                                                                 "Caption").second))
2682                 tpar = tpar->next();
2683 #endif
2684         if (tpar &&
2685             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2686                                                          "Caption").second) {
2687                 sgmlOpenTag(os, depth + 1, inner_tag);
2688                 string extra_par;
2689                 SimpleDocBookOnePar(os, extra_par, tpar,
2690                                     desc_on, depth + 2);
2691                 sgmlCloseTag(os, depth+1, inner_tag);
2692                 if (!extra_par.empty())
2693                         os << extra_par;
2694         }
2695 }
2696
2697
2698 #ifndef NEW_INSETS
2699 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2700                                    int depth)
2701 {
2702         string tag, inner_tag;
2703         string tmp_par, extra_par;
2704         bool inner_span = false;
2705         int desc_on = 4;
2706
2707         // Someone should give this enum a proper name (Lgb)
2708         enum SOME_ENUM {
2709                 NO_ONE,
2710                 FOOTNOTE_LIKE,
2711                 MARGIN_LIKE,
2712                 FIG_LIKE,
2713                 TAB_LIKE
2714         };
2715         SOME_ENUM last = NO_ONE;
2716         SOME_ENUM present = FOOTNOTE_LIKE;
2717
2718         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2719                 if (last == present) {
2720                         if (inner_span) {
2721                                 if (!tmp_par.empty()) {
2722                                         os << tmp_par;
2723                                         tmp_par.erase();
2724                                         sgmlCloseTag(os, depth + 1, inner_tag);
2725                                         sgmlOpenTag(os, depth + 1, inner_tag);
2726                                 }
2727                         } else {
2728                                 os << "\n";
2729                         }
2730                 } else {
2731                         os << tmp_par;
2732                         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2733                                                             inner_tag);
2734                         if (!extra_par.empty()) os << extra_par;
2735                         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2736                         extra_par.erase();
2737
2738                         switch (par->footnotekind) {
2739                         case LyXParagraph::FOOTNOTE:
2740                         case LyXParagraph::ALGORITHM:
2741                                 tag = "footnote";
2742                                 inner_tag = "para";
2743                                 present = FOOTNOTE_LIKE;
2744                                 inner_span = true;
2745                                 break;
2746                         case LyXParagraph::MARGIN:
2747                                 tag = "sidebar";
2748                                 inner_tag = "para";
2749                                 present = MARGIN_LIKE;
2750                                 inner_span = true;
2751                                 break;
2752                         case LyXParagraph::FIG:
2753                         case LyXParagraph::WIDE_FIG:
2754                                 tag = "figure";
2755                                 inner_tag = "title";
2756                                 present = FIG_LIKE;
2757                                 inner_span = false;
2758                                 break;
2759                         case LyXParagraph::TAB:
2760                         case LyXParagraph::WIDE_TAB:
2761                                 tag = "table";
2762                                 inner_tag = "title";
2763                                 present = TAB_LIKE;
2764                                 inner_span = false;
2765                                 break;
2766                         }
2767                         sgmlOpenTag(os, depth, tag);
2768                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2769                                 DocBookHandleCaption(os, inner_tag, depth,
2770                                                      desc_on, par);
2771                                 inner_tag.erase();
2772                         } else {
2773                                 sgmlOpenTag(os, depth + 1, inner_tag);
2774                         }
2775                 }
2776                 // ignore all caption here, we processed them above!!!
2777                 if (par->layout != textclasslist
2778                     .NumberOfLayout(params.textclass,
2779                                     "Caption").second) {
2780                         std::ostringstream ost;
2781                         SimpleDocBookOnePar(ost, extra_par, par,
2782                                             desc_on, depth + 2);
2783                         tmp_par += ost.str().c_str();
2784                 }
2785                 tmp_par = frontStrip(strip(tmp_par));
2786
2787                 last = present;
2788                 par = par->next_;
2789         }
2790         os << tmp_par;
2791         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2792         if (!extra_par.empty()) os << extra_par;
2793         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2794 }
2795 #endif
2796
2797
2798 // checks, if newcol chars should be put into this line
2799 // writes newline, if necessary.
2800 namespace {
2801
2802 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2803                           string::size_type newcol)
2804 {
2805         colcount += newcol;
2806         if (colcount > lyxrc.ascii_linelen) {
2807                 os << "\n";
2808                 colcount = newcol; // assume write after this call
2809         }
2810 }
2811
2812 enum PAR_TAG {
2813         NONE=0,
2814         TT = 1,
2815         SF = 2,
2816         BF = 4,
2817         IT = 8,
2818         SL = 16,
2819         EM = 32
2820 };
2821
2822
2823 string tag_name(PAR_TAG const & pt) {
2824         switch (pt) {
2825         case NONE: return "!-- --";
2826         case TT: return "tt";
2827         case SF: return "sf";
2828         case BF: return "bf";
2829         case IT: return "it";
2830         case SL: return "sl";
2831         case EM: return "em";
2832         }
2833         return "";
2834 }
2835
2836
2837 inline
2838 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2839 {
2840         p1 = static_cast<PAR_TAG>(p1 | p2);
2841 }
2842
2843
2844 inline
2845 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2846 {
2847         p1 = static_cast<PAR_TAG>( p1 & ~p2);
2848 }
2849
2850 } // namespace anon
2851
2852
2853
2854
2855 // Handle internal paragraph parsing -- layout already processed.
2856 void Buffer::SimpleLinuxDocOnePar(ostream & os,
2857                                   LyXParagraph * par, int /*depth*/)
2858 {
2859         LyXLayout const & style = textclasslist.Style(params.textclass,
2860                                                       par->GetLayout());
2861         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2862
2863         // gets paragraph main font
2864         LyXFont font_old;
2865         bool desc_on;
2866         if (style.labeltype == LABEL_MANUAL) {
2867                 font_old = style.labelfont;
2868                 desc_on = true;
2869         } else {
2870                 font_old = style.font;
2871                 desc_on = false;
2872         }
2873
2874         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2875         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2876         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2877         bool is_em = false;
2878
2879         stack < PAR_TAG > tag_state;
2880         // parsing main loop
2881         for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
2882
2883                 PAR_TAG tag_close = NONE;
2884                 list < PAR_TAG > tag_open;
2885
2886                 LyXFont const font = par->getFont(params, i);
2887
2888                 if (font_old.family() != font.family()) {
2889                         switch (family_type) {
2890                         case LyXFont::SANS_FAMILY:
2891                                 tag_close |= SF;
2892                                 break;
2893                         case LyXFont::TYPEWRITER_FAMILY:
2894                                 tag_close |= TT;
2895                                 break;
2896                         default:
2897                                 break;
2898                         }
2899
2900                         family_type = font.family();
2901
2902                         switch (family_type) {
2903                         case LyXFont::SANS_FAMILY:
2904                                 tag_open.push_back(SF);
2905                                 break;
2906                         case LyXFont::TYPEWRITER_FAMILY:
2907                                 tag_open.push_back(TT);
2908                                 break;
2909                         default:
2910                                 break;
2911                         }
2912                 }
2913
2914                 if (font_old.series() != font.series()) {
2915                         switch (series_type) {
2916                         case LyXFont::BOLD_SERIES:
2917                                 tag_close |= BF;
2918                                 break;
2919                         default:
2920                                 break;
2921                         }
2922
2923                         series_type = font.series();
2924
2925                         switch (series_type) {
2926                         case LyXFont::BOLD_SERIES:
2927                                 tag_open.push_back(BF);
2928                                 break;
2929                         default:
2930                                 break;
2931                         }
2932
2933                 }
2934
2935                 if (font_old.shape() != font.shape()) {
2936                         switch (shape_type) {
2937                         case LyXFont::ITALIC_SHAPE:
2938                                 tag_close |= IT;
2939                                 break;
2940                         case LyXFont::SLANTED_SHAPE:
2941                                 tag_close |= SL;
2942                                 break;
2943                         default:
2944                                 break;
2945                         }
2946
2947                         shape_type = font.shape();
2948
2949                         switch (shape_type) {
2950                         case LyXFont::ITALIC_SHAPE:
2951                                 tag_open.push_back(IT);
2952                                 break;
2953                         case LyXFont::SLANTED_SHAPE:
2954                                 tag_open.push_back(SL);
2955                                 break;
2956                         default:
2957                                 break;
2958                         }
2959                 }
2960                 // handle <em> tag
2961                 if (font_old.emph() != font.emph()) {
2962                         if (font.emph() == LyXFont::ON) {
2963                                 tag_open.push_back(EM);
2964                                 is_em = true;
2965                         }
2966                         else if (is_em) {
2967                                 tag_close |= EM;
2968                                 is_em = false;
2969                         }
2970                 }
2971
2972                 list < PAR_TAG > temp;
2973                 while(!tag_state.empty() && tag_close ) {
2974                         PAR_TAG k =  tag_state.top();
2975                         tag_state.pop();
2976                         os << "</" << tag_name(k) << ">";
2977                         if (tag_close & k)
2978                                 reset(tag_close,k);
2979                         else
2980                                 temp.push_back(k);
2981                 }
2982
2983                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2984                     j != temp.end(); ++j) {
2985                         tag_state.push(*j);
2986                         os << "<" << tag_name(*j) << ">";
2987                 }
2988
2989                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2990                     j != tag_open.end(); ++j) {
2991                         tag_state.push(*j);
2992                         os << "<" << tag_name(*j) << ">";
2993                 }
2994
2995                 char c = par->GetChar(i);
2996
2997                 if (c == LyXParagraph::META_INSET) {
2998                         Inset * inset = par->GetInset(i);
2999                         inset->Linuxdoc(this, os);
3000                         font_old = font;
3001                         continue;
3002                 }
3003
3004                 if (font.latex() == LyXFont::ON || style.latexparam() == "CDATA") {
3005                         // "TeX"-Mode on == > SGML-Mode on.
3006                         if (c != '\0')
3007                                 os << c;
3008                         ++char_line_count;
3009                 } else {
3010                         string sgml_string;
3011                         if (par->linuxDocConvertChar(c, sgml_string)
3012                             && !style.free_spacing) { 
3013                                 // in freespacing mode, spaces are
3014                                 // non-breaking characters
3015                                 if (desc_on) {// if char is ' ' then...
3016
3017                                         ++char_line_count;
3018                                         linux_doc_line_break(os, char_line_count, 6);
3019                                         os << "</tag>";
3020                                         desc_on = false;
3021                                 } else  {
3022                                         linux_doc_line_break(os, char_line_count, 1);
3023                                         os << c;
3024                                 }
3025                         } else {
3026                                 os << sgml_string;
3027                                 char_line_count += sgml_string.length();
3028                         }
3029                 }
3030                 font_old = font;
3031         }
3032
3033         while (!tag_state.empty()) {
3034                 os << "</" << tag_name(tag_state.top()) << ">";
3035                 tag_state.pop();
3036         }
3037
3038         // resets description flag correctly
3039         if (desc_on) {
3040                 // <tag> not closed...
3041                 linux_doc_line_break(os, char_line_count, 6);
3042                 os << "</tag>";
3043         }
3044 }
3045
3046
3047 // Print an error message.
3048 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
3049                            string const & message) 
3050 {
3051         // insert an error marker in text
3052         InsetError * new_inset = new InsetError(message);
3053         par->InsertInset(pos, new_inset);
3054 }
3055
3056
3057 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3058 {
3059         ofstream ofs(fname.c_str());
3060         if (!ofs) {
3061                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3062                 return;
3063         }
3064
3065         LyXParagraph * par = paragraph;
3066
3067         niceFile = nice; // this will be used by Insetincludes.
3068
3069         LyXTextClass const & tclass =
3070                 textclasslist.TextClass(params.textclass);
3071
3072         LaTeXFeatures features(params, tclass.numLayouts());
3073         validate(features);
3074    
3075         texrow.reset();
3076
3077         string top_element = textclasslist.LatexnameOfClass(params.textclass);
3078
3079         if (!only_body) {
3080                 string sgml_includedfiles = features.getIncludedFiles(fname);
3081
3082                 ofs << "<!doctype " << top_element
3083                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3084
3085                 if (params.preamble.empty() && sgml_includedfiles.empty())
3086                         ofs << ">\n\n";
3087                 else
3088                         ofs << "\n [ " << params.preamble 
3089                             << sgml_includedfiles << " \n]>\n\n";
3090         }
3091
3092         string top = top_element;       
3093         top += " lang=\"";
3094         top += params.language->code();
3095         top += "\"";
3096
3097         if (!params.options.empty()) {
3098                 top += " ";
3099                 top += params.options;
3100         }
3101         sgmlOpenTag(ofs, 0, top);
3102
3103         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
3104             << "\n  See http://www.lyx.org/ for more information -->\n";
3105
3106         vector<string> environment_stack(10);
3107         vector<string> environment_inner(10);
3108         vector<string> command_stack(10);
3109
3110         bool command_flag = false;
3111         int command_depth = 0;
3112         int command_base = 0;
3113         int cmd_depth = 0;
3114         int depth = 0; // paragraph depth
3115
3116         string item_name;
3117         string command_name;
3118
3119         while (par) {
3120                 string sgmlparam;
3121                 string c_depth;
3122                 string c_params;
3123                 int desc_on = 0; // description mode
3124
3125                 LyXLayout const & style =
3126                         textclasslist.Style(params.textclass,
3127                                             par->layout);
3128
3129                 // environment tag closing
3130                 for (; depth > par->params.depth(); --depth) {
3131                         if (environment_inner[depth] != "!-- --") {
3132                                 item_name = "listitem";
3133                                 sgmlCloseTag(ofs, command_depth + depth,
3134                                              item_name);
3135                                 if (environment_inner[depth] == "varlistentry")
3136                                         sgmlCloseTag(ofs, depth+command_depth,
3137                                                      environment_inner[depth]);
3138                         }
3139                         sgmlCloseTag(ofs, depth + command_depth,
3140                                      environment_stack[depth]);
3141                         environment_stack[depth].erase();
3142                         environment_inner[depth].erase();
3143                 }
3144
3145                 if (depth == par->params.depth()
3146                    && environment_stack[depth] != style.latexname()
3147                    && !environment_stack[depth].empty()) {
3148                         if (environment_inner[depth] != "!-- --") {
3149                                 item_name= "listitem";
3150                                 sgmlCloseTag(ofs, command_depth+depth,
3151                                              item_name);
3152                                 if (environment_inner[depth] == "varlistentry")
3153                                         sgmlCloseTag(ofs,
3154                                                      depth + command_depth,
3155                                                      environment_inner[depth]);
3156                         }
3157                         
3158                         sgmlCloseTag(ofs, depth + command_depth,
3159                                      environment_stack[depth]);
3160                         
3161                         environment_stack[depth].erase();
3162                         environment_inner[depth].erase();
3163                 }
3164
3165                 // Write opening SGML tags.
3166                 switch (style.latextype) {
3167                 case LATEX_PARAGRAPH:
3168                         sgmlOpenTag(ofs, depth + command_depth,
3169                                     style.latexname());
3170                         break;
3171
3172                 case LATEX_COMMAND:
3173                         if (depth != 0)
3174                                 LinuxDocError(par, 0,
3175                                               _("Error : Wrong depth for "
3176                                                 "LatexType Command.\n"));
3177                         
3178                         command_name = style.latexname();
3179                         
3180                         sgmlparam = style.latexparam();
3181                         c_params = split(sgmlparam, c_depth,'|');
3182                         
3183                         cmd_depth = lyx::atoi(c_depth);
3184                         
3185                         if (command_flag) {
3186                                 if (cmd_depth < command_base) {
3187                                         for (int j = command_depth; j >= command_base; --j)
3188                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3189                                         command_depth = command_base = cmd_depth;
3190                                 } else if (cmd_depth <= command_depth) {
3191                                         for (int j = command_depth; j >= cmd_depth; --j)
3192                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3193                                         command_depth = cmd_depth;
3194                                 } else
3195                                         command_depth = cmd_depth;
3196                         } else {
3197                                 command_depth = command_base = cmd_depth;
3198                                 command_flag = true;
3199                         }
3200                         if (command_stack.size() == command_depth + 1)
3201                                 command_stack.push_back("");
3202                         command_stack[command_depth] = command_name;
3203
3204                         // treat label as a special case for
3205                         // more WYSIWYM handling.
3206                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
3207                                 Inset * inset = par->GetInset(0);
3208                                 Inset::Code lyx_code = inset->LyxCode();
3209                                 if (lyx_code == Inset::LABEL_CODE){
3210                                         command_name += " id=\"";
3211                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3212                                         command_name += "\"";
3213                                         desc_on = 3;
3214                                 }
3215                         }
3216
3217                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3218                         if (c_params.empty())
3219                                 item_name = "title";
3220                         else
3221                                 item_name = c_params;
3222                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3223                         break;
3224
3225                 case LATEX_ENVIRONMENT:
3226                 case LATEX_ITEM_ENVIRONMENT:
3227                         if (depth < par->params.depth()) {
3228                                 depth = par->params.depth();
3229                                 environment_stack[depth].erase();
3230                         }
3231
3232                         if (environment_stack[depth] != style.latexname()) {
3233                                 if(environment_stack.size() == depth + 1) {
3234                                         environment_stack.push_back("!-- --");
3235                                         environment_inner.push_back("!-- --");
3236                                 }
3237                                 environment_stack[depth] = style.latexname();
3238                                 environment_inner[depth] = "!-- --";
3239                                 sgmlOpenTag(ofs, depth + command_depth,
3240                                             environment_stack[depth]);
3241                         } else {
3242                                 if (environment_inner[depth] != "!-- --") {
3243                                         item_name= "listitem";
3244                                         sgmlCloseTag(ofs,
3245                                                      command_depth + depth,
3246                                                      item_name);
3247                                         if (environment_inner[depth] == "varlistentry")
3248                                                 sgmlCloseTag(ofs,
3249                                                              depth + command_depth,
3250                                                              environment_inner[depth]);
3251                                 }
3252                         }
3253                         
3254                         if (style.latextype == LATEX_ENVIRONMENT) {
3255                                 if (!style.latexparam().empty()) {
3256                                         if(style.latexparam() == "CDATA")
3257                                                 ofs << "<![CDATA[";
3258                                         else
3259                                                 sgmlOpenTag(ofs, depth + command_depth,
3260                                                             style.latexparam());
3261                                 }
3262                                 break;
3263                         }
3264
3265                         desc_on = (style.labeltype == LABEL_MANUAL);
3266
3267                         if (desc_on)
3268                                 environment_inner[depth]= "varlistentry";
3269                         else
3270                                 environment_inner[depth]= "listitem";
3271
3272                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3273                                     environment_inner[depth]);
3274
3275                         if (desc_on) {
3276                                 item_name= "term";
3277                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3278                                             item_name);
3279                         } else {
3280                                 item_name= "para";
3281                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3282                                             item_name);
3283                         }
3284                         break;
3285                 default:
3286                         sgmlOpenTag(ofs, depth + command_depth,
3287                                     style.latexname());
3288                         break;
3289                 }
3290
3291 #ifndef NEW_INSETS
3292                 do {
3293                         string extra_par;
3294                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3295                                             depth + 1 + command_depth);
3296                         par = par->next_;
3297                         DocBookHandleFootnote(ofs, par,
3298                                               depth + 1 + command_depth);
3299                 } while(par && par->IsDummy());
3300 #else
3301                 string extra_par;
3302                 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3303                                     depth + 1 + command_depth);
3304                 par = par->next();
3305 #endif
3306                 string end_tag;
3307                 // write closing SGML tags
3308                 switch (style.latextype) {
3309                 case LATEX_COMMAND:
3310                         if (c_params.empty())
3311                                 end_tag = "title";
3312                         else
3313                                 end_tag = c_params;
3314                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3315                         break;
3316                 case LATEX_ENVIRONMENT:
3317                         if (!style.latexparam().empty()) {
3318                                 if(style.latexparam() == "CDATA")
3319                                         ofs << "]]>";
3320                                 else
3321                                         sgmlCloseTag(ofs, depth + command_depth,
3322                                                      style.latexparam());
3323                         }
3324                         break;
3325                 case LATEX_ITEM_ENVIRONMENT:
3326                         if (desc_on == 1) break;
3327                         end_tag= "para";
3328                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3329                         break;
3330                 case LATEX_PARAGRAPH:
3331                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3332                         break;
3333                 default:
3334                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3335                         break;
3336                 }
3337         }
3338
3339         // Close open tags
3340         for (; depth >= 0; --depth) {
3341                 if (!environment_stack[depth].empty()) {
3342                         if (environment_inner[depth] != "!-- --") {
3343                                 item_name = "listitem";
3344                                 sgmlCloseTag(ofs, command_depth + depth,
3345                                              item_name);
3346                                if (environment_inner[depth] == "varlistentry")
3347                                        sgmlCloseTag(ofs, depth + command_depth,
3348                                                     environment_inner[depth]);
3349                         }
3350                         
3351                         sgmlCloseTag(ofs, depth + command_depth,
3352                                      environment_stack[depth]);
3353                 }
3354         }
3355         
3356         for (int j = command_depth; j >= command_base; --j)
3357                 if (!command_stack[j].empty())
3358                         sgmlCloseTag(ofs, j, command_stack[j]);
3359
3360         ofs << "\n\n";
3361         sgmlCloseTag(ofs, 0, top_element);
3362
3363         ofs.close();
3364         // How to check for successful close
3365 }
3366
3367
3368 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3369                                  LyXParagraph * par, int & desc_on,
3370                                  int depth) const
3371 {
3372         bool emph_flag = false;
3373
3374         LyXLayout const & style = textclasslist.Style(params.textclass,
3375                                                       par->GetLayout());
3376
3377         LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3378
3379         int char_line_count = depth;
3380         if (!style.free_spacing)
3381                 os << string(depth,' ');
3382
3383         // parsing main loop
3384         for (LyXParagraph::size_type i = 0;
3385              i < par->size(); ++i) {
3386                 LyXFont font = par->getFont(params, i);
3387
3388                 // handle <emphasis> tag
3389                 if (font_old.emph() != font.emph()) {
3390                         if (font.emph() == LyXFont::ON) {
3391                                 os << "<emphasis>";
3392                                 emph_flag = true;
3393                         }else if(i) {
3394                                 os << "</emphasis>";
3395                                 emph_flag = false;
3396                         }
3397                 }
3398       
3399                 char c = par->GetChar(i);
3400
3401                 if (c == LyXParagraph::META_INSET) {
3402                         Inset * inset = par->GetInset(i);
3403                         std::ostringstream ost;
3404                         inset->DocBook(this, ost);
3405                         string tmp_out = ost.str().c_str();
3406
3407                         //
3408                         // This code needs some explanation:
3409                         // Two insets are treated specially
3410                         //   label if it is the first element in a command paragraph
3411                         //         desc_on == 3
3412                         //   graphics inside tables or figure floats can't go on
3413                         //   title (the equivalente in latex for this case is caption
3414                         //   and title should come first
3415                         //         desc_on == 4
3416                         //
3417                         if (desc_on!= 3 || i!= 0) {
3418                                 if (!tmp_out.empty() && tmp_out[0] == '@') {
3419                                         if (desc_on == 4)
3420                                                 extra += frontStrip(tmp_out, '@');
3421                                         else
3422                                                 os << frontStrip(tmp_out, '@');
3423                                 }
3424                                 else
3425                                         os << tmp_out;
3426                         }
3427                 } else if (font.latex() == LyXFont::ON) {
3428                         // "TeX"-Mode on ==> SGML-Mode on.
3429                         if (c != '\0')
3430                                 os << c;
3431                         ++char_line_count;
3432                 } else {
3433                         string sgml_string;
3434                         if (par->linuxDocConvertChar(c, sgml_string)
3435                             && !style.free_spacing) { // in freespacing
3436                                                      // mode, spaces are
3437                                                      // non-breaking characters
3438                                 // char is ' '
3439                                 if (desc_on == 1) {
3440                                         ++char_line_count;
3441                                         os << "\n</term><listitem><para>";
3442                                         desc_on = 2;
3443                                 } else {
3444                                         os << c;
3445                                 }
3446                         } else {
3447                                 os << sgml_string;
3448                         }
3449                 }
3450                 font_old = font;
3451         }
3452
3453         if (emph_flag) {
3454                 os << "</emphasis>";
3455         }
3456         
3457         // resets description flag correctly
3458         if (desc_on == 1) {
3459                 // <term> not closed...
3460                 os << "</term>";
3461         }
3462         os << '\n';
3463 }
3464
3465
3466 // This should be enabled when the Chktex class is implemented. (Asger)
3467 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3468 // Other flags: -wall -v0 -x
3469 int Buffer::runChktex()
3470 {
3471         if (!users->text) return 0;
3472
3473         ProhibitInput(users);
3474
3475         // get LaTeX-Filename
3476         string const name = getLatexName();
3477         string path = OnlyPath(filename);
3478
3479         string const org_path = path;
3480         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3481                 path = tmppath;  
3482         }
3483
3484         Path p(path); // path to LaTeX file
3485         users->owner()->getLyXFunc()->Dispatch(LFUN_MESSAGE,
3486                                                _("Running chktex..."));
3487
3488         // Remove all error insets
3489         bool const removedErrorInsets = users->removeAutoInsets();
3490
3491         // Generate the LaTeX file if neccessary
3492         makeLaTeXFile(name, org_path, false);
3493
3494         TeXErrors terr;
3495         Chktex chktex(lyxrc.chktex_command, name, filepath);
3496         int res = chktex.run(terr); // run chktex
3497
3498         if (res == -1) {
3499                 WriteAlert(_("chktex did not work!"),
3500                            _("Could not run with file:"), name);
3501         } else if (res > 0) {
3502                 // Insert all errors as errors boxes
3503                 users->insertErrors(terr);
3504         }
3505
3506         // if we removed error insets before we ran chktex or if we inserted
3507         // error insets after we ran chktex, this must be run:
3508         if (removedErrorInsets || res){
3509                 users->redraw();
3510                 users->fitCursor(users->text);
3511         }
3512         AllowInput(users);
3513
3514         return res;
3515 }
3516
3517
3518 void Buffer::validate(LaTeXFeatures & features) const
3519 {
3520         LyXParagraph * par = paragraph;
3521         LyXTextClass const & tclass = 
3522                 textclasslist.TextClass(params.textclass);
3523     
3524         // AMS Style is at document level
3525     
3526         features.amsstyle = (params.use_amsmath ||
3527                              tclass.provides(LyXTextClass::amsmath));
3528     
3529         while (par) {
3530                 // We don't use "lyxerr.debug" because of speed. (Asger)
3531                 if (lyxerr.debugging(Debug::LATEX))
3532                         lyxerr << "Paragraph: " <<  par << endl;
3533
3534                 // Now just follow the list of paragraphs and run
3535                 // validate on each of them.
3536                 par->validate(features);
3537
3538                 // and then the next paragraph
3539 #ifndef NEW_INSETS
3540                 par = par->next_;
3541 #else
3542                 par = par->next();
3543 #endif
3544         }
3545
3546         // the bullet shapes are buffer level not paragraph level
3547         // so they are tested here
3548         for (int i = 0; i < 4; ++i) {
3549                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3550                         int const font = params.user_defined_bullets[i].getFont();
3551                         if (font == 0) {
3552                                 int const c = params
3553                                         .user_defined_bullets[i]
3554                                         .getCharacter();
3555                                 if (c == 16
3556                                    || c == 17
3557                                    || c == 25
3558                                    || c == 26
3559                                    || c == 31) {
3560                                         features.latexsym = true;
3561                                 }
3562                         } else if (font == 1) {
3563                                 features.amssymb = true;
3564                         } else if ((font >= 2 && font <= 5)) {
3565                                 features.pifont = true;
3566                         }
3567                 }
3568         }
3569         
3570         if (lyxerr.debugging(Debug::LATEX)) {
3571                 features.showStruct();
3572         }
3573 }
3574
3575
3576 void Buffer::setPaperStuff()
3577 {
3578         params.papersize = BufferParams::PAPER_DEFAULT;
3579         char const c1 = params.paperpackage;
3580         if (c1 == BufferParams::PACKAGE_NONE) {
3581                 char const c2 = params.papersize2;
3582                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3583                         params.papersize = BufferParams::PAPER_USLETTER;
3584                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3585                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3586                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3587                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3588                 else if (c2 == BufferParams::VM_PAPER_A3)
3589                         params.papersize = BufferParams::PAPER_A3PAPER;
3590                 else if (c2 == BufferParams::VM_PAPER_A4)
3591                         params.papersize = BufferParams::PAPER_A4PAPER;
3592                 else if (c2 == BufferParams::VM_PAPER_A5)
3593                         params.papersize = BufferParams::PAPER_A5PAPER;
3594                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3595                          (c2 == BufferParams::VM_PAPER_B5))
3596                         params.papersize = BufferParams::PAPER_B5PAPER;
3597         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3598                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3599                 params.papersize = BufferParams::PAPER_A4PAPER;
3600 }
3601
3602
3603 // This function should be in Buffer because it's a buffer's property (ale)
3604 string const Buffer::getIncludeonlyList(char delim)
3605 {
3606         string lst;
3607         for (inset_iterator it = inset_iterator_begin();
3608             it != inset_iterator_end(); ++it) {
3609                 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3610                         InsetInclude * insetinc = 
3611                                 static_cast<InsetInclude *>(*it);
3612                         if (insetinc->isIncludeOnly()) {
3613                                 if (!lst.empty())
3614                                         lst += delim;
3615                                 lst += insetinc->getRelFileBaseName();
3616                         }
3617                 }
3618         }
3619         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3620         return lst;
3621 }
3622
3623
3624 vector<string> const Buffer::getLabelList()
3625 {
3626         /// if this is a child document and the parent is already loaded
3627         /// Use the parent's list instead  [ale990407]
3628         if (!params.parentname.empty()
3629             && bufferlist.exists(params.parentname)) {
3630                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3631                 if (tmp)
3632                         return tmp->getLabelList();
3633         }
3634
3635         vector<string> label_list;
3636         for (inset_iterator it = inset_iterator_begin();
3637              it != inset_iterator_end(); ++it) {
3638                 vector<string> const l = (*it)->getLabelList();
3639                 label_list.insert(label_list.end(), l.begin(), l.end());
3640         }
3641         return label_list;
3642 }
3643
3644
3645 Buffer::Lists const Buffer::getLists() const
3646 {
3647         Lists l;
3648         LyXParagraph * par = paragraph;
3649 #ifdef NEW_INSETS
3650         bool found;
3651         LyXTextClassList::size_type cap;
3652         boost::tie(found, cap) = textclasslist
3653                 .NumberOfLayout(params.textclass, "Caption");
3654 #endif
3655
3656         while (par) {
3657 #ifndef NEW_INSETS
3658                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3659                         if (textclasslist.Style(params.textclass, 
3660                                                 par->GetLayout()).labeltype
3661                             == LABEL_SENSITIVE) {
3662                                 string type;
3663                                 switch (par->footnotekind) {
3664                                 case LyXParagraph::FIG:
3665                                 case LyXParagraph::WIDE_FIG:
3666                                         type = "LOF";
3667                                         break;
3668                                 case LyXParagraph::TAB:
3669                                 case LyXParagraph::WIDE_TAB:
3670                                         type = "LOT";
3671                                         break;
3672                                 case LyXParagraph::ALGORITHM:
3673                                         type = "LOA";
3674                                         break;
3675                                 case LyXParagraph::FOOTNOTE:
3676                                 case LyXParagraph::MARGIN:
3677                                         break;
3678                                 }
3679                                 if (!type.empty()) {
3680                                         SingleList & item = l[type];
3681                                         string const str =
3682                                                 tostr(item.size()+1) + ". " + par->String(this, false);
3683                                         item.push_back(TocItem(par, 0, str));
3684                                 }
3685                         }
3686                 } else if (!par->IsDummy()) {
3687 #endif
3688                         char const labeltype =
3689                                 textclasslist.Style(params.textclass, 
3690                                                     par->GetLayout()).labeltype;
3691       
3692                         if (labeltype >= LABEL_COUNTER_CHAPTER
3693                             && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3694                                 // insert this into the table of contents
3695                                 SingleList & item = l["TOC"];
3696                                 int depth = max(0,
3697                                                 labeltype - 
3698                                                 textclasslist.TextClass(params.textclass).maxcounter());
3699                                 item.push_back(TocItem(par, depth, par->String(this, true)));
3700                         }
3701 #ifdef NEW_INSETS
3702                         // For each paragrph, traverse its insets and look for
3703                         // FLOAT_CODE
3704                         
3705                         if (found) {
3706                                 LyXParagraph::inset_iterator it =
3707                                         par->inset_iterator_begin();
3708                                 LyXParagraph::inset_iterator end =
3709                                         par->inset_iterator_end();
3710
3711                                 for (; it != end; ++it) {
3712                                         if ((*it)->LyxCode() == Inset::FLOAT_CODE) {
3713                                                 InsetFloat * il =
3714                                                         static_cast<InsetFloat*>(*it);
3715                                                 
3716                                                 string const type = il->type();
3717                                                 
3718                                                 // Now find the caption in the float...
3719                                                 // We now tranverse the paragraphs of
3720                                                 // the inset...
3721                                                 LyXParagraph * tmp = il->inset.par;
3722                                                 while (tmp) {
3723                                                         if (tmp->layout == cap) {
3724                                                                 SingleList & item = l[type];
3725                                                                 string const str =
3726                                                                         tostr(item.size()+1) + ". " + tmp->String(this, false);
3727                                                                 item.push_back(TocItem(tmp, 0 , str));
3728                                                         }
3729                                                         tmp = tmp->next();
3730                                                 }
3731                                         }
3732                                 }
3733                         } else {
3734                                 lyxerr << "caption not found" << endl;
3735                         }
3736                         
3737 #endif
3738 #ifndef NEW_INSETS
3739                 }
3740                 par = par->next_;
3741 #else
3742                 par = par->next();
3743 #endif
3744         }
3745         return l;
3746 }
3747
3748
3749 // This is also a buffer property (ale)
3750 vector<pair<string, string> > const Buffer::getBibkeyList()
3751 {
3752         /// if this is a child document and the parent is already loaded
3753         /// Use the parent's list instead  [ale990412]
3754         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3755                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3756                 if (tmp)
3757                         return tmp->getBibkeyList();
3758         }
3759
3760         vector<pair<string, string> > keys;
3761         LyXParagraph * par = paragraph;
3762         while (par) {
3763                 if (par->bibkey)
3764                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3765                                                            par->String(this, false)));
3766 #ifndef NEW_INSETS
3767                 par = par->next_;
3768 #else
3769                 par = par->next();
3770 #endif
3771         }
3772
3773         // Might be either using bibtex or a child has bibliography
3774         if (keys.empty()) {
3775                 for (inset_iterator it = inset_iterator_begin();
3776                         it != inset_iterator_end(); ++it) {
3777                         // Search for Bibtex or Include inset
3778                         if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3779                                 vector<pair<string,string> > tmp =
3780                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3781                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3782                         } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3783                                 vector<pair<string,string> > const tmp =
3784                                         static_cast<InsetInclude*>(*it)->getKeys();
3785                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3786                         }
3787                 }
3788         }
3789  
3790         return keys;
3791 }
3792
3793
3794 bool Buffer::isDepClean(string const & name) const
3795 {
3796         DEPCLEAN * item = dep_clean;
3797         while (item && item->master != name)
3798                 item = item->next;
3799         if (!item) return true;
3800         return item->clean;
3801 }
3802
3803
3804 void Buffer::markDepClean(string const & name)
3805 {
3806         if (!dep_clean) {
3807                 dep_clean = new DEPCLEAN;
3808                 dep_clean->clean = true;
3809                 dep_clean->master = name;
3810                 dep_clean->next = 0;
3811         } else {
3812                 DEPCLEAN * item = dep_clean;
3813                 while (item && item->master != name)
3814                         item = item->next;
3815                 if (item) {
3816                         item->clean = true;
3817                 } else {
3818                         item = new DEPCLEAN;
3819                         item->clean = true;
3820                         item->master = name;
3821                         item->next = 0;
3822                 }
3823         }
3824 }
3825
3826
3827 bool Buffer::Dispatch(string const & command)
3828 {
3829         // Split command string into command and argument
3830         string cmd;
3831         string line = frontStrip(command);
3832         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3833
3834         return Dispatch(lyxaction.LookupFunc(cmd), arg);
3835 }
3836
3837
3838 bool Buffer::Dispatch(int action, string const & argument)
3839 {
3840         bool dispatched = true;
3841         switch (action) {
3842                 case LFUN_EXPORT: 
3843                         Exporter::Export(this, argument, false);
3844                         break;
3845
3846                 default:
3847                         dispatched = false;
3848         }
3849         return dispatched;
3850 }
3851
3852
3853 void Buffer::resize()
3854 {
3855         /// resize the BufferViews!
3856         if (users)
3857                 users->resize();
3858 }
3859
3860
3861 void Buffer::resizeInsets(BufferView * bv)
3862 {
3863         /// then remove all LyXText in text-insets
3864         LyXParagraph * par = paragraph;
3865 #ifndef NEW_INSETS
3866         for (; par; par = par->next_) {
3867             par->resizeInsetsLyXText(bv);
3868         }
3869 #else
3870         for (; par; par = par->next()) {
3871             par->resizeInsetsLyXText(bv);
3872         }
3873 #endif
3874 }
3875
3876
3877 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3878 {
3879
3880         LyXParagraph * par = paragraph;
3881         while (par) {
3882                 par->ChangeLanguage(params, from, to);
3883 #ifndef NEW_INSETS
3884                 par = par->next_;
3885 #else
3886                 par = par->next();
3887 #endif
3888         }
3889 }
3890
3891
3892 bool Buffer::isMultiLingual()
3893 {
3894         LyXParagraph * par = paragraph;
3895         while (par) {
3896                 if (par->isMultiLingual(params))
3897                         return true;
3898 #ifndef NEW_INSETS
3899                 par = par->next_;
3900 #else
3901                 par = par->next();
3902 #endif
3903         }
3904         return false;
3905 }
3906
3907
3908 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3909                                        LyXParagraph::size_type pos)
3910         : par(paragraph)
3911 {
3912         it = par->InsetIterator(pos);
3913         if (it == par->inset_iterator_end()) {
3914 #ifndef NEW_INSETS
3915                 par = par->next_;
3916 #else
3917                 par = par->next();
3918 #endif
3919                 SetParagraph();
3920         }
3921 }
3922
3923
3924 void Buffer::inset_iterator::SetParagraph()
3925 {
3926         while (par) {
3927                 it = par->inset_iterator_begin();
3928                 if (it != par->inset_iterator_end())
3929                         return;
3930 #ifndef NEW_INSETS
3931                 par = par->next_;
3932 #else
3933                 par = par->next();
3934 #endif
3935         }
3936         //it = 0;
3937         // We maintain an invariant that whenever par = 0 then it = 0
3938 }