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