]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Applied Angus patch to compile on DEC C++ and to avoid name clashes
[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                         mini->widthp(par->params.pextraWidthp());
1157                         mini->inset->par = par;
1158                         // Insert the minipage last in the
1159                         // previous paragraph.
1160                         if (par->params.pextraHfill()) {
1161                                 parBeforeMinipage->InsertChar
1162                                         (parBeforeMinipage->size(), LyXParagraph::META_HFILL);
1163                         }
1164                         parBeforeMinipage->InsertInset
1165                                 (parBeforeMinipage->size(), mini);
1166                                 
1167                         minipar = par;
1168                 } else {
1169                         lyxerr << "new minipage par" << endl;
1170                         //nothing to do just continue reading
1171                 }
1172                         
1173         } else if (minipar && (minipar != par)) {
1174                 lyxerr << "last minipage par read" << endl;
1175                 // The last paragraph read was not part of a
1176                 // minipage but the par linked list is...
1177                 // So we need to remove the last par from the
1178                 // rest
1179                 if (par->previous())
1180                         par->previous()->next(0);
1181                 par->previous(parBeforeMinipage);
1182                 parBeforeMinipage->next(par);
1183                 LyXParagraph * tmp = minipar;
1184                 while (tmp) {
1185                         tmp->params.pextraType(0);
1186                         tmp->params.pextraWidth(string());
1187                         tmp->params.pextraWidthp(string());
1188                         tmp->params.pextraAlignment(0);
1189                         tmp->params.pextraHfill(false);
1190                         tmp->params.pextraStartMinipage(false);
1191                         tmp = tmp->next();
1192                 }
1193                 depth = parBeforeMinipage->params.depth();
1194                 minipar = parBeforeMinipage = 0;
1195         } else if (!minipar &&
1196                    (par->params.pextraType() == LyXParagraph::PEXTRA_MINIPAGE))
1197         {
1198                 // par is the first paragraph in a minipage
1199                 lyxerr << "begin minipage" << endl;
1200                 // To minimize problems for
1201                 // the users we will insert
1202                 // the first minipage in
1203                 // a sequence of minipages
1204                 // in its own paragraph.
1205                 LyXParagraph * p = new LyXParagraph;
1206                 p->layout = 0;
1207                 p->previous(par->previous());
1208                 p->next(0);
1209                 p->params.depth(depth);
1210                 par->params.depth(0);
1211                 depth = 0;
1212                 if (par->previous())
1213                         par->previous()->next(p);
1214                 par->previous(0);
1215                 parBeforeMinipage = p;
1216                 minipar = par;
1217                 if (!return_par || (return_par == par))
1218                         return_par = p;
1219
1220                 InsetMinipage * mini = new InsetMinipage;
1221                 mini->pos(static_cast<InsetMinipage::Position>(minipar->params.pextraAlignment()));
1222                 mini->width(minipar->params.pextraWidth());
1223                 mini->widthp(minipar->params.pextraWidthp());
1224                 mini->inset->par = minipar;
1225                         
1226                 // Insert the minipage last in the
1227                 // previous paragraph.
1228                 if (minipar->params.pextraHfill()) {
1229                         parBeforeMinipage->InsertChar
1230                                 (parBeforeMinipage->size(),LyXParagraph::META_HFILL);
1231                 }
1232                 parBeforeMinipage->InsertInset
1233                         (parBeforeMinipage->size(), mini);
1234         }
1235         }
1236         // End of pextra_minipage compability
1237 #endif
1238         --call_depth;
1239         return the_end_read;
1240 }
1241
1242
1243 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
1244                        int & pos, LyXFont & font)
1245 {
1246         // consistency check
1247         if (lex.GetString() != "\\begin_inset") {
1248                 lyxerr << "Buffer::readInset: Consistency check failed."
1249                        << endl;
1250         }
1251         
1252         Inset * inset = 0;
1253
1254         lex.next();
1255         string const tmptok = lex.GetString();
1256         last_inset_read = tmptok;
1257
1258         // test the different insets
1259         if (tmptok == "LatexCommand") {
1260                 InsetCommandParams inscmd;
1261                 inscmd.Read(lex);
1262
1263                 if (inscmd.getCmdName() == "cite") {
1264                         inset = new InsetCitation(inscmd);
1265                 } else if (inscmd.getCmdName() == "bibitem") {
1266                         lex.printError("Wrong place for bibitem");
1267                         inset = new InsetBibKey(inscmd);
1268                 } else if (inscmd.getCmdName() == "BibTeX") {
1269                         inset = new InsetBibtex(inscmd);
1270                 } else if (inscmd.getCmdName() == "index") {
1271                         inset = new InsetIndex(inscmd);
1272                 } else if (inscmd.getCmdName() == "include") {
1273                         inset = new InsetInclude(inscmd, *this);
1274                 } else if (inscmd.getCmdName() == "label") {
1275                         inset = new InsetLabel(inscmd);
1276                 } else if (inscmd.getCmdName() == "url"
1277                            || inscmd.getCmdName() == "htmlurl") {
1278                         inset = new InsetUrl(inscmd);
1279                 } else if (inscmd.getCmdName() == "ref"
1280                            || inscmd.getCmdName() == "pageref"
1281                            || inscmd.getCmdName() == "vref"
1282                            || inscmd.getCmdName() == "vpageref"
1283                            || inscmd.getCmdName() == "prettyref") {
1284                         if (!inscmd.getOptions().empty()
1285                             || !inscmd.getContents().empty()) {
1286                                 inset = new InsetRef(inscmd, *this);
1287                         }
1288                 } else if (inscmd.getCmdName() == "tableofcontents"
1289                            || inscmd.getCmdName() == "listofalgorithms"
1290                            || inscmd.getCmdName() == "listoffigures"
1291                            || inscmd.getCmdName() == "listoftables") {
1292                         inset = new InsetTOC(inscmd);
1293                 } else if (inscmd.getCmdName() == "printindex") {
1294                         inset = new InsetPrintIndex(inscmd);
1295                 } else if (inscmd.getCmdName() == "lyxparent") {
1296                         inset = new InsetParent(inscmd, *this);
1297                 }
1298         } else {
1299                 if (tmptok == "Quotes") {
1300                         inset = new InsetQuotes;
1301                 } else if (tmptok == "External") {
1302                         inset = new InsetExternal;
1303                 } else if (tmptok == "FormulaMacro") {
1304                         inset = new InsetFormulaMacro;
1305                 } else if (tmptok == "Formula") {
1306                         inset = new InsetFormula;
1307                 } else if (tmptok == "Figure") {
1308                         inset = new InsetFig(100, 100, *this);
1309                 } else if (tmptok == "Info") {
1310                         inset = new InsetInfo;
1311                 } else if (tmptok == "Include") {
1312                         InsetCommandParams p( "Include" );
1313                         inset = new InsetInclude(p, *this);
1314                 } else if (tmptok == "ERT") {
1315                         inset = new InsetERT;
1316                 } else if (tmptok == "Tabular") {
1317                         inset = new InsetTabular(*this);
1318                 } else if (tmptok == "Text") {
1319                         inset = new InsetText;
1320                 } else if (tmptok == "Foot") {
1321                         inset = new InsetFoot;
1322                 } else if (tmptok == "Marginal") {
1323                         inset = new InsetMarginal;
1324                 } else if (tmptok == "Minipage") {
1325                         inset = new InsetMinipage;
1326                 } else if (tmptok == "Float") {
1327                         lex.next();
1328                         string tmptok = lex.GetString();
1329                         inset = new InsetFloat(tmptok);
1330                 } else if (tmptok == "List") {
1331                         inset = new InsetList;
1332                 } else if (tmptok == "Theorem") {
1333                         inset = new InsetList;
1334                 } else if (tmptok == "Caption") {
1335                         inset = new InsetCaption;
1336                 } else if (tmptok == "GRAPHICS") {
1337                         inset = new InsetGraphics;
1338                 }
1339                 
1340                 if (inset) inset->Read(this, lex);
1341         }
1342         
1343         if (inset) {
1344                 par->InsertInset(pos, inset, font);
1345                 ++pos;
1346         }
1347 }
1348
1349
1350 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1351 {
1352         if (lex.IsOK()) {
1353                 lex.next();
1354                 string const token(lex.GetString());
1355                 if (token == "\\lyxformat") { // the first token _must_ be...
1356                         lex.EatLine();
1357                         string tmp_format = lex.GetString();
1358                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1359                         // if present remove ".," from string.
1360                         string::size_type dot = tmp_format.find_first_of(".,");
1361                         //lyxerr << "           dot found at " << dot << endl;
1362                         if (dot != string::npos)
1363                                 tmp_format.erase(dot, 1);
1364                         file_format = strToInt(tmp_format);
1365                         if (file_format == LYX_FORMAT) {
1366                                 // current format
1367                         } else if (file_format > LYX_FORMAT) {
1368                                 // future format
1369                                 WriteAlert(_("Warning!"),
1370                                            _("LyX file format is newer that what"),
1371                                            _("is supported in this LyX version. Expect some problems."));
1372                                 
1373                         } else if (file_format < LYX_FORMAT) {
1374                                 // old formats
1375                                 if (file_format < 200) {
1376                                         WriteAlert(_("ERROR!"),
1377                                                    _("Old LyX file format found. "
1378                                                      "Use LyX 0.10.x to read this!"));
1379                                         return false;
1380                                 }
1381                         }
1382                         bool the_end = readLyXformat2(lex, par);
1383                         setPaperStuff();
1384                         // the_end was added in 213
1385                         if (file_format < 213)
1386                                 the_end = true;
1387
1388                         if (!the_end)
1389                                 WriteAlert(_("Warning!"),
1390                                            _("Reading of document is not complete"),
1391                                            _("Maybe the document is truncated"));
1392                         return true;
1393                 } else { // "\\lyxformat" not found
1394                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1395                 }
1396         } else
1397                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1398         return false;
1399 }
1400                     
1401
1402
1403 // Should probably be moved to somewhere else: BufferView? LyXView?
1404 bool Buffer::save() const
1405 {
1406         // We don't need autosaves in the immediate future. (Asger)
1407         resetAutosaveTimers();
1408
1409         // make a backup
1410         string s;
1411         if (lyxrc.make_backup) {
1412                 s = fileName() + '~';
1413                 if (!lyxrc.backupdir_path.empty())
1414                         s = AddName(lyxrc.backupdir_path,
1415                                     subst(CleanupPath(s),'/','!'));
1416
1417                 // Rename is the wrong way of making a backup,
1418                 // this is the correct way.
1419                 /* truss cp fil fil2:
1420                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1421                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1422                    open("LyXVC.lyx", O_RDONLY)                     = 3
1423                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1424                    fstat(4, 0xEFFFF508)                            = 0
1425                    fstat(3, 0xEFFFF508)                            = 0
1426                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1427                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1428                    read(3, 0xEFFFD4A0, 8192)                       = 0
1429                    close(4)                                        = 0
1430                    close(3)                                        = 0
1431                    chmod("LyXVC3.lyx", 0100644)                    = 0
1432                    lseek(0, 0, SEEK_CUR)                           = 46440
1433                    _exit(0)
1434                 */
1435
1436                 // Should proabaly have some more error checking here.
1437                 // Should be cleaned up in 0.13, at least a bit.
1438                 // Doing it this way, also makes the inodes stay the same.
1439                 // This is still not a very good solution, in particular we
1440                 // might loose the owner of the backup.
1441                 FileInfo finfo(fileName());
1442                 if (finfo.exist()) {
1443                         mode_t fmode = finfo.getMode();
1444                         struct utimbuf times = {
1445                                 finfo.getAccessTime(),
1446                                 finfo.getModificationTime() };
1447
1448                         ifstream ifs(fileName().c_str());
1449                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1450                         if (ifs && ofs) {
1451                                 ofs << ifs.rdbuf();
1452                                 ifs.close();
1453                                 ofs.close();
1454                                 ::chmod(s.c_str(), fmode);
1455                                 
1456                                 if (::utime(s.c_str(), &times)) {
1457                                         lyxerr << "utime error." << endl;
1458                                 }
1459                         } else {
1460                                 lyxerr << "LyX was not able to make "
1461                                         "backupcopy. Beware." << endl;
1462                         }
1463                 }
1464         }
1465         
1466         if (writeFile(fileName(), false)) {
1467                 markLyxClean();
1468                 removeAutosaveFile(fileName());
1469         } else {
1470                 // Saving failed, so backup is not backup
1471                 if (lyxrc.make_backup) {
1472                         lyx::rename(s, fileName());
1473                 }
1474                 return false;
1475         }
1476         return true;
1477 }
1478
1479
1480 // Returns false if unsuccesful
1481 bool Buffer::writeFile(string const & fname, bool flag) const
1482 {
1483         // if flag is false writeFile will not create any GUI
1484         // warnings, only cerr.
1485         // Needed for autosave in background or panic save (Matthias 120496)
1486
1487         if (read_only && (fname == filename)) {
1488                 // Here we should come with a question if we should
1489                 // perform the write anyway.
1490                 if (flag)
1491                         lyxerr << _("Error! Document is read-only: ")
1492                                << fname << endl;
1493                 else
1494                         WriteAlert(_("Error! Document is read-only: "),
1495                                    fname);
1496                 return false;
1497         }
1498
1499         FileInfo finfo(fname);
1500         if (finfo.exist() && !finfo.writable()) {
1501                 // Here we should come with a question if we should
1502                 // try to do the save anyway. (i.e. do a chmod first)
1503                 if (flag)
1504                         lyxerr << _("Error! Cannot write file: ")
1505                                << fname << endl;
1506                 else
1507                         WriteFSAlert(_("Error! Cannot write file: "),
1508                                      fname);
1509                 return false;
1510         }
1511
1512         ofstream ofs(fname.c_str());
1513         if (!ofs) {
1514                 if (flag)
1515                         lyxerr << _("Error! Cannot open file: ")
1516                                << fname << endl;
1517                 else
1518                         WriteFSAlert(_("Error! Cannot open file: "),
1519                                      fname);
1520                 return false;
1521         }
1522
1523 #ifdef HAVE_LOCALE
1524         // Use the standard "C" locale for file output.
1525         ofs.imbue(std::locale::classic());
1526 #endif
1527
1528         // The top of the file should not be written by params.
1529
1530         // write out a comment in the top of the file
1531         ofs << '#' << LYX_DOCVERSION 
1532             << " created this file. For more info see http://www.lyx.org/\n"
1533             << "\\lyxformat " << LYX_FORMAT << "\n";
1534
1535         // now write out the buffer paramters.
1536         params.writeFile(ofs);
1537
1538         char footnoteflag = 0;
1539         char depth = 0;
1540
1541         // this will write out all the paragraphs
1542         // using recursive descent.
1543         paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1544
1545         // Write marker that shows file is complete
1546         ofs << "\n\\the_end" << endl;
1547
1548         ofs.close();
1549
1550         // how to check if close went ok?
1551         // Following is an attempt... (BE 20001011)
1552         
1553         // good() returns false if any error occured, including some
1554         //        formatting error.
1555         // bad()  returns true if something bad happened in the buffer,
1556         //        which should include file system full errors.
1557
1558         bool status = true;
1559         if (!ofs.good()) {
1560                 status = false;
1561 #if 0
1562                 if (ofs.bad()) {
1563                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1564                 } else {
1565                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1566                                << endl;
1567                 }
1568 #endif
1569         }
1570         
1571         return status;
1572 }
1573
1574
1575 string const Buffer::asciiParagraph(LyXParagraph const * par,
1576                                     unsigned int linelen) const
1577 {
1578         ostringstream buffer;
1579         LyXFont font1;
1580         LyXFont font2;
1581         Inset const * inset;
1582         char c;
1583 #ifndef NEW_INSETS
1584         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1585 #endif
1586         char depth = 0;
1587         int ltype = 0;
1588         int ltype_depth = 0;
1589         unsigned int currlinelen = 0;
1590         bool ref_printed = false;
1591
1592         int noparbreak = 0;
1593         int islatex = 0;
1594 #ifndef NEW_INSETS
1595         if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1596             !par->previous_
1597             || par->previous()->footnoteflag == LyXParagraph::NO_FOOTNOTE) {
1598                 /* begins a footnote environment ? */ 
1599                 if (footnoteflag != par->footnoteflag) {
1600                         footnoteflag = par->footnoteflag;
1601                         if (footnoteflag) {
1602                                 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1603                                 if ((linelen > 0) &&
1604                                     ((currlinelen + j) > linelen)) {
1605                                         buffer << "\n";
1606                                         currlinelen = 0;
1607                                 }
1608                                 buffer << "(["
1609                                        << string_footnotekinds[par->footnotekind]
1610                                        << "] ";
1611                                 currlinelen += j;
1612                         }
1613                 }
1614 #else
1615                 if (!par->previous()) {
1616 #endif
1617                 /* begins or ends a deeper area ?*/ 
1618                 if (depth != par->params.depth()) {
1619                         if (par->params.depth() > depth) {
1620                                 while (par->params.depth() > depth) {
1621                                         ++depth;
1622                                 }
1623                         } else {
1624                                 while (par->params.depth() < depth) {
1625                                         --depth;
1626                                 }
1627                         }
1628                 }
1629                 
1630                 /* First write the layout */
1631                 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1632                 if (tmp == "Itemize") {
1633                         ltype = 1;
1634                         ltype_depth = depth + 1;
1635                 } else if (tmp == "Enumerate") {
1636                         ltype = 2;
1637                         ltype_depth = depth + 1;
1638                 } else if (strstr(tmp.c_str(), "ection")) {
1639                         ltype = 3;
1640                         ltype_depth = depth + 1;
1641                 } else if (strstr(tmp.c_str(), "aragraph")) {
1642                         ltype = 4;
1643                         ltype_depth = depth + 1;
1644                 } else if (tmp == "Description") {
1645                         ltype = 5;
1646                         ltype_depth = depth + 1;
1647                 } else if (tmp == "Abstract") {
1648                         ltype = 6;
1649                         ltype_depth = 0;
1650                 } else if (tmp == "Bibliography") {
1651                         ltype = 7;
1652                         ltype_depth = 0;
1653                 } else {
1654                         ltype = 0;
1655                         ltype_depth = 0;
1656                 }
1657                 
1658                 /* maybe some vertical spaces */ 
1659                 
1660                 /* the labelwidthstring used in lists */ 
1661                 
1662                 /* some lines? */ 
1663                 
1664                 /* some pagebreaks? */ 
1665                 
1666                 /* noindent ? */ 
1667                 
1668                 /* what about the alignment */ 
1669         } else {
1670 #ifndef NEW_INSETS
1671                 /* dummy layout, that means a footnote ended */ 
1672                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1673                 buffer << ") ";
1674                 noparbreak = 1;
1675 #else
1676                 lyxerr << "Should this ever happen?" << endl;
1677 #endif
1678         }
1679       
1680         font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1681         for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1682                 if (!i &&
1683 #ifndef NEW_INSETS
1684                     !footnoteflag &&
1685 #endif
1686                     !noparbreak) {
1687                         if (linelen > 0)
1688                                 buffer << "\n\n";
1689                         for (char j = 0; j < depth; ++j)
1690                                 buffer << "  ";
1691                         currlinelen = depth * 2;
1692                         switch (ltype) {
1693                         case 0: /* Standard */
1694                         case 4: /* (Sub)Paragraph */
1695                         case 5: /* Description */
1696                                 break;
1697                         case 6: /* Abstract */
1698                                 if (linelen > 0)
1699                                         buffer << "Abstract\n\n";
1700                                 else
1701                                         buffer << "Abstract: ";
1702                                 break;
1703                         case 7: /* Bibliography */
1704                                 if (!ref_printed) {
1705                                         if (linelen > 0)
1706                                                 buffer << "References\n\n";
1707                                         else
1708                                                 buffer << "References: ";
1709                                         ref_printed = true;
1710                                 }
1711                                 break;
1712                         default:
1713                                 buffer << par->params.labelString() << " ";
1714                                 break;
1715                         }
1716                         if (ltype_depth > depth) {
1717                                 for (char j = ltype_depth - 1; j > depth; --j)
1718                                         buffer << "  ";
1719                                 currlinelen += (ltype_depth-depth)*2;
1720                         }
1721                 }
1722                 font2 = par->GetFontSettings(params, i);
1723                 if (font1.latex() != font2.latex()) {
1724                         if (font2.latex() == LyXFont::OFF)
1725                                 islatex = 0;
1726                         else
1727                                 islatex = 1;
1728                 } else {
1729                         islatex = 0;
1730                 }
1731                 c = par->GetUChar(params, i);
1732                 if (islatex)
1733                         continue;
1734                 switch (c) {
1735                 case LyXParagraph::META_INSET:
1736                         if ((inset = par->GetInset(i))) {
1737                                 if (!inset->Ascii(this, buffer)) {
1738                                         string dummy;
1739                                         string s = rsplit(buffer.str().c_str(),
1740                                                           dummy, '\n');
1741                                         currlinelen += s.length();
1742                                 } else {
1743                                         // to be sure it breaks paragraph
1744                                         currlinelen += linelen;
1745                                 }
1746                         }
1747                         break;
1748                 case LyXParagraph::META_NEWLINE:
1749                         if (linelen > 0) {
1750                                 buffer << "\n";
1751                                 for (char j = 0; j < depth; ++j)
1752                                         buffer << "  ";
1753                         }
1754                         currlinelen = depth * 2;
1755                         if (ltype_depth > depth) {
1756                                 for (char j = ltype_depth;
1757                                     j > depth; --j)
1758                                         buffer << "  ";
1759                                 currlinelen += (ltype_depth - depth) * 2;
1760                         }
1761                         break;
1762                 case LyXParagraph::META_HFILL: 
1763                         buffer << "\t";
1764                         break;
1765                 case '\\':
1766                         buffer << "\\";
1767                         break;
1768                 default:
1769                         if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1770                             (c == ' ') && ((i + 2) < par->size()))
1771                         {
1772                                 buffer << "\n";
1773                                 for (char j = 0; j < depth; ++j)
1774                                         buffer << "  ";
1775                                 currlinelen = depth * 2;
1776                                 if (ltype_depth > depth) {
1777                                         for (char j = ltype_depth;
1778                                             j > depth; --j)
1779                                                 buffer << "  ";
1780                                         currlinelen += (ltype_depth-depth)*2;
1781                                 }
1782                         } else if (c != '\0')
1783                                 buffer << c;
1784                         else if (c == '\0')
1785                                 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1786                         ++currlinelen;
1787                         break;
1788                 }
1789         }
1790         return buffer.str().c_str();
1791 }
1792
1793
1794 void Buffer::writeFileAscii(string const & fname, int linelen) 
1795 {
1796         ofstream ofs(fname.c_str());
1797         if (!ofs) {
1798                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1799                 return;
1800         }
1801         writeFileAscii(ofs, linelen);
1802 }
1803
1804
1805 void Buffer::writeFileAscii(ostream & ofs, int linelen) 
1806 {
1807         LyXParagraph * par = paragraph;
1808         while (par) {
1809                 ofs << asciiParagraph(par, linelen);
1810                 par = par->next();
1811         }
1812         ofs << "\n";
1813 }
1814
1815 bool use_babel;
1816
1817 void Buffer::makeLaTeXFile(string const & fname, 
1818                            string const & original_path,
1819                            bool nice, bool only_body)
1820 {
1821         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1822         
1823         niceFile = nice; // this will be used by Insetincludes.
1824
1825         tex_code_break_column = lyxrc.ascii_linelen;
1826
1827         LyXTextClass const & tclass =
1828                 textclasslist.TextClass(params.textclass);
1829
1830         ofstream ofs(fname.c_str());
1831         if (!ofs) {
1832                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1833                 return;
1834         }
1835         
1836         // validate the buffer.
1837         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1838         LaTeXFeatures features(params, tclass.numLayouts());
1839         validate(features);
1840         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1841         
1842         texrow.reset();
1843         // The starting paragraph of the coming rows is the 
1844         // first paragraph of the document. (Asger)
1845         texrow.start(paragraph, 0);
1846
1847         if (!only_body && nice) {
1848                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1849                         "For more info, see http://www.lyx.org/.\n"
1850                         "%% Do not edit unless you really know what "
1851                         "you are doing.\n";
1852                 texrow.newline();
1853                 texrow.newline();
1854         }
1855         lyxerr.debug() << "lyx header finished" << endl;
1856         // There are a few differences between nice LaTeX and usual files:
1857         // usual is \batchmode and has a 
1858         // special input@path to allow the including of figures
1859         // with either \input or \includegraphics (what figinsets do).
1860         // batchmode is not set if there is a tex_code_break_column.
1861         // In this case somebody is interested in the generated LaTeX,
1862         // so this is OK. input@path is set when the actual parameter
1863         // original_path is set. This is done for usual tex-file, but not
1864         // for nice-latex-file. (Matthias 250696)
1865         if (!only_body) {
1866                 if (!nice){
1867                         // code for usual, NOT nice-latex-file
1868                         ofs << "\\batchmode\n"; // changed
1869                         // from \nonstopmode
1870                         texrow.newline();
1871                 }
1872                 if (!original_path.empty()) {
1873                         ofs << "\\makeatletter\n"
1874                             << "\\def\\input@path{{"
1875                             << original_path << "/}}\n"
1876                             << "\\makeatother\n";
1877                         texrow.newline();
1878                         texrow.newline();
1879                         texrow.newline();
1880                 }
1881                 
1882                 ofs << "\\documentclass";
1883                 
1884                 string options; // the document class options.
1885                 
1886                 if (tokenPos(tclass.opt_fontsize(),
1887                              '|', params.fontsize) >= 0) {
1888                         // only write if existing in list (and not default)
1889                         options += params.fontsize;
1890                         options += "pt,";
1891                 }
1892                 
1893                 
1894                 if (!params.use_geometry &&
1895                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1896                         switch (params.papersize) {
1897                         case BufferParams::PAPER_A4PAPER:
1898                                 options += "a4paper,";
1899                                 break;
1900                         case BufferParams::PAPER_USLETTER:
1901                                 options += "letterpaper,";
1902                                 break;
1903                         case BufferParams::PAPER_A5PAPER:
1904                                 options += "a5paper,";
1905                                 break;
1906                         case BufferParams::PAPER_B5PAPER:
1907                                 options += "b5paper,";
1908                                 break;
1909                         case BufferParams::PAPER_EXECUTIVEPAPER:
1910                                 options += "executivepaper,";
1911                                 break;
1912                         case BufferParams::PAPER_LEGALPAPER:
1913                                 options += "legalpaper,";
1914                                 break;
1915                         }
1916                 }
1917
1918                 // if needed
1919                 if (params.sides != tclass.sides()) {
1920                         switch (params.sides) {
1921                         case LyXTextClass::OneSide:
1922                                 options += "oneside,";
1923                                 break;
1924                         case LyXTextClass::TwoSides:
1925                                 options += "twoside,";
1926                                 break;
1927                         }
1928
1929                 }
1930
1931                 // if needed
1932                 if (params.columns != tclass.columns()) {
1933                         if (params.columns == 2)
1934                                 options += "twocolumn,";
1935                         else
1936                                 options += "onecolumn,";
1937                 }
1938
1939                 if (!params.use_geometry 
1940                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1941                         options += "landscape,";
1942                 
1943                 // language should be a parameter to \documentclass
1944                 use_babel = false;
1945                 string language_options;
1946                 if (params.language->babel() == "hebrew"
1947                     && default_language->babel() != "hebrew")
1948                          // This seems necessary
1949                         features.UsedLanguages.insert(default_language);
1950
1951                 if (lyxrc.language_use_babel ||
1952                     params.language->lang() != lyxrc.default_language ||
1953                     !features.UsedLanguages.empty()) {
1954                         use_babel = true;
1955                         for (LaTeXFeatures::LanguageList::const_iterator cit =
1956                                      features.UsedLanguages.begin();
1957                              cit != features.UsedLanguages.end(); ++cit)
1958                                 language_options += (*cit)->babel() + ',';
1959                         language_options += params.language->babel();
1960                         if (lyxrc.language_global_options)
1961                                 options += language_options + ',';
1962                 }
1963
1964                 // the user-defined options
1965                 if (!params.options.empty()) {
1966                         options += params.options + ',';
1967                 }
1968                 
1969                 if (!options.empty()){
1970                         options = strip(options, ',');
1971                         ofs << '[' << options << ']';
1972                 }
1973                 
1974                 ofs << '{'
1975                     << textclasslist.LatexnameOfClass(params.textclass)
1976                     << "}\n";
1977                 texrow.newline();
1978                 // end of \documentclass defs
1979                 
1980                 // font selection must be done before loading fontenc.sty
1981                 // The ae package is not needed when using OT1 font encoding.
1982                 if (params.fonts != "default" &&
1983                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1984                         ofs << "\\usepackage{" << params.fonts << "}\n";
1985                         texrow.newline();
1986                         if (params.fonts == "ae") {
1987                                 ofs << "\\usepackage{aecompl}\n";
1988                                 texrow.newline();
1989                         }
1990                 }
1991                 // this one is not per buffer
1992                 if (lyxrc.fontenc != "default") {
1993                         ofs << "\\usepackage[" << lyxrc.fontenc
1994                             << "]{fontenc}\n";
1995                         texrow.newline();
1996                 }
1997
1998                 if (params.inputenc == "auto") {
1999                         string const doc_encoding =
2000                                 params.language->encoding()->LatexName();
2001
2002                         // Create a list with all the input encodings used 
2003                         // in the document
2004                         set<string> encodings;
2005                         for (LaTeXFeatures::LanguageList::const_iterator it =
2006                                      features.UsedLanguages.begin();
2007                              it != features.UsedLanguages.end(); ++it)
2008                                 if ((*it)->encoding()->LatexName() != doc_encoding)
2009                                         encodings.insert((*it)->encoding()->LatexName());
2010
2011                         ofs << "\\usepackage[";
2012                         std::copy(encodings.begin(), encodings.end(),
2013                                   std::ostream_iterator<string>(ofs, ","));
2014                         ofs << doc_encoding << "]{inputenc}\n";
2015                         texrow.newline();
2016                 } else if (params.inputenc != "default") {
2017                         ofs << "\\usepackage[" << params.inputenc
2018                             << "]{inputenc}\n";
2019                         texrow.newline();
2020                 }
2021
2022                 // At the very beginning the text parameters.
2023                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2024                         switch (params.paperpackage) {
2025                         case BufferParams::PACKAGE_A4:
2026                                 ofs << "\\usepackage{a4}\n";
2027                                 texrow.newline();
2028                                 break;
2029                         case BufferParams::PACKAGE_A4WIDE:
2030                                 ofs << "\\usepackage{a4wide}\n";
2031                                 texrow.newline();
2032                                 break;
2033                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2034                                 ofs << "\\usepackage[widemargins]{a4}\n";
2035                                 texrow.newline();
2036                                 break;
2037                         }
2038                 }
2039                 if (params.use_geometry) {
2040                         ofs << "\\usepackage{geometry}\n";
2041                         texrow.newline();
2042                         ofs << "\\geometry{verbose";
2043                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2044                                 ofs << ",landscape";
2045                         switch (params.papersize2) {
2046                         case BufferParams::VM_PAPER_CUSTOM:
2047                                 if (!params.paperwidth.empty())
2048                                         ofs << ",paperwidth="
2049                                             << params.paperwidth;
2050                                 if (!params.paperheight.empty())
2051                                         ofs << ",paperheight="
2052                                             << params.paperheight;
2053                                 break;
2054                         case BufferParams::VM_PAPER_USLETTER:
2055                                 ofs << ",letterpaper";
2056                                 break;
2057                         case BufferParams::VM_PAPER_USLEGAL:
2058                                 ofs << ",legalpaper";
2059                                 break;
2060                         case BufferParams::VM_PAPER_USEXECUTIVE:
2061                                 ofs << ",executivepaper";
2062                                 break;
2063                         case BufferParams::VM_PAPER_A3:
2064                                 ofs << ",a3paper";
2065                                 break;
2066                         case BufferParams::VM_PAPER_A4:
2067                                 ofs << ",a4paper";
2068                                 break;
2069                         case BufferParams::VM_PAPER_A5:
2070                                 ofs << ",a5paper";
2071                                 break;
2072                         case BufferParams::VM_PAPER_B3:
2073                                 ofs << ",b3paper";
2074                                 break;
2075                         case BufferParams::VM_PAPER_B4:
2076                                 ofs << ",b4paper";
2077                                 break;
2078                         case BufferParams::VM_PAPER_B5:
2079                                 ofs << ",b5paper";
2080                                 break;
2081                         default:
2082                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2083                                 switch (lyxrc.default_papersize) {
2084                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2085                                 case BufferParams::PAPER_USLETTER:
2086                                         ofs << ",letterpaper";
2087                                         break;
2088                                 case BufferParams::PAPER_LEGALPAPER:
2089                                         ofs << ",legalpaper";
2090                                         break;
2091                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2092                                         ofs << ",executivepaper";
2093                                         break;
2094                                 case BufferParams::PAPER_A3PAPER:
2095                                         ofs << ",a3paper";
2096                                         break;
2097                                 case BufferParams::PAPER_A4PAPER:
2098                                         ofs << ",a4paper";
2099                                         break;
2100                                 case BufferParams::PAPER_A5PAPER:
2101                                         ofs << ",a5paper";
2102                                         break;
2103                                 case BufferParams::PAPER_B5PAPER:
2104                                         ofs << ",b5paper";
2105                                         break;
2106                                 }
2107                         }
2108                         if (!params.topmargin.empty())
2109                                 ofs << ",tmargin=" << params.topmargin;
2110                         if (!params.bottommargin.empty())
2111                                 ofs << ",bmargin=" << params.bottommargin;
2112                         if (!params.leftmargin.empty())
2113                                 ofs << ",lmargin=" << params.leftmargin;
2114                         if (!params.rightmargin.empty())
2115                                 ofs << ",rmargin=" << params.rightmargin;
2116                         if (!params.headheight.empty())
2117                                 ofs << ",headheight=" << params.headheight;
2118                         if (!params.headsep.empty())
2119                                 ofs << ",headsep=" << params.headsep;
2120                         if (!params.footskip.empty())
2121                                 ofs << ",footskip=" << params.footskip;
2122                         ofs << "}\n";
2123                         texrow.newline();
2124                 }
2125                 if (features.amsstyle
2126                     && !tclass.provides(LyXTextClass::amsmath)) {
2127                         ofs << "\\usepackage{amsmath}\n";
2128                         texrow.newline();
2129                 }
2130
2131                 if (tokenPos(tclass.opt_pagestyle(),
2132                              '|', params.pagestyle) >= 0) {
2133                         if (params.pagestyle == "fancy") {
2134                                 ofs << "\\usepackage{fancyhdr}\n";
2135                                 texrow.newline();
2136                         }
2137                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2138                         texrow.newline();
2139                 }
2140
2141                 // We try to load babel late, in case it interferes
2142                 // with other packages.
2143                 if (use_babel) {
2144                         string tmp = lyxrc.language_package;
2145                         if (!lyxrc.language_global_options
2146                             && tmp == "\\usepackage{babel}")
2147                                 tmp = "\\usepackage[" +
2148                                         language_options + "]{babel}";
2149                         ofs << tmp << "\n";
2150                         texrow.newline();
2151                 }
2152
2153                 if (params.secnumdepth != tclass.secnumdepth()) {
2154                         ofs << "\\setcounter{secnumdepth}{"
2155                             << params.secnumdepth
2156                             << "}\n";
2157                         texrow.newline();
2158                 }
2159                 if (params.tocdepth != tclass.tocdepth()) {
2160                         ofs << "\\setcounter{tocdepth}{"
2161                             << params.tocdepth
2162                             << "}\n";
2163                         texrow.newline();
2164                 }
2165                 
2166                 if (params.paragraph_separation) {
2167                         switch (params.defskip.kind()) {
2168                         case VSpace::SMALLSKIP: 
2169                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2170                                 break;
2171                         case VSpace::MEDSKIP:
2172                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2173                                 break;
2174                         case VSpace::BIGSKIP:
2175                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2176                                 break;
2177                         case VSpace::LENGTH:
2178                                 ofs << "\\setlength\\parskip{"
2179                                     << params.defskip.length().asLatexString()
2180                                     << "}\n";
2181                                 break;
2182                         default: // should never happen // Then delete it.
2183                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2184                                 break;
2185                         }
2186                         texrow.newline();
2187                         
2188                         ofs << "\\setlength\\parindent{0pt}\n";
2189                         texrow.newline();
2190                 }
2191
2192                 // Now insert the LyX specific LaTeX commands...
2193
2194                 // The optional packages;
2195                 string preamble(features.getPackages());
2196
2197                 // this might be useful...
2198                 preamble += "\n\\makeatletter\n";
2199
2200                 // Some macros LyX will need
2201                 string tmppreamble(features.getMacros());
2202
2203                 if (!tmppreamble.empty()) {
2204                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2205                                 "LyX specific LaTeX commands.\n"
2206                                 + tmppreamble + '\n';
2207                 }
2208
2209                 // the text class specific preamble 
2210                 tmppreamble = features.getTClassPreamble();
2211                 if (!tmppreamble.empty()) {
2212                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2213                                 "Textclass specific LaTeX commands.\n"
2214                                 + tmppreamble + '\n';
2215                 }
2216
2217                 /* the user-defined preamble */
2218                 if (!params.preamble.empty()) {
2219                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2220                                 "User specified LaTeX commands.\n"
2221                                 + params.preamble + '\n';
2222                 }
2223
2224                 preamble += "\\makeatother\n";
2225
2226                 // Itemize bullet settings need to be last in case the user
2227                 // defines their own bullets that use a package included
2228                 // in the user-defined preamble -- ARRae
2229                 // Actually it has to be done much later than that
2230                 // since some packages like frenchb make modifications
2231                 // at \begin{document} time -- JMarc 
2232                 string bullets_def;
2233                 for (int i = 0; i < 4; ++i) {
2234                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2235                                 if (bullets_def.empty())
2236                                         bullets_def="\\AtBeginDocument{\n";
2237                                 bullets_def += "  \\renewcommand{\\labelitemi";
2238                                 switch (i) {
2239                                 // `i' is one less than the item to modify
2240                                 case 0:
2241                                         break;
2242                                 case 1:
2243                                         bullets_def += 'i';
2244                                         break;
2245                                 case 2:
2246                                         bullets_def += "ii";
2247                                         break;
2248                                 case 3:
2249                                         bullets_def += 'v';
2250                                         break;
2251                                 }
2252                                 bullets_def += "}{" + 
2253                                   params.user_defined_bullets[i].getText() 
2254                                   + "}\n";
2255                         }
2256                 }
2257
2258                 if (!bullets_def.empty())
2259                   preamble += bullets_def + "}\n\n";
2260
2261                 for (int j = countChar(preamble, '\n'); j-- ;) {
2262                         texrow.newline();
2263                 }
2264
2265                 ofs << preamble;
2266
2267                 // make the body.
2268                 ofs << "\\begin{document}\n";
2269                 texrow.newline();
2270         } // only_body
2271         lyxerr.debug() << "preamble finished, now the body." << endl;
2272
2273         if (!lyxrc.language_auto_begin) {
2274                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2275                              params.language->babel())
2276                     << endl;
2277                 texrow.newline();
2278         }
2279         
2280         latexParagraphs(ofs, paragraph, 0, texrow);
2281
2282         // add this just in case after all the paragraphs
2283         ofs << endl;
2284         texrow.newline();
2285
2286         if (!lyxrc.language_auto_end) {
2287                 ofs << subst(lyxrc.language_command_end, "$$lang",
2288                              params.language->babel())
2289                     << endl;
2290                 texrow.newline();
2291         }
2292
2293         if (!only_body) {
2294                 ofs << "\\end{document}\n";
2295                 texrow.newline();
2296         
2297                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2298         } else {
2299                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2300                                      << endl;
2301         }
2302
2303         // Just to be sure. (Asger)
2304         texrow.newline();
2305
2306         // tex_code_break_column's value is used to decide
2307         // if we are in batchmode or not (within mathed_write()
2308         // in math_write.C) so we must set it to a non-zero
2309         // value when we leave otherwise we save incorrect .lyx files.
2310         tex_code_break_column = lyxrc.ascii_linelen;
2311
2312         ofs.close();
2313         if (ofs.fail()) {
2314                 lyxerr << "File was not closed properly." << endl;
2315         }
2316         
2317         lyxerr.debug() << "Finished making latex file." << endl;
2318 }
2319
2320
2321 //
2322 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2323 //
2324 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2325                              LyXParagraph * endpar, TexRow & texrow) const
2326 {
2327         bool was_title = false;
2328         bool already_title = false;
2329         std::ostringstream ftnote;
2330         TexRow ft_texrow;
2331         int ftcount = 0;
2332
2333         // if only_body
2334         while (par != endpar) {
2335 #ifndef NEW_INSETS
2336                 if (par->IsDummy())
2337                         lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2338                                              << endl;
2339 #endif
2340                 LyXLayout const & layout =
2341                         textclasslist.Style(params.textclass,
2342                                             par->layout);
2343             
2344                 if (layout.intitle) {
2345                         if (already_title) {
2346                                 lyxerr <<"Error in latexParagraphs: You"
2347                                         " should not mix title layouts"
2348                                         " with normal ones." << endl;
2349                         } else
2350                                 was_title = true;
2351                 } else if (was_title && !already_title) {
2352                         ofs << "\\maketitle\n";
2353                         texrow.newline();
2354                         already_title = true;
2355                         was_title = false;                  
2356                 }
2357                 // We are at depth 0 so we can just use
2358                 // ordinary \footnote{} generation
2359                 // flag this with ftcount
2360                 ftcount = -1;
2361                 if (layout.isEnvironment()
2362 #ifndef NEW_INSETS
2363                     || par->params.pextraType() != LyXParagraph::PEXTRA_NONE
2364 #endif
2365                         ) {
2366                         par = par->TeXEnvironment(this, params, ofs, texrow
2367 #ifndef NEW_INSETS
2368                                                   ,ftnote, ft_texrow, ftcount
2369 #endif
2370                                 );
2371                 } else {
2372                         par = par->TeXOnePar(this, params, ofs, texrow, false
2373 #ifndef NEW_INSETS
2374                                              ,
2375                                              ftnote, ft_texrow, ftcount
2376 #endif
2377                                 );
2378                 }
2379
2380                 // Write out what we've generated...
2381                 if (ftcount >= 1) {
2382                         if (ftcount > 1) {
2383                                 ofs << "\\addtocounter{footnote}{-"
2384                                     << ftcount - 1
2385                                     << '}';
2386                         }
2387                         ofs << ftnote.str();
2388                         texrow += ft_texrow;
2389
2390                         // The extra .c_str() is needed when we use
2391                         // lyxstring instead of the STL string class. 
2392                         ftnote.str(string().c_str());
2393                         ft_texrow.reset();
2394                         ftcount = 0;
2395                 }
2396         }
2397         // It might be that we only have a title in this document
2398         if (was_title && !already_title) {
2399                 ofs << "\\maketitle\n";
2400                 texrow.newline();
2401         }
2402 }
2403
2404
2405 bool Buffer::isLatex() const
2406 {
2407         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2408 }
2409
2410
2411 bool Buffer::isLinuxDoc() const
2412 {
2413         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2414 }
2415
2416
2417 bool Buffer::isLiterate() const
2418 {
2419         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2420 }
2421
2422
2423 bool Buffer::isDocBook() const
2424 {
2425         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2426 }
2427
2428
2429 bool Buffer::isSGML() const
2430 {
2431         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2432                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2433 }
2434
2435
2436 void Buffer::sgmlOpenTag(ostream & os, int depth,
2437                          string const & latexname) const
2438 {
2439         if (!latexname.empty() && latexname != "!-- --")
2440                 os << string(depth, ' ') << "<" << latexname << ">\n";
2441 }
2442
2443
2444 void Buffer::sgmlCloseTag(ostream & os, int depth,
2445                           string const & latexname) const
2446 {
2447         if (!latexname.empty() && latexname != "!-- --")
2448                 os << string(depth, ' ') << "</" << latexname << ">\n";
2449 }
2450
2451
2452 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2453 {
2454         ofstream ofs(fname.c_str());
2455
2456         if (!ofs) {
2457                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2458                 return;
2459         }
2460
2461         niceFile = nice; // this will be used by included files.
2462
2463         LyXTextClass const & tclass =
2464                 textclasslist.TextClass(params.textclass);
2465
2466         LaTeXFeatures features(params, tclass.numLayouts());
2467         validate(features);
2468
2469         texrow.reset();
2470
2471         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2472
2473         if (!body_only) {
2474                 string sgml_includedfiles=features.getIncludedFiles(fname);
2475
2476                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2477                         ofs << "<!doctype linuxdoc system>\n\n";
2478                 } else {
2479                         ofs << "<!doctype linuxdoc system [ "
2480                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2481                 }
2482
2483                 if (params.options.empty())
2484                         sgmlOpenTag(ofs, 0, top_element);
2485                 else {
2486                         string top = top_element;
2487                         top += " ";
2488                         top += params.options;
2489                         sgmlOpenTag(ofs, 0, top);
2490                 }
2491         }
2492
2493         ofs << "<!-- "  << LYX_DOCVERSION 
2494             << " created this file. For more info see http://www.lyx.org/"
2495             << " -->\n";
2496
2497         int depth = 0; // paragraph depth
2498         LyXParagraph * par = paragraph;
2499         string item_name;
2500         vector<string> environment_stack(5);
2501
2502         while (par) {
2503                 LyXLayout const & style =
2504                         textclasslist.Style(params.textclass,
2505                                             par->layout);
2506
2507                 // treat <toc> as a special case for compatibility with old code
2508                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2509                         Inset * inset = par->GetInset(0);
2510                         Inset::Code lyx_code = inset->LyxCode();
2511                         if (lyx_code == Inset::TOC_CODE){
2512                                 string const temp = "toc";
2513                                 sgmlOpenTag(ofs, depth, temp);
2514
2515 #ifndef NEW_INSETS
2516                                 par = par->next_;
2517                                 linuxDocHandleFootnote(ofs, par, depth);
2518 #else
2519                                 par = par->next();
2520 #endif
2521                                 continue;
2522                         }
2523                 }
2524
2525                 // environment tag closing
2526                 for (; depth > par->params.depth(); --depth) {
2527                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2528                         environment_stack[depth].erase();
2529                 }
2530
2531                 // write opening SGML tags
2532                 switch (style.latextype) {
2533                 case LATEX_PARAGRAPH:
2534                         if (depth == par->params.depth() 
2535                            && !environment_stack[depth].empty()) {
2536                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2537                                 environment_stack[depth].erase();
2538                                 if (depth) 
2539                                         --depth;
2540                                 else
2541                                         ofs << "</p>";
2542                         }
2543                         sgmlOpenTag(ofs, depth, style.latexname());
2544                         break;
2545
2546                 case LATEX_COMMAND:
2547                         if (depth!= 0)
2548                                 LinuxDocError(par, 0,
2549                                               _("Error : Wrong depth for"
2550                                                 " LatexType Command.\n"));
2551
2552                         if (!environment_stack[depth].empty()){
2553                                 sgmlCloseTag(ofs, depth,
2554                                              environment_stack[depth]);
2555                                 ofs << "</p>";
2556                         }
2557
2558                         environment_stack[depth].erase();
2559                         sgmlOpenTag(ofs, depth, style.latexname());
2560                         break;
2561
2562                 case LATEX_ENVIRONMENT:
2563                 case LATEX_ITEM_ENVIRONMENT:
2564                         if (depth == par->params.depth() 
2565                             && environment_stack[depth] != style.latexname()) {
2566                                 sgmlCloseTag(ofs, depth,
2567                                              environment_stack[depth]);
2568                                 environment_stack[depth].erase();
2569                         }
2570                         if (depth < par->params.depth()) {
2571                                depth = par->params.depth();
2572                                environment_stack[depth].erase();
2573                         }
2574                         if (environment_stack[depth] != style.latexname()) {
2575                                 if (depth == 0) {
2576                                         sgmlOpenTag(ofs, depth, "p");
2577                                 }
2578                                 sgmlOpenTag(ofs, depth, style.latexname());
2579
2580                                 if (environment_stack.size() == depth+1)
2581                                         environment_stack.push_back("!-- --");
2582                                 environment_stack[depth] = style.latexname();
2583                         }
2584
2585                         if (style.latexparam() == "CDATA")
2586                                 ofs << "<![CDATA[";
2587
2588                         if (style.latextype == LATEX_ENVIRONMENT) break;
2589
2590                         if (style.labeltype == LABEL_MANUAL)
2591                                 item_name = "tag";
2592                         else
2593                                 item_name = "item";
2594
2595                         sgmlOpenTag(ofs, depth + 1, item_name);
2596                         break;
2597                 default:
2598                         sgmlOpenTag(ofs, depth, style.latexname());
2599                         break;
2600                 }
2601
2602 #ifndef NEW_INSETS
2603                 do {
2604                         SimpleLinuxDocOnePar(ofs, par, depth);
2605                         
2606                         par = par->next_;
2607                         linuxDocHandleFootnote(ofs, par, depth);
2608                 }
2609                 while(par && par->IsDummy());
2610 #else
2611                 SimpleLinuxDocOnePar(ofs, par, depth);
2612
2613                 par = par->next();
2614 #endif
2615
2616                 ofs << "\n";
2617                 // write closing SGML tags
2618                 switch (style.latextype) {
2619                 case LATEX_COMMAND:
2620                         break;
2621                 case LATEX_ENVIRONMENT:
2622                 case LATEX_ITEM_ENVIRONMENT:
2623                         if (style.latexparam() == "CDATA")
2624                                 ofs << "]]>";
2625                         break;
2626                 default:
2627                         sgmlCloseTag(ofs, depth, style.latexname());
2628                         break;
2629                 }
2630         }
2631    
2632         // Close open tags
2633         for (int i=depth; i >= 0; --i)
2634                 sgmlCloseTag(ofs, depth, environment_stack[i]);
2635
2636         if (!body_only) {
2637                 ofs << "\n\n";
2638                 sgmlCloseTag(ofs, 0, top_element);
2639         }
2640
2641         ofs.close();
2642         // How to check for successful close
2643 }
2644
2645
2646 #ifndef NEW_INSETS
2647 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2648                                     int depth)
2649 {
2650         string const tag = "footnote";
2651
2652         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2653                 sgmlOpenTag(os, depth + 1, tag);
2654                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2655                 sgmlCloseTag(os, depth + 1, tag);
2656                 par = par->next_;
2657         }
2658 }
2659 #endif
2660
2661
2662 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2663                                   int depth, int desc_on,
2664                                   LyXParagraph * & par)
2665 {
2666         LyXParagraph * tpar = par;
2667 #ifndef NEW_INSETS
2668         while (tpar
2669                && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2670                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2671                                                              "Caption").second))
2672                 tpar = tpar->next_;
2673 #else
2674         while (tpar
2675                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2676                                                                 "Caption").second))
2677                 tpar = tpar->next();
2678 #endif
2679         if (tpar &&
2680             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2681                                                          "Caption").second) {
2682                 sgmlOpenTag(os, depth + 1, inner_tag);
2683                 string extra_par;
2684                 SimpleDocBookOnePar(os, extra_par, tpar,
2685                                     desc_on, depth + 2);
2686                 sgmlCloseTag(os, depth+1, inner_tag);
2687                 if (!extra_par.empty())
2688                         os << extra_par;
2689         }
2690 }
2691
2692
2693 #ifndef NEW_INSETS
2694 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2695                                    int depth)
2696 {
2697         string tag, inner_tag;
2698         string tmp_par, extra_par;
2699         bool inner_span = false;
2700         int desc_on = 4;
2701
2702         // Someone should give this enum a proper name (Lgb)
2703         enum SOME_ENUM {
2704                 NO_ONE,
2705                 FOOTNOTE_LIKE,
2706                 MARGIN_LIKE,
2707                 FIG_LIKE,
2708                 TAB_LIKE
2709         };
2710         SOME_ENUM last = NO_ONE;
2711         SOME_ENUM present = FOOTNOTE_LIKE;
2712
2713         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2714                 if (last == present) {
2715                         if (inner_span) {
2716                                 if (!tmp_par.empty()) {
2717                                         os << tmp_par;
2718                                         tmp_par.erase();
2719                                         sgmlCloseTag(os, depth + 1, inner_tag);
2720                                         sgmlOpenTag(os, depth + 1, inner_tag);
2721                                 }
2722                         } else {
2723                                 os << "\n";
2724                         }
2725                 } else {
2726                         os << tmp_par;
2727                         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2728                                                             inner_tag);
2729                         if (!extra_par.empty()) os << extra_par;
2730                         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2731                         extra_par.erase();
2732
2733                         switch (par->footnotekind) {
2734                         case LyXParagraph::FOOTNOTE:
2735                         case LyXParagraph::ALGORITHM:
2736                                 tag = "footnote";
2737                                 inner_tag = "para";
2738                                 present = FOOTNOTE_LIKE;
2739                                 inner_span = true;
2740                                 break;
2741                         case LyXParagraph::MARGIN:
2742                                 tag = "sidebar";
2743                                 inner_tag = "para";
2744                                 present = MARGIN_LIKE;
2745                                 inner_span = true;
2746                                 break;
2747                         case LyXParagraph::FIG:
2748                         case LyXParagraph::WIDE_FIG:
2749                                 tag = "figure";
2750                                 inner_tag = "title";
2751                                 present = FIG_LIKE;
2752                                 inner_span = false;
2753                                 break;
2754                         case LyXParagraph::TAB:
2755                         case LyXParagraph::WIDE_TAB:
2756                                 tag = "table";
2757                                 inner_tag = "title";
2758                                 present = TAB_LIKE;
2759                                 inner_span = false;
2760                                 break;
2761                         }
2762                         sgmlOpenTag(os, depth, tag);
2763                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2764                                 DocBookHandleCaption(os, inner_tag, depth,
2765                                                      desc_on, par);
2766                                 inner_tag.erase();
2767                         } else {
2768                                 sgmlOpenTag(os, depth + 1, inner_tag);
2769                         }
2770                 }
2771                 // ignore all caption here, we processed them above!!!
2772                 if (par->layout != textclasslist
2773                     .NumberOfLayout(params.textclass,
2774                                     "Caption").second) {
2775                         std::ostringstream ost;
2776                         SimpleDocBookOnePar(ost, extra_par, par,
2777                                             desc_on, depth + 2);
2778                         tmp_par += ost.str().c_str();
2779                 }
2780                 tmp_par = frontStrip(strip(tmp_par));
2781
2782                 last = present;
2783                 par = par->next_;
2784         }
2785         os << tmp_par;
2786         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2787         if (!extra_par.empty()) os << extra_par;
2788         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2789 }
2790 #endif
2791
2792
2793 // checks, if newcol chars should be put into this line
2794 // writes newline, if necessary.
2795 namespace {
2796
2797 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2798                           string::size_type newcol)
2799 {
2800         colcount += newcol;
2801         if (colcount > lyxrc.ascii_linelen) {
2802                 os << "\n";
2803                 colcount = newcol; // assume write after this call
2804         }
2805 }
2806
2807 enum PAR_TAG {
2808         NONE=0,
2809         TT = 1,
2810         SF = 2,
2811         BF = 4,
2812         IT = 8,
2813         SL = 16,
2814         EM = 32
2815 };
2816
2817
2818 string tag_name(PAR_TAG const & pt) {
2819         switch (pt) {
2820         case NONE: return "!-- --";
2821         case TT: return "tt";
2822         case SF: return "sf";
2823         case BF: return "bf";
2824         case IT: return "it";
2825         case SL: return "sl";
2826         case EM: return "em";
2827         }
2828         return "";
2829 }
2830
2831
2832 inline
2833 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2834 {
2835         p1 = static_cast<PAR_TAG>(p1 | p2);
2836 }
2837
2838
2839 inline
2840 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2841 {
2842         p1 = static_cast<PAR_TAG>( p1 & ~p2);
2843 }
2844
2845 } // namespace anon
2846
2847
2848
2849
2850 // Handle internal paragraph parsing -- layout already processed.
2851 void Buffer::SimpleLinuxDocOnePar(ostream & os,
2852                                   LyXParagraph * par, int /*depth*/)
2853 {
2854         LyXLayout const & style = textclasslist.Style(params.textclass,
2855                                                       par->GetLayout());
2856         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2857
2858         // gets paragraph main font
2859         LyXFont font_old;
2860         bool desc_on;
2861         if (style.labeltype == LABEL_MANUAL) {
2862                 font_old = style.labelfont;
2863                 desc_on = true;
2864         } else {
2865                 font_old = style.font;
2866                 desc_on = false;
2867         }
2868
2869         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2870         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2871         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2872         bool is_em = false;
2873
2874         stack < PAR_TAG > tag_state;
2875         // parsing main loop
2876         for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
2877
2878                 PAR_TAG tag_close = NONE;
2879                 list < PAR_TAG > tag_open;
2880
2881                 LyXFont const font = par->getFont(params, i);
2882
2883                 if (font_old.family() != font.family()) {
2884                         switch (family_type) {
2885                         case LyXFont::SANS_FAMILY:
2886                                 tag_close |= SF;
2887                                 break;
2888                         case LyXFont::TYPEWRITER_FAMILY:
2889                                 tag_close |= TT;
2890                                 break;
2891                         default:
2892                                 break;
2893                         }
2894
2895                         family_type = font.family();
2896
2897                         switch (family_type) {
2898                         case LyXFont::SANS_FAMILY:
2899                                 tag_open.push_back(SF);
2900                                 break;
2901                         case LyXFont::TYPEWRITER_FAMILY:
2902                                 tag_open.push_back(TT);
2903                                 break;
2904                         default:
2905                                 break;
2906                         }
2907                 }
2908
2909                 if (font_old.series() != font.series()) {
2910                         switch (series_type) {
2911                         case LyXFont::BOLD_SERIES:
2912                                 tag_close |= BF;
2913                                 break;
2914                         default:
2915                                 break;
2916                         }
2917
2918                         series_type = font.series();
2919
2920                         switch (series_type) {
2921                         case LyXFont::BOLD_SERIES:
2922                                 tag_open.push_back(BF);
2923                                 break;
2924                         default:
2925                                 break;
2926                         }
2927
2928                 }
2929
2930                 if (font_old.shape() != font.shape()) {
2931                         switch (shape_type) {
2932                         case LyXFont::ITALIC_SHAPE:
2933                                 tag_close |= IT;
2934                                 break;
2935                         case LyXFont::SLANTED_SHAPE:
2936                                 tag_close |= SL;
2937                                 break;
2938                         default:
2939                                 break;
2940                         }
2941
2942                         shape_type = font.shape();
2943
2944                         switch (shape_type) {
2945                         case LyXFont::ITALIC_SHAPE:
2946                                 tag_open.push_back(IT);
2947                                 break;
2948                         case LyXFont::SLANTED_SHAPE:
2949                                 tag_open.push_back(SL);
2950                                 break;
2951                         default:
2952                                 break;
2953                         }
2954                 }
2955                 // handle <em> tag
2956                 if (font_old.emph() != font.emph()) {
2957                         if (font.emph() == LyXFont::ON) {
2958                                 tag_open.push_back(EM);
2959                                 is_em = true;
2960                         }
2961                         else if (is_em) {
2962                                 tag_close |= EM;
2963                                 is_em = false;
2964                         }
2965                 }
2966
2967                 list < PAR_TAG > temp;
2968                 while(!tag_state.empty() && tag_close ) {
2969                         PAR_TAG k =  tag_state.top();
2970                         tag_state.pop();
2971                         os << "</" << tag_name(k) << ">";
2972                         if (tag_close & k)
2973                                 reset(tag_close,k);
2974                         else
2975                                 temp.push_back(k);
2976                 }
2977
2978                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2979                     j != temp.end(); ++j) {
2980                         tag_state.push(*j);
2981                         os << "<" << tag_name(*j) << ">";
2982                 }
2983
2984                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2985                     j != tag_open.end(); ++j) {
2986                         tag_state.push(*j);
2987                         os << "<" << tag_name(*j) << ">";
2988                 }
2989
2990                 char c = par->GetChar(i);
2991
2992                 if (c == LyXParagraph::META_INSET) {
2993                         Inset * inset = par->GetInset(i);
2994                         inset->Linuxdoc(this, os);
2995                         font_old = font;
2996                         continue;
2997                 }
2998
2999                 if (font.latex() == LyXFont::ON || style.latexparam() == "CDATA") {
3000                         // "TeX"-Mode on == > SGML-Mode on.
3001                         if (c != '\0')
3002                                 os << c;
3003                         ++char_line_count;
3004                 } else {
3005                         string sgml_string;
3006                         if (par->linuxDocConvertChar(c, sgml_string)
3007                             && !style.free_spacing) { 
3008                                 // in freespacing mode, spaces are
3009                                 // non-breaking characters
3010                                 if (desc_on) {// if char is ' ' then...
3011
3012                                         ++char_line_count;
3013                                         linux_doc_line_break(os, char_line_count, 6);
3014                                         os << "</tag>";
3015                                         desc_on = false;
3016                                 } else  {
3017                                         linux_doc_line_break(os, char_line_count, 1);
3018                                         os << c;
3019                                 }
3020                         } else {
3021                                 os << sgml_string;
3022                                 char_line_count += sgml_string.length();
3023                         }
3024                 }
3025                 font_old = font;
3026         }
3027
3028         while (!tag_state.empty()) {
3029                 os << "</" << tag_name(tag_state.top()) << ">";
3030                 tag_state.pop();
3031         }
3032
3033         // resets description flag correctly
3034         if (desc_on) {
3035                 // <tag> not closed...
3036                 linux_doc_line_break(os, char_line_count, 6);
3037                 os << "</tag>";
3038         }
3039 }
3040
3041
3042 // Print an error message.
3043 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
3044                            string const & message) 
3045 {
3046         // insert an error marker in text
3047         InsetError * new_inset = new InsetError(message);
3048         par->InsertInset(pos, new_inset);
3049 }
3050
3051
3052 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3053 {
3054         ofstream ofs(fname.c_str());
3055         if (!ofs) {
3056                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3057                 return;
3058         }
3059
3060         LyXParagraph * par = paragraph;
3061
3062         niceFile = nice; // this will be used by Insetincludes.
3063
3064         LyXTextClass const & tclass =
3065                 textclasslist.TextClass(params.textclass);
3066
3067         LaTeXFeatures features(params, tclass.numLayouts());
3068         validate(features);
3069    
3070         texrow.reset();
3071
3072         string top_element= textclasslist.LatexnameOfClass(params.textclass);
3073
3074         if (!only_body) {
3075                 string sgml_includedfiles=features.getIncludedFiles(fname);
3076
3077                 ofs << "<!doctype " << top_element
3078                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3079
3080                 if (params.preamble.empty() && sgml_includedfiles.empty())
3081                         ofs << ">\n\n";
3082                 else
3083                         ofs << "\n [ " << params.preamble 
3084                             << sgml_includedfiles << " \n]>\n\n";
3085         }
3086
3087         string top = top_element;       
3088         top += " lang=\"";
3089         top += params.language->code();
3090         top += "\"";
3091
3092         if (!params.options.empty()) {
3093                 top += " ";
3094                 top += params.options;
3095         }
3096         sgmlOpenTag(ofs, 0, top);
3097
3098         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
3099             << "\n  See http://www.lyx.org/ for more information -->\n";
3100
3101         vector <string> environment_stack(10);
3102         vector <string> environment_inner(10);
3103         vector <string> command_stack(10);
3104
3105         bool command_flag= false;
3106         int command_depth= 0, command_base= 0, cmd_depth= 0;
3107         int depth = 0; // paragraph depth
3108
3109         string item_name, command_name;
3110
3111         while (par) {
3112                 string sgmlparam, c_depth, c_params;
3113                 int desc_on = 0; // description mode
3114
3115                 LyXLayout const & style =
3116                         textclasslist.Style(params.textclass,
3117                                             par->layout);
3118
3119                 // environment tag closing
3120                 for (; depth > par->params.depth(); --depth) {
3121                         if (environment_inner[depth] != "!-- --") {
3122                                 item_name= "listitem";
3123                                 sgmlCloseTag(ofs, command_depth + depth,
3124                                              item_name);
3125                                 if (environment_inner[depth] == "varlistentry")
3126                                         sgmlCloseTag(ofs, depth+command_depth,
3127                                                      environment_inner[depth]);
3128                         }
3129                         sgmlCloseTag(ofs, depth + command_depth,
3130                                      environment_stack[depth]);
3131                         environment_stack[depth].erase();
3132                         environment_inner[depth].erase();
3133                 }
3134
3135                 if (depth == par->params.depth()
3136                    && environment_stack[depth] != style.latexname()
3137                    && !environment_stack[depth].empty()) {
3138                         if (environment_inner[depth] != "!-- --") {
3139                                 item_name= "listitem";
3140                                 sgmlCloseTag(ofs, command_depth+depth,
3141                                              item_name);
3142                                 if (environment_inner[depth] == "varlistentry")
3143                                         sgmlCloseTag(ofs,
3144                                                      depth + command_depth,
3145                                                      environment_inner[depth]);
3146                         }
3147                         
3148                         sgmlCloseTag(ofs, depth + command_depth,
3149                                      environment_stack[depth]);
3150                         
3151                         environment_stack[depth].erase();
3152                         environment_inner[depth].erase();
3153                 }
3154
3155                 // Write opening SGML tags.
3156                 switch (style.latextype) {
3157                 case LATEX_PARAGRAPH:
3158                         sgmlOpenTag(ofs, depth+command_depth, style.latexname());
3159                         break;
3160
3161                 case LATEX_COMMAND:
3162                         if (depth!= 0)
3163                                 LinuxDocError(par, 0,
3164                                               _("Error : Wrong depth for "
3165                                                 "LatexType Command.\n"));
3166                         
3167                         command_name = style.latexname();
3168                         
3169                         sgmlparam = style.latexparam();
3170                         c_params = split(sgmlparam, c_depth,'|');
3171                         
3172                         cmd_depth= lyx::atoi(c_depth);
3173                         
3174                         if (command_flag) {
3175                                 if (cmd_depth<command_base) {
3176                                         for (int j = command_depth; j >= command_base; --j)
3177                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3178                                         command_depth= command_base= cmd_depth;
3179                                 } else if (cmd_depth <= command_depth) {
3180                                         for (int j = command_depth; j >= cmd_depth; --j)
3181                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3182                                         command_depth= cmd_depth;
3183                                 } else
3184                                         command_depth= cmd_depth;
3185                         } else {
3186                                 command_depth = command_base = cmd_depth;
3187                                 command_flag = true;
3188                         }
3189                         if (command_stack.size() == command_depth +1)
3190                                 command_stack.push_back("");
3191                         command_stack[command_depth]= command_name;
3192
3193                         // treat label as a special case for
3194                         // more WYSIWYM handling.
3195                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
3196                                 Inset * inset = par->GetInset(0);
3197                                 Inset::Code lyx_code = inset->LyxCode();
3198                                 if (lyx_code == Inset::LABEL_CODE){
3199                                         command_name += " id=\"";
3200                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3201                                         command_name += "\"";
3202                                         desc_on = 3;
3203                                 }
3204                         }
3205
3206                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3207                         if (c_params.empty())
3208                                 item_name = "title";
3209                         else
3210                                 item_name = c_params;
3211                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3212                         break;
3213
3214                 case LATEX_ENVIRONMENT:
3215                 case LATEX_ITEM_ENVIRONMENT:
3216                         if (depth < par->params.depth()) {
3217                                 depth = par->params.depth();
3218                                 environment_stack[depth].erase();
3219                         }
3220
3221                         if (environment_stack[depth] != style.latexname()) {
3222                                 if(environment_stack.size() == depth+1) {
3223                                         environment_stack.push_back("!-- --");
3224                                         environment_inner.push_back("!-- --");
3225                                 }
3226                                 environment_stack[depth] = style.latexname();
3227                                 environment_inner[depth] = "!-- --";
3228                                 sgmlOpenTag(ofs, depth + command_depth,
3229                                             environment_stack[depth]);
3230                         } else {
3231                                 if (environment_inner[depth] != "!-- --") {
3232                                         item_name= "listitem";
3233                                         sgmlCloseTag(ofs,
3234                                                      command_depth + depth,
3235                                                      item_name);
3236                                         if (environment_inner[depth] == "varlistentry")
3237                                                 sgmlCloseTag(ofs,
3238                                                              depth + command_depth,
3239                                                              environment_inner[depth]);
3240                                 }
3241                         }
3242                         
3243                         if (style.latextype == LATEX_ENVIRONMENT) {
3244                                 if (!style.latexparam().empty()) {
3245                                         if(style.latexparam() == "CDATA")
3246                                                 ofs << "<![CDATA[";
3247                                         else
3248                                                 sgmlOpenTag(ofs, depth + command_depth,
3249                                                             style.latexparam());
3250                                 }
3251                                 break;
3252                         }
3253
3254                         desc_on = (style.labeltype == LABEL_MANUAL);
3255
3256                         if (desc_on)
3257                                 environment_inner[depth]= "varlistentry";
3258                         else
3259                                 environment_inner[depth]= "listitem";
3260
3261                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3262                                     environment_inner[depth]);
3263
3264                         if (desc_on) {
3265                                 item_name= "term";
3266                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3267                                             item_name);
3268                         } else {
3269                                 item_name= "para";
3270                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3271                                             item_name);
3272                         }
3273                         break;
3274                 default:
3275                         sgmlOpenTag(ofs, depth + command_depth,
3276                                     style.latexname());
3277                         break;
3278                 }
3279
3280 #ifndef NEW_INSETS
3281                 do {
3282                         string extra_par;
3283                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3284                                             depth + 1 + command_depth);
3285                         par = par->next_;
3286                         DocBookHandleFootnote(ofs, par,
3287                                               depth + 1 + command_depth);
3288                 } while(par && par->IsDummy());
3289 #else
3290                 string extra_par;
3291                 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3292                                     depth + 1 + command_depth);
3293                 par = par->next();
3294 #endif
3295                 string end_tag;
3296                 // write closing SGML tags
3297                 switch (style.latextype) {
3298                 case LATEX_COMMAND:
3299                         if (c_params.empty())
3300                                 end_tag = "title";
3301                         else
3302                                 end_tag = c_params;
3303                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3304                         break;
3305                 case LATEX_ENVIRONMENT:
3306                         if (!style.latexparam().empty()) {
3307                                 if(style.latexparam() == "CDATA")
3308                                         ofs << "]]>";
3309                                 else
3310                                         sgmlCloseTag(ofs, depth + command_depth,
3311                                                      style.latexparam());
3312                         }
3313                         break;
3314                 case LATEX_ITEM_ENVIRONMENT:
3315                         if (desc_on == 1) break;
3316                         end_tag= "para";
3317                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3318                         break;
3319                 case LATEX_PARAGRAPH:
3320                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3321                         break;
3322                 default:
3323                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3324                         break;
3325                 }
3326         }
3327
3328         // Close open tags
3329         for (; depth >= 0; --depth) {
3330                 if (!environment_stack[depth].empty()) {
3331                         if (environment_inner[depth] != "!-- --") {
3332                                 item_name= "listitem";
3333                                 sgmlCloseTag(ofs, command_depth + depth,
3334                                              item_name);
3335                                if (environment_inner[depth] == "varlistentry")
3336                                        sgmlCloseTag(ofs, depth + command_depth,
3337                                                     environment_inner[depth]);
3338                         }
3339                         
3340                         sgmlCloseTag(ofs, depth + command_depth,
3341                                      environment_stack[depth]);
3342                 }
3343         }
3344         
3345         for (int j = command_depth; j >= command_base; --j)
3346                 if (!command_stack[j].empty())
3347                         sgmlCloseTag(ofs, j, command_stack[j]);
3348
3349         ofs << "\n\n";
3350         sgmlCloseTag(ofs, 0, top_element);
3351
3352         ofs.close();
3353         // How to check for successful close
3354 }
3355
3356
3357 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3358                                  LyXParagraph * par, int & desc_on,
3359                                  int depth) const
3360 {
3361         bool emph_flag = false;
3362
3363         LyXLayout const & style = textclasslist.Style(params.textclass,
3364                                                       par->GetLayout());
3365
3366         LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3367
3368         int char_line_count = depth;
3369         if (!style.free_spacing)
3370                 os << string(depth,' ');
3371
3372         // parsing main loop
3373         for (LyXParagraph::size_type i = 0;
3374              i < par->size(); ++i) {
3375                 LyXFont font = par->getFont(params, i);
3376
3377                 // handle <emphasis> tag
3378                 if (font_old.emph() != font.emph()) {
3379                         if (font.emph() == LyXFont::ON) {
3380                                 os << "<emphasis>";
3381                                 emph_flag = true;
3382                         }else if(i) {
3383                                 os << "</emphasis>";
3384                                 emph_flag = false;
3385                         }
3386                 }
3387       
3388                 char c = par->GetChar(i);
3389
3390                 if (c == LyXParagraph::META_INSET) {
3391                         Inset * inset = par->GetInset(i);
3392                         std::ostringstream ost;
3393                         inset->DocBook(this, ost);
3394                         string tmp_out = ost.str().c_str();
3395
3396                         //
3397                         // This code needs some explanation:
3398                         // Two insets are treated specially
3399                         //   label if it is the first element in a command paragraph
3400                         //         desc_on == 3
3401                         //   graphics inside tables or figure floats can't go on
3402                         //   title (the equivalente in latex for this case is caption
3403                         //   and title should come first
3404                         //         desc_on == 4
3405                         //
3406                         if (desc_on!= 3 || i!= 0) {
3407                                 if (!tmp_out.empty() && tmp_out[0] == '@') {
3408                                         if (desc_on == 4)
3409                                                 extra += frontStrip(tmp_out, '@');
3410                                         else
3411                                                 os << frontStrip(tmp_out, '@');
3412                                 }
3413                                 else
3414                                         os << tmp_out;
3415                         }
3416                 } else if (font.latex() == LyXFont::ON) {
3417                         // "TeX"-Mode on ==> SGML-Mode on.
3418                         if (c != '\0')
3419                                 os << c;
3420                         ++char_line_count;
3421                 } else {
3422                         string sgml_string;
3423                         if (par->linuxDocConvertChar(c, sgml_string)
3424                             && !style.free_spacing) { // in freespacing
3425                                                      // mode, spaces are
3426                                                      // non-breaking characters
3427                                 // char is ' '
3428                                 if (desc_on == 1) {
3429                                         ++char_line_count;
3430                                         os << "\n</term><listitem><para>";
3431                                         desc_on = 2;
3432                                 } else {
3433                                         os << c;
3434                                 }
3435                         } else {
3436                                 os << sgml_string;
3437                         }
3438                 }
3439                 font_old = font;
3440         }
3441
3442         if (emph_flag) {
3443                 os << "</emphasis>";
3444         }
3445         
3446         // resets description flag correctly
3447         if (desc_on == 1) {
3448                 // <term> not closed...
3449                 os << "</term>";
3450         }
3451         os << '\n';
3452 }
3453
3454
3455 // This should be enabled when the Chktex class is implemented. (Asger)
3456 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3457 // Other flags: -wall -v0 -x
3458 int Buffer::runChktex()
3459 {
3460         if (!users->text) return 0;
3461
3462         ProhibitInput(users);
3463
3464         // get LaTeX-Filename
3465         string const name = getLatexName();
3466         string path = OnlyPath(filename);
3467
3468         string const org_path = path;
3469         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3470                 path = tmppath;  
3471         }
3472
3473         Path p(path); // path to LaTeX file
3474         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3475
3476         // Remove all error insets
3477         bool const removedErrorInsets = users->removeAutoInsets();
3478
3479         // Generate the LaTeX file if neccessary
3480         makeLaTeXFile(name, org_path, false);
3481
3482         TeXErrors terr;
3483         Chktex chktex(lyxrc.chktex_command, name, filepath);
3484         int res = chktex.run(terr); // run chktex
3485
3486         if (res == -1) {
3487                 WriteAlert(_("chktex did not work!"),
3488                            _("Could not run with file:"), name);
3489         } else if (res > 0) {
3490                 // Insert all errors as errors boxes
3491                 users->insertErrors(terr);
3492         }
3493
3494         // if we removed error insets before we ran chktex or if we inserted
3495         // error insets after we ran chktex, this must be run:
3496         if (removedErrorInsets || res){
3497                 users->redraw();
3498                 users->fitCursor(users->text);
3499         }
3500         AllowInput(users);
3501
3502         return res;
3503 }
3504
3505
3506 void Buffer::validate(LaTeXFeatures & features) const
3507 {
3508         LyXParagraph * par = paragraph;
3509         LyXTextClass const & tclass = 
3510                 textclasslist.TextClass(params.textclass);
3511     
3512         // AMS Style is at document level
3513     
3514         features.amsstyle = (params.use_amsmath ||
3515                              tclass.provides(LyXTextClass::amsmath));
3516     
3517         while (par) {
3518                 // We don't use "lyxerr.debug" because of speed. (Asger)
3519                 if (lyxerr.debugging(Debug::LATEX))
3520                         lyxerr << "Paragraph: " <<  par << endl;
3521
3522                 // Now just follow the list of paragraphs and run
3523                 // validate on each of them.
3524                 par->validate(features);
3525
3526                 // and then the next paragraph
3527 #ifndef NEW_INSETS
3528                 par = par->next_;
3529 #else
3530                 par = par->next();
3531 #endif
3532         }
3533
3534         // the bullet shapes are buffer level not paragraph level
3535         // so they are tested here
3536         for (int i = 0; i < 4; ++i) {
3537                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3538                         int const font = params.user_defined_bullets[i].getFont();
3539                         if (font == 0) {
3540                                 int const c = params
3541                                         .user_defined_bullets[i]
3542                                         .getCharacter();
3543                                 if (c == 16
3544                                    || c == 17
3545                                    || c == 25
3546                                    || c == 26
3547                                    || c == 31) {
3548                                         features.latexsym = true;
3549                                 }
3550                         } else if (font == 1) {
3551                                 features.amssymb = true;
3552                         } else if ((font >= 2 && font <= 5)) {
3553                                 features.pifont = true;
3554                         }
3555                 }
3556         }
3557         
3558         if (lyxerr.debugging(Debug::LATEX)) {
3559                 features.showStruct();
3560         }
3561 }
3562
3563
3564 void Buffer::setPaperStuff()
3565 {
3566         params.papersize = BufferParams::PAPER_DEFAULT;
3567         char const c1 = params.paperpackage;
3568         if (c1 == BufferParams::PACKAGE_NONE) {
3569                 char const c2 = params.papersize2;
3570                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3571                         params.papersize = BufferParams::PAPER_USLETTER;
3572                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3573                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3574                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3575                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3576                 else if (c2 == BufferParams::VM_PAPER_A3)
3577                         params.papersize = BufferParams::PAPER_A3PAPER;
3578                 else if (c2 == BufferParams::VM_PAPER_A4)
3579                         params.papersize = BufferParams::PAPER_A4PAPER;
3580                 else if (c2 == BufferParams::VM_PAPER_A5)
3581                         params.papersize = BufferParams::PAPER_A5PAPER;
3582                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3583                          (c2 == BufferParams::VM_PAPER_B5))
3584                         params.papersize = BufferParams::PAPER_B5PAPER;
3585         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3586                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3587                 params.papersize = BufferParams::PAPER_A4PAPER;
3588 }
3589
3590
3591 // This function should be in Buffer because it's a buffer's property (ale)
3592 string const Buffer::getIncludeonlyList(char delim)
3593 {
3594         string lst;
3595         for (inset_iterator it = inset_iterator_begin();
3596             it != inset_iterator_end(); ++it) {
3597                 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3598                         InsetInclude * insetinc = 
3599                                 static_cast<InsetInclude *>(*it);
3600                         if (insetinc->isIncludeOnly()) {
3601                                 if (!lst.empty())
3602                                         lst += delim;
3603                                 lst += insetinc->getRelFileBaseName();
3604                         }
3605                 }
3606         }
3607         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3608         return lst;
3609 }
3610
3611
3612 vector<string> const Buffer::getLabelList()
3613 {
3614         /// if this is a child document and the parent is already loaded
3615         /// Use the parent's list instead  [ale990407]
3616         if (!params.parentname.empty()
3617             && bufferlist.exists(params.parentname)) {
3618                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3619                 if (tmp)
3620                         return tmp->getLabelList();
3621         }
3622
3623         vector<string> label_list;
3624         for (inset_iterator it = inset_iterator_begin();
3625              it != inset_iterator_end(); ++it) {
3626                 vector<string> const l = (*it)->getLabelList();
3627                 label_list.insert(label_list.end(), l.begin(), l.end());
3628         }
3629         return label_list;
3630 }
3631
3632
3633 Buffer::Lists const Buffer::getLists() const
3634 {
3635         Lists l;
3636         LyXParagraph * par = paragraph;
3637 #ifdef NEW_INSETS
3638         bool found;
3639         LyXTextClassList::size_type cap;
3640         boost::tie(found, cap) = textclasslist
3641                 .NumberOfLayout(params.textclass, "Caption");
3642 #endif
3643
3644         while (par) {
3645 #ifndef NEW_INSETS
3646                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3647                         if (textclasslist.Style(params.textclass, 
3648                                                 par->GetLayout()).labeltype
3649                             == LABEL_SENSITIVE) {
3650                                 string type;
3651                                 switch (par->footnotekind) {
3652                                 case LyXParagraph::FIG:
3653                                 case LyXParagraph::WIDE_FIG:
3654                                         type = "LOF";
3655                                         break;
3656                                 case LyXParagraph::TAB:
3657                                 case LyXParagraph::WIDE_TAB:
3658                                         type = "LOT";
3659                                         break;
3660                                 case LyXParagraph::ALGORITHM:
3661                                         type = "LOA";
3662                                         break;
3663                                 case LyXParagraph::FOOTNOTE:
3664                                 case LyXParagraph::MARGIN:
3665                                         break;
3666                                 }
3667                                 if (!type.empty()) {
3668                                         SingleList & item = l[type];
3669                                         string const str =
3670                                                 tostr(item.size()+1) + ". " + par->String(this, false);
3671                                         item.push_back(TocItem(par, 0, str));
3672                                 }
3673                         }
3674                 } else if (!par->IsDummy()) {
3675 #endif
3676                         char const labeltype =
3677                                 textclasslist.Style(params.textclass, 
3678                                                     par->GetLayout()).labeltype;
3679       
3680                         if (labeltype >= LABEL_COUNTER_CHAPTER
3681                             && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3682                                 // insert this into the table of contents
3683                                 SingleList & item = l["TOC"];
3684                                 int depth = max(0,
3685                                                 labeltype - 
3686                                                 textclasslist.TextClass(params.textclass).maxcounter());
3687                                 item.push_back(TocItem(par, depth, par->String(this, true)));
3688                         }
3689 #ifdef NEW_INSETS
3690                         // For each paragrph, traverse its insets and look for
3691                         // FLOAT_CODE
3692                         
3693                         if (found) {
3694                                 LyXParagraph::inset_iterator it =
3695                                         par->inset_iterator_begin();
3696                                 LyXParagraph::inset_iterator end =
3697                                         par->inset_iterator_end();
3698
3699                                 for (; it != end; ++it) {
3700                                         if ((*it)->LyxCode() == Inset::FLOAT_CODE) {
3701                                                 InsetFloat * il =
3702                                                         static_cast<InsetFloat*>(*it);
3703                                                 
3704                                                 string const type = il->type();
3705                                                 
3706                                                 // Now find the caption in the float...
3707                                                 // We now tranverse the paragraphs of
3708                                                 // the inset...
3709                                                 LyXParagraph * tmp = il->inset->par;
3710                                                 while (tmp) {
3711                                                         if (tmp->layout == cap) {
3712                                                                 SingleList & item = l[type];
3713                                                                 string const str =
3714                                                                         tostr(item.size()+1) + ". " + tmp->String(this, false);
3715                                                                 item.push_back(TocItem(tmp, 0 , str));
3716                                                         }
3717                                                         tmp = tmp->next();
3718                                                 }
3719                                         }
3720                                 }
3721                         } else {
3722                                 lyxerr << "caption not found" << endl;
3723                         }
3724                         
3725 #endif
3726 #ifndef NEW_INSETS
3727                 }
3728                 par = par->next_;
3729 #else
3730                 par = par->next();
3731 #endif
3732         }
3733         return l;
3734 }
3735
3736
3737 // This is also a buffer property (ale)
3738 vector<pair<string, string> > const Buffer::getBibkeyList()
3739 {
3740         /// if this is a child document and the parent is already loaded
3741         /// Use the parent's list instead  [ale990412]
3742         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3743                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3744                 if (tmp)
3745                         return tmp->getBibkeyList();
3746         }
3747
3748         vector<pair<string, string> > keys;
3749         LyXParagraph * par = paragraph;
3750         while (par) {
3751                 if (par->bibkey)
3752                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3753                                                            par->String(this, false)));
3754 #ifndef NEW_INSETS
3755                 par = par->next_;
3756 #else
3757                 par = par->next();
3758 #endif
3759         }
3760
3761         // Might be either using bibtex or a child has bibliography
3762         if (keys.empty()) {
3763                 for (inset_iterator it = inset_iterator_begin();
3764                         it != inset_iterator_end(); ++it) {
3765                         // Search for Bibtex or Include inset
3766                         if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3767                                 vector<pair<string,string> > tmp =
3768                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3769                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3770                         } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3771                                 vector<pair<string,string> > const tmp =
3772                                         static_cast<InsetInclude*>(*it)->getKeys();
3773                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3774                         }
3775                 }
3776         }
3777  
3778         return keys;
3779 }
3780
3781
3782 bool Buffer::isDepClean(string const & name) const
3783 {
3784         DEPCLEAN * item = dep_clean;
3785         while (item && item->master != name)
3786                 item = item->next;
3787         if (!item) return true;
3788         return item->clean;
3789 }
3790
3791
3792 void Buffer::markDepClean(string const & name)
3793 {
3794         if (!dep_clean) {
3795                 dep_clean = new DEPCLEAN;
3796                 dep_clean->clean = true;
3797                 dep_clean->master = name;
3798                 dep_clean->next = 0;
3799         } else {
3800                 DEPCLEAN * item = dep_clean;
3801                 while (item && item->master != name)
3802                         item = item->next;
3803                 if (item) {
3804                         item->clean = true;
3805                 } else {
3806                         item = new DEPCLEAN;
3807                         item->clean = true;
3808                         item->master = name;
3809                         item->next = 0;
3810                 }
3811         }
3812 }
3813
3814
3815 bool Buffer::Dispatch(string const & command)
3816 {
3817         // Split command string into command and argument
3818         string cmd;
3819         string line = frontStrip(command);
3820         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3821
3822         return Dispatch(lyxaction.LookupFunc(cmd), arg);
3823 }
3824
3825
3826 bool Buffer::Dispatch(int action, string const & argument)
3827 {
3828         bool dispatched = true;
3829         switch (action) {
3830                 case LFUN_EXPORT: 
3831                         Exporter::Export(this, argument, false);
3832                         break;
3833
3834                 default:
3835                         dispatched = false;
3836         }
3837         return dispatched;
3838 }
3839
3840
3841 void Buffer::resize()
3842 {
3843         /// resize the BufferViews!
3844         if (users)
3845                 users->resize();
3846 }
3847
3848
3849 void Buffer::resizeInsets(BufferView * bv)
3850 {
3851         /// then remove all LyXText in text-insets
3852         LyXParagraph * par = paragraph;
3853 #ifndef NEW_INSETS
3854         for (; par; par = par->next_) {
3855             par->resizeInsetsLyXText(bv);
3856         }
3857 #else
3858         for (; par; par = par->next()) {
3859             par->resizeInsetsLyXText(bv);
3860         }
3861 #endif
3862 }
3863
3864
3865 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3866 {
3867
3868         LyXParagraph * par = paragraph;
3869         while (par) {
3870                 par->ChangeLanguage(params, from, to);
3871 #ifndef NEW_INSETS
3872                 par = par->next_;
3873 #else
3874                 par = par->next();
3875 #endif
3876         }
3877 }
3878
3879
3880 bool Buffer::isMultiLingual()
3881 {
3882         LyXParagraph * par = paragraph;
3883         while (par) {
3884                 if (par->isMultiLingual(params))
3885                         return true;
3886 #ifndef NEW_INSETS
3887                 par = par->next_;
3888 #else
3889                 par = par->next();
3890 #endif
3891         }
3892         return false;
3893 }
3894
3895
3896 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3897                                        LyXParagraph::size_type pos)
3898         : par(paragraph)
3899 {
3900         it = par->InsetIterator(pos);
3901         if (it == par->inset_iterator_end()) {
3902 #ifndef NEW_INSETS
3903                 par = par->next_;
3904 #else
3905                 par = par->next();
3906 #endif
3907                 SetParagraph();
3908         }
3909 }
3910
3911
3912 void Buffer::inset_iterator::SetParagraph()
3913 {
3914         while (par) {
3915                 it = par->inset_iterator_begin();
3916                 if (it != par->inset_iterator_end())
3917                         return;
3918 #ifndef NEW_INSETS
3919                 par = par->next_;
3920 #else
3921                 par = par->next();
3922 #endif
3923         }
3924         //it = 0;
3925         // We maintain an invariant that whenever par = 0 then it = 0
3926 }