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