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