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