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