1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * This file is Copyright 1996-2001
12 * ======================================================
18 #pragma implementation
22 #include "bufferlist.h"
24 #include "lyx_gui_misc.h"
25 #include "LyXAction.h"
28 #include "tex-strings.h"
30 #include "bufferview_funcs.h"
33 #include "mathed/formulamacro.h"
34 #include "mathed/formula.h"
35 #include "insets/inset.h"
36 #include "insets/inseterror.h"
37 #include "insets/insetlabel.h"
38 #include "insets/insetref.h"
39 #include "insets/inseturl.h"
40 #include "insets/insetnote.h"
41 #include "insets/insetquotes.h"
42 #include "insets/insetlatexaccent.h"
43 #include "insets/insetbib.h"
44 #include "insets/insetcite.h"
45 #include "insets/insetexternal.h"
46 #include "insets/insetindex.h"
47 #include "insets/insetinclude.h"
48 #include "insets/insettoc.h"
49 #include "insets/insetparent.h"
50 #include "insets/insetspecialchar.h"
51 #include "insets/figinset.h"
52 #include "insets/insettext.h"
53 #include "insets/insetert.h"
54 #include "insets/insetgraphics.h"
55 #include "insets/insetfoot.h"
56 #include "insets/insetmarginal.h"
57 #include "insets/insetminipage.h"
58 #include "insets/insetfloat.h"
59 #include "insets/insettabular.h"
61 #include "insets/insettheorem.h"
62 #include "insets/insetlist.h"
64 #include "insets/insetcaption.h"
65 #include "insets/insetfloatlist.h"
66 #include "support/textutils.h"
67 #include "support/filetools.h"
68 #include "support/path.h"
69 #include "support/os.h"
74 #include "LaTeXFeatures.h"
75 #include "support/syscall.h"
76 #include "support/lyxlib.h"
77 #include "support/FileInfo.h"
78 #include "support/lyxmanip.h"
82 #include "frontends/Dialogs.h"
83 #include "frontends/Alert.h"
87 #include "converter.h"
88 #include "BufferView.h"
89 #include "ParagraphParameters.h"
90 #include "iterators.h"
101 #include <sys/types.h>
119 using std::make_pair;
128 using lyx::layout_type;
129 using lyx::textclass_type;
131 // all these externs should eventually be removed.
132 extern BufferList bufferlist;
134 extern LyXAction lyxaction;
138 const int LYX_FORMAT = 220;
142 extern int tex_code_break_column;
145 Buffer::Buffer(string const & file, bool ronly)
147 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
149 filepath = OnlyPath(file);
158 if (read_only || (lyxrc.use_tempdir)) {
159 tmppath = CreateBufferTmpDir();
160 } else tmppath.erase();
166 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
167 // here the buffer should take care that it is
168 // saved properly, before it goes into the void.
170 // make sure that views using this buffer
175 if (!tmppath.empty()) {
176 DestroyBufferTmpDir(tmppath);
179 Paragraph * par = paragraph;
182 tmppar = par->next();
190 string const Buffer::getLatexName(bool no_path) const
192 string const name = ChangeExtension(MakeLatexName(filename), ".tex");
194 return OnlyFilename(name);
200 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
202 string const filename = getLatexName(false);
204 if (filename.empty())
205 return make_pair(Buffer::latexlog, string());
207 string path = OnlyPath(filename);
209 if (lyxrc.use_tempdir || !IsDirWriteable(path))
212 string const fname = AddName(path,
213 OnlyFilename(ChangeExtension(filename,
216 AddName(path, OnlyFilename(
217 ChangeExtension(filename,
218 formats.extension("literate") + ".out")));
220 // If no Latex log or Build log is newer, show Build log
222 FileInfo const f_fi(fname);
223 FileInfo const b_fi(bname);
226 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
227 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
228 return make_pair(Buffer::buildlog, bname);
230 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
231 return make_pair(Buffer::latexlog, fname);
235 void Buffer::setReadonly(bool flag)
237 if (read_only != flag) {
240 users->owner()->getDialogs()->updateBufferDependent(false);
245 /// Update window titles of all users
246 // Should work on a list
247 void Buffer::updateTitles() const
250 users->owner()->updateWindowTitle();
254 /// Reset autosave timer of all users
255 // Should work on a list
256 void Buffer::resetAutosaveTimers() const
259 users->owner()->resetAutosaveTimer();
263 void Buffer::setFileName(string const & newfile)
265 filename = MakeAbsPath(newfile);
266 filepath = OnlyPath(filename);
267 setReadonly(IsFileWriteable(filename) == 0);
272 // We'll remove this later. (Lgb)
275 string last_inset_read;
277 #ifndef NO_COMPABILITY
280 ErtComp() : active(false), in_tabular(false) {
287 std::stack<ErtComp> ert_stack;
291 #warning And _why_ is this here? (Lgb)
298 // candidate for move to BufferView
299 // (at least some parts in the beginning of the func)
302 // changed to be public and have one parameter
303 // if par = 0 normal behavior
304 // else insert behavior
305 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
306 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
310 #ifndef NO_COMPABILITY
311 ert_comp.contents.erase();
312 ert_comp.active = false;
313 ert_comp.in_tabular = false;
316 Paragraph::depth_type depth = 0;
317 bool the_end_read = false;
319 Paragraph * first_par = 0;
320 LyXFont font(LyXFont::ALL_INHERIT, params.language);
321 if (file_format < 216 && params.language->lang() == "hebrew")
322 font.setLanguage(default_language);
327 // We are inserting into an existing document
328 users->text->breakParagraph(users);
329 first_par = users->text->firstParagraph();
332 // We don't want to adopt the parameters from the
333 // document we insert, so we skip until the text begins:
336 string const pretoken = lex.getString();
337 if (pretoken == "\\layout") {
338 lex.pushToken(pretoken);
346 string const token = lex.getString();
348 if (token.empty()) continue;
350 lyxerr[Debug::PARSER] << "Handling token: `"
351 << token << "'" << endl;
354 parseSingleLyXformat2Token(lex, par, first_par,
362 paragraph = first_par;
364 if (unknown_layouts > 0) {
365 string s = _("Couldn't set the layout for ");
366 if (unknown_layouts == 1) {
367 s += _("one paragraph");
369 s += tostr(unknown_layouts);
370 s += _(" paragraphs");
372 Alert::alert(_("Textclass Loading Error!"), s,
373 _("When reading " + fileName()));
376 if (unknown_tokens > 0) {
377 string s = _("Encountered ");
378 if (unknown_tokens == 1) {
379 s += _("one unknown token");
381 s += tostr(unknown_tokens);
382 s += _(" unknown tokens");
384 Alert::alert(_("Textclass Loading Error!"), s,
385 _("When reading " + fileName()));
392 #ifndef NO_COMPABILITY
393 void Buffer::insertErtContents(Paragraph * par, int & pos,
394 LyXFont const & f, bool set_inactive)
396 if (!ert_comp.contents.empty()) {
397 lyxerr[Debug::INSETS] << "ERT contents:\n'"
398 << ert_comp.contents << "'" << endl;
399 Inset * inset = new InsetERT(ert_comp.contents, true);
401 font.setLanguage(f.language());
402 par->insertInset(pos++, inset, font);
403 ert_comp.contents.erase();
406 ert_comp.active = false;
413 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
414 Paragraph *& first_par,
415 string const & token, int & pos,
416 Paragraph::depth_type & depth,
420 bool the_end_read = false;
421 #ifndef NO_COMPABILITY
422 #ifndef NO_PEXTRA_REALLY
423 // This is super temporary but is needed to get the compability
424 // mode for minipages work correctly together with new tabulars.
425 static int call_depth;
427 bool checkminipage = false;
428 static Paragraph * minipar;
429 static Paragraph * parBeforeMinipage;
432 if (token[0] != '\\') {
433 #ifndef NO_COMPABILITY
434 if (ert_comp.active) {
435 ert_comp.contents += token;
438 for (string::const_iterator cit = token.begin();
439 cit != token.end(); ++cit) {
440 par->insertChar(pos, (*cit), font);
443 #ifndef NO_COMPABILITY
446 } else if (token == "\\i") {
447 Inset * inset = new InsetLatexAccent;
448 inset->read(this, lex);
449 par->insertInset(pos, inset, font);
451 } else if (token == "\\layout") {
452 #ifndef NO_COMPABILITY
453 ert_comp.in_tabular = false;
455 insertErtContents(par, pos, font);
458 string const layoutname = lex.getString();
459 pair<bool, layout_type> pp
460 = textclasslist.NumberOfLayout(params.textclass, layoutname);
462 #ifndef NO_COMPABILITY
463 if (compare_no_case(layoutname, "latex") == 0) {
464 ert_comp.active = true;
468 // The is the compability reading of layout caption.
469 // It can be removed in LyX version 1.3.0. (Lgb)
470 if (compare_no_case(layoutname, "caption") == 0) {
471 // We expect that the par we are now working on is
472 // really inside a InsetText inside a InsetFloat.
473 // We also know that captions can only be
474 // one paragraph. (Lgb)
476 // We should now read until the next "\layout"
478 // This is probably not good enough, what if the
479 // caption is the last par in the document (Lgb)
480 istream & ist = lex.getStream();
486 if (prefixIs(line, "\\layout")) {
490 if (prefixIs(line, "\\begin_inset"))
492 if (prefixIs(line, "\\end_inset")) {
503 // Now we should have the whole layout in ss
504 // we should now be able to give this to the
506 ss << "\\end_inset\n";
508 // This seems like a bug in stringstream.
509 // We really should be able to use ss
511 istringstream is(ss.str());
513 tmplex.setStream(is);
514 Inset * inset = new InsetCaption;
515 inset->Read(this, tmplex);
516 par->InsertInset(pos, inset, font);
523 par = new Paragraph(par);
527 par->layout = pp.second;
528 #ifndef NO_COMPABILITY
529 } else if (ert_comp.active) {
534 // use default layout "Standard" (0)
537 string const s = _("Layout had to be changed from\n")
538 + layoutname + _(" to ")
539 + textclasslist.NameOfLayout(params.textclass, par->layout);
540 InsetError * new_inset = new InsetError(s);
541 par->insertInset(0, new_inset);
542 par->setFont(0, LyXFont(LyXFont::ALL_INHERIT,
545 // Test whether the layout is obsolete.
546 LyXLayout const & layout =
547 textclasslist.Style(params.textclass,
549 if (!layout.obsoleted_by().empty())
550 par->layout = textclasslist
551 .NumberOfLayout(params.textclass,
552 layout.obsoleted_by())
554 par->params().depth(depth);
555 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
556 if (file_format < 216
557 && params.language->lang() == "hebrew")
558 font.setLanguage(default_language);
563 #ifndef NO_COMPABILITY
564 } else if (token == "\\begin_float") {
565 insertErtContents(par, pos, font);
566 //insertErtContents(par, pos, font, false);
567 //ert_stack.push(ert_comp);
568 //ert_comp = ErtComp();
570 // This is the compability reader. It can be removed in
571 // LyX version 1.3.0. (Lgb)
573 string const tmptok = lex.getString();
574 //lyxerr << "old float: " << tmptok << endl;
577 stringstream old_float;
579 if (tmptok == "footnote") {
580 inset = new InsetFoot;
581 old_float << "collapsed true\n";
582 } else if (tmptok == "margin") {
583 inset = new InsetMarginal;
584 old_float << "collapsed true\n";
585 } else if (tmptok == "fig") {
586 inset = new InsetFloat("figure");
587 old_float << "placement htbp\n"
589 << "collapsed false\n";
590 } else if (tmptok == "tab") {
591 inset = new InsetFloat("table");
592 old_float << "placement htbp\n"
594 << "collapsed false\n";
595 } else if (tmptok == "alg") {
596 inset = new InsetFloat("algorithm");
597 old_float << "placement htbp\n"
599 << "collapsed false\n";
600 } else if (tmptok == "wide-fig") {
601 inset = new InsetFloat("figure");
602 //InsetFloat * tmp = new InsetFloat("figure");
605 old_float << "placement htbp\n"
607 << "collapsed false\n";
608 } else if (tmptok == "wide-tab") {
609 inset = new InsetFloat("table");
610 //InsetFloat * tmp = new InsetFloat("table");
613 old_float << "placement htbp\n"
615 << "collapsed false\n";
619 #ifndef NO_PEXTRA_REALLY
622 return false; // no end read yet
625 // Here we need to check for \end_deeper and handle that
626 // before we do the footnote parsing.
627 // This _is_ a hack! (Lgb)
630 string const tmp = lex.getString();
631 if (tmp == "\\end_deeper") {
632 //lyxerr << "\\end_deeper caught!" << endl;
634 lex.printError("\\end_deeper: "
635 "depth is already null");
640 old_float << tmp << ' ';
645 old_float << lex.getLongString("\\end_float")
646 << "\n\\end_inset\n";
647 //lyxerr << "Float Body:\n" << old_float.str() << endl;
648 // That this does not work seems like a bug
649 // in stringstream. (Lgb)
650 istringstream istr(old_float.str());
652 nylex.setStream(istr);
653 inset->read(this, nylex);
654 par->insertInset(pos, inset, font);
656 insertErtContents(par, pos, font);
658 } else if (token == "\\begin_deeper") {
660 } else if (token == "\\end_deeper") {
662 lex.printError("\\end_deeper: "
663 "depth is already null");
667 } else if (token == "\\begin_preamble") {
668 params.readPreamble(lex);
669 } else if (token == "\\textclass") {
671 pair<bool, textclass_type> pp =
672 textclasslist.NumberOfClass(lex.getString());
674 params.textclass = pp.second;
676 Alert::alert(string(_("Textclass error")),
677 string(_("The document uses an unknown textclass \"")) +
678 lex.getString() + string("\"."),
679 string(_("LyX will not be able to produce output correctly.")));
680 params.textclass = 0;
682 if (!textclasslist.Load(params.textclass)) {
683 // if the textclass wasn't loaded properly
684 // we need to either substitute another
685 // or stop loading the file.
686 // I can substitute but I don't see how I can
687 // stop loading... ideas?? ARRae980418
688 Alert::alert(_("Textclass Loading Error!"),
689 string(_("Can't load textclass ")) +
690 textclasslist.NameOfClass(params.textclass),
691 _("-- substituting default"));
692 params.textclass = 0;
694 } else if (token == "\\options") {
696 params.options = lex.getString();
697 } else if (token == "\\language") {
698 params.readLanguage(lex);
699 } else if (token == "\\fontencoding") {
701 } else if (token == "\\inputencoding") {
703 params.inputenc = lex.getString();
704 } else if (token == "\\graphics") {
705 params.readGraphicsDriver(lex);
706 } else if (token == "\\fontscheme") {
708 params.fonts = lex.getString();
709 } else if (token == "\\noindent") {
710 par->params().noindent(true);
711 } else if (token == "\\fill_top") {
712 par->params().spaceTop(VSpace(VSpace::VFILL));
713 } else if (token == "\\fill_bottom") {
714 par->params().spaceBottom(VSpace(VSpace::VFILL));
715 } else if (token == "\\line_top") {
716 par->params().lineTop(true);
717 } else if (token == "\\line_bottom") {
718 par->params().lineBottom(true);
719 } else if (token == "\\pagebreak_top") {
720 par->params().pagebreakTop(true);
721 } else if (token == "\\pagebreak_bottom") {
722 par->params().pagebreakBottom(true);
723 } else if (token == "\\start_of_appendix") {
724 par->params().startOfAppendix(true);
725 } else if (token == "\\paragraph_separation") {
726 int tmpret = lex.findToken(string_paragraph_separation);
727 if (tmpret == -1) ++tmpret;
728 if (tmpret != LYX_LAYOUT_DEFAULT)
729 params.paragraph_separation =
730 static_cast<BufferParams::PARSEP>(tmpret);
731 } else if (token == "\\defskip") {
733 params.defskip = VSpace(lex.getString());
734 } else if (token == "\\epsfig") { // obsolete
735 // Indeed it is obsolete, but we HAVE to be backwards
736 // compatible until 0.14, because otherwise all figures
737 // in existing documents are irretrivably lost. (Asger)
738 params.readGraphicsDriver(lex);
739 } else if (token == "\\quotes_language") {
740 int tmpret = lex.findToken(string_quotes_language);
741 if (tmpret == -1) ++tmpret;
742 if (tmpret != LYX_LAYOUT_DEFAULT) {
743 InsetQuotes::quote_language tmpl =
744 InsetQuotes::EnglishQ;
747 tmpl = InsetQuotes::EnglishQ;
750 tmpl = InsetQuotes::SwedishQ;
753 tmpl = InsetQuotes::GermanQ;
756 tmpl = InsetQuotes::PolishQ;
759 tmpl = InsetQuotes::FrenchQ;
762 tmpl = InsetQuotes::DanishQ;
765 params.quotes_language = tmpl;
767 } else if (token == "\\quotes_times") {
769 switch (lex.getInteger()) {
771 params.quotes_times = InsetQuotes::SingleQ;
774 params.quotes_times = InsetQuotes::DoubleQ;
777 } else if (token == "\\papersize") {
778 int tmpret = lex.findToken(string_papersize);
782 params.papersize2 = tmpret;
783 } else if (token == "\\paperpackage") {
784 int tmpret = lex.findToken(string_paperpackages);
787 params.paperpackage = BufferParams::PACKAGE_NONE;
789 params.paperpackage = tmpret;
790 } else if (token == "\\use_geometry") {
792 params.use_geometry = lex.getInteger();
793 } else if (token == "\\use_amsmath") {
795 params.use_amsmath = lex.getInteger();
796 } else if (token == "\\use_natbib") {
798 params.use_natbib = lex.getInteger();
799 } else if (token == "\\use_numerical_citations") {
801 params.use_numerical_citations = lex.getInteger();
802 } else if (token == "\\paperorientation") {
803 int tmpret = lex.findToken(string_orientation);
804 if (tmpret == -1) ++tmpret;
805 if (tmpret != LYX_LAYOUT_DEFAULT)
806 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
807 } else if (token == "\\paperwidth") {
809 params.paperwidth = lex.getString();
810 } else if (token == "\\paperheight") {
812 params.paperheight = lex.getString();
813 } else if (token == "\\leftmargin") {
815 params.leftmargin = lex.getString();
816 } else if (token == "\\topmargin") {
818 params.topmargin = lex.getString();
819 } else if (token == "\\rightmargin") {
821 params.rightmargin = lex.getString();
822 } else if (token == "\\bottommargin") {
824 params.bottommargin = lex.getString();
825 } else if (token == "\\headheight") {
827 params.headheight = lex.getString();
828 } else if (token == "\\headsep") {
830 params.headsep = lex.getString();
831 } else if (token == "\\footskip") {
833 params.footskip = lex.getString();
834 } else if (token == "\\paperfontsize") {
836 params.fontsize = strip(lex.getString());
837 } else if (token == "\\papercolumns") {
839 params.columns = lex.getInteger();
840 } else if (token == "\\papersides") {
842 switch (lex.getInteger()) {
844 case 1: params.sides = LyXTextClass::OneSide; break;
845 case 2: params.sides = LyXTextClass::TwoSides; break;
847 } else if (token == "\\paperpagestyle") {
849 params.pagestyle = strip(lex.getString());
850 } else if (token == "\\bullet") {
852 int const index = lex.getInteger();
854 int temp_int = lex.getInteger();
855 params.user_defined_bullets[index].setFont(temp_int);
856 params.temp_bullets[index].setFont(temp_int);
858 temp_int = lex.getInteger();
859 params.user_defined_bullets[index].setCharacter(temp_int);
860 params.temp_bullets[index].setCharacter(temp_int);
862 temp_int = lex.getInteger();
863 params.user_defined_bullets[index].setSize(temp_int);
864 params.temp_bullets[index].setSize(temp_int);
866 string const temp_str = lex.getString();
867 if (temp_str != "\\end_bullet") {
868 // this element isn't really necessary for
869 // parsing but is easier for humans
870 // to understand bullets. Put it back and
871 // set a debug message?
872 lex.printError("\\end_bullet expected, got" + temp_str);
873 //how can I put it back?
875 } else if (token == "\\bulletLaTeX") {
877 int const index = lex.getInteger();
879 string temp_str = lex.getString();
881 while (temp_str != "\\end_bullet") {
882 // this loop structure is needed when user
883 // enters an empty string since the first
884 // thing returned will be the \\end_bullet
886 // if the LaTeX entry has spaces. Each element
887 // therefore needs to be read in turn
890 temp_str = lex.getString();
892 params.user_defined_bullets[index].setText(sum_str);
893 params.temp_bullets[index].setText(sum_str);
894 } else if (token == "\\secnumdepth") {
896 params.secnumdepth = lex.getInteger();
897 } else if (token == "\\tocdepth") {
899 params.tocdepth = lex.getInteger();
900 } else if (token == "\\spacing") {
902 string const tmp = strip(lex.getString());
903 Spacing::Space tmp_space = Spacing::Default;
905 if (tmp == "single") {
906 tmp_space = Spacing::Single;
907 } else if (tmp == "onehalf") {
908 tmp_space = Spacing::Onehalf;
909 } else if (tmp == "double") {
910 tmp_space = Spacing::Double;
911 } else if (tmp == "other") {
913 tmp_space = Spacing::Other;
914 tmp_val = lex.getFloat();
916 lex.printError("Unknown spacing token: '$$Token'");
918 // Small hack so that files written with klyx will be
921 par->params().spacing(Spacing(tmp_space, tmp_val));
923 params.spacing.set(tmp_space, tmp_val);
925 } else if (token == "\\paragraph_spacing") {
927 string const tmp = strip(lex.getString());
928 if (tmp == "single") {
929 par->params().spacing(Spacing(Spacing::Single));
930 } else if (tmp == "onehalf") {
931 par->params().spacing(Spacing(Spacing::Onehalf));
932 } else if (tmp == "double") {
933 par->params().spacing(Spacing(Spacing::Double));
934 } else if (tmp == "other") {
936 par->params().spacing(Spacing(Spacing::Other,
939 lex.printError("Unknown spacing token: '$$Token'");
941 } else if (token == "\\float_placement") {
943 params.float_placement = lex.getString();
944 } else if (token == "\\family") {
946 font.setLyXFamily(lex.getString());
947 } else if (token == "\\series") {
949 font.setLyXSeries(lex.getString());
950 } else if (token == "\\shape") {
952 font.setLyXShape(lex.getString());
953 } else if (token == "\\size") {
955 font.setLyXSize(lex.getString());
956 #ifndef NO_COMPABILITY
957 } else if (token == "\\latex") {
959 string const tok = lex.getString();
960 if (tok == "no_latex") {
962 insertErtContents(par, pos, font);
963 } else if (tok == "latex") {
964 ert_comp.active = true;
965 } else if (tok == "default") {
967 insertErtContents(par, pos, font);
969 lex.printError("Unknown LaTeX font flag "
973 } else if (token == "\\lang") {
975 string const tok = lex.getString();
976 Language const * lang = languages.getLanguage(tok);
978 font.setLanguage(lang);
980 font.setLanguage(params.language);
981 lex.printError("Unknown language `$$Token'");
983 } else if (token == "\\numeric") {
985 font.setNumber(font.setLyXMisc(lex.getString()));
986 } else if (token == "\\emph") {
988 font.setEmph(font.setLyXMisc(lex.getString()));
989 } else if (token == "\\bar") {
991 string const tok = lex.getString();
992 // This is dirty, but gone with LyX3. (Asger)
994 font.setUnderbar(LyXFont::ON);
995 else if (tok == "no")
996 font.setUnderbar(LyXFont::OFF);
997 else if (tok == "default")
998 font.setUnderbar(LyXFont::INHERIT);
1000 lex.printError("Unknown bar font flag "
1002 } else if (token == "\\noun") {
1004 font.setNoun(font.setLyXMisc(lex.getString()));
1005 } else if (token == "\\color") {
1007 font.setLyXColor(lex.getString());
1008 } else if (token == "\\align") {
1009 int tmpret = lex.findToken(string_align);
1010 if (tmpret == -1) ++tmpret;
1011 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1012 int const tmpret2 = int(pow(2.0, tmpret));
1013 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1014 par->params().align(LyXAlignment(tmpret2));
1016 } else if (token == "\\added_space_top") {
1018 par->params().spaceTop(VSpace(lex.getString()));
1019 } else if (token == "\\added_space_bottom") {
1021 par->params().spaceBottom(VSpace(lex.getString()));
1022 #ifndef NO_COMPABILITY
1023 #ifndef NO_PEXTRA_REALLY
1024 } else if (token == "\\pextra_type") {
1026 par->params().pextraType(lex.getInteger());
1027 } else if (token == "\\pextra_width") {
1029 par->params().pextraWidth(lex.getString());
1030 } else if (token == "\\pextra_widthp") {
1032 par->params().pextraWidthp(lex.getString());
1033 } else if (token == "\\pextra_alignment") {
1035 par->params().pextraAlignment(lex.getInteger());
1036 } else if (token == "\\pextra_hfill") {
1038 par->params().pextraHfill(lex.getInteger());
1039 } else if (token == "\\pextra_start_minipage") {
1041 par->params().pextraStartMinipage(lex.getInteger());
1044 } else if (token == "\\labelwidthstring") {
1046 par->params().labelWidthString(lex.getString());
1047 // do not delete this token, it is still needed!
1048 } else if (token == "\\end_inset") {
1049 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1050 << "Last inset read was: " << last_inset_read
1052 // Simply ignore this. The insets do not have
1054 // But insets should read it, it is a part of
1055 // the inset isn't it? Lgb.
1056 } else if (token == "\\begin_inset") {
1057 #ifndef NO_COMPABILITY
1058 insertErtContents(par, pos, font, false);
1059 ert_stack.push(ert_comp);
1060 ert_comp = ErtComp();
1062 readInset(lex, par, pos, font);
1063 #ifndef NO_COMPABILITY
1064 ert_comp = ert_stack.top();
1066 insertErtContents(par, pos, font);
1068 } else if (token == "\\SpecialChar") {
1069 LyXLayout const & layout =
1070 textclasslist.Style(params.textclass,
1073 // Insets don't make sense in a free-spacing context! ---Kayvan
1074 if (layout.free_spacing || par->isFreeSpacing()) {
1077 string next_token = lex.getString();
1078 if (next_token == "\\-") {
1079 par->insertChar(pos, '-', font);
1080 } else if (next_token == "\\protected_separator"
1081 || next_token == "~") {
1082 par->insertChar(pos, ' ', font);
1084 lex.printError("Token `$$Token' "
1086 "paragraph layout!");
1091 Inset * inset = new InsetSpecialChar;
1092 inset->read(this, lex);
1093 par->insertInset(pos, inset, font);
1096 } else if (token == "\\newline") {
1097 #ifndef NO_COMPABILITY
1098 if (!ert_comp.in_tabular && ert_comp.active) {
1099 ert_comp.contents += char(Paragraph::META_NEWLINE);
1101 // Since we cannot know it this is only a regular
1102 // newline or a tabular cell delimter we have to
1103 // handle the ERT here.
1104 insertErtContents(par, pos, font, false);
1106 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1110 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1113 } else if (token == "\\LyXTable") {
1114 #ifndef NO_COMPABILITY
1115 ert_comp.in_tabular = true;
1117 Inset * inset = new InsetTabular(*this);
1118 inset->read(this, lex);
1119 par->insertInset(pos, inset, font);
1121 } else if (token == "\\hfill") {
1122 par->insertChar(pos, Paragraph::META_HFILL, font);
1124 } else if (token == "\\protected_separator") { // obsolete
1125 // This is a backward compability thingie. (Lgb)
1126 // Remove it later some time...introduced with fileformat
1128 LyXLayout const & layout =
1129 textclasslist.Style(params.textclass,
1132 if (layout.free_spacing || par->isFreeSpacing()) {
1133 par->insertChar(pos, ' ', font);
1135 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1136 par->insertInset(pos, inset, font);
1139 } else if (token == "\\bibitem") { // ale970302
1141 InsetCommandParams p("bibitem", "dummy");
1142 par->bibkey = new InsetBibKey(p);
1144 par->bibkey->read(this, lex);
1145 } else if (token == "\\backslash") {
1146 #ifndef NO_COMPABILITY
1147 if (ert_comp.active) {
1148 ert_comp.contents += "\\";
1151 par->insertChar(pos, '\\', font);
1153 #ifndef NO_COMPABILITY
1156 } else if (token == "\\the_end") {
1157 #ifndef NO_COMPABILITY
1158 // If we still have some ert active here we have to insert
1159 // it so we don't loose it. (Lgb)
1160 insertErtContents(par, pos, font);
1162 the_end_read = true;
1163 #ifndef NO_COMPABILITY
1164 #ifndef NO_PEXTRA_REALLY
1165 minipar = parBeforeMinipage = 0;
1169 #ifndef NO_COMPABILITY
1170 if (ert_comp.active) {
1171 ert_comp.contents += token;
1174 // This should be insurance for the future: (Asger)
1177 string const s = _("Unknown token: ") + token
1178 + " " + lex.text() + "\n";
1180 InsetError * new_inset = new InsetError(s);
1181 par->insertInset(pos, new_inset);
1182 par->setFont(pos, LyXFont(LyXFont::ALL_INHERIT,
1185 #ifndef NO_COMPABILITY
1190 #ifndef NO_COMPABILITY
1191 #ifndef NO_PEXTRA_REALLY
1192 // I wonder if we could use this blanket fix for all the
1193 // checkminipage cases...
1194 if (par && par->size()) {
1195 // It is possible that this will check to often,
1196 // but that should not be an correctness issue.
1197 // Only a speed issue.
1198 checkminipage = true;
1201 // now check if we have a minipage paragraph as at this
1202 // point we already read all the necessary data!
1203 // this cannot be done in layout because there we did
1204 // not read yet the paragraph PEXTRA-params (Jug)
1206 // BEGIN pextra_minipage compability
1207 // This should be removed in 1.3.x (Lgb)
1209 // This compability code is not perfect. In a couple
1210 // of rand cases it fails. When the minipage par is
1211 // the first par in the document, and when there are
1212 // none or only one regular paragraphs after the
1213 // minipage. Currently I am not investing any effort
1214 // in fixing those cases.
1216 //lyxerr << "Call depth: " << call_depth << endl;
1217 if (checkminipage && (call_depth == 1)) {
1218 checkminipage = false;
1219 if (minipar && (minipar != par) &&
1220 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1222 lyxerr << "minipages in a row" << endl;
1223 if (par->params().pextraStartMinipage()) {
1224 lyxerr << "start new minipage" << endl;
1225 // minipages in a row
1226 par->previous()->next(0);
1229 Paragraph * tmp = minipar;
1231 tmp->params().pextraType(0);
1232 tmp->params().pextraWidth(string());
1233 tmp->params().pextraWidthp(string());
1234 tmp->params().pextraAlignment(0);
1235 tmp->params().pextraHfill(false);
1236 tmp->params().pextraStartMinipage(false);
1239 // create a new paragraph to insert the
1240 // minipages in the following case
1241 if (par->params().pextraStartMinipage() &&
1242 !par->params().pextraHfill())
1244 Paragraph * p = new Paragraph;
1246 p->previous(parBeforeMinipage);
1247 parBeforeMinipage->next(p);
1249 p->params().depth(parBeforeMinipage->params().depth());
1250 parBeforeMinipage = p;
1252 InsetMinipage * mini = new InsetMinipage;
1253 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1254 mini->width(par->params().pextraWidth());
1255 if (!par->params().pextraWidthp().empty()) {
1256 lyxerr << "WP:" << mini->width() << endl;
1257 mini->width(tostr(par->params().pextraWidthp())+"%");
1259 mini->inset.paragraph(par);
1260 // Insert the minipage last in the
1261 // previous paragraph.
1262 if (par->params().pextraHfill()) {
1263 parBeforeMinipage->insertChar
1264 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1266 parBeforeMinipage->insertInset
1267 (parBeforeMinipage->size(), mini);
1271 lyxerr << "new minipage par" << endl;
1272 //nothing to do just continue reading
1275 } else if (minipar && (minipar != par)) {
1276 lyxerr << "last minipage par read" << endl;
1277 // The last paragraph read was not part of a
1278 // minipage but the par linked list is...
1279 // So we need to remove the last par from the
1281 if (par->previous())
1282 par->previous()->next(0);
1283 par->previous(parBeforeMinipage);
1284 parBeforeMinipage->next(par);
1285 Paragraph * tmp = minipar;
1287 tmp->params().pextraType(0);
1288 tmp->params().pextraWidth(string());
1289 tmp->params().pextraWidthp(string());
1290 tmp->params().pextraAlignment(0);
1291 tmp->params().pextraHfill(false);
1292 tmp->params().pextraStartMinipage(false);
1295 depth = parBeforeMinipage->params().depth();
1296 minipar = parBeforeMinipage = 0;
1297 } else if (!minipar &&
1298 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1300 // par is the first paragraph in a minipage
1301 lyxerr << "begin minipage" << endl;
1302 // To minimize problems for
1303 // the users we will insert
1304 // the first minipage in
1305 // a sequence of minipages
1306 // in its own paragraph.
1307 Paragraph * p = new Paragraph;
1309 p->previous(par->previous());
1311 p->params().depth(depth);
1312 par->params().depth(0);
1314 if (par->previous())
1315 par->previous()->next(p);
1317 parBeforeMinipage = p;
1319 if (!first_par || (first_par == par))
1322 InsetMinipage * mini = new InsetMinipage;
1323 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1324 mini->width(minipar->params().pextraWidth());
1325 if (!par->params().pextraWidthp().empty()) {
1326 lyxerr << "WP:" << mini->width() << endl;
1327 mini->width(tostr(par->params().pextraWidthp())+"%");
1329 mini->inset.paragraph(minipar);
1331 // Insert the minipage last in the
1332 // previous paragraph.
1333 if (minipar->params().pextraHfill()) {
1334 parBeforeMinipage->insertChar
1335 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1337 parBeforeMinipage->insertInset
1338 (parBeforeMinipage->size(), mini);
1341 // End of pextra_minipage compability
1345 return the_end_read;
1348 // needed to insert the selection
1349 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1350 LyXFont const & fn,string const & str) const
1352 LyXLayout const & layout = textclasslist.Style(params.textclass,
1356 (void)par->checkInsertChar(font);
1357 // insert the string, don't insert doublespace
1358 bool space_inserted = true;
1359 for(string::const_iterator cit = str.begin();
1360 cit != str.end(); ++cit) {
1362 if (par->size() || layout.keepempty) {
1363 par->breakParagraph(params, pos,
1364 layout.isEnvironment());
1367 space_inserted = true;
1371 // do not insert consecutive spaces if !free_spacing
1372 } else if ((*cit == ' ' || *cit == '\t') &&
1373 space_inserted && !layout.free_spacing &&
1374 !par->isFreeSpacing())
1377 } else if (*cit == '\t') {
1378 if (!layout.free_spacing && !par->isFreeSpacing()) {
1379 // tabs are like spaces here
1380 par->insertChar(pos, ' ', font);
1382 space_inserted = true;
1384 const pos_type nb = 8 - pos % 8;
1385 for (pos_type a = 0; a < nb ; ++a) {
1386 par->insertChar(pos, ' ', font);
1389 space_inserted = true;
1391 } else if (!IsPrintable(*cit)) {
1392 // Ignore unprintables
1395 // just insert the character
1396 par->insertChar(pos, *cit, font);
1398 space_inserted = (*cit == ' ');
1405 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1406 int & pos, LyXFont & font)
1408 // consistency check
1409 if (lex.getString() != "\\begin_inset") {
1410 lyxerr << "Buffer::readInset: Consistency check failed."
1417 string const tmptok = lex.getString();
1418 last_inset_read = tmptok;
1420 // test the different insets
1421 if (tmptok == "LatexCommand") {
1422 InsetCommandParams inscmd;
1425 string const cmdName = inscmd.getCmdName();
1427 // This strange command allows LyX to recognize "natbib" style
1428 // citations: citet, citep, Citet etc.
1429 if (compare_no_case(cmdName, "cite", 4) == 0) {
1430 inset = new InsetCitation(inscmd);
1431 } else if (cmdName == "bibitem") {
1432 lex.printError("Wrong place for bibitem");
1433 inset = new InsetBibKey(inscmd);
1434 } else if (cmdName == "BibTeX") {
1435 inset = new InsetBibtex(inscmd);
1436 } else if (cmdName == "index") {
1437 inset = new InsetIndex(inscmd);
1438 } else if (cmdName == "include") {
1439 inset = new InsetInclude(inscmd, *this);
1440 } else if (cmdName == "label") {
1441 inset = new InsetLabel(inscmd);
1442 } else if (cmdName == "url"
1443 || cmdName == "htmlurl") {
1444 inset = new InsetUrl(inscmd);
1445 } else if (cmdName == "ref"
1446 || cmdName == "pageref"
1447 || cmdName == "vref"
1448 || cmdName == "vpageref"
1449 || cmdName == "prettyref") {
1450 if (!inscmd.getOptions().empty()
1451 || !inscmd.getContents().empty()) {
1452 inset = new InsetRef(inscmd, *this);
1454 } else if (cmdName == "tableofcontents") {
1455 inset = new InsetTOC(inscmd);
1456 } else if (cmdName == "listofalgorithms") {
1457 inset = new InsetFloatList("algorithm");
1458 } else if (cmdName == "listoffigures") {
1459 inset = new InsetFloatList("figure");
1460 } else if (cmdName == "listoftables") {
1461 inset = new InsetFloatList("table");
1462 } else if (cmdName == "printindex") {
1463 inset = new InsetPrintIndex(inscmd);
1464 } else if (cmdName == "lyxparent") {
1465 inset = new InsetParent(inscmd, *this);
1468 bool alreadyread = false;
1469 if (tmptok == "Quotes") {
1470 inset = new InsetQuotes;
1471 } else if (tmptok == "External") {
1472 inset = new InsetExternal;
1473 } else if (tmptok == "FormulaMacro") {
1474 inset = new InsetFormulaMacro;
1475 } else if (tmptok == "Formula") {
1476 inset = new InsetFormula;
1477 } else if (tmptok == "Figure") { // Backward compatibility
1478 inset = new InsetFig(100, 100, *this);
1479 //inset = new InsetGraphics;
1480 } else if (tmptok == "Graphics") {
1481 inset = new InsetGraphics;
1482 } else if (tmptok == "Info") {// backwards compatibility
1483 inset = new InsetNote(this,
1484 lex.getLongString("\\end_inset"),
1487 } else if (tmptok == "Note") {
1488 inset = new InsetNote;
1489 } else if (tmptok == "Include") {
1490 InsetCommandParams p( "Include" );
1491 inset = new InsetInclude(p, *this);
1492 } else if (tmptok == "ERT") {
1493 inset = new InsetERT;
1494 } else if (tmptok == "Tabular") {
1495 inset = new InsetTabular(*this);
1496 } else if (tmptok == "Text") {
1497 inset = new InsetText;
1498 } else if (tmptok == "Foot") {
1499 inset = new InsetFoot;
1500 } else if (tmptok == "Marginal") {
1501 inset = new InsetMarginal;
1502 } else if (tmptok == "Minipage") {
1503 inset = new InsetMinipage;
1504 } else if (tmptok == "Float") {
1506 string tmptok = lex.getString();
1507 inset = new InsetFloat(tmptok);
1509 } else if (tmptok == "List") {
1510 inset = new InsetList;
1511 } else if (tmptok == "Theorem") {
1512 inset = new InsetList;
1514 } else if (tmptok == "Caption") {
1515 inset = new InsetCaption;
1516 } else if (tmptok == "FloatList") {
1517 inset = new InsetFloatList;
1520 if (inset && !alreadyread) inset->read(this, lex);
1524 par->insertInset(pos, inset, font);
1530 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1534 string const token(lex.getString());
1535 if (token == "\\lyxformat") { // the first token _must_ be...
1537 string tmp_format = lex.getString();
1538 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1539 // if present remove ".," from string.
1540 string::size_type dot = tmp_format.find_first_of(".,");
1541 //lyxerr << " dot found at " << dot << endl;
1542 if (dot != string::npos)
1543 tmp_format.erase(dot, 1);
1544 file_format = strToInt(tmp_format);
1545 if (file_format == LYX_FORMAT) {
1547 } else if (file_format > LYX_FORMAT) {
1549 Alert::alert(_("Warning!"),
1550 _("LyX file format is newer that what"),
1551 _("is supported in this LyX version. Expect some problems."));
1553 } else if (file_format < LYX_FORMAT) {
1555 if (file_format < 200) {
1556 Alert::alert(_("ERROR!"),
1557 _("Old LyX file format found. "
1558 "Use LyX 0.10.x to read this!"));
1562 bool the_end = readLyXformat2(lex, par);
1563 params.setPaperStuff();
1564 // the_end was added in 213
1565 if (file_format < 213)
1569 Alert::alert(_("Warning!"),
1570 _("Reading of document is not complete"),
1571 _("Maybe the document is truncated"));
1574 } else { // "\\lyxformat" not found
1575 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1578 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1583 // Should probably be moved to somewhere else: BufferView? LyXView?
1584 bool Buffer::save() const
1586 // We don't need autosaves in the immediate future. (Asger)
1587 resetAutosaveTimers();
1591 if (lyxrc.make_backup) {
1592 s = fileName() + '~';
1593 if (!lyxrc.backupdir_path.empty())
1594 s = AddName(lyxrc.backupdir_path,
1595 subst(os::slashify_path(s),'/','!'));
1597 // Rename is the wrong way of making a backup,
1598 // this is the correct way.
1599 /* truss cp fil fil2:
1600 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1601 stat("LyXVC.lyx", 0xEFFFF688) = 0
1602 open("LyXVC.lyx", O_RDONLY) = 3
1603 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1604 fstat(4, 0xEFFFF508) = 0
1605 fstat(3, 0xEFFFF508) = 0
1606 read(3, " # T h i s f i l e w".., 8192) = 5579
1607 write(4, " # T h i s f i l e w".., 5579) = 5579
1608 read(3, 0xEFFFD4A0, 8192) = 0
1611 chmod("LyXVC3.lyx", 0100644) = 0
1612 lseek(0, 0, SEEK_CUR) = 46440
1616 // Should probably have some more error checking here.
1617 // Should be cleaned up in 0.13, at least a bit.
1618 // Doing it this way, also makes the inodes stay the same.
1619 // This is still not a very good solution, in particular we
1620 // might loose the owner of the backup.
1621 FileInfo finfo(fileName());
1622 if (finfo.exist()) {
1623 mode_t fmode = finfo.getMode();
1624 struct utimbuf times = {
1625 finfo.getAccessTime(),
1626 finfo.getModificationTime() };
1628 ifstream ifs(fileName().c_str());
1629 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1634 ::chmod(s.c_str(), fmode);
1636 if (::utime(s.c_str(), ×)) {
1637 lyxerr << "utime error." << endl;
1640 lyxerr << "LyX was not able to make "
1641 "backup copy. Beware." << endl;
1646 if (writeFile(fileName(), false)) {
1648 removeAutosaveFile(fileName());
1650 // Saving failed, so backup is not backup
1651 if (lyxrc.make_backup) {
1652 lyx::rename(s, fileName());
1660 // Returns false if unsuccesful
1661 bool Buffer::writeFile(string const & fname, bool flag) const
1663 // if flag is false writeFile will not create any GUI
1664 // warnings, only cerr.
1665 // Needed for autosave in background or panic save (Matthias 120496)
1667 if (read_only && (fname == filename)) {
1668 // Here we should come with a question if we should
1669 // perform the write anyway.
1671 lyxerr << _("Error! Document is read-only: ")
1674 Alert::alert(_("Error! Document is read-only: "),
1679 FileInfo finfo(fname);
1680 if (finfo.exist() && !finfo.writable()) {
1681 // Here we should come with a question if we should
1682 // try to do the save anyway. (i.e. do a chmod first)
1684 lyxerr << _("Error! Cannot write file: ")
1687 Alert::err_alert(_("Error! Cannot write file: "),
1692 ofstream ofs(fname.c_str());
1695 lyxerr << _("Error! Cannot open file: ")
1698 Alert::err_alert(_("Error! Cannot open file: "),
1704 // Use the standard "C" locale for file output.
1705 ofs.imbue(std::locale::classic());
1708 // The top of the file should not be written by params.
1710 // write out a comment in the top of the file
1711 ofs << '#' << lyx_docversion
1712 << " created this file. For more info see http://www.lyx.org/\n"
1713 << "\\lyxformat " << LYX_FORMAT << "\n";
1715 // now write out the buffer paramters.
1716 params.writeFile(ofs);
1718 Paragraph::depth_type depth = 0;
1720 // this will write out all the paragraphs
1721 // using recursive descent.
1722 paragraph->writeFile(this, ofs, params, depth);
1724 // Write marker that shows file is complete
1725 ofs << "\n\\the_end" << endl;
1729 // how to check if close went ok?
1730 // Following is an attempt... (BE 20001011)
1732 // good() returns false if any error occured, including some
1733 // formatting error.
1734 // bad() returns true if something bad happened in the buffer,
1735 // which should include file system full errors.
1742 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1744 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1754 string const Buffer::asciiParagraph(Paragraph const * par,
1755 unsigned int linelen) const
1757 ostringstream buffer;
1758 Paragraph::depth_type depth = 0;
1760 Paragraph::depth_type ltype_depth = 0;
1761 string::size_type currlinelen = 0;
1762 bool ref_printed = false;
1766 if (!par->previous()) {
1767 // begins or ends a deeper area ?
1768 if (depth != par->params().depth()) {
1769 if (par->params().depth() > depth) {
1770 while (par->params().depth() > depth) {
1774 while (par->params().depth() < depth) {
1780 // First write the layout
1781 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1782 if (tmp == "Itemize") {
1784 ltype_depth = depth + 1;
1785 } else if (tmp == "Enumerate") {
1787 ltype_depth = depth + 1;
1788 } else if (contains(tmp, "ection")) {
1790 ltype_depth = depth + 1;
1791 } else if (contains(tmp, "aragraph")) {
1793 ltype_depth = depth + 1;
1794 } else if (tmp == "Description") {
1796 ltype_depth = depth + 1;
1797 } else if (tmp == "Abstract") {
1800 } else if (tmp == "Bibliography") {
1808 /* maybe some vertical spaces */
1810 /* the labelwidthstring used in lists */
1814 /* some pagebreaks? */
1818 /* what about the alignment */
1820 lyxerr << "Should this ever happen?" << endl;
1823 for (pos_type i = 0; i < par->size(); ++i) {
1824 if (!i && !noparbreak) {
1827 for (Paragraph::depth_type j = 0; j < depth; ++j)
1829 currlinelen = depth * 2;
1832 case 4: // (Sub)Paragraph
1833 case 5: // Description
1837 buffer << "Abstract\n\n";
1839 buffer << "Abstract: ";
1841 case 7: // Bibliography
1844 buffer << "References\n\n";
1846 buffer << "References: ";
1851 buffer << par->params().labelString() << " ";
1854 if (ltype_depth > depth) {
1855 for (Paragraph::depth_type j = ltype_depth - 1;
1858 currlinelen += (ltype_depth-depth)*2;
1862 char c = par->getUChar(params, i);
1866 case Paragraph::META_INSET:
1868 Inset const * inset = par->getInset(i);
1870 if (!inset->ascii(this, buffer)) {
1873 rsplit(buffer.str().c_str(),
1875 currlinelen += s.length();
1877 // to be sure it breaks paragraph
1878 currlinelen += linelen;
1884 case Paragraph::META_NEWLINE:
1887 for (Paragraph::depth_type j = 0;
1891 currlinelen = depth * 2;
1892 if (ltype_depth > depth) {
1893 for (Paragraph::depth_type j = ltype_depth;
1896 currlinelen += (ltype_depth - depth) * 2;
1900 case Paragraph::META_HFILL:
1905 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1906 (c == ' ') && ((i + 2) < par->size()))
1909 for (Paragraph::depth_type j = 0;
1912 currlinelen = depth * 2;
1913 if (ltype_depth > depth) {
1914 for (Paragraph::depth_type j = ltype_depth;
1917 currlinelen += (ltype_depth-depth)*2;
1919 } else if (c != '\0') {
1923 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1927 return buffer.str().c_str();
1931 void Buffer::writeFileAscii(string const & fname, int linelen)
1933 ofstream ofs(fname.c_str());
1935 Alert::err_alert(_("Error: Cannot write file:"), fname);
1938 writeFileAscii(ofs, linelen);
1942 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1944 Paragraph * par = paragraph;
1946 ofs << asciiParagraph(par, linelen);
1954 void Buffer::makeLaTeXFile(string const & fname,
1955 string const & original_path,
1956 bool nice, bool only_body)
1958 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1960 niceFile = nice; // this will be used by Insetincludes.
1962 tex_code_break_column = lyxrc.ascii_linelen;
1964 LyXTextClass const & tclass =
1965 textclasslist.TextClass(params.textclass);
1967 ofstream ofs(fname.c_str());
1969 Alert::err_alert(_("Error: Cannot open file: "), fname);
1973 // validate the buffer.
1974 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1975 LaTeXFeatures features(params, tclass.numLayouts());
1977 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1980 // The starting paragraph of the coming rows is the
1981 // first paragraph of the document. (Asger)
1982 texrow.start(paragraph, 0);
1984 if (!only_body && nice) {
1985 ofs << "%% " << lyx_docversion << " created this file. "
1986 "For more info, see http://www.lyx.org/.\n"
1987 "%% Do not edit unless you really know what "
1992 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1993 // There are a few differences between nice LaTeX and usual files:
1994 // usual is \batchmode and has a
1995 // special input@path to allow the including of figures
1996 // with either \input or \includegraphics (what figinsets do).
1997 // batchmode is not set if there is a tex_code_break_column.
1998 // In this case somebody is interested in the generated LaTeX,
1999 // so this is OK. input@path is set when the actual parameter
2000 // original_path is set. This is done for usual tex-file, but not
2001 // for nice-latex-file. (Matthias 250696)
2004 // code for usual, NOT nice-latex-file
2005 ofs << "\\batchmode\n"; // changed
2006 // from \nonstopmode
2009 if (!original_path.empty()) {
2010 ofs << "\\makeatletter\n"
2011 << "\\def\\input@path{{"
2012 << os::external_path(original_path) << "/}}\n"
2013 << "\\makeatother\n";
2019 ofs << "\\documentclass";
2021 ostringstream options; // the document class options.
2023 if (tokenPos(tclass.opt_fontsize(),
2024 '|', params.fontsize) >= 0) {
2025 // only write if existing in list (and not default)
2026 options << params.fontsize << "pt,";
2030 if (!params.use_geometry &&
2031 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2032 switch (params.papersize) {
2033 case BufferParams::PAPER_A4PAPER:
2034 options << "a4paper,";
2036 case BufferParams::PAPER_USLETTER:
2037 options << "letterpaper,";
2039 case BufferParams::PAPER_A5PAPER:
2040 options << "a5paper,";
2042 case BufferParams::PAPER_B5PAPER:
2043 options << "b5paper,";
2045 case BufferParams::PAPER_EXECUTIVEPAPER:
2046 options << "executivepaper,";
2048 case BufferParams::PAPER_LEGALPAPER:
2049 options << "legalpaper,";
2055 if (params.sides != tclass.sides()) {
2056 switch (params.sides) {
2057 case LyXTextClass::OneSide:
2058 options << "oneside,";
2060 case LyXTextClass::TwoSides:
2061 options << "twoside,";
2067 if (params.columns != tclass.columns()) {
2068 if (params.columns == 2)
2069 options << "twocolumn,";
2071 options << "onecolumn,";
2074 if (!params.use_geometry
2075 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2076 options << "landscape,";
2078 // language should be a parameter to \documentclass
2080 ostringstream language_options;
2081 if (params.language->babel() == "hebrew"
2082 && default_language->babel() != "hebrew")
2083 // This seems necessary
2084 features.useLanguage(default_language);
2086 if (lyxrc.language_use_babel ||
2087 params.language->lang() != lyxrc.default_language ||
2088 !features.hasLanguages()) {
2090 language_options << features.getLanguages();
2091 language_options << params.language->babel();
2092 if (lyxrc.language_global_options)
2093 options << language_options.str() << ',';
2096 // the user-defined options
2097 if (!params.options.empty()) {
2098 options << params.options << ',';
2101 string strOptions(options.str().c_str());
2102 if (!strOptions.empty()){
2103 strOptions = strip(strOptions, ',');
2104 ofs << '[' << strOptions << ']';
2108 << textclasslist.LatexnameOfClass(params.textclass)
2111 // end of \documentclass defs
2113 // font selection must be done before loading fontenc.sty
2114 // The ae package is not needed when using OT1 font encoding.
2115 if (params.fonts != "default" &&
2116 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2117 ofs << "\\usepackage{" << params.fonts << "}\n";
2119 if (params.fonts == "ae") {
2120 ofs << "\\usepackage{aecompl}\n";
2124 // this one is not per buffer
2125 if (lyxrc.fontenc != "default") {
2126 ofs << "\\usepackage[" << lyxrc.fontenc
2131 if (params.inputenc == "auto") {
2132 string const doc_encoding =
2133 params.language->encoding()->LatexName();
2135 // Create a list with all the input encodings used
2137 set<string> encodings = features.getEncodingSet(doc_encoding);
2139 ofs << "\\usepackage[";
2140 std::copy(encodings.begin(), encodings.end(),
2141 std::ostream_iterator<string>(ofs, ","));
2142 ofs << doc_encoding << "]{inputenc}\n";
2144 } else if (params.inputenc != "default") {
2145 ofs << "\\usepackage[" << params.inputenc
2150 // At the very beginning the text parameters.
2151 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2152 switch (params.paperpackage) {
2153 case BufferParams::PACKAGE_A4:
2154 ofs << "\\usepackage{a4}\n";
2157 case BufferParams::PACKAGE_A4WIDE:
2158 ofs << "\\usepackage{a4wide}\n";
2161 case BufferParams::PACKAGE_WIDEMARGINSA4:
2162 ofs << "\\usepackage[widemargins]{a4}\n";
2167 if (params.use_geometry) {
2168 ofs << "\\usepackage{geometry}\n";
2170 ofs << "\\geometry{verbose";
2171 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2172 ofs << ",landscape";
2173 switch (params.papersize2) {
2174 case BufferParams::VM_PAPER_CUSTOM:
2175 if (!params.paperwidth.empty())
2176 ofs << ",paperwidth="
2177 << params.paperwidth;
2178 if (!params.paperheight.empty())
2179 ofs << ",paperheight="
2180 << params.paperheight;
2182 case BufferParams::VM_PAPER_USLETTER:
2183 ofs << ",letterpaper";
2185 case BufferParams::VM_PAPER_USLEGAL:
2186 ofs << ",legalpaper";
2188 case BufferParams::VM_PAPER_USEXECUTIVE:
2189 ofs << ",executivepaper";
2191 case BufferParams::VM_PAPER_A3:
2194 case BufferParams::VM_PAPER_A4:
2197 case BufferParams::VM_PAPER_A5:
2200 case BufferParams::VM_PAPER_B3:
2203 case BufferParams::VM_PAPER_B4:
2206 case BufferParams::VM_PAPER_B5:
2210 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2211 switch (lyxrc.default_papersize) {
2212 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2213 case BufferParams::PAPER_USLETTER:
2214 ofs << ",letterpaper";
2216 case BufferParams::PAPER_LEGALPAPER:
2217 ofs << ",legalpaper";
2219 case BufferParams::PAPER_EXECUTIVEPAPER:
2220 ofs << ",executivepaper";
2222 case BufferParams::PAPER_A3PAPER:
2225 case BufferParams::PAPER_A4PAPER:
2228 case BufferParams::PAPER_A5PAPER:
2231 case BufferParams::PAPER_B5PAPER:
2236 if (!params.topmargin.empty())
2237 ofs << ",tmargin=" << params.topmargin;
2238 if (!params.bottommargin.empty())
2239 ofs << ",bmargin=" << params.bottommargin;
2240 if (!params.leftmargin.empty())
2241 ofs << ",lmargin=" << params.leftmargin;
2242 if (!params.rightmargin.empty())
2243 ofs << ",rmargin=" << params.rightmargin;
2244 if (!params.headheight.empty())
2245 ofs << ",headheight=" << params.headheight;
2246 if (!params.headsep.empty())
2247 ofs << ",headsep=" << params.headsep;
2248 if (!params.footskip.empty())
2249 ofs << ",footskip=" << params.footskip;
2254 if (features.isRequired("amsstyle")
2255 && !tclass.provides(LyXTextClass::amsmath)) {
2256 ofs << "\\usepackage{amsmath}\n";
2260 if (tokenPos(tclass.opt_pagestyle(),
2261 '|', params.pagestyle) >= 0) {
2262 if (params.pagestyle == "fancy") {
2263 ofs << "\\usepackage{fancyhdr}\n";
2266 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2270 if (params.secnumdepth != tclass.secnumdepth()) {
2271 ofs << "\\setcounter{secnumdepth}{"
2272 << params.secnumdepth
2276 if (params.tocdepth != tclass.tocdepth()) {
2277 ofs << "\\setcounter{tocdepth}{"
2283 if (params.paragraph_separation) {
2284 switch (params.defskip.kind()) {
2285 case VSpace::SMALLSKIP:
2286 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2288 case VSpace::MEDSKIP:
2289 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2291 case VSpace::BIGSKIP:
2292 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2294 case VSpace::LENGTH:
2295 ofs << "\\setlength\\parskip{"
2296 << params.defskip.length().asLatexString()
2299 default: // should never happen // Then delete it.
2300 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2305 ofs << "\\setlength\\parindent{0pt}\n";
2309 // Now insert the LyX specific LaTeX commands...
2311 // The optional packages;
2312 string preamble(features.getPackages());
2314 // this might be useful...
2315 preamble += "\n\\makeatletter\n";
2317 // Some macros LyX will need
2318 string tmppreamble(features.getMacros());
2320 if (!tmppreamble.empty()) {
2321 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2322 "LyX specific LaTeX commands.\n"
2323 + tmppreamble + '\n';
2326 // the text class specific preamble
2327 tmppreamble = features.getTClassPreamble();
2328 if (!tmppreamble.empty()) {
2329 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2330 "Textclass specific LaTeX commands.\n"
2331 + tmppreamble + '\n';
2334 /* the user-defined preamble */
2335 if (!params.preamble.empty()) {
2336 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2337 "User specified LaTeX commands.\n"
2338 + params.preamble + '\n';
2341 preamble += "\\makeatother\n";
2343 // Itemize bullet settings need to be last in case the user
2344 // defines their own bullets that use a package included
2345 // in the user-defined preamble -- ARRae
2346 // Actually it has to be done much later than that
2347 // since some packages like frenchb make modifications
2348 // at \begin{document} time -- JMarc
2350 for (int i = 0; i < 4; ++i) {
2351 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2352 if (bullets_def.empty())
2353 bullets_def="\\AtBeginDocument{\n";
2354 bullets_def += " \\renewcommand{\\labelitemi";
2356 // `i' is one less than the item to modify
2363 bullets_def += "ii";
2369 bullets_def += "}{" +
2370 params.user_defined_bullets[i].getText()
2375 if (!bullets_def.empty())
2376 preamble += bullets_def + "}\n\n";
2378 for (int j = countChar(preamble, '\n'); j-- ;) {
2384 // We try to load babel late, in case it interferes
2385 // with other packages.
2387 string tmp = lyxrc.language_package;
2388 if (!lyxrc.language_global_options
2389 && tmp == "\\usepackage{babel}")
2390 tmp = string("\\usepackage[") +
2391 language_options.str().c_str() +
2398 ofs << "\\begin{document}\n";
2401 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2403 if (!lyxrc.language_auto_begin) {
2404 ofs << subst(lyxrc.language_command_begin, "$$lang",
2405 params.language->babel())
2410 latexParagraphs(ofs, paragraph, 0, texrow);
2412 // add this just in case after all the paragraphs
2416 if (!lyxrc.language_auto_end) {
2417 ofs << subst(lyxrc.language_command_end, "$$lang",
2418 params.language->babel())
2424 ofs << "\\end{document}\n";
2427 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2429 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2433 // Just to be sure. (Asger)
2436 // tex_code_break_column's value is used to decide
2437 // if we are in batchmode or not (within mathed_write()
2438 // in math_write.C) so we must set it to a non-zero
2439 // value when we leave otherwise we save incorrect .lyx files.
2440 tex_code_break_column = lyxrc.ascii_linelen;
2444 lyxerr << "File was not closed properly." << endl;
2447 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2452 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2454 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2455 Paragraph * endpar, TexRow & texrow) const
2457 bool was_title = false;
2458 bool already_title = false;
2461 while (par != endpar) {
2462 LyXLayout const & layout =
2463 textclasslist.Style(params.textclass,
2466 if (layout.intitle) {
2467 if (already_title) {
2468 lyxerr <<"Error in latexParagraphs: You"
2469 " should not mix title layouts"
2470 " with normal ones." << endl;
2473 } else if (was_title && !already_title) {
2474 ofs << "\\maketitle\n";
2476 already_title = true;
2480 if (layout.isEnvironment()) {
2481 par = par->TeXEnvironment(this, params, ofs, texrow);
2483 par = par->TeXOnePar(this, params, ofs, texrow, false);
2486 // It might be that we only have a title in this document
2487 if (was_title && !already_title) {
2488 ofs << "\\maketitle\n";
2494 bool Buffer::isLatex() const
2496 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2500 bool Buffer::isLinuxDoc() const
2502 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2506 bool Buffer::isLiterate() const
2508 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2512 bool Buffer::isDocBook() const
2514 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2518 bool Buffer::isSGML() const
2520 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2521 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2525 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2526 string const & latexname) const
2528 if (!latexname.empty() && latexname != "!-- --")
2529 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2530 os << string(depth, ' ') << "<" << latexname << ">\n";
2534 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2535 string const & latexname) const
2537 if (!latexname.empty() && latexname != "!-- --")
2538 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2539 os << string(depth, ' ') << "</" << latexname << ">\n";
2543 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2545 ofstream ofs(fname.c_str());
2548 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2552 niceFile = nice; // this will be used by included files.
2554 LyXTextClass const & tclass =
2555 textclasslist.TextClass(params.textclass);
2557 LaTeXFeatures features(params, tclass.numLayouts());
2562 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2565 ofs << "<!doctype linuxdoc system";
2567 string preamble = params.preamble;
2568 preamble += features.getIncludedFiles(fname);
2569 preamble += features.getLyXSGMLEntities();
2571 if (!preamble.empty()) {
2572 ofs << " [ " << preamble << " ]";
2576 if (params.options.empty())
2577 sgmlOpenTag(ofs, 0, top_element);
2579 string top = top_element;
2581 top += params.options;
2582 sgmlOpenTag(ofs, 0, top);
2586 ofs << "<!-- " << lyx_docversion
2587 << " created this file. For more info see http://www.lyx.org/"
2590 Paragraph::depth_type depth = 0; // paragraph depth
2591 Paragraph * par = paragraph;
2593 vector<string> environment_stack(5);
2596 LyXLayout const & style =
2597 textclasslist.Style(params.textclass,
2600 // treat <toc> as a special case for compatibility with old code
2601 if (par->isInset(0)) {
2602 Inset * inset = par->getInset(0);
2603 Inset::Code lyx_code = inset->lyxCode();
2604 if (lyx_code == Inset::TOC_CODE){
2605 string const temp = "toc";
2606 sgmlOpenTag(ofs, depth, temp);
2613 // environment tag closing
2614 for (; depth > par->params().depth(); --depth) {
2615 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2616 environment_stack[depth].erase();
2619 // write opening SGML tags
2620 switch (style.latextype) {
2621 case LATEX_PARAGRAPH:
2622 if (depth == par->params().depth()
2623 && !environment_stack[depth].empty()) {
2624 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2625 environment_stack[depth].erase();
2631 sgmlOpenTag(ofs, depth, style.latexname());
2637 _("Error : Wrong depth for"
2638 " LatexType Command.\n"));
2640 if (!environment_stack[depth].empty()){
2641 sgmlCloseTag(ofs, depth,
2642 environment_stack[depth]);
2646 environment_stack[depth].erase();
2647 sgmlOpenTag(ofs, depth, style.latexname());
2650 case LATEX_ENVIRONMENT:
2651 case LATEX_ITEM_ENVIRONMENT:
2652 if (depth == par->params().depth()
2653 && environment_stack[depth] != style.latexname()) {
2654 sgmlCloseTag(ofs, depth,
2655 environment_stack[depth]);
2656 environment_stack[depth].erase();
2658 if (depth < par->params().depth()) {
2659 depth = par->params().depth();
2660 environment_stack[depth].erase();
2662 if (environment_stack[depth] != style.latexname()) {
2664 sgmlOpenTag(ofs, depth, "p");
2666 sgmlOpenTag(ofs, depth, style.latexname());
2668 if (environment_stack.size() == depth + 1)
2669 environment_stack.push_back("!-- --");
2670 environment_stack[depth] = style.latexname();
2673 if (style.latexparam() == "CDATA")
2676 if (style.latextype == LATEX_ENVIRONMENT) break;
2678 if (style.labeltype == LABEL_MANUAL)
2683 sgmlOpenTag(ofs, depth + 1, item_name);
2686 sgmlOpenTag(ofs, depth, style.latexname());
2690 simpleLinuxDocOnePar(ofs, par, depth);
2695 // write closing SGML tags
2696 switch (style.latextype) {
2699 case LATEX_ENVIRONMENT:
2700 case LATEX_ITEM_ENVIRONMENT:
2701 if (style.latexparam() == "CDATA")
2705 sgmlCloseTag(ofs, depth, style.latexname());
2711 for (int i=depth; i >= 0; --i)
2712 sgmlCloseTag(ofs, depth, environment_stack[i]);
2716 sgmlCloseTag(ofs, 0, top_element);
2720 // How to check for successful close
2724 // checks, if newcol chars should be put into this line
2725 // writes newline, if necessary.
2728 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2729 string::size_type newcol)
2732 if (colcount > lyxrc.ascii_linelen) {
2734 colcount = newcol; // assume write after this call
2749 string tag_name(PAR_TAG const & pt) {
2751 case NONE: return "!-- --";
2752 case TT: return "tt";
2753 case SF: return "sf";
2754 case BF: return "bf";
2755 case IT: return "it";
2756 case SL: return "sl";
2757 case EM: return "em";
2764 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2766 p1 = static_cast<PAR_TAG>(p1 | p2);
2771 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2773 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2779 // Handle internal paragraph parsing -- layout already processed.
2780 void Buffer::simpleLinuxDocOnePar(ostream & os,
2782 Paragraph::depth_type /*depth*/)
2784 LyXLayout const & style = textclasslist.Style(params.textclass,
2786 string::size_type char_line_count = 5; // Heuristic choice ;-)
2788 // gets paragraph main font
2791 if (style.labeltype == LABEL_MANUAL) {
2792 font_old = style.labelfont;
2795 font_old = style.font;
2799 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2800 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2801 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2804 stack<PAR_TAG> tag_state;
2805 // parsing main loop
2806 for (pos_type i = 0; i < par->size(); ++i) {
2808 PAR_TAG tag_close = NONE;
2809 list < PAR_TAG > tag_open;
2811 LyXFont const font = par->getFont(params, i);
2813 if (font_old.family() != font.family()) {
2814 switch (family_type) {
2815 case LyXFont::SANS_FAMILY:
2818 case LyXFont::TYPEWRITER_FAMILY:
2825 family_type = font.family();
2827 switch (family_type) {
2828 case LyXFont::SANS_FAMILY:
2829 tag_open.push_back(SF);
2831 case LyXFont::TYPEWRITER_FAMILY:
2832 tag_open.push_back(TT);
2839 if (font_old.series() != font.series()) {
2840 switch (series_type) {
2841 case LyXFont::BOLD_SERIES:
2848 series_type = font.series();
2850 switch (series_type) {
2851 case LyXFont::BOLD_SERIES:
2852 tag_open.push_back(BF);
2860 if (font_old.shape() != font.shape()) {
2861 switch (shape_type) {
2862 case LyXFont::ITALIC_SHAPE:
2865 case LyXFont::SLANTED_SHAPE:
2872 shape_type = font.shape();
2874 switch (shape_type) {
2875 case LyXFont::ITALIC_SHAPE:
2876 tag_open.push_back(IT);
2878 case LyXFont::SLANTED_SHAPE:
2879 tag_open.push_back(SL);
2886 if (font_old.emph() != font.emph()) {
2887 if (font.emph() == LyXFont::ON) {
2888 tag_open.push_back(EM);
2897 list < PAR_TAG > temp;
2898 while (!tag_state.empty() && tag_close ) {
2899 PAR_TAG k = tag_state.top();
2901 os << "</" << tag_name(k) << ">";
2908 for(list< PAR_TAG >::const_iterator j = temp.begin();
2909 j != temp.end(); ++j) {
2911 os << "<" << tag_name(*j) << ">";
2914 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2915 j != tag_open.end(); ++j) {
2917 os << "<" << tag_name(*j) << ">";
2920 char c = par->getChar(i);
2922 if (c == Paragraph::META_INSET) {
2923 Inset * inset = par->getInset(i);
2924 inset->linuxdoc(this, os);
2929 if (style.latexparam() == "CDATA") {
2930 // "TeX"-Mode on == > SGML-Mode on.
2936 if (par->sgmlConvertChar(c, sgml_string)
2937 && !style.free_spacing && !par->isFreeSpacing())
2939 // in freespacing mode, spaces are
2940 // non-breaking characters
2941 if (desc_on) {// if char is ' ' then...
2944 sgmlLineBreak(os, char_line_count, 6);
2948 sgmlLineBreak(os, char_line_count, 1);
2953 char_line_count += sgml_string.length();
2959 while (!tag_state.empty()) {
2960 os << "</" << tag_name(tag_state.top()) << ">";
2964 // resets description flag correctly
2966 // <tag> not closed...
2967 sgmlLineBreak(os, char_line_count, 6);
2973 // Print an error message.
2974 void Buffer::sgmlError(Paragraph * par, int pos,
2975 string const & message) const
2977 // insert an error marker in text
2978 InsetError * new_inset = new InsetError(message);
2979 par->insertInset(pos, new_inset);
2980 par->setFont(pos, LyXFont(LyXFont::ALL_INHERIT, params.language));
2984 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2986 ofstream ofs(fname.c_str());
2988 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2992 Paragraph * par = paragraph;
2994 niceFile = nice; // this will be used by Insetincludes.
2996 LyXTextClass const & tclass =
2997 textclasslist.TextClass(params.textclass);
2999 LaTeXFeatures features(params, tclass.numLayouts());
3004 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3007 ofs << "<!DOCTYPE " << top_element
3008 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3010 string preamble = params.preamble;
3011 preamble += features.getIncludedFiles(fname);
3012 preamble += features.getLyXSGMLEntities();
3014 if (!preamble.empty()) {
3015 ofs << "\n [ " << preamble << " ]";
3020 string top = top_element;
3022 top += params.language->code();
3025 if (!params.options.empty()) {
3027 top += params.options;
3029 sgmlOpenTag(ofs, 0, top);
3031 ofs << "<!-- DocBook file was created by " << lyx_docversion
3032 << "\n See http://www.lyx.org/ for more information -->\n";
3034 vector<string> environment_stack(10);
3035 vector<string> environment_inner(10);
3036 vector<string> command_stack(10);
3038 bool command_flag = false;
3039 Paragraph::depth_type command_depth = 0;
3040 Paragraph::depth_type command_base = 0;
3041 Paragraph::depth_type cmd_depth = 0;
3042 Paragraph::depth_type depth = 0; // paragraph depth
3045 string command_name;
3051 int desc_on = 0; // description mode
3053 LyXLayout const & style =
3054 textclasslist.Style(params.textclass,
3057 // environment tag closing
3058 for (; depth > par->params().depth(); --depth) {
3059 if (environment_inner[depth] != "!-- --") {
3060 item_name = "listitem";
3061 sgmlCloseTag(ofs, command_depth + depth,
3063 if (environment_inner[depth] == "varlistentry")
3064 sgmlCloseTag(ofs, depth+command_depth,
3065 environment_inner[depth]);
3067 sgmlCloseTag(ofs, depth + command_depth,
3068 environment_stack[depth]);
3069 environment_stack[depth].erase();
3070 environment_inner[depth].erase();
3073 if (depth == par->params().depth()
3074 && environment_stack[depth] != style.latexname()
3075 && !environment_stack[depth].empty()) {
3076 if (environment_inner[depth] != "!-- --") {
3077 item_name= "listitem";
3078 sgmlCloseTag(ofs, command_depth+depth,
3080 if (environment_inner[depth] == "varlistentry")
3082 depth + command_depth,
3083 environment_inner[depth]);
3086 sgmlCloseTag(ofs, depth + command_depth,
3087 environment_stack[depth]);
3089 environment_stack[depth].erase();
3090 environment_inner[depth].erase();
3093 // Write opening SGML tags.
3094 switch (style.latextype) {
3095 case LATEX_PARAGRAPH:
3096 sgmlOpenTag(ofs, depth + command_depth,
3103 _("Error : Wrong depth for "
3104 "LatexType Command.\n"));
3106 command_name = style.latexname();
3108 sgmlparam = style.latexparam();
3109 c_params = split(sgmlparam, c_depth,'|');
3111 cmd_depth = lyx::atoi(c_depth);
3114 if (cmd_depth < command_base) {
3115 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3116 sgmlCloseTag(ofs, j, command_stack[j]);
3117 command_depth = command_base = cmd_depth;
3118 } else if (cmd_depth <= command_depth) {
3119 for (int j = command_depth; j >= int(cmd_depth); --j)
3120 sgmlCloseTag(ofs, j, command_stack[j]);
3121 command_depth = cmd_depth;
3123 command_depth = cmd_depth;
3125 command_depth = command_base = cmd_depth;
3126 command_flag = true;
3128 if (command_stack.size() == command_depth + 1)
3129 command_stack.push_back(string());
3130 command_stack[command_depth] = command_name;
3132 // treat label as a special case for
3133 // more WYSIWYM handling.
3134 // This is a hack while paragraphs can't have
3135 // attributes, like id in this case.
3136 if (par->isInset(0)) {
3137 Inset * inset = par->getInset(0);
3138 Inset::Code lyx_code = inset->lyxCode();
3139 if (lyx_code == Inset::LABEL_CODE){
3140 command_name += " id=\"";
3141 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3142 command_name += "\"";
3147 sgmlOpenTag(ofs, depth + command_depth, command_name);
3148 if (c_params.empty())
3149 item_name = "title";
3151 item_name = c_params;
3152 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3155 case LATEX_ENVIRONMENT:
3156 case LATEX_ITEM_ENVIRONMENT:
3157 if (depth < par->params().depth()) {
3158 depth = par->params().depth();
3159 environment_stack[depth].erase();
3162 if (environment_stack[depth] != style.latexname()) {
3163 if(environment_stack.size() == depth + 1) {
3164 environment_stack.push_back("!-- --");
3165 environment_inner.push_back("!-- --");
3167 environment_stack[depth] = style.latexname();
3168 environment_inner[depth] = "!-- --";
3169 sgmlOpenTag(ofs, depth + command_depth,
3170 environment_stack[depth]);
3172 if (environment_inner[depth] != "!-- --") {
3173 item_name= "listitem";
3175 command_depth + depth,
3177 if (environment_inner[depth] == "varlistentry")
3179 depth + command_depth,
3180 environment_inner[depth]);
3184 if (style.latextype == LATEX_ENVIRONMENT) {
3185 if (!style.latexparam().empty()) {
3186 if(style.latexparam() == "CDATA")
3189 sgmlOpenTag(ofs, depth + command_depth,
3190 style.latexparam());
3195 desc_on = (style.labeltype == LABEL_MANUAL);
3198 environment_inner[depth]= "varlistentry";
3200 environment_inner[depth]= "listitem";
3202 sgmlOpenTag(ofs, depth + 1 + command_depth,
3203 environment_inner[depth]);
3207 sgmlOpenTag(ofs, depth + 1 + command_depth,
3211 sgmlOpenTag(ofs, depth + 1 + command_depth,
3216 sgmlOpenTag(ofs, depth + command_depth,
3221 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3225 // write closing SGML tags
3226 switch (style.latextype) {
3228 if (c_params.empty())
3232 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3234 case LATEX_ENVIRONMENT:
3235 if (!style.latexparam().empty()) {
3236 if(style.latexparam() == "CDATA")
3239 sgmlCloseTag(ofs, depth + command_depth,
3240 style.latexparam());
3243 case LATEX_ITEM_ENVIRONMENT:
3244 if (desc_on == 1) break;
3246 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3248 case LATEX_PARAGRAPH:
3249 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3252 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3258 for (int d = depth; d >= 0; --d) {
3259 if (!environment_stack[depth].empty()) {
3260 if (environment_inner[depth] != "!-- --") {
3261 item_name = "listitem";
3262 sgmlCloseTag(ofs, command_depth + depth,
3264 if (environment_inner[depth] == "varlistentry")
3265 sgmlCloseTag(ofs, depth + command_depth,
3266 environment_inner[depth]);
3269 sgmlCloseTag(ofs, depth + command_depth,
3270 environment_stack[depth]);
3274 for (int j = command_depth; j >= 0 ; --j)
3275 if (!command_stack[j].empty())
3276 sgmlCloseTag(ofs, j, command_stack[j]);
3279 sgmlCloseTag(ofs, 0, top_element);
3282 // How to check for successful close
3286 void Buffer::simpleDocBookOnePar(ostream & os,
3287 Paragraph * par, int & desc_on,
3288 Paragraph::depth_type depth) const
3290 bool emph_flag = false;
3292 LyXLayout const & style = textclasslist.Style(params.textclass,
3295 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3297 int char_line_count = depth;
3298 //if (!style.free_spacing)
3299 // os << string(depth,' ');
3301 // parsing main loop
3302 for (pos_type i = 0; i < par->size(); ++i) {
3303 LyXFont font = par->getFont(params, i);
3305 // handle <emphasis> tag
3306 if (font_old.emph() != font.emph()) {
3307 if (font.emph() == LyXFont::ON) {
3311 os << "</emphasis>";
3317 if ( par->isInset(i) ) {
3318 Inset * inset = par->getInset(i);
3319 // don't print the inset in position 0 if desc_on == 3 (label)
3320 if ( i || desc_on != 3)
3321 inset->docbook(this, os);
3323 char c = par->getChar(i);
3325 par->sgmlConvertChar(c, sgml_string);
3327 if (style.pass_thru) {
3329 } else if(style.free_spacing || par->isFreeSpacing() || c != ' ') {
3331 } else if (desc_on ==1) {
3333 os << "\n</term><listitem><para>";
3343 os << "</emphasis>";
3346 // resets description flag correctly
3348 // <term> not closed...
3351 if(style.free_spacing) os << '\n';
3355 // This should be enabled when the Chktex class is implemented. (Asger)
3356 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3357 // Other flags: -wall -v0 -x
3358 int Buffer::runChktex()
3360 if (!users->text) return 0;
3362 users->owner()->prohibitInput();
3364 // get LaTeX-Filename
3365 string const name = getLatexName();
3366 string path = OnlyPath(filename);
3368 string const org_path = path;
3369 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3373 Path p(path); // path to LaTeX file
3374 users->owner()->message(_("Running chktex..."));
3376 // Remove all error insets
3377 bool const removedErrorInsets = users->removeAutoInsets();
3379 // Generate the LaTeX file if neccessary
3380 makeLaTeXFile(name, org_path, false);
3383 Chktex chktex(lyxrc.chktex_command, name, filepath);
3384 int res = chktex.run(terr); // run chktex
3387 Alert::alert(_("chktex did not work!"),
3388 _("Could not run with file:"), name);
3389 } else if (res > 0) {
3390 // Insert all errors as errors boxes
3391 users->insertErrors(terr);
3394 // if we removed error insets before we ran chktex or if we inserted
3395 // error insets after we ran chktex, this must be run:
3396 if (removedErrorInsets || res){
3400 users->owner()->allowInput();
3406 void Buffer::validate(LaTeXFeatures & features) const
3408 Paragraph * par = paragraph;
3409 LyXTextClass const & tclass =
3410 textclasslist.TextClass(params.textclass);
3412 // AMS Style is at document level
3413 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3414 features.require("amsstyle");
3417 // We don't use "lyxerr.debug" because of speed. (Asger)
3418 if (lyxerr.debugging(Debug::LATEX))
3419 lyxerr << "Paragraph: " << par << endl;
3421 // Now just follow the list of paragraphs and run
3422 // validate on each of them.
3423 par->validate(features);
3425 // and then the next paragraph
3429 // the bullet shapes are buffer level not paragraph level
3430 // so they are tested here
3431 for (int i = 0; i < 4; ++i) {
3432 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3433 int const font = params.user_defined_bullets[i].getFont();
3435 int const c = params
3436 .user_defined_bullets[i]
3443 features.require("latexsym");
3445 } else if (font == 1) {
3446 features.require("amssymb");
3447 } else if ((font >= 2 && font <= 5)) {
3448 features.require("pifont");
3453 if (lyxerr.debugging(Debug::LATEX)) {
3454 features.showStruct();
3459 // This function should be in Buffer because it's a buffer's property (ale)
3460 string const Buffer::getIncludeonlyList(char delim)
3463 for (inset_iterator it = inset_iterator_begin();
3464 it != inset_iterator_end(); ++it) {
3465 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3466 InsetInclude * insetinc =
3467 static_cast<InsetInclude *>(*it);
3468 if (insetinc->isIncludeOnly()) {
3471 lst += insetinc->getRelFileBaseName();
3475 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3480 vector<string> const Buffer::getLabelList()
3482 /// if this is a child document and the parent is already loaded
3483 /// Use the parent's list instead [ale990407]
3484 if (!params.parentname.empty()
3485 && bufferlist.exists(params.parentname)) {
3486 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3488 return tmp->getLabelList();
3491 vector<string> label_list;
3492 for (inset_iterator it = inset_iterator_begin();
3493 it != inset_iterator_end(); ++it) {
3494 vector<string> const l = (*it)->getLabelList();
3495 label_list.insert(label_list.end(), l.begin(), l.end());
3501 Buffer::Lists const Buffer::getLists() const
3504 Paragraph * par = paragraph;
3507 std::pair<bool, textclass_type> const tmp =
3508 textclasslist.NumberOfLayout(params.textclass, "Caption");
3509 bool const found = tmp.first;
3510 textclass_type const cap = tmp.second;
3513 // This is the prefered way to to this, but boost::tie can break
3517 boost::tie(found, cap) = textclasslist
3518 .NumberOfLayout(params.textclass, "Caption");
3522 char const labeltype =
3523 textclasslist.Style(params.textclass,
3524 par->getLayout()).labeltype;
3526 if (labeltype >= LABEL_COUNTER_CHAPTER
3527 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3528 // insert this into the table of contents
3529 SingleList & item = l["TOC"];
3532 textclasslist.TextClass(params.textclass).maxcounter());
3533 item.push_back(TocItem(par, depth, par->asString(this, true)));
3535 // For each paragrph, traverse its insets and look for
3539 Paragraph::inset_iterator it =
3540 par->inset_iterator_begin();
3541 Paragraph::inset_iterator end =
3542 par->inset_iterator_end();
3544 for (; it != end; ++it) {
3545 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3547 static_cast<InsetFloat*>(*it);
3549 string const type = il->type();
3551 // Now find the caption in the float...
3552 // We now tranverse the paragraphs of
3554 Paragraph * tmp = il->inset.paragraph();
3556 if (tmp->layout == cap) {
3557 SingleList & item = l[type];
3559 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3560 item.push_back(TocItem(tmp, 0 , str));
3567 lyxerr << "caption not found" << endl;
3576 // This is also a buffer property (ale)
3577 vector<pair<string, string> > const Buffer::getBibkeyList()
3579 /// if this is a child document and the parent is already loaded
3580 /// Use the parent's list instead [ale990412]
3581 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3582 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3584 return tmp->getBibkeyList();
3587 vector<pair<string, string> > keys;
3588 Paragraph * par = paragraph;
3591 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3592 par->asString(this, false)));
3596 // Might be either using bibtex or a child has bibliography
3598 for (inset_iterator it = inset_iterator_begin();
3599 it != inset_iterator_end(); ++it) {
3600 // Search for Bibtex or Include inset
3601 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3602 vector<pair<string,string> > tmp =
3603 static_cast<InsetBibtex*>(*it)->getKeys(this);
3604 keys.insert(keys.end(), tmp.begin(), tmp.end());
3605 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3606 vector<pair<string,string> > const tmp =
3607 static_cast<InsetInclude*>(*it)->getKeys();
3608 keys.insert(keys.end(), tmp.begin(), tmp.end());
3617 bool Buffer::isDepClean(string const & name) const
3619 DEPCLEAN * item = dep_clean;
3620 while (item && item->master != name)
3622 if (!item) return true;
3627 void Buffer::markDepClean(string const & name)
3630 dep_clean = new DEPCLEAN;
3631 dep_clean->clean = true;
3632 dep_clean->master = name;
3633 dep_clean->next = 0;
3635 DEPCLEAN * item = dep_clean;
3636 while (item && item->master != name)
3641 item = new DEPCLEAN;
3643 item->master = name;
3650 bool Buffer::dispatch(string const & command)
3652 // Split command string into command and argument
3654 string line = frontStrip(command);
3655 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3657 return dispatch(lyxaction.LookupFunc(cmd), arg);
3661 bool Buffer::dispatch(int action, string const & argument)
3663 bool dispatched = true;
3666 Exporter::Export(this, argument, false);
3676 void Buffer::resizeInsets(BufferView * bv)
3678 /// then remove all LyXText in text-insets
3679 Paragraph * par = paragraph;
3680 for (; par; par = par->next()) {
3681 par->resizeInsetsLyXText(bv);
3686 void Buffer::redraw()
3693 void Buffer::changeLanguage(Language const * from, Language const * to)
3696 ParIterator end = par_iterator_end();
3697 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3698 (*it)->changeLanguage(params, from, to);
3702 bool Buffer::isMultiLingual()
3704 ParIterator end = par_iterator_end();
3705 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3706 if ((*it)->isMultiLingual(params))
3713 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3716 it = par->InsetIterator(pos);
3717 if (it == par->inset_iterator_end()) {
3724 void Buffer::inset_iterator::setParagraph()
3727 it = par->inset_iterator_begin();
3728 if (it != par->inset_iterator_end())
3733 // We maintain an invariant that whenever par = 0 then it = 0
3737 Inset * Buffer::getInsetFromID(int id_arg) const
3739 for (inset_iterator it = inset_const_iterator_begin();
3740 it != inset_const_iterator_end(); ++it)
3742 if ((*it)->id() == id_arg)
3744 Inset * in = (*it)->getInsetFromID(id_arg);
3752 Paragraph * Buffer::getParFromID(int id) const
3754 if (id < 0) return 0;
3755 Paragraph * par = paragraph;
3757 if (par->id() == id) {
3760 Paragraph * tmp = par->getParFromID(id);
3770 ParIterator Buffer::par_iterator_begin()
3772 return ParIterator(paragraph);
3776 ParIterator Buffer::par_iterator_end()
3778 return ParIterator();