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