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