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