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