]> git.lyx.org Git - lyx.git/blob - src/buffer.C
4caaed8059bb4a2b0ed262f78085932e8fb6d236
[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 "lyxtext.h"
88 #include "gettext.h"
89 #include "language.h"
90 #include "lyx_gui_misc.h"       // WarnReadonly()
91 #include "frontends/Dialogs.h"
92 #include "encoding.h"
93 #include "exporter.h"
94 #include "Lsstream.h"
95
96 using std::ostream;
97 using std::ofstream;
98 using std::ifstream;
99 using std::fstream;
100 using std::ios;
101 using std::setw;
102 using std::endl;
103 using std::pair;
104 using std::vector;
105 using std::max;
106 using std::set;
107 using std::istringstream;
108
109 // all these externs should eventually be removed.
110 extern BufferList bufferlist;
111
112 extern LyXAction lyxaction;
113
114
115 static const float LYX_FORMAT = 2.17;
116
117 extern int tex_code_break_column;
118
119
120 Buffer::Buffer(string const & file, bool ronly)
121 {
122         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
123         filename = file;
124         filepath = OnlyPath(file);
125         paragraph = 0;
126         lyx_clean = true;
127         bak_clean = true;
128         dep_clean = 0;
129         read_only = ronly;
130         unnamed = false;
131         users = 0;
132         lyxvc.buffer(this);
133         if (read_only || (lyxrc.use_tempdir)) {
134                 tmppath = CreateBufferTmpDir();
135         } else tmppath.erase();
136 }
137
138
139 Buffer::~Buffer()
140 {
141         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
142         // here the buffer should take care that it is
143         // saved properly, before it goes into the void.
144
145         // make sure that views using this buffer
146         // forgets it.
147         if (users)
148                 users->buffer(0);
149         
150         if (!tmppath.empty()) {
151                 DestroyBufferTmpDir(tmppath);
152         }
153         
154         LyXParagraph * par = paragraph;
155         LyXParagraph * tmppar;
156         while (par) {
157                 tmppar = par->next;
158                 delete par;
159                 par = tmppar;
160         }
161         paragraph = 0;
162 }
163
164
165 string const Buffer::getLatexName(bool no_path) const
166 {
167         if (no_path)
168                 return OnlyFilename(ChangeExtension(MakeLatexName(filename), 
169                                                     ".tex"));
170         else
171                 return ChangeExtension(MakeLatexName(filename), 
172                                        ".tex"); 
173 }
174
175
176 void Buffer::setReadonly(bool flag)
177 {
178         if (read_only != flag) {
179                 read_only = flag; 
180                 updateTitles();
181                 users->owner()->getDialogs()->updateBufferDependent();
182         }
183         if (read_only) {
184                 WarnReadonly(filename);
185         }
186 }
187
188
189 bool Buffer::saveParamsAsDefaults() // const
190 {
191         string const fname = AddName(AddPath(user_lyxdir, "templates/"),
192                                "defaults.lyx");
193         Buffer defaults = Buffer(fname);
194         
195         // Use the current buffer's parameters as default
196         defaults.params = params;
197         
198         // add an empty paragraph. Is this enough?
199         defaults.paragraph = new LyXParagraph;
200
201         return defaults.writeFile(defaults.filename, false);
202 }
203
204
205 /// Update window titles of all users
206 // Should work on a list
207 void Buffer::updateTitles() const
208 {
209         if (users) users->owner()->updateWindowTitle();
210 }
211
212
213 /// Reset autosave timer of all users
214 // Should work on a list
215 void Buffer::resetAutosaveTimers() const
216 {
217         if (users) users->owner()->resetAutosaveTimer();
218 }
219
220
221 void Buffer::fileName(string const & newfile)
222 {
223         filename = MakeAbsPath(newfile);
224         filepath = OnlyPath(filename);
225         setReadonly(IsFileWriteable(filename) == 0);
226         updateTitles();
227 }
228
229
230 // candidate for move to BufferView
231 // (at least some parts in the beginning of the func)
232 //
233 // Uwe C. Schroeder
234 // changed to be public and have one parameter
235 // if par = 0 normal behavior
236 // else insert behavior
237 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
238 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
239 {
240         int pos = 0;
241         char depth = 0; // signed or unsigned?
242 #ifndef NEW_INSETS
243         LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
244         LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
245 #endif
246         bool the_end_read = false;
247
248         LyXParagraph * return_par = 0;
249         LyXFont font(LyXFont::ALL_INHERIT, params.language);
250         if (format < 2.16 && params.language->lang() == "hebrew")
251                 font.setLanguage(default_language);
252
253         // If we are inserting, we cheat and get a token in advance
254         bool has_token = false;
255         string pretoken;
256
257         if(!par) {
258                 par = new LyXParagraph;
259         } else {
260                 users->text->BreakParagraph(users);
261                 return_par = users->text->FirstParagraph();
262                 pos = 0;
263                 markDirty();
264                 // We don't want to adopt the parameters from the
265                 // document we insert, so we skip until the text begins:
266                 while (lex.IsOK()) {
267                         lex.nextToken();
268                         pretoken = lex.GetString();
269                         if (pretoken == "\\layout") {
270                                 has_token = true;
271                                 break;
272                         }
273                 }
274         }
275
276         while (lex.IsOK()) {
277                 if (has_token) {
278                         has_token = false;
279                 } else {
280                         lex.nextToken();
281                         pretoken = lex.GetString();
282                 }
283
284                 if (pretoken.empty()) continue;
285                 
286                 the_end_read =
287                         parseSingleLyXformat2Token(lex, par, return_par,
288                                                    pretoken, pos, depth,
289                                                    font
290 #ifndef NEW_INSETS
291                                                    , footnoteflag,
292                                                    footnotekind
293 #endif
294                                 );
295         }
296    
297         if (!return_par)
298                 return_par = par;
299
300         paragraph = return_par;
301         
302         return the_end_read;
303 }
304
305
306 // We'll remove this later. (Lgb)
307 static string last_inset_read;
308
309
310 bool
311 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
312                                    LyXParagraph *& return_par,
313                                    string const & token, int & pos,
314                                    char & depth, LyXFont & font
315 #ifndef NEW_INSETS
316                                    , LyXParagraph::footnote_flag & footnoteflag,
317                                    LyXParagraph::footnote_kind & footnotekind
318 #endif
319         )
320 {
321         bool the_end_read = false;
322         
323         if (token[0] != '\\') {
324                 for (string::const_iterator cit = token.begin();
325                      cit != token.end(); ++cit) {
326                         par->InsertChar(pos, (*cit), font);
327                         ++pos;
328                 }
329         } else if (token == "\\i") {
330                 Inset * inset = new InsetLatexAccent;
331                 inset->Read(this, lex);
332                 par->InsertInset(pos, inset, font);
333                 ++pos;
334         } else if (token == "\\layout") {
335                 if (!return_par) 
336                         return_par = par;
337                 else {
338                         par->fitToSize();
339                         par = new LyXParagraph(par);
340                 }
341                 pos = 0;
342                 lex.EatLine();
343                 string const layoutname = lex.GetString();
344                 pair<bool, LyXTextClass::LayoutList::size_type> pp
345                         = textclasslist.NumberOfLayout(params.textclass,
346                                                        layoutname);
347                 if (pp.first) {
348                         par->layout = pp.second;
349                 } else { // layout not found
350                         // use default layout "Standard" (0)
351                         par->layout = 0;
352                 }
353                 // Test whether the layout is obsolete.
354                 LyXLayout const & layout =
355                         textclasslist.Style(params.textclass,
356                                             par->layout); 
357                 if (!layout.obsoleted_by().empty())
358                         par->layout = 
359                                 textclasslist.NumberOfLayout(params.textclass, 
360                                                              layout.obsoleted_by()).second;
361 #ifndef NEW_INSETS
362                 par->footnoteflag = footnoteflag;
363                 par->footnotekind = footnotekind;
364 #endif
365                 par->depth = depth;
366                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
367                 if (format < 2.16 && params.language->lang() == "hebrew")
368                         font.setLanguage(default_language);
369 #ifndef NEW_INSETS
370         } else if (token == "\\end_float") {
371                 if (!return_par) 
372                         return_par = par;
373                 else {
374                         par->fitToSize();
375                         par = new LyXParagraph(par);
376                 }
377                 footnotekind = LyXParagraph::FOOTNOTE;
378                 footnoteflag = LyXParagraph::NO_FOOTNOTE;
379                 pos = 0;
380                 lex.EatLine();
381                 par->layout = LYX_DUMMY_LAYOUT;
382                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
383                 if (format < 2.16 && params.language->lang() == "hebrew")
384                         font.setLanguage(default_language);
385         } else if (token == "\\begin_float") {
386                 int tmpret = lex.FindToken(string_footnotekinds);
387                 if (tmpret == -1) ++tmpret;
388                 if (tmpret != LYX_LAYOUT_DEFAULT) 
389                         footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
390                 if (footnotekind == LyXParagraph::FOOTNOTE
391                     || footnotekind == LyXParagraph::MARGIN)
392                         footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
393                 else 
394                         footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
395 #else
396         } else if (token == "\\begin_float") {
397                 // This is the compability reader, unfinished but tested.
398                 // (Lgb)
399                 lex.next();
400                 string const tmptok = lex.GetString();
401                 //lyxerr << "old float: " << tmptok << endl;
402                 
403                 Inset * inset = 0;
404                 string old_float;
405                 
406                 if (tmptok == "footnote") {
407                         inset = new InsetFoot;
408                 } else if (tmptok == "margin") {
409                         inset = new InsetMarginal;
410                 } else if (tmptok == "fig") {
411                         inset = new InsetFloat("figure");
412                         old_float += "placement htbp\n";
413                 } else if (tmptok == "tab") {
414                         inset = new InsetFloat("table");
415                         old_float += "placement htbp\n";
416                 } else if (tmptok == "alg") {
417                         inset = new InsetFloat("algorithm");
418                         old_float += "placement htbp\n";
419                 } else if (tmptok == "wide-fig") {
420                         InsetFloat * tmp = new InsetFloat("figure");
421                         tmp->wide(true);
422                         inset = tmp;
423                         old_float += "placement htbp\n";
424                 } else if (tmptok == "wide-tab") {
425                         InsetFloat * tmp = new InsetFloat("table");
426                         tmp->wide(true);
427                         inset = tmp;
428                         old_float += "placement htbp\n";
429                 }
430
431                 if (!inset) return false; // no end read yet
432                 
433                 old_float += "collapsed true\n";
434
435                 // Here we need to check for \end_deeper and handle that
436                 // before we do the footnote parsing.
437                 // This _is_ a hack! (Lgb)
438                 while(true) {
439                         lex.next();
440                         string const tmp = lex.GetString();
441                         if (tmp == "\\end_deeper") {
442                                 lyxerr << "\\end_deeper caught!" << endl;
443                                 if (!depth) {
444                                         lex.printError("\\end_deeper: "
445                                                        "depth is already null");
446                                 } else
447                                         --depth;
448                                 
449                         } else {
450                                 old_float += tmp;
451                                 old_float += ' ';
452                                 break;
453                         }
454                 }
455                 
456                 old_float += lex.getLongString("\\end_float");
457                 old_float += "\n\\end_inset\n";
458                 //lyxerr << "float body: " << old_float << endl;
459
460                 istringstream istr(old_float);
461                 
462                 LyXLex nylex(0, 0);
463                 nylex.setStream(istr);
464                 
465                 inset->Read(this, nylex);
466                 par->InsertInset(pos, inset, font);
467                 ++pos;
468 #endif
469         } else if (token == "\\begin_deeper") {
470                 ++depth;
471         } else if (token == "\\end_deeper") {
472                 if (!depth) {
473                         lex.printError("\\end_deeper: "
474                                        "depth is already null");
475                 }
476                 else
477                         --depth;
478         } else if (token == "\\begin_preamble") {
479                 params.readPreamble(lex);
480         } else if (token == "\\textclass") {
481                 lex.EatLine();
482                 pair<bool, LyXTextClassList::size_type> pp = 
483                         textclasslist.NumberOfClass(lex.GetString());
484                 if (pp.first) {
485                         params.textclass = pp.second;
486                 } else {
487                   lex.printError("Unknown textclass `$$Token'");
488                         params.textclass = 0;
489                 }
490                 if (!textclasslist.Load(params.textclass)) {
491                                 // if the textclass wasn't loaded properly
492                                 // we need to either substitute another
493                                 // or stop loading the file.
494                                 // I can substitute but I don't see how I can
495                                 // stop loading... ideas??  ARRae980418
496                         WriteAlert(_("Textclass Loading Error!"),
497                                    string(_("Can't load textclass ")) +
498                                    textclasslist.NameOfClass(params.textclass),
499                                    _("-- substituting default"));
500                         params.textclass = 0;
501                 }
502         } else if (token == "\\options") {
503                 lex.EatLine();
504                 params.options = lex.GetString();
505         } else if (token == "\\language") {
506                 params.readLanguage(lex);    
507         } else if (token == "\\fontencoding") {
508                 lex.EatLine();
509         } else if (token == "\\inputencoding") {
510                 lex.EatLine();
511                 params.inputenc = lex.GetString();
512         } else if (token == "\\graphics") {
513                 params.readGraphicsDriver(lex);
514         } else if (token == "\\fontscheme") {
515                 lex.EatLine();
516                 params.fonts = lex.GetString();
517         } else if (token == "\\noindent") {
518                 par->noindent = true;
519         } else if (token == "\\fill_top") {
520                 par->added_space_top = VSpace(VSpace::VFILL);
521         } else if (token == "\\fill_bottom") {
522                 par->added_space_bottom = VSpace(VSpace::VFILL);
523         } else if (token == "\\line_top") {
524                 par->line_top = true;
525         } else if (token == "\\line_bottom") {
526                 par->line_bottom = true;
527         } else if (token == "\\pagebreak_top") {
528                 par->pagebreak_top = true;
529         } else if (token == "\\pagebreak_bottom") {
530                 par->pagebreak_bottom = true;
531         } else if (token == "\\start_of_appendix") {
532                 par->start_of_appendix = true;
533         } else if (token == "\\paragraph_separation") {
534                 int tmpret = lex.FindToken(string_paragraph_separation);
535                 if (tmpret == -1) ++tmpret;
536                 if (tmpret != LYX_LAYOUT_DEFAULT) 
537                         params.paragraph_separation =
538                                 static_cast<BufferParams::PARSEP>(tmpret);
539         } else if (token == "\\defskip") {
540                 lex.nextToken();
541                 params.defskip = VSpace(lex.GetString());
542         } else if (token == "\\epsfig") { // obsolete
543                 // Indeed it is obsolete, but we HAVE to be backwards
544                 // compatible until 0.14, because otherwise all figures
545                 // in existing documents are irretrivably lost. (Asger)
546                 params.readGraphicsDriver(lex);
547         } else if (token == "\\quotes_language") {
548                 int tmpret = lex.FindToken(string_quotes_language);
549                 if (tmpret == -1) ++tmpret;
550                 if (tmpret != LYX_LAYOUT_DEFAULT) {
551                         InsetQuotes::quote_language tmpl = 
552                                 InsetQuotes::EnglishQ;
553                         switch(tmpret) {
554                         case 0:
555                                 tmpl = InsetQuotes::EnglishQ;
556                                 break;
557                         case 1:
558                                 tmpl = InsetQuotes::SwedishQ;
559                                 break;
560                         case 2:
561                                 tmpl = InsetQuotes::GermanQ;
562                                 break;
563                         case 3:
564                                 tmpl = InsetQuotes::PolishQ;
565                                 break;
566                         case 4:
567                                 tmpl = InsetQuotes::FrenchQ;
568                                 break;
569                         case 5:
570                                 tmpl = InsetQuotes::DanishQ;
571                                 break;  
572                         }
573                         params.quotes_language = tmpl;
574                 }
575         } else if (token == "\\quotes_times") {
576                 lex.nextToken();
577                 switch(lex.GetInteger()) {
578                 case 1: 
579                         params.quotes_times = InsetQuotes::SingleQ; 
580                         break;
581                 case 2: 
582                         params.quotes_times = InsetQuotes::DoubleQ; 
583                         break;
584                 }
585         } else if (token == "\\papersize") {
586                 int tmpret = lex.FindToken(string_papersize);
587                 if (tmpret == -1)
588                         ++tmpret;
589                 else
590                         params.papersize2 = tmpret;
591         } else if (token == "\\paperpackage") {
592                 int tmpret = lex.FindToken(string_paperpackages);
593                 if (tmpret == -1) {
594                         ++tmpret;
595                         params.paperpackage = BufferParams::PACKAGE_NONE;
596                 } else
597                         params.paperpackage = tmpret;
598         } else if (token == "\\use_geometry") {
599                 lex.nextToken();
600                 params.use_geometry = lex.GetInteger();
601         } else if (token == "\\use_amsmath") {
602                 lex.nextToken();
603                 params.use_amsmath = lex.GetInteger();
604         } else if (token == "\\paperorientation") {
605                 int tmpret = lex.FindToken(string_orientation);
606                 if (tmpret == -1) ++tmpret;
607                 if (tmpret != LYX_LAYOUT_DEFAULT) 
608                         params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
609         } else if (token == "\\paperwidth") {
610                 lex.next();
611                 params.paperwidth = lex.GetString();
612         } else if (token == "\\paperheight") {
613                 lex.next();
614                 params.paperheight = lex.GetString();
615         } else if (token == "\\leftmargin") {
616                 lex.next();
617                 params.leftmargin = lex.GetString();
618         } else if (token == "\\topmargin") {
619                 lex.next();
620                 params.topmargin = lex.GetString();
621         } else if (token == "\\rightmargin") {
622                 lex.next();
623                 params.rightmargin = lex.GetString();
624         } else if (token == "\\bottommargin") {
625                 lex.next();
626                 params.bottommargin = lex.GetString();
627         } else if (token == "\\headheight") {
628                 lex.next();
629                 params.headheight = lex.GetString();
630         } else if (token == "\\headsep") {
631                 lex.next();
632                 params.headsep = lex.GetString();
633         } else if (token == "\\footskip") {
634                 lex.next();
635                 params.footskip = lex.GetString();
636         } else if (token == "\\paperfontsize") {
637                 lex.nextToken();
638                 params.fontsize = strip(lex.GetString());
639         } else if (token == "\\papercolumns") {
640                 lex.nextToken();
641                 params.columns = lex.GetInteger();
642         } else if (token == "\\papersides") {
643                 lex.nextToken();
644                 switch(lex.GetInteger()) {
645                 default:
646                 case 1: params.sides = LyXTextClass::OneSide; break;
647                 case 2: params.sides = LyXTextClass::TwoSides; break;
648                 }
649         } else if (token == "\\paperpagestyle") {
650                 lex.nextToken();
651                 params.pagestyle = strip(lex.GetString());
652         } else if (token == "\\bullet") {
653                 lex.nextToken();
654                 int const index = lex.GetInteger();
655                 lex.nextToken();
656                 int temp_int = lex.GetInteger();
657                 params.user_defined_bullets[index].setFont(temp_int);
658                 params.temp_bullets[index].setFont(temp_int);
659                 lex.nextToken();
660                 temp_int = lex.GetInteger();
661                 params.user_defined_bullets[index].setCharacter(temp_int);
662                 params.temp_bullets[index].setCharacter(temp_int);
663                 lex.nextToken();
664                 temp_int = lex.GetInteger();
665                 params.user_defined_bullets[index].setSize(temp_int);
666                 params.temp_bullets[index].setSize(temp_int);
667                 lex.nextToken();
668                 string const temp_str = lex.GetString();
669                 if (temp_str != "\\end_bullet") {
670                                 // this element isn't really necessary for
671                                 // parsing but is easier for humans
672                                 // to understand bullets. Put it back and
673                                 // set a debug message?
674                         lex.printError("\\end_bullet expected, got" + temp_str);
675                                 //how can I put it back?
676                 }
677         } else if (token == "\\bulletLaTeX") {
678                 lex.nextToken();
679                 int const index = lex.GetInteger();
680                 lex.next();
681                 string temp_str = lex.GetString();
682                 string sum_str;
683                 while (temp_str != "\\end_bullet") {
684                                 // this loop structure is needed when user
685                                 // enters an empty string since the first
686                                 // thing returned will be the \\end_bullet
687                                 // OR
688                                 // if the LaTeX entry has spaces. Each element
689                                 // therefore needs to be read in turn
690                         sum_str += temp_str;
691                         lex.next();
692                         temp_str = lex.GetString();
693                 }
694                 params.user_defined_bullets[index].setText(sum_str);
695                 params.temp_bullets[index].setText(sum_str);
696         } else if (token == "\\secnumdepth") {
697                 lex.nextToken();
698                 params.secnumdepth = lex.GetInteger();
699         } else if (token == "\\tocdepth") {
700                 lex.nextToken();
701                 params.tocdepth = lex.GetInteger();
702         } else if (token == "\\spacing") {
703                 lex.next();
704                 string const tmp = strip(lex.GetString());
705                 Spacing::Space tmp_space = Spacing::Default;
706                 float tmp_val = 0.0;
707                 if (tmp == "single") {
708                         tmp_space = Spacing::Single;
709                 } else if (tmp == "onehalf") {
710                         tmp_space = Spacing::Onehalf;
711                 } else if (tmp == "double") {
712                         tmp_space = Spacing::Double;
713                 } else if (tmp == "other") {
714                         lex.next();
715                         tmp_space = Spacing::Other;
716                         tmp_val = lex.GetFloat();
717                 } else {
718                         lex.printError("Unknown spacing token: '$$Token'");
719                 }
720                 // Small hack so that files written with klyx will be
721                 // parsed correctly.
722                 if (return_par) {
723                         par->spacing.set(tmp_space, tmp_val);
724                 } else {
725                         params.spacing.set(tmp_space, tmp_val);
726                 }
727         } else if (token == "\\paragraph_spacing") {
728                 lex.next();
729                 string const tmp = strip(lex.GetString());
730                 if (tmp == "single") {
731                         par->spacing.set(Spacing::Single);
732                 } else if (tmp == "onehalf") {
733                         par->spacing.set(Spacing::Onehalf);
734                 } else if (tmp == "double") {
735                         par->spacing.set(Spacing::Double);
736                 } else if (tmp == "other") {
737                         lex.next();
738                         par->spacing.set(Spacing::Other,
739                                          lex.GetFloat());
740                 } else {
741                         lex.printError("Unknown spacing token: '$$Token'");
742                 }
743         } else if (token == "\\float_placement") {
744                 lex.nextToken();
745                 params.float_placement = lex.GetString();
746         } else if (token == "\\family") { 
747                 lex.next();
748                 font.setLyXFamily(lex.GetString());
749         } else if (token == "\\series") {
750                 lex.next();
751                 font.setLyXSeries(lex.GetString());
752         } else if (token == "\\shape") {
753                 lex.next();
754                 font.setLyXShape(lex.GetString());
755         } else if (token == "\\size") {
756                 lex.next();
757                 font.setLyXSize(lex.GetString());
758         } else if (token == "\\latex") {
759                 lex.next();
760                 string const tok = lex.GetString();
761                 // This is dirty, but gone with LyX3. (Asger)
762                 if (tok == "no_latex")
763                         font.setLatex(LyXFont::OFF);
764                 else if (tok == "latex")
765                         font.setLatex(LyXFont::ON);
766                 else if (tok == "default")
767                         font.setLatex(LyXFont::INHERIT);
768                 else
769                         lex.printError("Unknown LaTeX font flag "
770                                        "`$$Token'");
771         } else if (token == "\\lang") {
772                 lex.next();
773                 string const tok = lex.GetString();
774                 Language const * lang = languages.getLanguage(tok);
775                 if (lang) {
776                         font.setLanguage(lang);
777                 } else {
778                         font.setLanguage(params.language);
779                         lex.printError("Unknown language `$$Token'");
780                 }
781         } else if (token == "\\numeric") {
782                 lex.next();
783                 font.setNumber(font.setLyXMisc(lex.GetString()));
784         } else if (token == "\\emph") {
785                 lex.next();
786                 font.setEmph(font.setLyXMisc(lex.GetString()));
787         } else if (token == "\\bar") {
788                 lex.next();
789                 string const tok = lex.GetString();
790                 // This is dirty, but gone with LyX3. (Asger)
791                 if (tok == "under")
792                         font.setUnderbar(LyXFont::ON);
793                 else if (tok == "no")
794                         font.setUnderbar(LyXFont::OFF);
795                 else if (tok == "default")
796                         font.setUnderbar(LyXFont::INHERIT);
797                 else
798                         lex.printError("Unknown bar font flag "
799                                        "`$$Token'");
800         } else if (token == "\\noun") {
801                 lex.next();
802                 font.setNoun(font.setLyXMisc(lex.GetString()));
803         } else if (token == "\\color") {
804                 lex.next();
805                 font.setLyXColor(lex.GetString());
806         } else if (token == "\\align") {
807                 int tmpret = lex.FindToken(string_align);
808                 if (tmpret == -1) ++tmpret;
809                 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
810                         int tmpret2 = 1;
811                         for (; tmpret > 0; --tmpret)
812                                 tmpret2 = tmpret2 * 2;
813                         par->align = LyXAlignment(tmpret2);
814                 }
815         } else if (token == "\\added_space_top") {
816                 lex.nextToken();
817                 par->added_space_top = VSpace(lex.GetString());
818         } else if (token == "\\added_space_bottom") {
819                 lex.nextToken();
820                 par->added_space_bottom = VSpace(lex.GetString());
821         } else if (token == "\\pextra_type") {
822                 lex.nextToken();
823                 par->pextra_type = lex.GetInteger();
824         } else if (token == "\\pextra_width") {
825                 lex.nextToken();
826                 par->pextra_width = lex.GetString();
827         } else if (token == "\\pextra_widthp") {
828                 lex.nextToken();
829                 par->pextra_widthp = lex.GetString();
830         } else if (token == "\\pextra_alignment") {
831                 lex.nextToken();
832                 par->pextra_alignment = lex.GetInteger();
833         } else if (token == "\\pextra_hfill") {
834                 lex.nextToken();
835                 par->pextra_hfill = lex.GetInteger();
836         } else if (token == "\\pextra_start_minipage") {
837                 lex.nextToken();
838                 par->pextra_start_minipage = lex.GetInteger();
839         } else if (token == "\\labelwidthstring") {
840                 lex.EatLine();
841                 par->labelwidthstring = lex.GetString();
842                 // do not delete this token, it is still needed!
843         } else if (token == "\\end_inset") {
844                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
845                        << "Last inset read was: " << last_inset_read
846                        << endl;
847                 // Simply ignore this. The insets do not have
848                 // to read this.
849                 // But insets should read it, it is a part of
850                 // the inset isn't it? Lgb.
851         } else if (token == "\\begin_inset") {
852                 readInset(lex, par, pos, font);
853         } else if (token == "\\SpecialChar") {
854                 LyXLayout const & layout =
855                         textclasslist.Style(params.textclass, 
856                                             par->GetLayout());
857
858                 // Insets don't make sense in a free-spacing context! ---Kayvan
859                 if (layout.free_spacing) {
860                         if (lex.IsOK()) {
861                                 lex.next();
862                                 string next_token = lex.GetString();
863                                 if (next_token == "\\-") {
864                                         par->InsertChar(pos, '-', font);
865                                 } else if (next_token == "\\protected_separator"
866                                         || next_token == "~") {
867                                         par->InsertChar(pos, ' ', font);
868                                 } else {
869                                         lex.printError("Token `$$Token' "
870                                                        "is in free space "
871                                                        "paragraph layout!");
872                                         --pos;
873                                 }
874                         }
875                 } else {
876                         Inset * inset = new InsetSpecialChar;
877                         inset->Read(this, lex);
878                         par->InsertInset(pos, inset, font);
879                 }
880                 ++pos;
881         } else if (token == "\\newline") {
882                 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
883                 ++pos;
884         } else if (token == "\\LyXTable") {
885                 Inset * inset = new InsetTabular(*this);
886                 inset->Read(this, lex);
887                 par->InsertInset(pos, inset, font);
888                 ++pos;
889         } else if (token == "\\hfill") {
890                 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
891                 ++pos;
892         } else if (token == "\\protected_separator") { // obsolete
893                 // This is a backward compability thingie. (Lgb)
894                 // Remove it later some time...introduced with fileformat
895                 // 2.16. (Lgb)
896                 LyXLayout const & layout =
897                         textclasslist.Style(params.textclass, 
898                                             par->GetLayout());
899
900                 if (layout.free_spacing) {
901                         par->InsertChar(pos, ' ', font);
902                 } else {
903                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
904                         par->InsertInset(pos, inset, font);
905                 }
906                 ++pos;
907         } else if (token == "\\bibitem") {  // ale970302
908                 if (!par->bibkey) {
909                         InsetCommandParams p( "bibitem" );
910                         par->bibkey = new InsetBibKey(p);
911                 }
912                 par->bibkey->Read(this, lex);                   
913         } else if (token == "\\backslash") {
914                 par->InsertChar(pos, '\\', font);
915                 ++pos;
916         } else if (token == "\\the_end") {
917                 the_end_read = true;
918         } else {
919                 // This should be insurance for the future: (Asger)
920                 lex.printError("Unknown token `$$Token'. "
921                                "Inserting as text.");
922                 string::const_iterator cit = token.begin();
923                 string::const_iterator end = token.end();
924                 for(; cit != end; ++cit) {
925                         par->InsertChar(pos, (*cit), font);
926                         ++pos;
927                 }
928         }
929         return the_end_read;
930 }
931
932
933 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
934                        int & pos, LyXFont & font)
935 {
936         // consistency check
937         if (lex.GetString() != "\\begin_inset") {
938                 lyxerr << "Buffer::readInset: Consistency check failed."
939                        << endl;
940         }
941         
942         Inset * inset = 0;
943
944         lex.next();
945         string const tmptok = lex.GetString();
946         last_inset_read = tmptok;
947
948         // test the different insets
949         if (tmptok == "LatexCommand") {
950                 InsetCommandParams inscmd;
951                 inscmd.Read(lex);
952
953                 if (inscmd.getCmdName() == "cite") {
954                         inset = new InsetCitation(inscmd);
955                 } else if (inscmd.getCmdName() == "bibitem") {
956                         lex.printError("Wrong place for bibitem");
957                         inset = new InsetBibKey(inscmd);
958                 } else if (inscmd.getCmdName() == "BibTeX") {
959                         inset = new InsetBibtex(inscmd);
960                 } else if (inscmd.getCmdName() == "index") {
961                         inset = new InsetIndex(inscmd);
962                 } else if (inscmd.getCmdName() == "include") {
963                         inset = new InsetInclude(inscmd, *this);
964                 } else if (inscmd.getCmdName() == "label") {
965                         inset = new InsetLabel(inscmd);
966                 } else if (inscmd.getCmdName() == "url"
967                            || inscmd.getCmdName() == "htmlurl") {
968                         inset = new InsetUrl(inscmd);
969                 } else if (inscmd.getCmdName() == "ref"
970                            || inscmd.getCmdName() == "pageref"
971                            || inscmd.getCmdName() == "vref"
972                            || inscmd.getCmdName() == "vpageref"
973                            || inscmd.getCmdName() == "prettyref") {
974                         if (!inscmd.getOptions().empty()
975                             || !inscmd.getContents().empty()) {
976                                 inset = new InsetRef(inscmd, *this);
977                         }
978                 } else if (inscmd.getCmdName() == "tableofcontents"
979                            || inscmd.getCmdName() == "listofalgorithms"
980                            || inscmd.getCmdName() == "listoffigures"
981                            || inscmd.getCmdName() == "listoftables") {
982                         inset = new InsetTOC(inscmd);
983                 } else if (inscmd.getCmdName() == "printindex") {
984                         inset = new InsetPrintIndex(inscmd);
985                 } else if (inscmd.getCmdName() == "lyxparent") {
986                         inset = new InsetParent(inscmd, *this);
987                 }
988         } else {
989                 if (tmptok == "Quotes") {
990                         inset = new InsetQuotes;
991                 } else if (tmptok == "External") {
992                         inset = new InsetExternal;
993                 } else if (tmptok == "FormulaMacro") {
994                         inset = new InsetFormulaMacro;
995                 } else if (tmptok == "Formula") {
996                         inset = new InsetFormula;
997                 } else if (tmptok == "Figure") {
998                         inset = new InsetFig(100, 100, *this);
999                 } else if (tmptok == "Info") {
1000                         inset = new InsetInfo;
1001                 } else if (tmptok == "Include") {
1002                         InsetCommandParams p( "Include" );
1003                         inset = new InsetInclude(p, *this);
1004                 } else if (tmptok == "ERT") {
1005                         inset = new InsetERT;
1006                 } else if (tmptok == "Tabular") {
1007                         inset = new InsetTabular(*this);
1008                 } else if (tmptok == "Text") {
1009                         inset = new InsetText;
1010                 } else if (tmptok == "Foot") {
1011                         inset = new InsetFoot;
1012                 } else if (tmptok == "Marginal") {
1013                         inset = new InsetMarginal;
1014                 } else if (tmptok == "Minipage") {
1015                         inset = new InsetMinipage;
1016                 } else if (tmptok == "Float") {
1017                         lex.next();
1018                         string tmptok = lex.GetString();
1019                         inset = new InsetFloat(tmptok);
1020                 } else if (tmptok == "List") {
1021                         inset = new InsetList;
1022                 } else if (tmptok == "Theorem") {
1023                         inset = new InsetList;
1024                 } else if (tmptok == "Caption") {
1025                         inset = new InsetCaption;
1026                 } else if (tmptok == "GRAPHICS") {
1027                         inset = new InsetGraphics;
1028                 }
1029                 
1030                 if (inset) inset->Read(this, lex);
1031         }
1032         
1033         if (inset) {
1034                 par->InsertInset(pos, inset, font);
1035                 ++pos;
1036         }
1037 }
1038
1039
1040 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1041 {
1042         if (lex.IsOK()) {
1043                 lex.next();
1044                 string const token(lex.GetString());
1045                 if (token == "\\lyxformat") { // the first token _must_ be...
1046                         lex.EatLine();
1047                         format = lex.GetFloat();
1048                         if (format > 1) {
1049                                 if (LYX_FORMAT - format > 0.05) {
1050                                         
1051                                         printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1052                                                LYX_FORMAT, format);
1053                                 }
1054                                 if (format - LYX_FORMAT > 0.05) {
1055                                         printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1056                                                LYX_FORMAT, format);
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                         for (set<string>::const_iterator it = encodings.begin();
1893                              it != encodings.end(); ++it)
1894                                 ofs << *it << ",";
1895                         ofs << doc_encoding << "]{inputenc}\n";
1896                         texrow.newline();
1897                 } else if (params.inputenc != "default") {
1898                         ofs << "\\usepackage[" << params.inputenc
1899                             << "]{inputenc}\n";
1900                         texrow.newline();
1901                 }
1902
1903                 // At the very beginning the text parameters.
1904                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1905                         switch (params.paperpackage) {
1906                         case BufferParams::PACKAGE_A4:
1907                                 ofs << "\\usepackage{a4}\n";
1908                                 texrow.newline();
1909                                 break;
1910                         case BufferParams::PACKAGE_A4WIDE:
1911                                 ofs << "\\usepackage{a4wide}\n";
1912                                 texrow.newline();
1913                                 break;
1914                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1915                                 ofs << "\\usepackage[widemargins]{a4}\n";
1916                                 texrow.newline();
1917                                 break;
1918                         }
1919                 }
1920                 if (params.use_geometry) {
1921                         ofs << "\\usepackage{geometry}\n";
1922                         texrow.newline();
1923                         ofs << "\\geometry{verbose";
1924                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1925                                 ofs << ",landscape";
1926                         switch (params.papersize2) {
1927                         case BufferParams::VM_PAPER_CUSTOM:
1928                                 if (!params.paperwidth.empty())
1929                                         ofs << ",paperwidth="
1930                                             << params.paperwidth;
1931                                 if (!params.paperheight.empty())
1932                                         ofs << ",paperheight="
1933                                             << params.paperheight;
1934                                 break;
1935                         case BufferParams::VM_PAPER_USLETTER:
1936                                 ofs << ",letterpaper";
1937                                 break;
1938                         case BufferParams::VM_PAPER_USLEGAL:
1939                                 ofs << ",legalpaper";
1940                                 break;
1941                         case BufferParams::VM_PAPER_USEXECUTIVE:
1942                                 ofs << ",executivepaper";
1943                                 break;
1944                         case BufferParams::VM_PAPER_A3:
1945                                 ofs << ",a3paper";
1946                                 break;
1947                         case BufferParams::VM_PAPER_A4:
1948                                 ofs << ",a4paper";
1949                                 break;
1950                         case BufferParams::VM_PAPER_A5:
1951                                 ofs << ",a5paper";
1952                                 break;
1953                         case BufferParams::VM_PAPER_B3:
1954                                 ofs << ",b3paper";
1955                                 break;
1956                         case BufferParams::VM_PAPER_B4:
1957                                 ofs << ",b4paper";
1958                                 break;
1959                         case BufferParams::VM_PAPER_B5:
1960                                 ofs << ",b5paper";
1961                                 break;
1962                         default:
1963                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1964                                 switch (lyxrc.default_papersize) {
1965                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1966                                 case BufferParams::PAPER_USLETTER:
1967                                         ofs << ",letterpaper";
1968                                         break;
1969                                 case BufferParams::PAPER_LEGALPAPER:
1970                                         ofs << ",legalpaper";
1971                                         break;
1972                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1973                                         ofs << ",executivepaper";
1974                                         break;
1975                                 case BufferParams::PAPER_A3PAPER:
1976                                         ofs << ",a3paper";
1977                                         break;
1978                                 case BufferParams::PAPER_A4PAPER:
1979                                         ofs << ",a4paper";
1980                                         break;
1981                                 case BufferParams::PAPER_A5PAPER:
1982                                         ofs << ",a5paper";
1983                                         break;
1984                                 case BufferParams::PAPER_B5PAPER:
1985                                         ofs << ",b5paper";
1986                                         break;
1987                                 }
1988                         }
1989                         if (!params.topmargin.empty())
1990                                 ofs << ",tmargin=" << params.topmargin;
1991                         if (!params.bottommargin.empty())
1992                                 ofs << ",bmargin=" << params.bottommargin;
1993                         if (!params.leftmargin.empty())
1994                                 ofs << ",lmargin=" << params.leftmargin;
1995                         if (!params.rightmargin.empty())
1996                                 ofs << ",rmargin=" << params.rightmargin;
1997                         if (!params.headheight.empty())
1998                                 ofs << ",headheight=" << params.headheight;
1999                         if (!params.headsep.empty())
2000                                 ofs << ",headsep=" << params.headsep;
2001                         if (!params.footskip.empty())
2002                                 ofs << ",footskip=" << params.footskip;
2003                         ofs << "}\n";
2004                         texrow.newline();
2005                 }
2006                 if (params.use_amsmath
2007                     && !tclass.provides(LyXTextClass::amsmath)) {
2008                         ofs << "\\usepackage{amsmath}\n";
2009                         texrow.newline();
2010                 }
2011
2012                 if (tokenPos(tclass.opt_pagestyle(),
2013                              '|', params.pagestyle) >= 0) {
2014                         if (params.pagestyle == "fancy") {
2015                                 ofs << "\\usepackage{fancyhdr}\n";
2016                                 texrow.newline();
2017                         }
2018                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2019                         texrow.newline();
2020                 }
2021
2022                 // We try to load babel late, in case it interferes
2023                 // with other packages.
2024                 if (use_babel) {
2025                         ofs << lyxrc.language_package << endl;
2026                         texrow.newline();
2027                 }
2028
2029                 if (params.secnumdepth != tclass.secnumdepth()) {
2030                         ofs << "\\setcounter{secnumdepth}{"
2031                             << params.secnumdepth
2032                             << "}\n";
2033                         texrow.newline();
2034                 }
2035                 if (params.tocdepth != tclass.tocdepth()) {
2036                         ofs << "\\setcounter{tocdepth}{"
2037                             << params.tocdepth
2038                             << "}\n";
2039                         texrow.newline();
2040                 }
2041                 
2042                 if (params.paragraph_separation) {
2043                         switch (params.defskip.kind()) {
2044                         case VSpace::SMALLSKIP: 
2045                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2046                                 break;
2047                         case VSpace::MEDSKIP:
2048                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2049                                 break;
2050                         case VSpace::BIGSKIP:
2051                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2052                                 break;
2053                         case VSpace::LENGTH:
2054                                 ofs << "\\setlength\\parskip{"
2055                                     << params.defskip.length().asLatexString()
2056                                     << "}\n";
2057                                 break;
2058                         default: // should never happen // Then delete it.
2059                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2060                                 break;
2061                         }
2062                         texrow.newline();
2063                         
2064                         ofs << "\\setlength\\parindent{0pt}\n";
2065                         texrow.newline();
2066                 }
2067
2068                 // Now insert the LyX specific LaTeX commands...
2069
2070                 // The optional packages;
2071                 string preamble(features.getPackages());
2072
2073                 // this might be useful...
2074                 preamble += "\n\\makeatletter\n";
2075
2076                 // Some macros LyX will need
2077                 string tmppreamble(features.getMacros());
2078
2079                 if (!tmppreamble.empty()) {
2080                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2081                                 "LyX specific LaTeX commands.\n"
2082                                 + tmppreamble + '\n';
2083                 }
2084
2085                 // the text class specific preamble 
2086                 tmppreamble = features.getTClassPreamble();
2087                 if (!tmppreamble.empty()) {
2088                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2089                                 "Textclass specific LaTeX commands.\n"
2090                                 + tmppreamble + '\n';
2091                 }
2092
2093                 /* the user-defined preamble */
2094                 if (!params.preamble.empty()) {
2095                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2096                                 "User specified LaTeX commands.\n"
2097                                 + params.preamble + '\n';
2098                 }
2099
2100                 preamble += "\\makeatother\n";
2101
2102                 // Itemize bullet settings need to be last in case the user
2103                 // defines their own bullets that use a package included
2104                 // in the user-defined preamble -- ARRae
2105                 // Actually it has to be done much later than that
2106                 // since some packages like frenchb make modifications
2107                 // at \begin{document} time -- JMarc 
2108                 string bullets_def;
2109                 for (int i = 0; i < 4; ++i) {
2110                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2111                                 if (bullets_def.empty())
2112                                         bullets_def="\\AtBeginDocument{\n";
2113                                 bullets_def += "  \\renewcommand{\\labelitemi";
2114                                 switch (i) {
2115                                 // `i' is one less than the item to modify
2116                                 case 0:
2117                                         break;
2118                                 case 1:
2119                                         bullets_def += 'i';
2120                                         break;
2121                                 case 2:
2122                                         bullets_def += "ii";
2123                                         break;
2124                                 case 3:
2125                                         bullets_def += 'v';
2126                                         break;
2127                                 }
2128                                 bullets_def += "}{" + 
2129                                   params.user_defined_bullets[i].getText() 
2130                                   + "}\n";
2131                         }
2132                 }
2133
2134                 if (!bullets_def.empty())
2135                   preamble += bullets_def + "}\n\n";
2136
2137                 for (int j = countChar(preamble, '\n'); j-- ;) {
2138                         texrow.newline();
2139                 }
2140
2141                 ofs << preamble;
2142
2143                 // make the body.
2144                 ofs << "\\begin{document}\n";
2145                 texrow.newline();
2146         } // only_body
2147         lyxerr.debug() << "preamble finished, now the body." << endl;
2148 #ifdef DO_USE_DEFAULT_LANGUAGE
2149         if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2150 #else
2151         if (!lyxrc.language_auto_begin) {
2152 #endif
2153                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2154                              params.language->babel())
2155                     << endl;
2156                 texrow.newline();
2157         }
2158         
2159         latexParagraphs(ofs, paragraph, 0, texrow);
2160
2161         // add this just in case after all the paragraphs
2162         ofs << endl;
2163         texrow.newline();
2164
2165 #ifdef DO_USE_DEFAULT_LANGUAGE
2166         if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2167 #else
2168                 if (!lyxrc.language_auto_end) {
2169 #endif
2170                 ofs << subst(lyxrc.language_command_end, "$$lang",
2171                              params.language->babel())
2172                     << endl;
2173                 texrow.newline();
2174         }
2175
2176         if (!only_body) {
2177                 ofs << "\\end{document}\n";
2178                 texrow.newline();
2179         
2180                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2181         } else {
2182                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2183                                      << endl;
2184         }
2185
2186         // Just to be sure. (Asger)
2187         texrow.newline();
2188
2189         // tex_code_break_column's value is used to decide
2190         // if we are in batchmode or not (within mathed_write()
2191         // in math_write.C) so we must set it to a non-zero
2192         // value when we leave otherwise we save incorrect .lyx files.
2193         tex_code_break_column = lyxrc.ascii_linelen;
2194
2195         ofs.close();
2196         if (ofs.fail()) {
2197                 lyxerr << "File was not closed properly." << endl;
2198         }
2199         
2200         lyxerr.debug() << "Finished making latex file." << endl;
2201 }
2202
2203
2204 //
2205 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2206 //
2207 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2208                              LyXParagraph * endpar, TexRow & texrow) const
2209 {
2210         bool was_title = false;
2211         bool already_title = false;
2212         std::ostringstream ftnote;
2213         TexRow ft_texrow;
2214         int ftcount = 0;
2215
2216         // if only_body
2217         while (par != endpar) {
2218 #ifndef NEW_INSETS
2219                 if (par->IsDummy())
2220                         lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2221                                              << endl;
2222 #endif
2223                 LyXLayout const & layout =
2224                         textclasslist.Style(params.textclass,
2225                                             par->layout);
2226             
2227                 if (layout.intitle) {
2228                         if (already_title) {
2229                                 lyxerr <<"Error in latexParagraphs: You"
2230                                         " should not mix title layouts"
2231                                         " with normal ones." << endl;
2232                         } else
2233                                 was_title = true;
2234                 } else if (was_title && !already_title) {
2235                         ofs << "\\maketitle\n";
2236                         texrow.newline();
2237                         already_title = true;
2238                         was_title = false;                  
2239                 }
2240                 // We are at depth 0 so we can just use
2241                 // ordinary \footnote{} generation
2242                 // flag this with ftcount
2243                 ftcount = -1;
2244                 if (layout.isEnvironment()
2245                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2246                         par = par->TeXEnvironment(this, params, ofs, texrow
2247 #ifndef NEW_INSETS
2248                                                   ,ftnote, ft_texrow, ftcount
2249 #endif
2250                                 );
2251                 } else {
2252                         par = par->TeXOnePar(this, params, ofs, texrow, false
2253 #ifndef NEW_INSETS
2254                                              ,
2255                                              ftnote, ft_texrow, ftcount
2256 #endif
2257                                 );
2258                 }
2259
2260                 // Write out what we've generated...
2261                 if (ftcount >= 1) {
2262                         if (ftcount > 1) {
2263                                 ofs << "\\addtocounter{footnote}{-"
2264                                     << ftcount - 1
2265                                     << '}';
2266                         }
2267                         ofs << ftnote.str();
2268                         texrow += ft_texrow;
2269
2270                         // The extra .c_str() is needed when we use
2271                         // lyxstring instead of the STL string class. 
2272                         ftnote.str(string().c_str());
2273                         ft_texrow.reset();
2274                         ftcount = 0;
2275                 }
2276         }
2277         // It might be that we only have a title in this document
2278         if (was_title && !already_title) {
2279                 ofs << "\\maketitle\n";
2280                 texrow.newline();
2281         }
2282 }
2283
2284
2285 bool Buffer::isLatex() const
2286 {
2287         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2288 }
2289
2290
2291 bool Buffer::isLinuxDoc() const
2292 {
2293         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2294 }
2295
2296
2297 bool Buffer::isLiterate() const
2298 {
2299         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2300 }
2301
2302
2303 bool Buffer::isDocBook() const
2304 {
2305         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2306 }
2307
2308
2309 bool Buffer::isSGML() const
2310 {
2311         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2312                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2313 }
2314
2315
2316 void Buffer::sgmlOpenTag(ostream & os, int depth,
2317                          string const & latexname) const
2318 {
2319         os << string(depth, ' ') << "<" << latexname << ">\n";
2320 }
2321
2322
2323 void Buffer::sgmlCloseTag(ostream & os, int depth,
2324                           string const & latexname) const
2325 {
2326         os << string(depth, ' ') << "</" << latexname << ">\n";
2327 }
2328
2329
2330 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2331 {
2332         LyXParagraph * par = paragraph;
2333
2334         niceFile = nice; // this will be used by Insetincludes.
2335
2336         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2337         string environment_stack[10];
2338         string item_name;
2339
2340         int depth = 0; // paragraph depth
2341
2342         ofstream ofs(fname.c_str());
2343
2344         if (!ofs) {
2345                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2346                 return;
2347         }
2348
2349         LyXTextClass const & tclass =
2350                 textclasslist.TextClass(params.textclass);
2351
2352         LaTeXFeatures features(params, tclass.numLayouts());
2353         validate(features);
2354
2355         //if(nice)
2356         tex_code_break_column = lyxrc.ascii_linelen;
2357         //else
2358         //tex_code_break_column = 0;
2359
2360         texrow.reset();
2361
2362         if (!body_only) {
2363                 string sgml_includedfiles=features.getIncludedFiles();
2364
2365                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2366                         ofs << "<!doctype linuxdoc system>\n\n";
2367                 } else {
2368                         ofs << "<!doctype linuxdoc system [ "
2369                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2370                 }
2371
2372                 if(params.options.empty())
2373                         sgmlOpenTag(ofs, 0, top_element);
2374                 else {
2375                         string top = top_element;
2376                         top += " ";
2377                         top += params.options;
2378                         sgmlOpenTag(ofs, 0, top);
2379                 }
2380         }
2381
2382         ofs << "<!-- "  << LYX_DOCVERSION 
2383             << " created this file. For more info see http://www.lyx.org/"
2384             << " -->\n";
2385
2386         while (par) {
2387                 int desc_on = 0; // description mode
2388                 LyXLayout const & style =
2389                         textclasslist.Style(params.textclass,
2390                                             par->layout);
2391
2392                 // treat <toc> as a special case for compatibility with old code
2393                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2394                         Inset * inset = par->GetInset(0);
2395                         Inset::Code lyx_code = inset->LyxCode();
2396                         if (lyx_code == Inset::TOC_CODE){
2397                                 string const temp = "toc";
2398                                 sgmlOpenTag(ofs, depth, temp);
2399
2400                                 par = par->next;
2401 #ifndef NEW_INSETS
2402                                 linuxDocHandleFootnote(ofs, par, depth);
2403 #endif
2404                                 continue;
2405                         }
2406                 }
2407
2408                 // environment tag closing
2409                 for (; depth > par->depth; --depth) {
2410                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2411                         environment_stack[depth].erase();
2412                 }
2413
2414                 // write opening SGML tags
2415                 switch (style.latextype) {
2416                 case LATEX_PARAGRAPH:
2417                         if(depth == par->depth 
2418                            && !environment_stack[depth].empty()) {
2419                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2420                                 environment_stack[depth].erase();
2421                                 if(depth) 
2422                                         --depth;
2423                                 else
2424                                         ofs << "</p>";
2425                         }
2426                         sgmlOpenTag(ofs, depth, style.latexname());
2427                         break;
2428
2429                 case LATEX_COMMAND:
2430                         if (depth!= 0)
2431                                 LinuxDocError(par, 0,
2432                                               _("Error : Wrong depth for"
2433                                                 " LatexType Command.\n"));
2434
2435                         if (!environment_stack[depth].empty()){
2436                                 sgmlCloseTag(ofs, depth,
2437                                              environment_stack[depth]);
2438                                 ofs << "</p>";
2439                         }
2440
2441                         environment_stack[depth].erase();
2442                         sgmlOpenTag(ofs, depth, style.latexname());
2443                         break;
2444
2445                 case LATEX_ENVIRONMENT:
2446                 case LATEX_ITEM_ENVIRONMENT:
2447                         if (depth == par->depth 
2448                            && environment_stack[depth] != style.latexname()
2449                            && !environment_stack[depth].empty()) {
2450
2451                                 sgmlCloseTag(ofs, depth,
2452                                              environment_stack[depth]);
2453                                 environment_stack[depth].erase();
2454                         }
2455                         if (depth < par->depth) {
2456                                depth = par->depth;
2457                                environment_stack[depth].erase();
2458                         }
2459                         if (environment_stack[depth] != style.latexname()) {
2460                                 if(depth == 0) {
2461                                         string const temp = "p";
2462                                         sgmlOpenTag(ofs, depth, temp);
2463                                 }
2464                                 environment_stack[depth] = style.latexname();
2465                                 sgmlOpenTag(ofs, depth,
2466                                             environment_stack[depth]);
2467                         }
2468                         if(style.latextype == LATEX_ENVIRONMENT) break;
2469
2470                         desc_on = (style.labeltype == LABEL_MANUAL);
2471
2472                         if(desc_on)
2473                                 item_name = "tag";
2474                         else
2475                                 item_name = "item";
2476
2477                         sgmlOpenTag(ofs, depth + 1, item_name);
2478                         break;
2479                 default:
2480                         sgmlOpenTag(ofs, depth, style.latexname());
2481                         break;
2482                 }
2483
2484 #ifndef NEW_INSETS
2485                 do {
2486 #endif
2487                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2488
2489                         par = par->next;
2490 #ifndef NEW_INSETS
2491                         linuxDocHandleFootnote(ofs, par, depth);
2492                 }
2493                 while(par && par->IsDummy());
2494 #endif
2495
2496                 ofs << "\n";
2497                 // write closing SGML tags
2498                 switch(style.latextype) {
2499                 case LATEX_COMMAND:
2500                 case LATEX_ENVIRONMENT:
2501                 case LATEX_ITEM_ENVIRONMENT:
2502                         break;
2503                 default:
2504                         sgmlCloseTag(ofs, depth, style.latexname());
2505                         break;
2506                 }
2507         }
2508    
2509         // Close open tags
2510         for(; depth > 0; --depth)
2511                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2512
2513         if(!environment_stack[depth].empty())
2514                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2515
2516         if (!body_only) {
2517                 ofs << "\n\n";
2518                 sgmlCloseTag(ofs, 0, top_element);
2519         }
2520
2521         ofs.close();
2522         // How to check for successful close
2523 }
2524
2525
2526 #ifndef NEW_INSETS
2527 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2528                                     int depth)
2529 {
2530         string const tag = "footnote";
2531
2532         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2533                 sgmlOpenTag(os, depth + 1, tag);
2534                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2535                 sgmlCloseTag(os, depth + 1, tag);
2536                 par = par->next;
2537         }
2538 }
2539 #endif
2540
2541
2542 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2543                                   int depth, int desc_on,
2544                                   LyXParagraph * & par)
2545 {
2546         LyXParagraph * tpar = par;
2547         while (tpar
2548 #ifndef NEW_INSETS
2549                && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2550 #endif
2551                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2552                                                              "Caption").second))
2553                 tpar = tpar->next;
2554         if (tpar &&
2555             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2556                                                          "Caption").second) {
2557                 sgmlOpenTag(os, depth + 1, inner_tag);
2558                 string extra_par;
2559                 SimpleDocBookOnePar(os, extra_par, tpar,
2560                                     desc_on, depth + 2);
2561                 sgmlCloseTag(os, depth+1, inner_tag);
2562                 if(!extra_par.empty())
2563                         os << extra_par;
2564         }
2565 }
2566
2567
2568 #ifndef NEW_INSETS
2569 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2570                                    int depth)
2571 {
2572         string tag, inner_tag;
2573         string tmp_par, extra_par;
2574         bool inner_span = false;
2575         int desc_on = 4;
2576
2577         // Someone should give this enum a proper name (Lgb)
2578         enum SOME_ENUM {
2579                 NO_ONE,
2580                 FOOTNOTE_LIKE,
2581                 MARGIN_LIKE,
2582                 FIG_LIKE,
2583                 TAB_LIKE
2584         };
2585         SOME_ENUM last = NO_ONE;
2586         SOME_ENUM present = FOOTNOTE_LIKE;
2587
2588         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2589                 if (last == present) {
2590                         if (inner_span) {
2591                                 if (!tmp_par.empty()) {
2592                                         os << tmp_par;
2593                                         tmp_par.erase();
2594                                         sgmlCloseTag(os, depth + 1, inner_tag);
2595                                         sgmlOpenTag(os, depth + 1, inner_tag);
2596                                 }
2597                         } else {
2598                                 os << "\n";
2599                         }
2600                 } else {
2601                         os << tmp_par;
2602                         if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2603                                                             inner_tag);
2604                         if (!extra_par.empty()) os << extra_par;
2605                         if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2606                         extra_par.erase();
2607
2608                         switch (par->footnotekind) {
2609                         case LyXParagraph::FOOTNOTE:
2610                         case LyXParagraph::ALGORITHM:
2611                                 tag = "footnote";
2612                                 inner_tag = "para";
2613                                 present = FOOTNOTE_LIKE;
2614                                 inner_span = true;
2615                                 break;
2616                         case LyXParagraph::MARGIN:
2617                                 tag = "sidebar";
2618                                 inner_tag = "para";
2619                                 present = MARGIN_LIKE;
2620                                 inner_span = true;
2621                                 break;
2622                         case LyXParagraph::FIG:
2623                         case LyXParagraph::WIDE_FIG:
2624                                 tag = "figure";
2625                                 inner_tag = "title";
2626                                 present = FIG_LIKE;
2627                                 inner_span = false;
2628                                 break;
2629                         case LyXParagraph::TAB:
2630                         case LyXParagraph::WIDE_TAB:
2631                                 tag = "table";
2632                                 inner_tag = "title";
2633                                 present = TAB_LIKE;
2634                                 inner_span = false;
2635                                 break;
2636                         }
2637                         sgmlOpenTag(os, depth, tag);
2638                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2639                                 DocBookHandleCaption(os, inner_tag, depth,
2640                                                      desc_on, par);
2641                                 inner_tag.erase();
2642                         } else {
2643                                 sgmlOpenTag(os, depth + 1, inner_tag);
2644                         }
2645                 }
2646                 // ignore all caption here, we processed them above!!!
2647                 if (par->layout != textclasslist
2648                     .NumberOfLayout(params.textclass,
2649                                     "Caption").second) {
2650                         std::ostringstream ost;
2651                         SimpleDocBookOnePar(ost, extra_par, par,
2652                                             desc_on, depth + 2);
2653                         tmp_par += ost.str().c_str();
2654                 }
2655                 tmp_par = frontStrip(strip(tmp_par));
2656
2657                 last = present;
2658                 par = par->next;
2659         }
2660         os << tmp_par;
2661         if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2662         if(!extra_par.empty()) os << extra_par;
2663         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2664 }
2665 #endif
2666
2667
2668 // push a tag in a style stack
2669 void Buffer::push_tag(ostream & os, string const & tag,
2670                       int & pos, char stack[5][3])
2671 {
2672 #warning Use a real stack! (Lgb)
2673         // pop all previous tags
2674         for (int j = pos; j >= 0; --j)
2675                 os << "</" << stack[j] << ">";
2676
2677         // add new tag
2678         sprintf(stack[++pos], "%s", tag.c_str());
2679
2680         // push all tags
2681         for (int i = 0; i <= pos; ++i)
2682                 os << "<" << stack[i] << ">";
2683 }
2684
2685
2686 void Buffer::pop_tag(ostream & os, string const & tag,
2687                      int & pos, char stack[5][3])
2688 {
2689 #ifdef WITH_WARNINGS
2690 #warning Use a real stack! (Lgb)
2691 #endif
2692         // Please, Lars, do not remove the global variable. I already
2693         // had to reintroduce it twice! (JMarc) 
2694         int j;
2695         
2696         // pop all tags till specified one
2697         for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2698                 os << "</" << stack[j] << ">";
2699
2700         // closes the tag
2701         os << "</" << tag << ">";
2702         
2703         // push all tags, but the specified one
2704         for (j = j + 1; j <= pos; ++j) {
2705                 os << "<" << stack[j] << ">";
2706                 strcpy(stack[j-1], stack[j]);
2707         }
2708         --pos;
2709 }
2710
2711
2712 // Handle internal paragraph parsing -- layout already processed.
2713
2714 // checks, if newcol chars should be put into this line
2715 // writes newline, if necessary.
2716 static
2717 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2718                           string::size_type newcol)
2719 {
2720         colcount += newcol;
2721         if (colcount > lyxrc.ascii_linelen) {
2722                 os << "\n";
2723                 colcount = newcol; // assume write after this call
2724         }
2725 }
2726
2727
2728 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2729                                   int desc_on, int /*depth*/)
2730 {
2731         LyXFont font1;
2732         char c;
2733         Inset * inset;
2734         LyXParagraph::size_type main_body;
2735         int j;
2736         LyXLayout const & style = textclasslist.Style(params.textclass,
2737                                                       par->GetLayout());
2738
2739         char family_type = 0;               // family font flag 
2740         bool is_bold     = false;           // series font flag 
2741         char shape_type  = 0;               // shape font flag 
2742         bool is_em = false;                 // emphasis (italic) font flag 
2743
2744         int stack_num = -1;          // style stack position
2745         // Can this be rewritten to use a std::stack, please. (Lgb)
2746         char stack[5][3];            // style stack 
2747         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2748
2749         if (style.labeltype != LABEL_MANUAL)
2750                 main_body = 0;
2751         else
2752                 main_body = par->BeginningOfMainBody();
2753
2754         // gets paragraph main font
2755         if (main_body > 0)
2756                 font1 = style.labelfont;
2757         else
2758                 font1 = style.font;
2759
2760   
2761         // parsing main loop
2762         for (LyXParagraph::size_type i = 0;
2763              i < par->size(); ++i) {
2764
2765                 // handle quote tag
2766                 if (i == main_body
2767 #ifndef NEW_INSETS
2768                     && !par->IsDummy()
2769 #endif
2770                         ) {
2771                         if (main_body > 0)
2772                                 font1 = style.font;
2773                 }
2774
2775                 LyXFont const font2 = par->getFont(params, i);
2776
2777                 if (font1.family() != font2.family()) {
2778                         switch(family_type) {
2779                         case 0:
2780                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2781                                         push_tag(os, "tt", stack_num, stack);
2782                                         family_type = 1;
2783                                 }
2784                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
2785                                         push_tag(os, "sf", stack_num, stack);
2786                                         family_type = 2;
2787                                 }
2788                                 break;
2789                         case 1:
2790                                 pop_tag(os, "tt", stack_num, stack);
2791                                 if (font2.family() == LyXFont::SANS_FAMILY) {
2792                                         push_tag(os, "sf", stack_num, stack);
2793                                         family_type = 2;
2794                                 } else {
2795                                         family_type = 0;
2796                                 }
2797                                 break;
2798                         case 2:
2799                                 pop_tag(os, "sf", stack_num, stack);
2800                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2801                                         push_tag(os, "tt", stack_num, stack);
2802                                         family_type = 1;
2803                                 } else {
2804                                         family_type = 0;
2805                                 }
2806                         }
2807                 }
2808
2809                 // handle bold face
2810                 if (font1.series() != font2.series()) {
2811                         if (font2.series() == LyXFont::BOLD_SERIES) {
2812                                 push_tag(os, "bf", stack_num, stack);
2813                                 is_bold = true;
2814                         } else if (is_bold) {
2815                                 pop_tag(os, "bf", stack_num, stack);
2816                                 is_bold = false;
2817                         }
2818                 }
2819
2820                 // handle italic and slanted fonts
2821                 if (font1.shape() != font2.shape()) {
2822                         switch(shape_type) {
2823                         case 0:
2824                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2825                                         push_tag(os, "it", stack_num, stack);
2826                                         shape_type = 1;
2827                                 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2828                                         push_tag(os, "sl", stack_num, stack);
2829                                         shape_type = 2;
2830                                 }
2831                                 break;
2832                         case 1:
2833                                 pop_tag(os, "it", stack_num, stack);
2834                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2835                                         push_tag(os, "sl", stack_num, stack);
2836                                         shape_type = 2;
2837                                 } else {
2838                                         shape_type = 0;
2839                                 }
2840                                 break;
2841                         case 2:
2842                                 pop_tag(os, "sl", stack_num, stack);
2843                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2844                                         push_tag(os, "it", stack_num, stack);
2845                                         shape_type = 1;
2846                                 } else {
2847                                         shape_type = 0;
2848                                 }
2849                         }
2850                 }
2851                 // handle <em> tag
2852                 if (font1.emph() != font2.emph()) {
2853                         if (font2.emph() == LyXFont::ON) {
2854                                 push_tag(os, "em", stack_num, stack);
2855                                 is_em = true;
2856                         } else if (is_em) {
2857                                 pop_tag(os, "em", stack_num, stack);
2858                                 is_em = false;
2859                         }
2860                 }
2861
2862                 c = par->GetChar(i);
2863
2864                 if (c == LyXParagraph::META_INSET) {
2865                         inset = par->GetInset(i);
2866                         inset->Linuxdoc(this, os);
2867                 }
2868
2869                 if (font2.latex() == LyXFont::ON) {
2870                         // "TeX"-Mode on == > SGML-Mode on.
2871                         if (c != '\0')
2872                                 os << c; // see LaTeX-Generation...
2873                         ++char_line_count;
2874                 } else {
2875                         string sgml_string;
2876                         if (par->linuxDocConvertChar(c, sgml_string)
2877                             && !style.free_spacing) { // in freespacing
2878                                                      // mode, spaces are
2879                                                      // non-breaking characters
2880                                 // char is ' '
2881                                 if (desc_on == 1) {
2882                                         ++char_line_count;
2883                                         linux_doc_line_break(os, char_line_count, 6);
2884                                         os << "</tag>";
2885                                         desc_on = 2;
2886                                 } else  {
2887                                         linux_doc_line_break(os, char_line_count, 1);
2888                                         os << c;
2889                                 }
2890                         } else {
2891                                 os << sgml_string;
2892                                 char_line_count += sgml_string.length();
2893                         }
2894                 }
2895                 font1 = font2;
2896         }
2897
2898         // needed if there is an optional argument but no contents
2899         if (main_body > 0 && main_body == par->size()) {
2900                 font1 = style.font;
2901         }
2902
2903         // pop all defined Styles
2904         for (j = stack_num; j >= 0; --j) {
2905                 linux_doc_line_break(os, 
2906                                      char_line_count, 
2907                                      3 + strlen(stack[j]));
2908                 os << "</" << stack[j] << ">";
2909         }
2910
2911         // resets description flag correctly
2912         switch(desc_on){
2913         case 1:
2914                 // <tag> not closed...
2915                 linux_doc_line_break(os, char_line_count, 6);
2916                 os << "</tag>";
2917                 break;
2918         case 2:
2919                 // fprintf(file, "</p>");
2920                 break;
2921         }
2922 }
2923
2924
2925 // Print an error message.
2926 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2927                            string const & message) 
2928 {
2929         // insert an error marker in text
2930         InsetError * new_inset = new InsetError(message);
2931         par->InsertInset(pos, new_inset);
2932 }
2933
2934 // This constant defines the maximum number of 
2935 // environment layouts that can be nesteded.
2936 // The same applies for command layouts.
2937 // These values should be more than enough.
2938 //           José Matos (1999/07/22)
2939
2940 enum { MAX_NEST_LEVEL = 25};
2941
2942 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2943 {
2944         LyXParagraph * par = paragraph;
2945
2946         niceFile = nice; // this will be used by Insetincludes.
2947
2948         string top_element= textclasslist.LatexnameOfClass(params.textclass);
2949         // Please use a real stack.
2950         string environment_stack[MAX_NEST_LEVEL];
2951         string environment_inner[MAX_NEST_LEVEL];
2952         // Please use a real stack.
2953         string command_stack[MAX_NEST_LEVEL];
2954         bool command_flag= false;
2955         int command_depth= 0, command_base= 0, cmd_depth= 0;
2956
2957         string item_name, command_name;
2958         string c_depth, c_params, tmps;
2959
2960         int depth = 0; // paragraph depth
2961         LyXTextClass const & tclass =
2962                 textclasslist.TextClass(params.textclass);
2963
2964         LaTeXFeatures features(params, tclass.numLayouts());
2965         validate(features);
2966
2967         //if(nice)
2968         tex_code_break_column = lyxrc.ascii_linelen;
2969         //else
2970         //tex_code_break_column = 0;
2971
2972         ofstream ofs(fname.c_str());
2973         if (!ofs) {
2974                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2975                 return;
2976         }
2977    
2978         texrow.reset();
2979
2980         if(!only_body) {
2981                 string sgml_includedfiles=features.getIncludedFiles();
2982
2983                 ofs << "<!doctype " << top_element
2984                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2985
2986                 if (params.preamble.empty() && sgml_includedfiles.empty())
2987                         ofs << ">\n\n";
2988                 else
2989                         ofs << "\n [ " << params.preamble 
2990                             << sgml_includedfiles << " \n]>\n\n";
2991
2992                 if(params.options.empty())
2993                         sgmlOpenTag(ofs, 0, top_element);
2994                 else {
2995                         string top = top_element;
2996                         top += " ";
2997                         top += params.options;
2998                         sgmlOpenTag(ofs, 0, top);
2999                 }
3000         }
3001
3002         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
3003             << "\n  See http://www.lyx.org/ for more information -->\n";
3004
3005         while (par) {
3006                 int desc_on = 0; // description mode
3007                 LyXLayout const & style =
3008                         textclasslist.Style(params.textclass,
3009                                             par->layout);
3010
3011                 // environment tag closing
3012                 for( ; depth > par->depth; --depth) {
3013                         if(environment_inner[depth] != "!-- --") {
3014                                 item_name= "listitem";
3015                                 sgmlCloseTag(ofs, command_depth + depth,
3016                                              item_name);
3017                                 if( environment_inner[depth] == "varlistentry")
3018                                         sgmlCloseTag(ofs, depth+command_depth,
3019                                                      environment_inner[depth]);
3020                         }
3021                         sgmlCloseTag(ofs, depth + command_depth,
3022                                      environment_stack[depth]);
3023                         environment_stack[depth].erase();
3024                         environment_inner[depth].erase();
3025                 }
3026
3027                 if(depth == par->depth
3028                    && environment_stack[depth] != style.latexname()
3029                    && !environment_stack[depth].empty()) {
3030                         if(environment_inner[depth] != "!-- --") {
3031                                 item_name= "listitem";
3032                                 sgmlCloseTag(ofs, command_depth+depth,
3033                                              item_name);
3034                                 if( environment_inner[depth] == "varlistentry")
3035                                         sgmlCloseTag(ofs,
3036                                                      depth + command_depth,
3037                                                      environment_inner[depth]);
3038                         }
3039                         
3040                         sgmlCloseTag(ofs, depth + command_depth,
3041                                      environment_stack[depth]);
3042                         
3043                         environment_stack[depth].erase();
3044                         environment_inner[depth].erase();
3045                 }
3046
3047                 // Write opening SGML tags.
3048                 switch(style.latextype) {
3049                 case LATEX_PARAGRAPH:
3050                         if(style.latexname() != "dummy")
3051                                sgmlOpenTag(ofs, depth+command_depth,
3052                                            style.latexname());
3053                         break;
3054
3055                 case LATEX_COMMAND:
3056                         if (depth!= 0)
3057                                 LinuxDocError(par, 0,
3058                                               _("Error : Wrong depth for "
3059                                                 "LatexType Command.\n"));
3060                         
3061                         command_name = style.latexname();
3062                         
3063                         tmps = style.latexparam();
3064                         c_params = split(tmps, c_depth,'|');
3065                         
3066                         cmd_depth= lyx::atoi(c_depth);
3067                         
3068                         if(command_flag) {
3069                                 if(cmd_depth<command_base) {
3070                                         for(int j = command_depth;
3071                                             j >= command_base; --j)
3072                                                 if(!command_stack[j].empty())
3073                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3074                                         command_depth= command_base= cmd_depth;
3075                                 } else if(cmd_depth <= command_depth) {
3076                                         for(int j = command_depth;
3077                                             j >= cmd_depth; --j)
3078
3079                                                 if(!command_stack[j].empty())
3080                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3081                                         command_depth= cmd_depth;
3082                                 } else
3083                                         command_depth= cmd_depth;
3084                         } else {
3085                                 command_depth = command_base = cmd_depth;
3086                                 command_flag = true;
3087                         }
3088                         command_stack[command_depth]= command_name;
3089
3090                         // treat label as a special case for
3091                         // more WYSIWYM handling.
3092                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
3093                                 Inset * inset = par->GetInset(0);
3094                                 Inset::Code lyx_code = inset->LyxCode();
3095                                 if (lyx_code == Inset::LABEL_CODE){
3096                                         command_name += " id=\"";
3097                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3098                                         command_name += "\"";
3099                                         desc_on = 3;
3100                                 }
3101                         }
3102
3103                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3104                         item_name = "title";
3105                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3106                         break;
3107
3108                 case LATEX_ENVIRONMENT:
3109                 case LATEX_ITEM_ENVIRONMENT:
3110                         if (depth < par->depth) {
3111                                 depth = par->depth;
3112                                 environment_stack[depth].erase();
3113                         }
3114
3115                         if (environment_stack[depth] != style.latexname()) {
3116                                 environment_stack[depth] = style.latexname();
3117                                 environment_inner[depth] = "!-- --";
3118                                 sgmlOpenTag(ofs, depth + command_depth,
3119                                             environment_stack[depth]);
3120                         } else {
3121                                 if(environment_inner[depth] != "!-- --") {
3122                                         item_name= "listitem";
3123                                         sgmlCloseTag(ofs,
3124                                                      command_depth + depth,
3125                                                      item_name);
3126                                         if (environment_inner[depth] == "varlistentry")
3127                                                 sgmlCloseTag(ofs,
3128                                                              depth + command_depth,
3129                                                              environment_inner[depth]);
3130                                 }
3131                         }
3132                         
3133                         if(style.latextype == LATEX_ENVIRONMENT) {
3134                                 if(!style.latexparam().empty())
3135                                         sgmlOpenTag(ofs, depth + command_depth,
3136                                                     style.latexparam());
3137                                 break;
3138                         }
3139
3140                         desc_on = (style.labeltype == LABEL_MANUAL);
3141
3142                         if(desc_on)
3143                                 environment_inner[depth]= "varlistentry";
3144                         else
3145                                 environment_inner[depth]= "listitem";
3146
3147                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3148                                     environment_inner[depth]);
3149
3150                         if(desc_on) {
3151                                 item_name= "term";
3152                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3153                                             item_name);
3154                         } else {
3155                                 item_name= "para";
3156                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3157                                             item_name);
3158                         }
3159                         break;
3160                 default:
3161                         sgmlOpenTag(ofs, depth + command_depth,
3162                                     style.latexname());
3163                         break;
3164                 }
3165
3166 #ifndef NEW_INSETS
3167                 do {
3168 #endif
3169                         string extra_par;
3170                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3171                                             depth + 1 + command_depth);
3172                         par = par->next;
3173 #ifndef NEW_INSETS
3174                         DocBookHandleFootnote(ofs, par,
3175                                               depth + 1 + command_depth);
3176                 }
3177                 while(par && par->IsDummy());
3178 #endif
3179                 string end_tag;
3180                 // write closing SGML tags
3181                 switch(style.latextype) {
3182                 case LATEX_COMMAND:
3183                         end_tag = "title";
3184                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3185                         break;
3186                 case LATEX_ENVIRONMENT:
3187                         if(!style.latexparam().empty())
3188                                 sgmlCloseTag(ofs, depth + command_depth,
3189                                              style.latexparam());
3190                         break;
3191                 case LATEX_ITEM_ENVIRONMENT:
3192                         if(desc_on == 1) break;
3193                         end_tag= "para";
3194                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3195                         break;
3196                 case LATEX_PARAGRAPH:
3197                         if(style.latexname() != "dummy")
3198                                 sgmlCloseTag(ofs, depth + command_depth,
3199                                              style.latexname());
3200                         break;
3201                 default:
3202                         sgmlCloseTag(ofs, depth + command_depth,
3203                                      style.latexname());
3204                         break;
3205                 }
3206         }
3207
3208         // Close open tags
3209         for(; depth >= 0; --depth) {
3210                 if(!environment_stack[depth].empty()) {
3211                         if(environment_inner[depth] != "!-- --") {
3212                                 item_name= "listitem";
3213                                 sgmlCloseTag(ofs, command_depth + depth,
3214                                              item_name);
3215                                if( environment_inner[depth] == "varlistentry")
3216                                        sgmlCloseTag(ofs, depth + command_depth,
3217                                                     environment_inner[depth]);
3218                         }
3219                         
3220                         sgmlCloseTag(ofs, depth + command_depth,
3221                                      environment_stack[depth]);
3222                 }
3223         }
3224         
3225         for(int j = command_depth; j >= command_base; --j)
3226                 if(!command_stack[j].empty())
3227                         sgmlCloseTag(ofs, j, command_stack[j]);
3228
3229         if (!only_body) {
3230                 ofs << "\n\n";
3231                 sgmlCloseTag(ofs, 0, top_element);
3232         }
3233
3234         ofs.close();
3235         // How to check for successful close
3236 }
3237
3238
3239 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3240                                  LyXParagraph * par, int & desc_on,
3241                                  int depth) 
3242 {
3243         bool emph_flag = false;
3244
3245         LyXLayout const & style = textclasslist.Style(params.textclass,
3246                                                       par->GetLayout());
3247
3248         LyXParagraph::size_type main_body;
3249         if (style.labeltype != LABEL_MANUAL)
3250                 main_body = 0;
3251         else
3252                 main_body = par->BeginningOfMainBody();
3253
3254         // gets paragraph main font
3255         LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3256         
3257         int char_line_count = depth;
3258         if(!style.free_spacing)
3259                 for (int j = 0; j < depth; ++j)
3260                         os << ' ';
3261
3262         // parsing main loop
3263         for (LyXParagraph::size_type i = 0;
3264              i < par->size(); ++i) {
3265                 LyXFont font2 = par->getFont(params, i);
3266
3267                 // handle <emphasis> tag
3268                 if (font1.emph() != font2.emph() && i) {
3269                         if (font2.emph() == LyXFont::ON) {
3270                                 os << "<emphasis>";
3271                                 emph_flag = true;
3272                         }else {
3273                                 os << "</emphasis>";
3274                                 emph_flag = false;
3275                         }
3276                 }
3277       
3278                 char c = par->GetChar(i);
3279
3280                 if (c == LyXParagraph::META_INSET) {
3281                         Inset * inset = par->GetInset(i);
3282                         std::ostringstream ost;
3283                         inset->DocBook(this, ost);
3284                         string tmp_out = ost.str().c_str();
3285
3286                         //
3287                         // This code needs some explanation:
3288                         // Two insets are treated specially
3289                         //   label if it is the first element in a command paragraph
3290                         //         desc_on == 3
3291                         //   graphics inside tables or figure floats can't go on
3292                         //   title (the equivalente in latex for this case is caption
3293                         //   and title should come first
3294                         //         desc_on == 4
3295                         //
3296                         if(desc_on!= 3 || i!= 0) {
3297                                 if(!tmp_out.empty() && tmp_out[0] == '@') {
3298                                         if(desc_on == 4)
3299                                                 extra += frontStrip(tmp_out, '@');
3300                                         else
3301                                                 os << frontStrip(tmp_out, '@');
3302                                 }
3303                                 else
3304                                         os << tmp_out;
3305                         }
3306                 } else if (font2.latex() == LyXFont::ON) {
3307                         // "TeX"-Mode on ==> SGML-Mode on.
3308                         if (c != '\0')
3309                                 os << c;
3310                         ++char_line_count;
3311                 } else {
3312                         string sgml_string;
3313                         if (par->linuxDocConvertChar(c, sgml_string)
3314                             && !style.free_spacing) { // in freespacing
3315                                                      // mode, spaces are
3316                                                      // non-breaking characters
3317                                 // char is ' '
3318                                 if (desc_on == 1) {
3319                                         ++char_line_count;
3320                                         os << "\n</term><listitem><para>";
3321                                         desc_on = 2;
3322                                 } else {
3323                                         os << c;
3324                                 }
3325                         } else {
3326                                 os << sgml_string;
3327                         }
3328                 }
3329                 font1 = font2;
3330         }
3331
3332         // needed if there is an optional argument but no contents
3333         if (main_body > 0 && main_body == par->size()) {
3334                 font1 = style.font;
3335         }
3336         if (emph_flag) {
3337                 os << "</emphasis>";
3338         }
3339         
3340         // resets description flag correctly
3341         switch(desc_on){
3342         case 1:
3343                 // <term> not closed...
3344                 os << "</term>";
3345                 break;
3346         }
3347         os << '\n';
3348 }
3349
3350
3351 // This should be enabled when the Chktex class is implemented. (Asger)
3352 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3353 // Other flags: -wall -v0 -x
3354 int Buffer::runChktex()
3355 {
3356         if (!users->text) return 0;
3357
3358         ProhibitInput(users);
3359
3360         // get LaTeX-Filename
3361         string const name = getLatexName();
3362         string path = OnlyPath(filename);
3363
3364         string const org_path = path;
3365         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3366                 path = tmppath;  
3367         }
3368
3369         Path p(path); // path to LaTeX file
3370         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3371
3372         // Remove all error insets
3373         bool const removedErrorInsets = users->removeAutoInsets();
3374
3375         // Generate the LaTeX file if neccessary
3376         makeLaTeXFile(name, org_path, false);
3377
3378         TeXErrors terr;
3379         Chktex chktex(lyxrc.chktex_command, name, filepath);
3380         int res = chktex.run(terr); // run chktex
3381
3382         if (res == -1) {
3383                 WriteAlert(_("chktex did not work!"),
3384                            _("Could not run with file:"), name);
3385         } else if (res > 0) {
3386                 // Insert all errors as errors boxes
3387                 users->insertErrors(terr);
3388         }
3389
3390         // if we removed error insets before we ran chktex or if we inserted
3391         // error insets after we ran chktex, this must be run:
3392         if (removedErrorInsets || res){
3393                 users->redraw();
3394                 users->fitCursor(users->text);
3395         }
3396         AllowInput(users);
3397
3398         return res;
3399 }
3400
3401
3402 void Buffer::validate(LaTeXFeatures & features) const
3403 {
3404         LyXParagraph * par = paragraph;
3405         LyXTextClass const & tclass = 
3406                 textclasslist.TextClass(params.textclass);
3407     
3408         // AMS Style is at document level
3409     
3410         features.amsstyle = (params.use_amsmath ||
3411                              tclass.provides(LyXTextClass::amsmath));
3412     
3413         while (par) {
3414                 // We don't use "lyxerr.debug" because of speed. (Asger)
3415                 if (lyxerr.debugging(Debug::LATEX))
3416                         lyxerr << "Paragraph: " <<  par << endl;
3417
3418                 // Now just follow the list of paragraphs and run
3419                 // validate on each of them.
3420                 par->validate(features);
3421
3422                 // and then the next paragraph
3423                 par = par->next;
3424         }
3425
3426         // the bullet shapes are buffer level not paragraph level
3427         // so they are tested here
3428         for (int i = 0; i < 4; ++i) {
3429                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3430                         int const font = params.user_defined_bullets[i].getFont();
3431                         if (font == 0) {
3432                                 int const c = params
3433                                         .user_defined_bullets[i]
3434                                         .getCharacter();
3435                                 if (c == 16
3436                                    || c == 17
3437                                    || c == 25
3438                                    || c == 26
3439                                    || c == 31) {
3440                                         features.latexsym = true;
3441                                 }
3442                         } else if (font == 1) {
3443                                 features.amssymb = true;
3444                         } else if ((font >= 2 && font <= 5)) {
3445                                 features.pifont = true;
3446                         }
3447                 }
3448         }
3449         
3450         if (lyxerr.debugging(Debug::LATEX)) {
3451                 features.showStruct();
3452         }
3453 }
3454
3455
3456 void Buffer::setPaperStuff()
3457 {
3458         params.papersize = BufferParams::PAPER_DEFAULT;
3459         char const c1 = params.paperpackage;
3460         if (c1 == BufferParams::PACKAGE_NONE) {
3461                 char const c2 = params.papersize2;
3462                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3463                         params.papersize = BufferParams::PAPER_USLETTER;
3464                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3465                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3466                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3467                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3468                 else if (c2 == BufferParams::VM_PAPER_A3)
3469                         params.papersize = BufferParams::PAPER_A3PAPER;
3470                 else if (c2 == BufferParams::VM_PAPER_A4)
3471                         params.papersize = BufferParams::PAPER_A4PAPER;
3472                 else if (c2 == BufferParams::VM_PAPER_A5)
3473                         params.papersize = BufferParams::PAPER_A5PAPER;
3474                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3475                          (c2 == BufferParams::VM_PAPER_B5))
3476                         params.papersize = BufferParams::PAPER_B5PAPER;
3477         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3478                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3479                 params.papersize = BufferParams::PAPER_A4PAPER;
3480 }
3481
3482
3483 // This function should be in Buffer because it's a buffer's property (ale)
3484 string const Buffer::getIncludeonlyList(char delim)
3485 {
3486         string lst;
3487         for (inset_iterator it = inset_iterator_begin();
3488             it != inset_iterator_end(); ++it) {
3489                 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3490                         InsetInclude * insetinc = 
3491                                 static_cast<InsetInclude *>(*it);
3492                         if (insetinc->isInclude() 
3493                             && insetinc->isNoLoad()) {
3494                                 if (!lst.empty())
3495                                         lst += delim;
3496                                 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3497                         }
3498                 }
3499         }
3500         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3501         return lst;
3502 }
3503
3504
3505 vector<string> const Buffer::getLabelList()
3506 {
3507         /// if this is a child document and the parent is already loaded
3508         /// Use the parent's list instead  [ale990407]
3509         if (!params.parentname.empty()
3510             && bufferlist.exists(params.parentname)) {
3511                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3512                 if (tmp)
3513                         return tmp->getLabelList();
3514         }
3515
3516         vector<string> label_list;
3517         for (inset_iterator it = inset_iterator_begin();
3518              it != inset_iterator_end(); ++it) {
3519                 vector<string> const l = (*it)->getLabelList();
3520                 label_list.insert(label_list.end(), l.begin(), l.end());
3521         }
3522         return label_list;
3523 }
3524
3525
3526 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3527 {
3528         vector<vector<TocItem> > l(4);
3529         LyXParagraph * par = paragraph;
3530         while (par) {
3531 #ifndef NEW_INSETS
3532                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3533                         if (textclasslist.Style(params.textclass, 
3534                                                 par->GetLayout()).labeltype
3535                             == LABEL_SENSITIVE) {
3536                                 TocItem tmp;
3537                                 tmp.par = par;
3538                                 tmp.depth = 0;
3539                                 tmp.str =  par->String(this, false);
3540                                 switch (par->footnotekind) {
3541                                 case LyXParagraph::FIG:
3542                                 case LyXParagraph::WIDE_FIG:
3543                                         l[TOC_LOF].push_back(tmp);
3544                                         break;
3545                                 case LyXParagraph::TAB:
3546                                 case LyXParagraph::WIDE_TAB:
3547                                         l[TOC_LOT].push_back(tmp);
3548                                         break;
3549                                 case LyXParagraph::ALGORITHM:
3550                                         l[TOC_LOA].push_back(tmp);
3551                                         break;
3552                                 case LyXParagraph::FOOTNOTE:
3553                                 case LyXParagraph::MARGIN:
3554                                         break;
3555                                 }
3556                         }
3557                 } else if (!par->IsDummy()) {
3558 #endif
3559                         char const labeltype =
3560                                 textclasslist.Style(params.textclass, 
3561                                                     par->GetLayout()).labeltype;
3562       
3563                         if (labeltype >= LABEL_COUNTER_CHAPTER
3564                             && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3565                                 // insert this into the table of contents
3566                                 TocItem tmp;
3567                                 tmp.par = par;
3568                                 tmp.depth = max(0,
3569                                                 labeltype - 
3570                                                 textclasslist.TextClass(params.textclass).maxcounter());
3571                                 tmp.str =  par->String(this, true);
3572                                 l[TOC_TOC].push_back(tmp);
3573                         }
3574 #ifndef NEW_INSETS
3575                 }
3576 #endif
3577                 par = par->next;
3578         }
3579         return l;
3580 }
3581
3582
3583 // This is also a buffer property (ale)
3584 vector<pair<string,string> > const Buffer::getBibkeyList()
3585 {
3586         /// if this is a child document and the parent is already loaded
3587         /// Use the parent's list instead  [ale990412]
3588         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3589                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3590                 if (tmp)
3591                         return tmp->getBibkeyList();
3592         }
3593
3594         vector<pair<string, string> > keys;
3595         LyXParagraph * par = paragraph;
3596         while (par) {
3597                 if (par->bibkey)
3598                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3599                                                            par->String(this, false)));
3600                 par = par->next;
3601         }
3602
3603         // Might be either using bibtex or a child has bibliography
3604         if (keys.empty()) {
3605                 for (inset_iterator it = inset_iterator_begin();
3606                         it != inset_iterator_end(); ++it) {
3607                         // Search for Bibtex or Include inset
3608                         if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3609                                 vector<pair<string,string> > tmp =
3610                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3611                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3612                         } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3613                                 vector<pair<string,string> > const tmp =
3614                                         static_cast<InsetInclude*>(*it)->getKeys();
3615                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3616                         }
3617                 }
3618         }
3619  
3620         return keys;
3621 }
3622
3623
3624 bool Buffer::isDepClean(string const & name) const
3625 {
3626         DEPCLEAN * item = dep_clean;
3627         while (item && item->master != name)
3628                 item = item->next;
3629         if (!item) return true;
3630         return item->clean;
3631 }
3632
3633
3634 void Buffer::markDepClean(string const & name)
3635 {
3636         if (!dep_clean) {
3637                 dep_clean = new DEPCLEAN;
3638                 dep_clean->clean = true;
3639                 dep_clean->master = name;
3640                 dep_clean->next = 0;
3641         } else {
3642                 DEPCLEAN * item = dep_clean;
3643                 while (item && item->master != name)
3644                         item = item->next;
3645                 if (item) {
3646                         item->clean = true;
3647                 } else {
3648                         item = new DEPCLEAN;
3649                         item->clean = true;
3650                         item->master = name;
3651                         item->next = 0;
3652                 }
3653         }
3654 }
3655
3656
3657 bool Buffer::Dispatch(string const & command)
3658 {
3659         // Split command string into command and argument
3660         string cmd;
3661         string line = frontStrip(command);
3662         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3663
3664         return Dispatch(lyxaction.LookupFunc(cmd), arg);
3665 }
3666
3667
3668 bool Buffer::Dispatch(int action, string const & argument)
3669 {
3670         bool dispatched = true;
3671         switch (action) {
3672                 case LFUN_EXPORT: 
3673                         Exporter::Export(this, argument, false);
3674                         break;
3675
3676                 default:
3677                         dispatched = false;
3678         }
3679         return dispatched;
3680 }
3681
3682
3683 void Buffer::resize()
3684 {
3685         /// resize the BufferViews!
3686         if (users)
3687                 users->resize();
3688 }
3689
3690
3691 void Buffer::resizeInsets(BufferView * bv)
3692 {
3693         /// then remove all LyXText in text-insets
3694         LyXParagraph * par = paragraph;
3695         for(; par; par = par->next) {
3696             par->resizeInsetsLyXText(bv);
3697         }
3698 }
3699
3700 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3701 {
3702
3703         LyXParagraph * par = paragraph;
3704         while (par) {
3705                 par->ChangeLanguage(params, from, to);
3706                 par = par->next;
3707         }
3708 }
3709
3710
3711 bool Buffer::isMultiLingual()
3712 {
3713         LyXParagraph * par = paragraph;
3714         while (par) {
3715                 if (par->isMultiLingual(params))
3716                         return true;
3717                 par = par->next;
3718         }
3719         return false;
3720 }
3721
3722
3723 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3724                                        LyXParagraph::size_type pos)
3725         : par(paragraph)
3726 {
3727         it = par->InsetIterator(pos);
3728         if (it == par->inset_iterator_end()) {
3729                 par = par->next;
3730                 SetParagraph();
3731         }
3732 }
3733
3734
3735 void Buffer::inset_iterator::SetParagraph()
3736 {
3737         while (par) {
3738                 it = par->inset_iterator_begin();
3739                 if (it != par->inset_iterator_end())
3740                         return;
3741                 par = par->next;
3742         }
3743         //it = 0;
3744         // We maintain an invariant that whenever par = 0 then it = 0
3745 }