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