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