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