1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
23 #include <sys/types.h>
33 #pragma implementation "buffer.h"
37 #include "bufferlist.h"
39 #include "lyx_gui_misc.h"
40 #include "LyXAction.h"
43 #include "tex-strings.h"
45 #include "bufferview_funcs.h"
46 #include "minibuffer.h"
49 #include "mathed/formulamacro.h"
50 #include "insets/lyxinset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insetlabel.h"
53 #include "insets/insetref.h"
54 #include "insets/inseturl.h"
55 #include "insets/insetinfo.h"
56 #include "insets/insetquotes.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetbib.h"
59 #include "insets/insetcite.h"
60 #include "insets/insetexternal.h"
61 #include "insets/insetindex.h"
62 #include "insets/insetinclude.h"
63 #include "insets/insettoc.h"
64 #include "insets/insetparent.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/figinset.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetminipage.h"
73 #include "insets/insetfloat.h"
74 #include "insets/insetlist.h"
75 #include "insets/insettabular.h"
76 #include "insets/insettheorem.h"
77 #include "insets/insetcaption.h"
78 #include "support/filetools.h"
79 #include "support/path.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "support/lyxmanip.h"
92 #include "lyx_gui_misc.h" // WarnReadonly()
93 #include "frontends/Dialogs.h"
97 #include "converter.h"
107 using std::make_pair;
112 // all these externs should eventually be removed.
113 extern BufferList bufferlist;
115 extern LyXAction lyxaction;
119 static const float LYX_FORMAT = 2.17;
121 static const int LYX_FORMAT = 218;
124 extern int tex_code_break_column;
127 Buffer::Buffer(string const & file, bool ronly)
129 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
131 filepath = OnlyPath(file);
140 if (read_only || (lyxrc.use_tempdir)) {
141 tmppath = CreateBufferTmpDir();
142 } else tmppath.erase();
148 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
149 // here the buffer should take care that it is
150 // saved properly, before it goes into the void.
152 // make sure that views using this buffer
157 if (!tmppath.empty()) {
158 DestroyBufferTmpDir(tmppath);
161 LyXParagraph * par = paragraph;
162 LyXParagraph * tmppar;
172 string const Buffer::getLatexName(bool no_path) const
175 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
178 return ChangeExtension(MakeLatexName(filename),
182 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
184 string filename, fname, bname, path;
186 filename = getLatexName(false);
188 if (filename.empty())
189 return make_pair(Buffer::latexlog, string());
191 path = OnlyPath(filename);
193 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
196 fname = AddName(path, OnlyFilename(ChangeExtension(filename, ".log")));
197 bname = AddName(path, OnlyFilename(ChangeExtension(filename,
198 formats.Extension("literate") + ".out")));
200 // If no Latex log or Build log is newer, show Build log
202 FileInfo f_fi(fname), b_fi(bname);
205 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
206 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
207 return make_pair(Buffer::buildlog, bname);
209 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
210 return make_pair(Buffer::latexlog, fname);
213 void Buffer::setReadonly(bool flag)
215 if (read_only != flag) {
218 users->owner()->getDialogs()->updateBufferDependent(false);
221 WarnReadonly(filename);
226 bool Buffer::saveParamsAsDefaults() // const
228 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
230 Buffer defaults = Buffer(fname);
232 // Use the current buffer's parameters as default
233 defaults.params = params;
235 // add an empty paragraph. Is this enough?
236 defaults.paragraph = new LyXParagraph;
238 return defaults.writeFile(defaults.filename, false);
242 /// Update window titles of all users
243 // Should work on a list
244 void Buffer::updateTitles() const
246 if (users) users->owner()->updateWindowTitle();
250 /// Reset autosave timer of all users
251 // Should work on a list
252 void Buffer::resetAutosaveTimers() const
254 if (users) users->owner()->resetAutosaveTimer();
258 void Buffer::setFileName(string const & newfile)
260 filename = MakeAbsPath(newfile);
261 filepath = OnlyPath(filename);
262 setReadonly(IsFileWriteable(filename) == 0);
267 // candidate for move to BufferView
268 // (at least some parts in the beginning of the func)
271 // changed to be public and have one parameter
272 // if par = 0 normal behavior
273 // else insert behavior
274 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
275 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
278 char depth = 0; // signed or unsigned?
280 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
281 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
283 bool the_end_read = false;
285 LyXParagraph * return_par = 0;
286 LyXFont font(LyXFont::ALL_INHERIT, params.language);
288 if (format < 2.16 && params.language->lang() == "hebrew")
289 font.setLanguage(default_language);
291 if (file_format < 216 && params.language->lang() == "hebrew")
292 font.setLanguage(default_language);
294 // If we are inserting, we cheat and get a token in advance
295 bool has_token = false;
299 par = new LyXParagraph;
301 users->text->BreakParagraph(users);
302 return_par = users->text->FirstParagraph();
305 // We don't want to adopt the parameters from the
306 // document we insert, so we skip until the text begins:
309 pretoken = lex.GetString();
310 if (pretoken == "\\layout") {
322 pretoken = lex.GetString();
325 if (pretoken.empty()) continue;
328 parseSingleLyXformat2Token(lex, par, return_par,
329 pretoken, pos, depth,
341 paragraph = return_par;
347 // We'll remove this later. (Lgb)
348 static string last_inset_read;
352 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
353 LyXParagraph *& return_par,
354 string const & token, int & pos,
355 char & depth, LyXFont & font
357 , LyXParagraph::footnote_flag & footnoteflag,
358 LyXParagraph::footnote_kind & footnotekind
362 bool the_end_read = false;
364 if (token[0] != '\\') {
365 for (string::const_iterator cit = token.begin();
366 cit != token.end(); ++cit) {
367 par->InsertChar(pos, (*cit), font);
370 } else if (token == "\\i") {
371 Inset * inset = new InsetLatexAccent;
372 inset->Read(this, lex);
373 par->InsertInset(pos, inset, font);
375 } else if (token == "\\layout") {
380 par = new LyXParagraph(par);
384 string const layoutname = lex.GetString();
385 pair<bool, LyXTextClass::LayoutList::size_type> pp
386 = textclasslist.NumberOfLayout(params.textclass,
389 par->layout = pp.second;
390 } else { // layout not found
391 // use default layout "Standard" (0)
394 // Test whether the layout is obsolete.
395 LyXLayout const & layout =
396 textclasslist.Style(params.textclass,
398 if (!layout.obsoleted_by().empty())
400 textclasslist.NumberOfLayout(params.textclass,
401 layout.obsoleted_by()).second;
403 par->footnoteflag = footnoteflag;
404 par->footnotekind = footnotekind;
407 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
409 if (format < 2.16 && params.language->lang() == "hebrew")
410 font.setLanguage(default_language);
412 if (file_format < 216 && params.language->lang() == "hebrew")
413 font.setLanguage(default_language);
416 } else if (token == "\\end_float") {
421 par = new LyXParagraph(par);
423 footnotekind = LyXParagraph::FOOTNOTE;
424 footnoteflag = LyXParagraph::NO_FOOTNOTE;
427 par->layout = LYX_DUMMY_LAYOUT;
428 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
430 if (format < 2.16 && params.language->lang() == "hebrew")
431 font.setLanguage(default_language);
433 if (file_format < 216 && params.language->lang() == "hebrew")
434 font.setLanguage(default_language);
436 } else if (token == "\\begin_float") {
437 int tmpret = lex.FindToken(string_footnotekinds);
438 if (tmpret == -1) ++tmpret;
439 if (tmpret != LYX_LAYOUT_DEFAULT)
440 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
441 if (footnotekind == LyXParagraph::FOOTNOTE
442 || footnotekind == LyXParagraph::MARGIN)
443 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
445 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
447 } else if (token == "\\begin_float") {
448 // This is the compability reader, unfinished but tested.
451 string const tmptok = lex.GetString();
452 //lyxerr << "old float: " << tmptok << endl;
457 if (tmptok == "footnote") {
458 inset = new InsetFoot;
459 } else if (tmptok == "margin") {
460 inset = new InsetMarginal;
461 } else if (tmptok == "fig") {
462 inset = new InsetFloat("figure");
463 old_float += "placement htbp\n";
464 } else if (tmptok == "tab") {
465 inset = new InsetFloat("table");
466 old_float += "placement htbp\n";
467 } else if (tmptok == "alg") {
468 inset = new InsetFloat("algorithm");
469 old_float += "placement htbp\n";
470 } else if (tmptok == "wide-fig") {
471 InsetFloat * tmp = new InsetFloat("figure");
474 old_float += "placement htbp\n";
475 } else if (tmptok == "wide-tab") {
476 InsetFloat * tmp = new InsetFloat("table");
479 old_float += "placement htbp\n";
482 if (!inset) return false; // no end read yet
484 old_float += "collapsed true\n";
486 // Here we need to check for \end_deeper and handle that
487 // before we do the footnote parsing.
488 // This _is_ a hack! (Lgb)
491 string const tmp = lex.GetString();
492 if (tmp == "\\end_deeper") {
493 lyxerr << "\\end_deeper caught!" << endl;
495 lex.printError("\\end_deeper: "
496 "depth is already null");
507 old_float += lex.getLongString("\\end_float");
508 old_float += "\n\\end_inset\n";
509 //lyxerr << "float body: " << old_float << endl;
511 istringstream istr(old_float);
514 nylex.setStream(istr);
516 inset->Read(this, nylex);
517 par->InsertInset(pos, inset, font);
520 } else if (token == "\\begin_deeper") {
522 } else if (token == "\\end_deeper") {
524 lex.printError("\\end_deeper: "
525 "depth is already null");
529 } else if (token == "\\begin_preamble") {
530 params.readPreamble(lex);
531 } else if (token == "\\textclass") {
533 pair<bool, LyXTextClassList::size_type> pp =
534 textclasslist.NumberOfClass(lex.GetString());
536 params.textclass = pp.second;
538 WriteAlert(string(_("Textclass error")),
539 string(_("The document uses an unknown textclass \"")) +
540 lex.GetString() + string("\"."),
541 string(_("LyX will not be able to produce output correctly.")));
542 params.textclass = 0;
544 if (!textclasslist.Load(params.textclass)) {
545 // if the textclass wasn't loaded properly
546 // we need to either substitute another
547 // or stop loading the file.
548 // I can substitute but I don't see how I can
549 // stop loading... ideas?? ARRae980418
550 WriteAlert(_("Textclass Loading Error!"),
551 string(_("Can't load textclass ")) +
552 textclasslist.NameOfClass(params.textclass),
553 _("-- substituting default"));
554 params.textclass = 0;
556 } else if (token == "\\options") {
558 params.options = lex.GetString();
559 } else if (token == "\\language") {
560 params.readLanguage(lex);
561 } else if (token == "\\fontencoding") {
563 } else if (token == "\\inputencoding") {
565 params.inputenc = lex.GetString();
566 } else if (token == "\\graphics") {
567 params.readGraphicsDriver(lex);
568 } else if (token == "\\fontscheme") {
570 params.fonts = lex.GetString();
571 } else if (token == "\\noindent") {
572 par->noindent = true;
573 } else if (token == "\\fill_top") {
574 par->added_space_top = VSpace(VSpace::VFILL);
575 } else if (token == "\\fill_bottom") {
576 par->added_space_bottom = VSpace(VSpace::VFILL);
577 } else if (token == "\\line_top") {
578 par->line_top = true;
579 } else if (token == "\\line_bottom") {
580 par->line_bottom = true;
581 } else if (token == "\\pagebreak_top") {
582 par->pagebreak_top = true;
583 } else if (token == "\\pagebreak_bottom") {
584 par->pagebreak_bottom = true;
585 } else if (token == "\\start_of_appendix") {
586 par->start_of_appendix = true;
587 } else if (token == "\\paragraph_separation") {
588 int tmpret = lex.FindToken(string_paragraph_separation);
589 if (tmpret == -1) ++tmpret;
590 if (tmpret != LYX_LAYOUT_DEFAULT)
591 params.paragraph_separation =
592 static_cast<BufferParams::PARSEP>(tmpret);
593 } else if (token == "\\defskip") {
595 params.defskip = VSpace(lex.GetString());
596 } else if (token == "\\epsfig") { // obsolete
597 // Indeed it is obsolete, but we HAVE to be backwards
598 // compatible until 0.14, because otherwise all figures
599 // in existing documents are irretrivably lost. (Asger)
600 params.readGraphicsDriver(lex);
601 } else if (token == "\\quotes_language") {
602 int tmpret = lex.FindToken(string_quotes_language);
603 if (tmpret == -1) ++tmpret;
604 if (tmpret != LYX_LAYOUT_DEFAULT) {
605 InsetQuotes::quote_language tmpl =
606 InsetQuotes::EnglishQ;
609 tmpl = InsetQuotes::EnglishQ;
612 tmpl = InsetQuotes::SwedishQ;
615 tmpl = InsetQuotes::GermanQ;
618 tmpl = InsetQuotes::PolishQ;
621 tmpl = InsetQuotes::FrenchQ;
624 tmpl = InsetQuotes::DanishQ;
627 params.quotes_language = tmpl;
629 } else if (token == "\\quotes_times") {
631 switch (lex.GetInteger()) {
633 params.quotes_times = InsetQuotes::SingleQ;
636 params.quotes_times = InsetQuotes::DoubleQ;
639 } else if (token == "\\papersize") {
640 int tmpret = lex.FindToken(string_papersize);
644 params.papersize2 = tmpret;
645 } else if (token == "\\paperpackage") {
646 int tmpret = lex.FindToken(string_paperpackages);
649 params.paperpackage = BufferParams::PACKAGE_NONE;
651 params.paperpackage = tmpret;
652 } else if (token == "\\use_geometry") {
654 params.use_geometry = lex.GetInteger();
655 } else if (token == "\\use_amsmath") {
657 params.use_amsmath = lex.GetInteger();
658 } else if (token == "\\paperorientation") {
659 int tmpret = lex.FindToken(string_orientation);
660 if (tmpret == -1) ++tmpret;
661 if (tmpret != LYX_LAYOUT_DEFAULT)
662 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
663 } else if (token == "\\paperwidth") {
665 params.paperwidth = lex.GetString();
666 } else if (token == "\\paperheight") {
668 params.paperheight = lex.GetString();
669 } else if (token == "\\leftmargin") {
671 params.leftmargin = lex.GetString();
672 } else if (token == "\\topmargin") {
674 params.topmargin = lex.GetString();
675 } else if (token == "\\rightmargin") {
677 params.rightmargin = lex.GetString();
678 } else if (token == "\\bottommargin") {
680 params.bottommargin = lex.GetString();
681 } else if (token == "\\headheight") {
683 params.headheight = lex.GetString();
684 } else if (token == "\\headsep") {
686 params.headsep = lex.GetString();
687 } else if (token == "\\footskip") {
689 params.footskip = lex.GetString();
690 } else if (token == "\\paperfontsize") {
692 params.fontsize = strip(lex.GetString());
693 } else if (token == "\\papercolumns") {
695 params.columns = lex.GetInteger();
696 } else if (token == "\\papersides") {
698 switch (lex.GetInteger()) {
700 case 1: params.sides = LyXTextClass::OneSide; break;
701 case 2: params.sides = LyXTextClass::TwoSides; break;
703 } else if (token == "\\paperpagestyle") {
705 params.pagestyle = strip(lex.GetString());
706 } else if (token == "\\bullet") {
708 int const index = lex.GetInteger();
710 int temp_int = lex.GetInteger();
711 params.user_defined_bullets[index].setFont(temp_int);
712 params.temp_bullets[index].setFont(temp_int);
714 temp_int = lex.GetInteger();
715 params.user_defined_bullets[index].setCharacter(temp_int);
716 params.temp_bullets[index].setCharacter(temp_int);
718 temp_int = lex.GetInteger();
719 params.user_defined_bullets[index].setSize(temp_int);
720 params.temp_bullets[index].setSize(temp_int);
722 string const temp_str = lex.GetString();
723 if (temp_str != "\\end_bullet") {
724 // this element isn't really necessary for
725 // parsing but is easier for humans
726 // to understand bullets. Put it back and
727 // set a debug message?
728 lex.printError("\\end_bullet expected, got" + temp_str);
729 //how can I put it back?
731 } else if (token == "\\bulletLaTeX") {
733 int const index = lex.GetInteger();
735 string temp_str = lex.GetString();
737 while (temp_str != "\\end_bullet") {
738 // this loop structure is needed when user
739 // enters an empty string since the first
740 // thing returned will be the \\end_bullet
742 // if the LaTeX entry has spaces. Each element
743 // therefore needs to be read in turn
746 temp_str = lex.GetString();
748 params.user_defined_bullets[index].setText(sum_str);
749 params.temp_bullets[index].setText(sum_str);
750 } else if (token == "\\secnumdepth") {
752 params.secnumdepth = lex.GetInteger();
753 } else if (token == "\\tocdepth") {
755 params.tocdepth = lex.GetInteger();
756 } else if (token == "\\spacing") {
758 string const tmp = strip(lex.GetString());
759 Spacing::Space tmp_space = Spacing::Default;
761 if (tmp == "single") {
762 tmp_space = Spacing::Single;
763 } else if (tmp == "onehalf") {
764 tmp_space = Spacing::Onehalf;
765 } else if (tmp == "double") {
766 tmp_space = Spacing::Double;
767 } else if (tmp == "other") {
769 tmp_space = Spacing::Other;
770 tmp_val = lex.GetFloat();
772 lex.printError("Unknown spacing token: '$$Token'");
774 // Small hack so that files written with klyx will be
777 par->spacing.set(tmp_space, tmp_val);
779 params.spacing.set(tmp_space, tmp_val);
781 } else if (token == "\\paragraph_spacing") {
783 string const tmp = strip(lex.GetString());
784 if (tmp == "single") {
785 par->spacing.set(Spacing::Single);
786 } else if (tmp == "onehalf") {
787 par->spacing.set(Spacing::Onehalf);
788 } else if (tmp == "double") {
789 par->spacing.set(Spacing::Double);
790 } else if (tmp == "other") {
792 par->spacing.set(Spacing::Other,
795 lex.printError("Unknown spacing token: '$$Token'");
797 } else if (token == "\\float_placement") {
799 params.float_placement = lex.GetString();
800 } else if (token == "\\family") {
802 font.setLyXFamily(lex.GetString());
803 } else if (token == "\\series") {
805 font.setLyXSeries(lex.GetString());
806 } else if (token == "\\shape") {
808 font.setLyXShape(lex.GetString());
809 } else if (token == "\\size") {
811 font.setLyXSize(lex.GetString());
812 } else if (token == "\\latex") {
814 string const tok = lex.GetString();
815 // This is dirty, but gone with LyX3. (Asger)
816 if (tok == "no_latex")
817 font.setLatex(LyXFont::OFF);
818 else if (tok == "latex")
819 font.setLatex(LyXFont::ON);
820 else if (tok == "default")
821 font.setLatex(LyXFont::INHERIT);
823 lex.printError("Unknown LaTeX font flag "
825 } else if (token == "\\lang") {
827 string const tok = lex.GetString();
828 Language const * lang = languages.getLanguage(tok);
830 font.setLanguage(lang);
832 font.setLanguage(params.language);
833 lex.printError("Unknown language `$$Token'");
835 } else if (token == "\\numeric") {
837 font.setNumber(font.setLyXMisc(lex.GetString()));
838 } else if (token == "\\emph") {
840 font.setEmph(font.setLyXMisc(lex.GetString()));
841 } else if (token == "\\bar") {
843 string const tok = lex.GetString();
844 // This is dirty, but gone with LyX3. (Asger)
846 font.setUnderbar(LyXFont::ON);
847 else if (tok == "no")
848 font.setUnderbar(LyXFont::OFF);
849 else if (tok == "default")
850 font.setUnderbar(LyXFont::INHERIT);
852 lex.printError("Unknown bar font flag "
854 } else if (token == "\\noun") {
856 font.setNoun(font.setLyXMisc(lex.GetString()));
857 } else if (token == "\\color") {
859 font.setLyXColor(lex.GetString());
860 } else if (token == "\\align") {
861 int tmpret = lex.FindToken(string_align);
862 if (tmpret == -1) ++tmpret;
863 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
866 for (; tmpret > 0; --tmpret)
867 tmpret2 = tmpret2 * 2;
869 int const tmpret2 = int(pow(2.0, tmpret));
871 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
872 par->align = LyXAlignment(tmpret2);
874 } else if (token == "\\added_space_top") {
876 par->added_space_top = VSpace(lex.GetString());
877 } else if (token == "\\added_space_bottom") {
879 par->added_space_bottom = VSpace(lex.GetString());
880 } else if (token == "\\pextra_type") {
882 par->pextra_type = lex.GetInteger();
883 } else if (token == "\\pextra_width") {
885 par->pextra_width = lex.GetString();
886 } else if (token == "\\pextra_widthp") {
888 par->pextra_widthp = lex.GetString();
889 } else if (token == "\\pextra_alignment") {
891 par->pextra_alignment = lex.GetInteger();
892 } else if (token == "\\pextra_hfill") {
894 par->pextra_hfill = lex.GetInteger();
895 } else if (token == "\\pextra_start_minipage") {
897 par->pextra_start_minipage = lex.GetInteger();
898 } else if (token == "\\labelwidthstring") {
900 par->labelwidthstring = lex.GetString();
901 // do not delete this token, it is still needed!
902 } else if (token == "\\end_inset") {
903 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
904 << "Last inset read was: " << last_inset_read
906 // Simply ignore this. The insets do not have
908 // But insets should read it, it is a part of
909 // the inset isn't it? Lgb.
910 } else if (token == "\\begin_inset") {
911 readInset(lex, par, pos, font);
912 } else if (token == "\\SpecialChar") {
913 LyXLayout const & layout =
914 textclasslist.Style(params.textclass,
917 // Insets don't make sense in a free-spacing context! ---Kayvan
918 if (layout.free_spacing) {
921 string next_token = lex.GetString();
922 if (next_token == "\\-") {
923 par->InsertChar(pos, '-', font);
924 } else if (next_token == "\\protected_separator"
925 || next_token == "~") {
926 par->InsertChar(pos, ' ', font);
928 lex.printError("Token `$$Token' "
930 "paragraph layout!");
935 Inset * inset = new InsetSpecialChar;
936 inset->Read(this, lex);
937 par->InsertInset(pos, inset, font);
940 } else if (token == "\\newline") {
941 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
943 } else if (token == "\\LyXTable") {
944 Inset * inset = new InsetTabular(*this);
945 inset->Read(this, lex);
946 par->InsertInset(pos, inset, font);
948 } else if (token == "\\hfill") {
949 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
951 } else if (token == "\\protected_separator") { // obsolete
952 // This is a backward compability thingie. (Lgb)
953 // Remove it later some time...introduced with fileformat
955 LyXLayout const & layout =
956 textclasslist.Style(params.textclass,
959 if (layout.free_spacing) {
960 par->InsertChar(pos, ' ', font);
962 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
963 par->InsertInset(pos, inset, font);
966 } else if (token == "\\bibitem") { // ale970302
968 InsetCommandParams p("bibitem", "dummy");
969 par->bibkey = new InsetBibKey(p);
971 par->bibkey->Read(this, lex);
972 } else if (token == "\\backslash") {
973 par->InsertChar(pos, '\\', font);
975 } else if (token == "\\the_end") {
978 // This should be insurance for the future: (Asger)
979 lex.printError("Unknown token `$$Token'. "
980 "Inserting as text.");
981 string::const_iterator cit = token.begin();
982 string::const_iterator end = token.end();
983 for (; cit != end; ++cit) {
984 par->InsertChar(pos, (*cit), font);
992 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
993 int & pos, LyXFont & font)
996 if (lex.GetString() != "\\begin_inset") {
997 lyxerr << "Buffer::readInset: Consistency check failed."
1004 string const tmptok = lex.GetString();
1005 last_inset_read = tmptok;
1007 // test the different insets
1008 if (tmptok == "LatexCommand") {
1009 InsetCommandParams inscmd;
1012 if (inscmd.getCmdName() == "cite") {
1013 inset = new InsetCitation(inscmd);
1014 } else if (inscmd.getCmdName() == "bibitem") {
1015 lex.printError("Wrong place for bibitem");
1016 inset = new InsetBibKey(inscmd);
1017 } else if (inscmd.getCmdName() == "BibTeX") {
1018 inset = new InsetBibtex(inscmd);
1019 } else if (inscmd.getCmdName() == "index") {
1020 inset = new InsetIndex(inscmd);
1021 } else if (inscmd.getCmdName() == "include") {
1022 inset = new InsetInclude(inscmd, *this);
1023 } else if (inscmd.getCmdName() == "label") {
1024 inset = new InsetLabel(inscmd);
1025 } else if (inscmd.getCmdName() == "url"
1026 || inscmd.getCmdName() == "htmlurl") {
1027 inset = new InsetUrl(inscmd);
1028 } else if (inscmd.getCmdName() == "ref"
1029 || inscmd.getCmdName() == "pageref"
1030 || inscmd.getCmdName() == "vref"
1031 || inscmd.getCmdName() == "vpageref"
1032 || inscmd.getCmdName() == "prettyref") {
1033 if (!inscmd.getOptions().empty()
1034 || !inscmd.getContents().empty()) {
1035 inset = new InsetRef(inscmd, *this);
1037 } else if (inscmd.getCmdName() == "tableofcontents"
1038 || inscmd.getCmdName() == "listofalgorithms"
1039 || inscmd.getCmdName() == "listoffigures"
1040 || inscmd.getCmdName() == "listoftables") {
1041 inset = new InsetTOC(inscmd);
1042 } else if (inscmd.getCmdName() == "printindex") {
1043 inset = new InsetPrintIndex(inscmd);
1044 } else if (inscmd.getCmdName() == "lyxparent") {
1045 inset = new InsetParent(inscmd, *this);
1048 if (tmptok == "Quotes") {
1049 inset = new InsetQuotes;
1050 } else if (tmptok == "External") {
1051 inset = new InsetExternal;
1052 } else if (tmptok == "FormulaMacro") {
1053 inset = new InsetFormulaMacro;
1054 } else if (tmptok == "Formula") {
1055 inset = new InsetFormula;
1056 } else if (tmptok == "Figure") {
1057 inset = new InsetFig(100, 100, *this);
1058 } else if (tmptok == "Info") {
1059 inset = new InsetInfo;
1060 } else if (tmptok == "Include") {
1061 InsetCommandParams p( "Include" );
1062 inset = new InsetInclude(p, *this);
1063 } else if (tmptok == "ERT") {
1064 inset = new InsetERT;
1065 } else if (tmptok == "Tabular") {
1066 inset = new InsetTabular(*this);
1067 } else if (tmptok == "Text") {
1068 inset = new InsetText;
1069 } else if (tmptok == "Foot") {
1070 inset = new InsetFoot;
1071 } else if (tmptok == "Marginal") {
1072 inset = new InsetMarginal;
1073 } else if (tmptok == "Minipage") {
1074 inset = new InsetMinipage;
1075 } else if (tmptok == "Float") {
1077 string tmptok = lex.GetString();
1078 inset = new InsetFloat(tmptok);
1079 } else if (tmptok == "List") {
1080 inset = new InsetList;
1081 } else if (tmptok == "Theorem") {
1082 inset = new InsetList;
1083 } else if (tmptok == "Caption") {
1084 inset = new InsetCaption;
1085 } else if (tmptok == "GRAPHICS") {
1086 inset = new InsetGraphics;
1089 if (inset) inset->Read(this, lex);
1093 par->InsertInset(pos, inset, font);
1099 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1103 string const token(lex.GetString());
1104 if (token == "\\lyxformat") { // the first token _must_ be...
1107 format = lex.GetFloat();
1109 if (LYX_FORMAT - format > 0.05) {
1110 lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1111 LYX_FORMAT, format) << endl;
1113 if (format - LYX_FORMAT > 0.05) {
1114 lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1115 LYX_FORMAT, format) << endl;
1117 bool the_end = readLyXformat2(lex, par);
1118 // Formats >= 2.13 support "\the_end" marker
1125 WriteAlert(_("Warning!"),
1126 _("Reading of document is not complete"),
1127 _("Maybe the document is truncated"));
1128 // We simulate a safe reading anyways to allow
1129 // users to take the chance... (Asger)
1133 WriteAlert(_("ERROR!"),
1134 _("Old LyX file format found. "
1135 "Use LyX 0.10.x to read this!"));
1140 string tmp_format = lex.GetString();
1141 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1142 // if present remove ".," from string.
1143 string::size_type dot = tmp_format.find_first_of(".,");
1144 //lyxerr << " dot found at " << dot << endl;
1145 if (dot != string::npos)
1146 tmp_format.erase(dot, 1);
1147 file_format = strToInt(tmp_format);
1148 if (file_format == LYX_FORMAT) {
1150 } else if (file_format > LYX_FORMAT) {
1152 WriteAlert(_("Warning!"),
1153 _("LyX file format is newer that what"),
1154 _("is supported in this LyX version. Expect some problems."));
1156 } else if (file_format < LYX_FORMAT) {
1158 if (file_format < 200) {
1159 WriteAlert(_("ERROR!"),
1160 _("Old LyX file format found. "
1161 "Use LyX 0.10.x to read this!"));
1165 bool the_end = readLyXformat2(lex, par);
1167 // the_end was added in 213
1168 if (file_format < 213)
1172 WriteAlert(_("Warning!"),
1173 _("Reading of document is not complete"),
1174 _("Maybe the document is truncated"));
1177 } else { // "\\lyxformat" not found
1178 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1181 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1187 // Should probably be moved to somewhere else: BufferView? LyXView?
1188 bool Buffer::save() const
1190 // We don't need autosaves in the immediate future. (Asger)
1191 resetAutosaveTimers();
1195 if (lyxrc.make_backup) {
1196 s = fileName() + '~';
1197 if (!lyxrc.backupdir_path.empty())
1198 s = AddName(lyxrc.backupdir_path,
1199 subst(CleanupPath(s),'/','!'));
1201 // Rename is the wrong way of making a backup,
1202 // this is the correct way.
1203 /* truss cp fil fil2:
1204 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1205 stat("LyXVC.lyx", 0xEFFFF688) = 0
1206 open("LyXVC.lyx", O_RDONLY) = 3
1207 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1208 fstat(4, 0xEFFFF508) = 0
1209 fstat(3, 0xEFFFF508) = 0
1210 read(3, " # T h i s f i l e w".., 8192) = 5579
1211 write(4, " # T h i s f i l e w".., 5579) = 5579
1212 read(3, 0xEFFFD4A0, 8192) = 0
1215 chmod("LyXVC3.lyx", 0100644) = 0
1216 lseek(0, 0, SEEK_CUR) = 46440
1220 // Should proabaly have some more error checking here.
1221 // Should be cleaned up in 0.13, at least a bit.
1222 // Doing it this way, also makes the inodes stay the same.
1223 // This is still not a very good solution, in particular we
1224 // might loose the owner of the backup.
1225 FileInfo finfo(fileName());
1226 if (finfo.exist()) {
1227 mode_t fmode = finfo.getMode();
1228 struct utimbuf times = {
1229 finfo.getAccessTime(),
1230 finfo.getModificationTime() };
1232 ifstream ifs(fileName().c_str());
1233 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1238 ::chmod(s.c_str(), fmode);
1240 if (::utime(s.c_str(), ×)) {
1241 lyxerr << "utime error." << endl;
1244 lyxerr << "LyX was not able to make "
1245 "backupcopy. Beware." << endl;
1250 if (writeFile(fileName(), false)) {
1252 removeAutosaveFile(fileName());
1254 // Saving failed, so backup is not backup
1255 if (lyxrc.make_backup) {
1256 lyx::rename(s, fileName());
1264 // Returns false if unsuccesful
1265 bool Buffer::writeFile(string const & fname, bool flag) const
1267 // if flag is false writeFile will not create any GUI
1268 // warnings, only cerr.
1269 // Needed for autosave in background or panic save (Matthias 120496)
1271 if (read_only && (fname == filename)) {
1272 // Here we should come with a question if we should
1273 // perform the write anyway.
1275 lyxerr << _("Error! Document is read-only: ")
1278 WriteAlert(_("Error! Document is read-only: "),
1283 FileInfo finfo(fname);
1284 if (finfo.exist() && !finfo.writable()) {
1285 // Here we should come with a question if we should
1286 // try to do the save anyway. (i.e. do a chmod first)
1288 lyxerr << _("Error! Cannot write file: ")
1291 WriteFSAlert(_("Error! Cannot write file: "),
1296 ofstream ofs(fname.c_str());
1299 lyxerr << _("Error! Cannot open file: ")
1302 WriteFSAlert(_("Error! Cannot open file: "),
1308 // Use the standard "C" locale for file output.
1309 ofs.imbue(std::locale::classic());
1312 // The top of the file should not be written by params.
1314 // write out a comment in the top of the file
1315 ofs << '#' << LYX_DOCVERSION
1316 << " created this file. For more info see http://www.lyx.org/\n";
1318 ofs.setf(ios::showpoint|ios::fixed);
1321 char dummy_format[512];
1322 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1323 ofs << "\\lyxformat " << dummy_format << "\n";
1325 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1328 ofs << "\\lyxformat " << LYX_FORMAT << "\n";
1330 // now write out the buffer paramters.
1331 params.writeFile(ofs);
1333 char footnoteflag = 0;
1336 // this will write out all the paragraphs
1337 // using recursive descent.
1338 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1340 // Write marker that shows file is complete
1341 ofs << "\n\\the_end" << endl;
1345 // how to check if close went ok?
1346 // Following is an attempt... (BE 20001011)
1348 // good() returns false if any error occured, including some
1349 // formatting error.
1350 // bad() returns true if something bad happened in the buffer,
1351 // which should include file system full errors.
1358 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1360 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1370 string const Buffer::asciiParagraph(LyXParagraph const * par,
1371 unsigned int linelen) const
1373 ostringstream buffer;
1376 Inset const * inset;
1379 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1383 int ltype_depth = 0;
1384 unsigned int currlinelen = 0;
1385 bool ref_printed = false;
1391 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1395 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1399 /* begins a footnote environment ? */
1400 if (footnoteflag != par->footnoteflag) {
1401 footnoteflag = par->footnoteflag;
1403 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1404 if ((linelen > 0) &&
1405 ((currlinelen + j) > linelen)) {
1410 << string_footnotekinds[par->footnotekind]
1416 /* begins or ends a deeper area ?*/
1417 if (depth != par->depth) {
1418 if (par->depth > depth) {
1419 while (par->depth > depth) {
1424 while (par->depth < depth) {
1430 /* First write the layout */
1431 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1432 if (tmp == "Itemize") {
1434 ltype_depth = depth+1;
1435 } else if (tmp == "Enumerate") {
1437 ltype_depth = depth+1;
1438 } else if (strstr(tmp.c_str(), "ection")) {
1440 ltype_depth = depth+1;
1441 } else if (strstr(tmp.c_str(), "aragraph")) {
1443 ltype_depth = depth+1;
1444 } else if (tmp == "Description") {
1446 ltype_depth = depth+1;
1447 } else if (tmp == "Abstract") {
1450 } else if (tmp == "Bibliography") {
1458 /* maybe some vertical spaces */
1460 /* the labelwidthstring used in lists */
1464 /* some pagebreaks? */
1468 /* what about the alignment */
1471 /* dummy layout, that means a footnote ended */
1472 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1476 lyxerr << "Should this ever happen?" << endl;
1480 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1481 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1489 for (char j = 0; j < depth; ++j)
1491 currlinelen = depth * 2;
1493 case 0: /* Standard */
1494 case 4: /* (Sub)Paragraph */
1495 case 5: /* Description */
1497 case 6: /* Abstract */
1499 buffer << "Abstract\n\n";
1501 buffer << "Abstract: ";
1503 case 7: /* Bibliography */
1506 buffer << "References\n\n";
1508 buffer << "References: ";
1513 buffer << par->labelstring << " ";
1516 if (ltype_depth > depth) {
1517 for (char j = ltype_depth - 1; j > depth; --j)
1519 currlinelen += (ltype_depth-depth)*2;
1522 font2 = par->GetFontSettings(params, i);
1523 if (font1.latex() != font2.latex()) {
1524 if (font2.latex() == LyXFont::OFF)
1531 c = par->GetUChar(params, i);
1535 case LyXParagraph::META_INSET:
1536 if ((inset = par->GetInset(i))) {
1537 if (!inset->Ascii(this, buffer)) {
1539 string s = rsplit(buffer.str().c_str(),
1541 currlinelen += s.length();
1543 // to be sure it breaks paragraph
1544 currlinelen += linelen;
1548 case LyXParagraph::META_NEWLINE:
1551 for (char j = 0; j < depth; ++j)
1554 currlinelen = depth * 2;
1555 if (ltype_depth > depth) {
1556 for (char j = ltype_depth;
1559 currlinelen += (ltype_depth - depth) * 2;
1562 case LyXParagraph::META_HFILL:
1569 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1570 (c == ' ') && ((i + 2) < par->size()))
1573 for (char j = 0; j < depth; ++j)
1575 currlinelen = depth * 2;
1576 if (ltype_depth > depth) {
1577 for (char j = ltype_depth;
1580 currlinelen += (ltype_depth-depth)*2;
1582 } else if (c != '\0')
1585 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1590 return buffer.str().c_str();
1594 void Buffer::writeFileAscii(string const & fname, int linelen)
1596 ofstream ofs(fname.c_str());
1598 WriteFSAlert(_("Error: Cannot write file:"), fname);
1601 writeFileAscii(ofs, linelen);
1605 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1607 LyXParagraph * par = paragraph;
1609 ofs << asciiParagraph(par, linelen);
1616 void Buffer::makeLaTeXFile(string const & fname,
1617 string const & original_path,
1618 bool nice, bool only_body)
1620 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1622 niceFile = nice; // this will be used by Insetincludes.
1624 tex_code_break_column = lyxrc.ascii_linelen;
1626 LyXTextClass const & tclass =
1627 textclasslist.TextClass(params.textclass);
1629 ofstream ofs(fname.c_str());
1631 WriteFSAlert(_("Error: Cannot open file: "), fname);
1635 // validate the buffer.
1636 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1637 LaTeXFeatures features(params, tclass.numLayouts());
1639 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1642 // The starting paragraph of the coming rows is the
1643 // first paragraph of the document. (Asger)
1644 texrow.start(paragraph, 0);
1646 if (!only_body && nice) {
1647 ofs << "%% " LYX_DOCVERSION " created this file. "
1648 "For more info, see http://www.lyx.org/.\n"
1649 "%% Do not edit unless you really know what "
1654 lyxerr.debug() << "lyx header finished" << endl;
1655 // There are a few differences between nice LaTeX and usual files:
1656 // usual is \batchmode and has a
1657 // special input@path to allow the including of figures
1658 // with either \input or \includegraphics (what figinsets do).
1659 // batchmode is not set if there is a tex_code_break_column.
1660 // In this case somebody is interested in the generated LaTeX,
1661 // so this is OK. input@path is set when the actual parameter
1662 // original_path is set. This is done for usual tex-file, but not
1663 // for nice-latex-file. (Matthias 250696)
1666 // code for usual, NOT nice-latex-file
1667 ofs << "\\batchmode\n"; // changed
1668 // from \nonstopmode
1671 if (!original_path.empty()) {
1672 ofs << "\\makeatletter\n"
1673 << "\\def\\input@path{{"
1674 << original_path << "/}}\n"
1675 << "\\makeatother\n";
1681 ofs << "\\documentclass";
1683 string options; // the document class options.
1685 if (tokenPos(tclass.opt_fontsize(),
1686 '|', params.fontsize) >= 0) {
1687 // only write if existing in list (and not default)
1688 options += params.fontsize;
1693 if (!params.use_geometry &&
1694 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1695 switch (params.papersize) {
1696 case BufferParams::PAPER_A4PAPER:
1697 options += "a4paper,";
1699 case BufferParams::PAPER_USLETTER:
1700 options += "letterpaper,";
1702 case BufferParams::PAPER_A5PAPER:
1703 options += "a5paper,";
1705 case BufferParams::PAPER_B5PAPER:
1706 options += "b5paper,";
1708 case BufferParams::PAPER_EXECUTIVEPAPER:
1709 options += "executivepaper,";
1711 case BufferParams::PAPER_LEGALPAPER:
1712 options += "legalpaper,";
1718 if (params.sides != tclass.sides()) {
1719 switch (params.sides) {
1720 case LyXTextClass::OneSide:
1721 options += "oneside,";
1723 case LyXTextClass::TwoSides:
1724 options += "twoside,";
1731 if (params.columns != tclass.columns()) {
1732 if (params.columns == 2)
1733 options += "twocolumn,";
1735 options += "onecolumn,";
1738 if (!params.use_geometry
1739 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1740 options += "landscape,";
1742 // language should be a parameter to \documentclass
1743 bool use_babel = false;
1744 if (params.language->babel() == "hebrew"
1745 && default_language->babel() != "hebrew")
1746 // This seems necessary
1747 features.UsedLanguages.insert(default_language);
1748 #ifdef DO_USE_DEFAULT_LANGUAGE
1749 if (params.language->lang() != "default" ||
1750 !features.UsedLanguages.empty()) {
1753 for (LaTeXFeatures::LanguageList::const_iterator cit =
1754 features.UsedLanguages.begin();
1755 cit != features.UsedLanguages.end(); ++cit)
1756 options += (*cit)->babel() + ",";
1757 options += params.language->babel() + ',';
1758 #ifdef DO_USE_DEFAULT_LANGUAGE
1762 // the user-defined options
1763 if (!params.options.empty()) {
1764 options += params.options + ',';
1767 if (!options.empty()){
1768 options = strip(options, ',');
1769 ofs << '[' << options << ']';
1773 << textclasslist.LatexnameOfClass(params.textclass)
1776 // end of \documentclass defs
1778 // font selection must be done before loading fontenc.sty
1779 // The ae package is not needed when using OT1 font encoding.
1780 if (params.fonts != "default" &&
1781 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1782 ofs << "\\usepackage{" << params.fonts << "}\n";
1784 if (params.fonts == "ae") {
1785 ofs << "\\usepackage{aecompl}\n";
1789 // this one is not per buffer
1790 if (lyxrc.fontenc != "default") {
1791 ofs << "\\usepackage[" << lyxrc.fontenc
1796 if (params.inputenc == "auto") {
1797 string const doc_encoding =
1798 params.language->encoding()->LatexName();
1800 // Create a list with all the input encodings used
1802 set<string> encodings;
1803 for (LaTeXFeatures::LanguageList::const_iterator it =
1804 features.UsedLanguages.begin();
1805 it != features.UsedLanguages.end(); ++it)
1806 if ((*it)->encoding()->LatexName() != doc_encoding)
1807 encodings.insert((*it)->encoding()->LatexName());
1809 ofs << "\\usepackage[";
1810 std::copy(encodings.begin(), encodings.end(),
1811 std::ostream_iterator<string>(ofs, ","));
1812 ofs << doc_encoding << "]{inputenc}\n";
1814 } else if (params.inputenc != "default") {
1815 ofs << "\\usepackage[" << params.inputenc
1820 // At the very beginning the text parameters.
1821 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1822 switch (params.paperpackage) {
1823 case BufferParams::PACKAGE_A4:
1824 ofs << "\\usepackage{a4}\n";
1827 case BufferParams::PACKAGE_A4WIDE:
1828 ofs << "\\usepackage{a4wide}\n";
1831 case BufferParams::PACKAGE_WIDEMARGINSA4:
1832 ofs << "\\usepackage[widemargins]{a4}\n";
1837 if (params.use_geometry) {
1838 ofs << "\\usepackage{geometry}\n";
1840 ofs << "\\geometry{verbose";
1841 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1842 ofs << ",landscape";
1843 switch (params.papersize2) {
1844 case BufferParams::VM_PAPER_CUSTOM:
1845 if (!params.paperwidth.empty())
1846 ofs << ",paperwidth="
1847 << params.paperwidth;
1848 if (!params.paperheight.empty())
1849 ofs << ",paperheight="
1850 << params.paperheight;
1852 case BufferParams::VM_PAPER_USLETTER:
1853 ofs << ",letterpaper";
1855 case BufferParams::VM_PAPER_USLEGAL:
1856 ofs << ",legalpaper";
1858 case BufferParams::VM_PAPER_USEXECUTIVE:
1859 ofs << ",executivepaper";
1861 case BufferParams::VM_PAPER_A3:
1864 case BufferParams::VM_PAPER_A4:
1867 case BufferParams::VM_PAPER_A5:
1870 case BufferParams::VM_PAPER_B3:
1873 case BufferParams::VM_PAPER_B4:
1876 case BufferParams::VM_PAPER_B5:
1880 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1881 switch (lyxrc.default_papersize) {
1882 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1883 case BufferParams::PAPER_USLETTER:
1884 ofs << ",letterpaper";
1886 case BufferParams::PAPER_LEGALPAPER:
1887 ofs << ",legalpaper";
1889 case BufferParams::PAPER_EXECUTIVEPAPER:
1890 ofs << ",executivepaper";
1892 case BufferParams::PAPER_A3PAPER:
1895 case BufferParams::PAPER_A4PAPER:
1898 case BufferParams::PAPER_A5PAPER:
1901 case BufferParams::PAPER_B5PAPER:
1906 if (!params.topmargin.empty())
1907 ofs << ",tmargin=" << params.topmargin;
1908 if (!params.bottommargin.empty())
1909 ofs << ",bmargin=" << params.bottommargin;
1910 if (!params.leftmargin.empty())
1911 ofs << ",lmargin=" << params.leftmargin;
1912 if (!params.rightmargin.empty())
1913 ofs << ",rmargin=" << params.rightmargin;
1914 if (!params.headheight.empty())
1915 ofs << ",headheight=" << params.headheight;
1916 if (!params.headsep.empty())
1917 ofs << ",headsep=" << params.headsep;
1918 if (!params.footskip.empty())
1919 ofs << ",footskip=" << params.footskip;
1923 if (features.amsstyle
1924 && !tclass.provides(LyXTextClass::amsmath)) {
1925 ofs << "\\usepackage{amsmath}\n";
1929 if (tokenPos(tclass.opt_pagestyle(),
1930 '|', params.pagestyle) >= 0) {
1931 if (params.pagestyle == "fancy") {
1932 ofs << "\\usepackage{fancyhdr}\n";
1935 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1939 // We try to load babel late, in case it interferes
1940 // with other packages.
1942 ofs << lyxrc.language_package << endl;
1946 if (params.secnumdepth != tclass.secnumdepth()) {
1947 ofs << "\\setcounter{secnumdepth}{"
1948 << params.secnumdepth
1952 if (params.tocdepth != tclass.tocdepth()) {
1953 ofs << "\\setcounter{tocdepth}{"
1959 if (params.paragraph_separation) {
1960 switch (params.defskip.kind()) {
1961 case VSpace::SMALLSKIP:
1962 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1964 case VSpace::MEDSKIP:
1965 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1967 case VSpace::BIGSKIP:
1968 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1970 case VSpace::LENGTH:
1971 ofs << "\\setlength\\parskip{"
1972 << params.defskip.length().asLatexString()
1975 default: // should never happen // Then delete it.
1976 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1981 ofs << "\\setlength\\parindent{0pt}\n";
1985 // Now insert the LyX specific LaTeX commands...
1987 // The optional packages;
1988 string preamble(features.getPackages());
1990 // this might be useful...
1991 preamble += "\n\\makeatletter\n";
1993 // Some macros LyX will need
1994 string tmppreamble(features.getMacros());
1996 if (!tmppreamble.empty()) {
1997 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1998 "LyX specific LaTeX commands.\n"
1999 + tmppreamble + '\n';
2002 // the text class specific preamble
2003 tmppreamble = features.getTClassPreamble();
2004 if (!tmppreamble.empty()) {
2005 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2006 "Textclass specific LaTeX commands.\n"
2007 + tmppreamble + '\n';
2010 /* the user-defined preamble */
2011 if (!params.preamble.empty()) {
2012 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2013 "User specified LaTeX commands.\n"
2014 + params.preamble + '\n';
2017 preamble += "\\makeatother\n";
2019 // Itemize bullet settings need to be last in case the user
2020 // defines their own bullets that use a package included
2021 // in the user-defined preamble -- ARRae
2022 // Actually it has to be done much later than that
2023 // since some packages like frenchb make modifications
2024 // at \begin{document} time -- JMarc
2026 for (int i = 0; i < 4; ++i) {
2027 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2028 if (bullets_def.empty())
2029 bullets_def="\\AtBeginDocument{\n";
2030 bullets_def += " \\renewcommand{\\labelitemi";
2032 // `i' is one less than the item to modify
2039 bullets_def += "ii";
2045 bullets_def += "}{" +
2046 params.user_defined_bullets[i].getText()
2051 if (!bullets_def.empty())
2052 preamble += bullets_def + "}\n\n";
2054 for (int j = countChar(preamble, '\n'); j-- ;) {
2061 ofs << "\\begin{document}\n";
2064 lyxerr.debug() << "preamble finished, now the body." << endl;
2065 #ifdef DO_USE_DEFAULT_LANGUAGE
2066 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2068 if (!lyxrc.language_auto_begin) {
2070 ofs << subst(lyxrc.language_command_begin, "$$lang",
2071 params.language->babel())
2076 latexParagraphs(ofs, paragraph, 0, texrow);
2078 // add this just in case after all the paragraphs
2082 #ifdef DO_USE_DEFAULT_LANGUAGE
2083 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2085 if (!lyxrc.language_auto_end) {
2087 ofs << subst(lyxrc.language_command_end, "$$lang",
2088 params.language->babel())
2094 ofs << "\\end{document}\n";
2097 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2099 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2103 // Just to be sure. (Asger)
2106 // tex_code_break_column's value is used to decide
2107 // if we are in batchmode or not (within mathed_write()
2108 // in math_write.C) so we must set it to a non-zero
2109 // value when we leave otherwise we save incorrect .lyx files.
2110 tex_code_break_column = lyxrc.ascii_linelen;
2114 lyxerr << "File was not closed properly." << endl;
2117 lyxerr.debug() << "Finished making latex file." << endl;
2122 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2124 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2125 LyXParagraph * endpar, TexRow & texrow) const
2127 bool was_title = false;
2128 bool already_title = false;
2129 std::ostringstream ftnote;
2134 while (par != endpar) {
2137 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2140 LyXLayout const & layout =
2141 textclasslist.Style(params.textclass,
2144 if (layout.intitle) {
2145 if (already_title) {
2146 lyxerr <<"Error in latexParagraphs: You"
2147 " should not mix title layouts"
2148 " with normal ones." << endl;
2151 } else if (was_title && !already_title) {
2152 ofs << "\\maketitle\n";
2154 already_title = true;
2157 // We are at depth 0 so we can just use
2158 // ordinary \footnote{} generation
2159 // flag this with ftcount
2161 if (layout.isEnvironment()
2162 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2163 par = par->TeXEnvironment(this, params, ofs, texrow
2165 ,ftnote, ft_texrow, ftcount
2169 par = par->TeXOnePar(this, params, ofs, texrow, false
2172 ftnote, ft_texrow, ftcount
2177 // Write out what we've generated...
2180 ofs << "\\addtocounter{footnote}{-"
2184 ofs << ftnote.str();
2185 texrow += ft_texrow;
2187 // The extra .c_str() is needed when we use
2188 // lyxstring instead of the STL string class.
2189 ftnote.str(string().c_str());
2194 // It might be that we only have a title in this document
2195 if (was_title && !already_title) {
2196 ofs << "\\maketitle\n";
2202 bool Buffer::isLatex() const
2204 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2208 bool Buffer::isLinuxDoc() const
2210 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2214 bool Buffer::isLiterate() const
2216 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2220 bool Buffer::isDocBook() const
2222 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2226 bool Buffer::isSGML() const
2228 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2229 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2233 void Buffer::sgmlOpenTag(ostream & os, int depth,
2234 string const & latexname) const
2236 if (latexname != "!-- --")
2237 os << string(depth, ' ') << "<" << latexname << ">\n";
2241 void Buffer::sgmlCloseTag(ostream & os, int depth,
2242 string const & latexname) const
2244 if (latexname != "!-- --")
2245 os << string(depth, ' ') << "</" << latexname << ">\n";
2249 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2251 LyXParagraph * par = paragraph;
2253 niceFile = nice; // this will be used by Insetincludes.
2255 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2256 string environment_stack[10];
2259 int depth = 0; // paragraph depth
2261 ofstream ofs(fname.c_str());
2264 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2268 LyXTextClass const & tclass =
2269 textclasslist.TextClass(params.textclass);
2271 LaTeXFeatures features(params, tclass.numLayouts());
2275 tex_code_break_column = lyxrc.ascii_linelen;
2277 //tex_code_break_column = 0;
2282 string sgml_includedfiles=features.getIncludedFiles(fname);
2284 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2285 ofs << "<!doctype linuxdoc system>\n\n";
2287 ofs << "<!doctype linuxdoc system [ "
2288 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2291 if (params.options.empty())
2292 sgmlOpenTag(ofs, 0, top_element);
2294 string top = top_element;
2296 top += params.options;
2297 sgmlOpenTag(ofs, 0, top);
2301 ofs << "<!-- " << LYX_DOCVERSION
2302 << " created this file. For more info see http://www.lyx.org/"
2306 int desc_on = 0; // description mode
2307 LyXLayout const & style =
2308 textclasslist.Style(params.textclass,
2311 // treat <toc> as a special case for compatibility with old code
2312 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2313 Inset * inset = par->GetInset(0);
2314 Inset::Code lyx_code = inset->LyxCode();
2315 if (lyx_code == Inset::TOC_CODE){
2316 string const temp = "toc";
2317 sgmlOpenTag(ofs, depth, temp);
2321 linuxDocHandleFootnote(ofs, par, depth);
2327 // environment tag closing
2328 for (; depth > par->depth; --depth) {
2329 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2330 environment_stack[depth].erase();
2333 // write opening SGML tags
2334 switch (style.latextype) {
2335 case LATEX_PARAGRAPH:
2336 if (depth == par->depth
2337 && !environment_stack[depth].empty()) {
2338 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2339 environment_stack[depth].erase();
2345 sgmlOpenTag(ofs, depth, style.latexname());
2350 LinuxDocError(par, 0,
2351 _("Error : Wrong depth for"
2352 " LatexType Command.\n"));
2354 if (!environment_stack[depth].empty()){
2355 sgmlCloseTag(ofs, depth,
2356 environment_stack[depth]);
2360 environment_stack[depth].erase();
2361 sgmlOpenTag(ofs, depth, style.latexname());
2364 case LATEX_ENVIRONMENT:
2365 case LATEX_ITEM_ENVIRONMENT:
2366 if (depth == par->depth
2367 && environment_stack[depth] != style.latexname()
2368 && !environment_stack[depth].empty()) {
2370 sgmlCloseTag(ofs, depth,
2371 environment_stack[depth]);
2372 environment_stack[depth].erase();
2374 if (depth < par->depth) {
2376 environment_stack[depth].erase();
2378 if (environment_stack[depth] != style.latexname()) {
2380 string const temp = "p";
2381 sgmlOpenTag(ofs, depth, temp);
2383 environment_stack[depth] = style.latexname();
2384 sgmlOpenTag(ofs, depth,
2385 environment_stack[depth]);
2387 if (style.latextype == LATEX_ENVIRONMENT) break;
2389 desc_on = (style.labeltype == LABEL_MANUAL);
2396 sgmlOpenTag(ofs, depth + 1, item_name);
2399 sgmlOpenTag(ofs, depth, style.latexname());
2406 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2410 linuxDocHandleFootnote(ofs, par, depth);
2412 while(par && par->IsDummy());
2416 // write closing SGML tags
2417 switch (style.latextype) {
2419 case LATEX_ENVIRONMENT:
2420 case LATEX_ITEM_ENVIRONMENT:
2423 sgmlCloseTag(ofs, depth, style.latexname());
2429 for (; depth > 0; --depth)
2430 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2432 if (!environment_stack[depth].empty())
2433 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2437 sgmlCloseTag(ofs, 0, top_element);
2441 // How to check for successful close
2446 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2449 string const tag = "footnote";
2451 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2452 sgmlOpenTag(os, depth + 1, tag);
2453 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2454 sgmlCloseTag(os, depth + 1, tag);
2461 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2462 int depth, int desc_on,
2463 LyXParagraph * & par)
2465 LyXParagraph * tpar = par;
2468 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2470 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2474 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2475 "Caption").second) {
2476 sgmlOpenTag(os, depth + 1, inner_tag);
2478 SimpleDocBookOnePar(os, extra_par, tpar,
2479 desc_on, depth + 2);
2480 sgmlCloseTag(os, depth+1, inner_tag);
2481 if (!extra_par.empty())
2488 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2491 string tag, inner_tag;
2492 string tmp_par, extra_par;
2493 bool inner_span = false;
2496 // Someone should give this enum a proper name (Lgb)
2504 SOME_ENUM last = NO_ONE;
2505 SOME_ENUM present = FOOTNOTE_LIKE;
2507 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2508 if (last == present) {
2510 if (!tmp_par.empty()) {
2513 sgmlCloseTag(os, depth + 1, inner_tag);
2514 sgmlOpenTag(os, depth + 1, inner_tag);
2521 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2523 if (!extra_par.empty()) os << extra_par;
2524 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2527 switch (par->footnotekind) {
2528 case LyXParagraph::FOOTNOTE:
2529 case LyXParagraph::ALGORITHM:
2532 present = FOOTNOTE_LIKE;
2535 case LyXParagraph::MARGIN:
2538 present = MARGIN_LIKE;
2541 case LyXParagraph::FIG:
2542 case LyXParagraph::WIDE_FIG:
2544 inner_tag = "title";
2548 case LyXParagraph::TAB:
2549 case LyXParagraph::WIDE_TAB:
2551 inner_tag = "title";
2556 sgmlOpenTag(os, depth, tag);
2557 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2558 DocBookHandleCaption(os, inner_tag, depth,
2562 sgmlOpenTag(os, depth + 1, inner_tag);
2565 // ignore all caption here, we processed them above!!!
2566 if (par->layout != textclasslist
2567 .NumberOfLayout(params.textclass,
2568 "Caption").second) {
2569 std::ostringstream ost;
2570 SimpleDocBookOnePar(ost, extra_par, par,
2571 desc_on, depth + 2);
2572 tmp_par += ost.str().c_str();
2574 tmp_par = frontStrip(strip(tmp_par));
2580 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2581 if (!extra_par.empty()) os << extra_par;
2582 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2587 // push a tag in a style stack
2588 void Buffer::push_tag(ostream & os, string const & tag,
2589 int & pos, char stack[5][3])
2591 #ifdef WITH_WARNINGS
2592 #warning Use a real stack! (Lgb)
2594 // pop all previous tags
2595 for (int j = pos; j >= 0; --j)
2596 os << "</" << stack[j] << ">";
2599 sprintf(stack[++pos], "%s", tag.c_str());
2602 for (int i = 0; i <= pos; ++i)
2603 os << "<" << stack[i] << ">";
2607 void Buffer::pop_tag(ostream & os, string const & tag,
2608 int & pos, char stack[5][3])
2610 #ifdef WITH_WARNINGS
2611 #warning Use a real stack! (Lgb)
2613 // Please, Lars, do not remove the global variable. I already
2614 // had to reintroduce it twice! (JMarc)
2615 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2619 // pop all tags till specified one
2620 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2621 os << "</" << stack[j] << ">";
2624 os << "</" << tag << ">";
2626 // push all tags, but the specified one
2627 for (j = j + 1; j <= pos; ++j) {
2628 os << "<" << stack[j] << ">";
2629 strcpy(stack[j - 1], stack[j]);
2633 // pop all tags till specified one
2635 for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2636 os << "</" << stack[j] << ">";
2639 os << "</" << tag << ">";
2641 // push all tags, but the specified one
2642 for (int i = j + 1; i <= pos; ++i) {
2643 os << "<" << stack[i] << ">";
2644 strcpy(stack[i - 1], stack[i]);
2651 // Handle internal paragraph parsing -- layout already processed.
2653 // checks, if newcol chars should be put into this line
2654 // writes newline, if necessary.
2656 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2657 string::size_type newcol)
2660 if (colcount > lyxrc.ascii_linelen) {
2662 colcount = newcol; // assume write after this call
2667 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2668 int desc_on, int /*depth*/)
2673 LyXParagraph::size_type main_body;
2675 LyXLayout const & style = textclasslist.Style(params.textclass,
2678 char family_type = 0; // family font flag
2679 bool is_bold = false; // series font flag
2680 char shape_type = 0; // shape font flag
2681 bool is_em = false; // emphasis (italic) font flag
2683 int stack_num = -1; // style stack position
2684 // Can this be rewritten to use a std::stack, please. (Lgb)
2685 char stack[5][3]; // style stack
2686 string::size_type char_line_count = 5; // Heuristic choice ;-)
2688 if (style.labeltype != LABEL_MANUAL)
2691 main_body = par->BeginningOfMainBody();
2693 // gets paragraph main font
2695 font1 = style.labelfont;
2700 // parsing main loop
2701 for (LyXParagraph::size_type i = 0;
2702 i < par->size(); ++i) {
2714 LyXFont const font2 = par->getFont(params, i);
2716 if (font1.family() != font2.family()) {
2717 switch (family_type) {
2719 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2720 push_tag(os, "tt", stack_num, stack);
2723 else if (font2.family() == LyXFont::SANS_FAMILY) {
2724 push_tag(os, "sf", stack_num, stack);
2729 pop_tag(os, "tt", stack_num, stack);
2730 if (font2.family() == LyXFont::SANS_FAMILY) {
2731 push_tag(os, "sf", stack_num, stack);
2738 pop_tag(os, "sf", stack_num, stack);
2739 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2740 push_tag(os, "tt", stack_num, stack);
2749 if (font1.series() != font2.series()) {
2750 if (font2.series() == LyXFont::BOLD_SERIES) {
2751 push_tag(os, "bf", stack_num, stack);
2753 } else if (is_bold) {
2754 pop_tag(os, "bf", stack_num, stack);
2759 // handle italic and slanted fonts
2760 if (font1.shape() != font2.shape()) {
2761 switch (shape_type) {
2763 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2764 push_tag(os, "it", stack_num, stack);
2766 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2767 push_tag(os, "sl", stack_num, stack);
2772 pop_tag(os, "it", stack_num, stack);
2773 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2774 push_tag(os, "sl", stack_num, stack);
2781 pop_tag(os, "sl", stack_num, stack);
2782 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2783 push_tag(os, "it", stack_num, stack);
2791 if (font1.emph() != font2.emph()) {
2792 if (font2.emph() == LyXFont::ON) {
2793 push_tag(os, "em", stack_num, stack);
2796 pop_tag(os, "em", stack_num, stack);
2801 c = par->GetChar(i);
2803 if (c == LyXParagraph::META_INSET) {
2804 inset = par->GetInset(i);
2805 inset->Linuxdoc(this, os);
2808 if (font2.latex() == LyXFont::ON) {
2809 // "TeX"-Mode on == > SGML-Mode on.
2811 os << c; // see LaTeX-Generation...
2815 if (par->linuxDocConvertChar(c, sgml_string)
2816 && !style.free_spacing) { // in freespacing
2818 // non-breaking characters
2822 linux_doc_line_break(os, char_line_count, 6);
2826 linux_doc_line_break(os, char_line_count, 1);
2831 char_line_count += sgml_string.length();
2837 // needed if there is an optional argument but no contents
2838 if (main_body > 0 && main_body == par->size()) {
2842 // pop all defined Styles
2843 for (j = stack_num; j >= 0; --j) {
2844 linux_doc_line_break(os,
2846 3 + strlen(stack[j]));
2847 os << "</" << stack[j] << ">";
2850 // resets description flag correctly
2853 // <tag> not closed...
2854 linux_doc_line_break(os, char_line_count, 6);
2858 // fprintf(file, "</p>");
2864 // Print an error message.
2865 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2866 string const & message)
2868 // insert an error marker in text
2869 InsetError * new_inset = new InsetError(message);
2870 par->InsertInset(pos, new_inset);
2873 // This constant defines the maximum number of
2874 // environment layouts that can be nesteded.
2875 // The same applies for command layouts.
2876 // These values should be more than enough.
2877 // José Matos (1999/07/22)
2879 enum { MAX_NEST_LEVEL = 25};
2881 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2883 LyXParagraph * par = paragraph;
2885 niceFile = nice; // this will be used by Insetincludes.
2887 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2888 // Please use a real stack.
2889 string environment_stack[MAX_NEST_LEVEL];
2890 string environment_inner[MAX_NEST_LEVEL];
2891 // Please use a real stack.
2892 string command_stack[MAX_NEST_LEVEL];
2893 bool command_flag= false;
2894 int command_depth= 0, command_base= 0, cmd_depth= 0;
2896 string item_name, command_name;
2897 string c_depth, c_params, tmps;
2899 int depth = 0; // paragraph depth
2900 LyXTextClass const & tclass =
2901 textclasslist.TextClass(params.textclass);
2903 LaTeXFeatures features(params, tclass.numLayouts());
2907 tex_code_break_column = lyxrc.ascii_linelen;
2909 //tex_code_break_column = 0;
2911 ofstream ofs(fname.c_str());
2913 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2920 string sgml_includedfiles=features.getIncludedFiles(fname);
2922 ofs << "<!doctype " << top_element
2923 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2925 if (params.preamble.empty() && sgml_includedfiles.empty())
2928 ofs << "\n [ " << params.preamble
2929 << sgml_includedfiles << " \n]>\n\n";
2932 string top = top_element;
2934 top += params.language->code();
2937 if (!params.options.empty()) {
2939 top += params.options;
2941 sgmlOpenTag(ofs, 0, top);
2943 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2944 << "\n See http://www.lyx.org/ for more information -->\n";
2947 int desc_on = 0; // description mode
2948 LyXLayout const & style =
2949 textclasslist.Style(params.textclass,
2952 // environment tag closing
2953 for (; depth > par->depth; --depth) {
2954 if (environment_inner[depth] != "!-- --") {
2955 item_name= "listitem";
2956 sgmlCloseTag(ofs, command_depth + depth,
2958 if (environment_inner[depth] == "varlistentry")
2959 sgmlCloseTag(ofs, depth+command_depth,
2960 environment_inner[depth]);
2962 sgmlCloseTag(ofs, depth + command_depth,
2963 environment_stack[depth]);
2964 environment_stack[depth].erase();
2965 environment_inner[depth].erase();
2968 if (depth == par->depth
2969 && environment_stack[depth] != style.latexname()
2970 && !environment_stack[depth].empty()) {
2971 if (environment_inner[depth] != "!-- --") {
2972 item_name= "listitem";
2973 sgmlCloseTag(ofs, command_depth+depth,
2975 if (environment_inner[depth] == "varlistentry")
2977 depth + command_depth,
2978 environment_inner[depth]);
2981 sgmlCloseTag(ofs, depth + command_depth,
2982 environment_stack[depth]);
2984 environment_stack[depth].erase();
2985 environment_inner[depth].erase();
2988 // Write opening SGML tags.
2989 switch (style.latextype) {
2990 case LATEX_PARAGRAPH:
2991 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2996 LinuxDocError(par, 0,
2997 _("Error : Wrong depth for "
2998 "LatexType Command.\n"));
3000 command_name = style.latexname();
3002 tmps = style.latexparam();
3003 c_params = split(tmps, c_depth,'|');
3005 cmd_depth= lyx::atoi(c_depth);
3008 if (cmd_depth<command_base) {
3009 for (int j = command_depth;
3010 j >= command_base; --j)
3011 if (!command_stack[j].empty())
3012 sgmlCloseTag(ofs, j, command_stack[j]);
3013 command_depth= command_base= cmd_depth;
3014 } else if (cmd_depth <= command_depth) {
3015 for (int j = command_depth;
3016 j >= cmd_depth; --j)
3018 if (!command_stack[j].empty())
3019 sgmlCloseTag(ofs, j, command_stack[j]);
3020 command_depth= cmd_depth;
3022 command_depth= cmd_depth;
3024 command_depth = command_base = cmd_depth;
3025 command_flag = true;
3027 command_stack[command_depth]= command_name;
3029 // treat label as a special case for
3030 // more WYSIWYM handling.
3031 if (par->GetChar(0) == LyXParagraph::META_INSET) {
3032 Inset * inset = par->GetInset(0);
3033 Inset::Code lyx_code = inset->LyxCode();
3034 if (lyx_code == Inset::LABEL_CODE){
3035 command_name += " id=\"";
3036 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3037 command_name += "\"";
3042 sgmlOpenTag(ofs, depth + command_depth, command_name);
3043 if (c_params.empty())
3044 item_name = "title";
3046 item_name = c_params;
3047 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3050 case LATEX_ENVIRONMENT:
3051 case LATEX_ITEM_ENVIRONMENT:
3052 if (depth < par->depth) {
3054 environment_stack[depth].erase();
3057 if (environment_stack[depth] != style.latexname()) {
3058 environment_stack[depth] = style.latexname();
3059 environment_inner[depth] = "!-- --";
3060 sgmlOpenTag(ofs, depth + command_depth,
3061 environment_stack[depth]);
3063 if (environment_inner[depth] != "!-- --") {
3064 item_name= "listitem";
3066 command_depth + depth,
3068 if (environment_inner[depth] == "varlistentry")
3070 depth + command_depth,
3071 environment_inner[depth]);
3075 if (style.latextype == LATEX_ENVIRONMENT) {
3076 if (!style.latexparam().empty()) {
3077 if(style.latexparam() == "CDATA")
3078 ofs << "<![ CDATA [";
3080 sgmlOpenTag(ofs, depth + command_depth,
3081 style.latexparam());
3086 desc_on = (style.labeltype == LABEL_MANUAL);
3089 environment_inner[depth]= "varlistentry";
3091 environment_inner[depth]= "listitem";
3093 sgmlOpenTag(ofs, depth + 1 + command_depth,
3094 environment_inner[depth]);
3098 sgmlOpenTag(ofs, depth + 1 + command_depth,
3102 sgmlOpenTag(ofs, depth + 1 + command_depth,
3107 sgmlOpenTag(ofs, depth + command_depth,
3116 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3117 depth + 1 + command_depth);
3120 DocBookHandleFootnote(ofs, par,
3121 depth + 1 + command_depth);
3123 while(par && par->IsDummy());
3126 // write closing SGML tags
3127 switch (style.latextype) {
3129 if (c_params.empty())
3133 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3135 case LATEX_ENVIRONMENT:
3136 if (!style.latexparam().empty()) {
3137 if(style.latexparam() == "CDATA")
3140 sgmlCloseTag(ofs, depth + command_depth,
3141 style.latexparam());
3144 case LATEX_ITEM_ENVIRONMENT:
3145 if (desc_on == 1) break;
3147 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3149 case LATEX_PARAGRAPH:
3150 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3153 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3159 for (; depth >= 0; --depth) {
3160 if (!environment_stack[depth].empty()) {
3161 if (environment_inner[depth] != "!-- --") {
3162 item_name= "listitem";
3163 sgmlCloseTag(ofs, command_depth + depth,
3165 if (environment_inner[depth] == "varlistentry")
3166 sgmlCloseTag(ofs, depth + command_depth,
3167 environment_inner[depth]);
3170 sgmlCloseTag(ofs, depth + command_depth,
3171 environment_stack[depth]);
3175 for (int j = command_depth; j >= command_base; --j)
3176 if (!command_stack[j].empty())
3177 sgmlCloseTag(ofs, j, command_stack[j]);
3180 sgmlCloseTag(ofs, 0, top_element);
3183 // How to check for successful close
3187 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3188 LyXParagraph * par, int & desc_on,
3191 bool emph_flag = false;
3193 LyXLayout const & style = textclasslist.Style(params.textclass,
3196 LyXParagraph::size_type main_body;
3197 if (style.labeltype != LABEL_MANUAL)
3200 main_body = par->BeginningOfMainBody();
3202 // gets paragraph main font
3203 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3205 int char_line_count = depth;
3206 if (!style.free_spacing)
3207 for (int j = 0; j < depth; ++j)
3210 // parsing main loop
3211 for (LyXParagraph::size_type i = 0;
3212 i < par->size(); ++i) {
3213 LyXFont font2 = par->getFont(params, i);
3215 // handle <emphasis> tag
3216 if (font1.emph() != font2.emph() && i) {
3217 if (font2.emph() == LyXFont::ON) {
3221 os << "</emphasis>";
3226 char c = par->GetChar(i);
3228 if (c == LyXParagraph::META_INSET) {
3229 Inset * inset = par->GetInset(i);
3230 std::ostringstream ost;
3231 inset->DocBook(this, ost);
3232 string tmp_out = ost.str().c_str();
3235 // This code needs some explanation:
3236 // Two insets are treated specially
3237 // label if it is the first element in a command paragraph
3239 // graphics inside tables or figure floats can't go on
3240 // title (the equivalente in latex for this case is caption
3241 // and title should come first
3244 if (desc_on!= 3 || i!= 0) {
3245 if (!tmp_out.empty() && tmp_out[0] == '@') {
3247 extra += frontStrip(tmp_out, '@');
3249 os << frontStrip(tmp_out, '@');
3254 } else if (font2.latex() == LyXFont::ON) {
3255 // "TeX"-Mode on ==> SGML-Mode on.
3261 if (par->linuxDocConvertChar(c, sgml_string)
3262 && !style.free_spacing) { // in freespacing
3264 // non-breaking characters
3268 os << "\n</term><listitem><para>";
3280 // needed if there is an optional argument but no contents
3281 if (main_body > 0 && main_body == par->size()) {
3285 os << "</emphasis>";
3288 // resets description flag correctly
3291 // <term> not closed...
3299 // This should be enabled when the Chktex class is implemented. (Asger)
3300 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3301 // Other flags: -wall -v0 -x
3302 int Buffer::runChktex()
3304 if (!users->text) return 0;
3306 ProhibitInput(users);
3308 // get LaTeX-Filename
3309 string const name = getLatexName();
3310 string path = OnlyPath(filename);
3312 string const org_path = path;
3313 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3317 Path p(path); // path to LaTeX file
3318 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3320 // Remove all error insets
3321 bool const removedErrorInsets = users->removeAutoInsets();
3323 // Generate the LaTeX file if neccessary
3324 makeLaTeXFile(name, org_path, false);
3327 Chktex chktex(lyxrc.chktex_command, name, filepath);
3328 int res = chktex.run(terr); // run chktex
3331 WriteAlert(_("chktex did not work!"),
3332 _("Could not run with file:"), name);
3333 } else if (res > 0) {
3334 // Insert all errors as errors boxes
3335 users->insertErrors(terr);
3338 // if we removed error insets before we ran chktex or if we inserted
3339 // error insets after we ran chktex, this must be run:
3340 if (removedErrorInsets || res){
3342 users->fitCursor(users->text);
3350 void Buffer::validate(LaTeXFeatures & features) const
3352 LyXParagraph * par = paragraph;
3353 LyXTextClass const & tclass =
3354 textclasslist.TextClass(params.textclass);
3356 // AMS Style is at document level
3358 features.amsstyle = (params.use_amsmath ||
3359 tclass.provides(LyXTextClass::amsmath));
3362 // We don't use "lyxerr.debug" because of speed. (Asger)
3363 if (lyxerr.debugging(Debug::LATEX))
3364 lyxerr << "Paragraph: " << par << endl;
3366 // Now just follow the list of paragraphs and run
3367 // validate on each of them.
3368 par->validate(features);
3370 // and then the next paragraph
3374 // the bullet shapes are buffer level not paragraph level
3375 // so they are tested here
3376 for (int i = 0; i < 4; ++i) {
3377 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3378 int const font = params.user_defined_bullets[i].getFont();
3380 int const c = params
3381 .user_defined_bullets[i]
3388 features.latexsym = true;
3390 } else if (font == 1) {
3391 features.amssymb = true;
3392 } else if ((font >= 2 && font <= 5)) {
3393 features.pifont = true;
3398 if (lyxerr.debugging(Debug::LATEX)) {
3399 features.showStruct();
3404 void Buffer::setPaperStuff()
3406 params.papersize = BufferParams::PAPER_DEFAULT;
3407 char const c1 = params.paperpackage;
3408 if (c1 == BufferParams::PACKAGE_NONE) {
3409 char const c2 = params.papersize2;
3410 if (c2 == BufferParams::VM_PAPER_USLETTER)
3411 params.papersize = BufferParams::PAPER_USLETTER;
3412 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3413 params.papersize = BufferParams::PAPER_LEGALPAPER;
3414 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3415 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3416 else if (c2 == BufferParams::VM_PAPER_A3)
3417 params.papersize = BufferParams::PAPER_A3PAPER;
3418 else if (c2 == BufferParams::VM_PAPER_A4)
3419 params.papersize = BufferParams::PAPER_A4PAPER;
3420 else if (c2 == BufferParams::VM_PAPER_A5)
3421 params.papersize = BufferParams::PAPER_A5PAPER;
3422 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3423 (c2 == BufferParams::VM_PAPER_B5))
3424 params.papersize = BufferParams::PAPER_B5PAPER;
3425 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3426 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3427 params.papersize = BufferParams::PAPER_A4PAPER;
3431 // This function should be in Buffer because it's a buffer's property (ale)
3432 string const Buffer::getIncludeonlyList(char delim)
3435 for (inset_iterator it = inset_iterator_begin();
3436 it != inset_iterator_end(); ++it) {
3437 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3438 InsetInclude * insetinc =
3439 static_cast<InsetInclude *>(*it);
3440 if (insetinc->isInclude()
3441 && insetinc->isNoLoad()) {
3444 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3448 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3453 vector<string> const Buffer::getLabelList()
3455 /// if this is a child document and the parent is already loaded
3456 /// Use the parent's list instead [ale990407]
3457 if (!params.parentname.empty()
3458 && bufferlist.exists(params.parentname)) {
3459 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3461 return tmp->getLabelList();
3464 vector<string> label_list;
3465 for (inset_iterator it = inset_iterator_begin();
3466 it != inset_iterator_end(); ++it) {
3467 vector<string> const l = (*it)->getLabelList();
3468 label_list.insert(label_list.end(), l.begin(), l.end());
3474 vector<vector<Buffer::TocItem> > const Buffer::getTocList() const
3479 vector<vector<TocItem> > l(4);
3480 LyXParagraph * par = paragraph;
3483 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3484 if (textclasslist.Style(params.textclass,
3485 par->GetLayout()).labeltype
3486 == LABEL_SENSITIVE) {
3490 tmp.str = par->String(this, false);
3491 switch (par->footnotekind) {
3492 case LyXParagraph::FIG:
3493 case LyXParagraph::WIDE_FIG:
3494 tmp.str = tostr(++figs) + ". "
3496 l[TOC_LOF].push_back(tmp);
3498 case LyXParagraph::TAB:
3499 case LyXParagraph::WIDE_TAB:
3500 tmp.str = tostr(++tables) + ". "
3502 l[TOC_LOT].push_back(tmp);
3504 case LyXParagraph::ALGORITHM:
3505 tmp.str = tostr(++algs) + ". "
3507 l[TOC_LOA].push_back(tmp);
3509 case LyXParagraph::FOOTNOTE:
3510 case LyXParagraph::MARGIN:
3514 } else if (!par->IsDummy()) {
3516 char const labeltype =
3517 textclasslist.Style(params.textclass,
3518 par->GetLayout()).labeltype;
3520 if (labeltype >= LABEL_COUNTER_CHAPTER
3521 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3522 // insert this into the table of contents
3527 textclasslist.TextClass(params.textclass).maxcounter());
3528 tmp.str = par->String(this, true);
3529 l[TOC_TOC].push_back(tmp);
3540 // This is also a buffer property (ale)
3541 vector<pair<string,string> > const Buffer::getBibkeyList()
3543 /// if this is a child document and the parent is already loaded
3544 /// Use the parent's list instead [ale990412]
3545 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3546 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3548 return tmp->getBibkeyList();
3551 vector<pair<string, string> > keys;
3552 LyXParagraph * par = paragraph;
3555 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3556 par->String(this, false)));
3560 // Might be either using bibtex or a child has bibliography
3562 for (inset_iterator it = inset_iterator_begin();
3563 it != inset_iterator_end(); ++it) {
3564 // Search for Bibtex or Include inset
3565 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3566 vector<pair<string,string> > tmp =
3567 static_cast<InsetBibtex*>(*it)->getKeys(this);
3568 keys.insert(keys.end(), tmp.begin(), tmp.end());
3569 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3570 vector<pair<string,string> > const tmp =
3571 static_cast<InsetInclude*>(*it)->getKeys();
3572 keys.insert(keys.end(), tmp.begin(), tmp.end());
3581 bool Buffer::isDepClean(string const & name) const
3583 DEPCLEAN * item = dep_clean;
3584 while (item && item->master != name)
3586 if (!item) return true;
3591 void Buffer::markDepClean(string const & name)
3594 dep_clean = new DEPCLEAN;
3595 dep_clean->clean = true;
3596 dep_clean->master = name;
3597 dep_clean->next = 0;
3599 DEPCLEAN * item = dep_clean;
3600 while (item && item->master != name)
3605 item = new DEPCLEAN;
3607 item->master = name;
3614 bool Buffer::Dispatch(string const & command)
3616 // Split command string into command and argument
3618 string line = frontStrip(command);
3619 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3621 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3625 bool Buffer::Dispatch(int action, string const & argument)
3627 bool dispatched = true;
3630 Exporter::Export(this, argument, false);
3640 void Buffer::resize()
3642 /// resize the BufferViews!
3648 void Buffer::resizeInsets(BufferView * bv)
3650 /// then remove all LyXText in text-insets
3651 LyXParagraph * par = paragraph;
3652 for (; par; par = par->next) {
3653 par->resizeInsetsLyXText(bv);
3657 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3660 LyXParagraph * par = paragraph;
3662 par->ChangeLanguage(params, from, to);
3668 bool Buffer::isMultiLingual()
3670 LyXParagraph * par = paragraph;
3672 if (par->isMultiLingual(params))
3680 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3681 LyXParagraph::size_type pos)
3684 it = par->InsetIterator(pos);
3685 if (it == par->inset_iterator_end()) {
3692 void Buffer::inset_iterator::SetParagraph()
3695 it = par->inset_iterator_begin();
3696 if (it != par->inset_iterator_end())
3701 // We maintain an invariant that whenever par = 0 then it = 0