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