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