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