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