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 * ======================================================
26 #include <sys/types.h>
36 #pragma implementation
40 #include "bufferlist.h"
42 #include "lyx_gui_misc.h"
43 #include "LyXAction.h"
46 #include "tex-strings.h"
48 #include "bufferview_funcs.h"
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
53 #include "insets/inset.h"
54 #include "insets/inseterror.h"
55 #include "insets/insetlabel.h"
56 #include "insets/insetref.h"
57 #include "insets/inseturl.h"
58 #include "insets/insetnote.h"
59 #include "insets/insetquotes.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetbib.h"
62 #include "insets/insetcite.h"
63 #include "insets/insetexternal.h"
64 #include "insets/insetindex.h"
65 #include "insets/insetinclude.h"
66 #include "insets/insettoc.h"
67 #include "insets/insetparent.h"
68 #include "insets/insetspecialchar.h"
69 #include "insets/figinset.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetminipage.h"
76 #include "insets/insetfloat.h"
77 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
84 #include "support/textutils.h"
85 #include "support/filetools.h"
86 #include "support/path.h"
87 #include "support/os.h"
92 #include "LaTeXFeatures.h"
93 #include "support/syscall.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
100 #include "lyx_gui_misc.h" // WarnReadonly()
101 #include "frontends/Dialogs.h"
102 #include "encoding.h"
103 #include "exporter.h"
104 #include "Lsstream.h"
105 #include "converter.h"
106 #include "BufferView.h"
107 #include "ParagraphParameters.h"
117 using std::make_pair;
125 // all these externs should eventually be removed.
126 extern BufferList bufferlist;
128 extern LyXAction lyxaction;
132 const int LYX_FORMAT = 220;
136 extern int tex_code_break_column;
139 Buffer::Buffer(string const & file, bool ronly)
141 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
143 filepath = OnlyPath(file);
152 if (read_only || (lyxrc.use_tempdir)) {
153 tmppath = CreateBufferTmpDir();
154 } else tmppath.erase();
160 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
161 // here the buffer should take care that it is
162 // saved properly, before it goes into the void.
164 // make sure that views using this buffer
169 if (!tmppath.empty()) {
170 DestroyBufferTmpDir(tmppath);
173 Paragraph * par = paragraph;
176 tmppar = par->next();
184 string const Buffer::getLatexName(bool no_path) const
186 string name = ChangeExtension(MakeLatexName(filename), ".tex");
188 return OnlyFilename(name);
194 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
196 string const filename = getLatexName(false);
198 if (filename.empty())
199 return make_pair(Buffer::latexlog, string());
201 string path = OnlyPath(filename);
203 if (lyxrc.use_tempdir || !IsDirWriteable(path))
206 string const fname = AddName(path,
207 OnlyFilename(ChangeExtension(filename,
210 AddName(path, OnlyFilename(
211 ChangeExtension(filename,
212 formats.extension("literate") + ".out")));
214 // If no Latex log or Build log is newer, show Build log
216 FileInfo const f_fi(fname);
217 FileInfo const b_fi(bname);
220 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
221 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
222 return make_pair(Buffer::buildlog, bname);
224 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
225 return make_pair(Buffer::latexlog, fname);
229 void Buffer::setReadonly(bool flag)
231 if (read_only != flag) {
234 users->owner()->getDialogs()->updateBufferDependent(false);
237 WarnReadonly(filename);
242 bool Buffer::saveParamsAsDefaults() // const
244 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
246 Buffer defaults = Buffer(fname);
248 // Use the current buffer's parameters as default
249 defaults.params = params;
251 // add an empty paragraph. Is this enough?
252 defaults.paragraph = new Paragraph;
254 return defaults.writeFile(defaults.filename, false);
258 /// Update window titles of all users
259 // Should work on a list
260 void Buffer::updateTitles() const
262 if (users) users->owner()->updateWindowTitle();
266 /// Reset autosave timer of all users
267 // Should work on a list
268 void Buffer::resetAutosaveTimers() const
270 if (users) users->owner()->resetAutosaveTimer();
274 void Buffer::setFileName(string const & newfile)
276 filename = MakeAbsPath(newfile);
277 filepath = OnlyPath(filename);
278 setReadonly(IsFileWriteable(filename) == 0);
283 // We'll remove this later. (Lgb)
286 string last_inset_read;
290 ErtComp() : active(false), in_tabular(false) {
297 std::stack<ErtComp> ert_stack;
306 // candidate for move to BufferView
307 // (at least some parts in the beginning of the func)
310 // changed to be public and have one parameter
311 // if par = 0 normal behavior
312 // else insert behavior
313 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
314 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
318 ert_comp.contents.erase();
319 ert_comp.active = false;
320 ert_comp.in_tabular = false;
324 Paragraph::depth_type depth = 0;
325 bool the_end_read = false;
327 Paragraph * first_par = 0;
328 LyXFont font(LyXFont::ALL_INHERIT, params.language);
329 if (file_format < 216 && params.language->lang() == "hebrew")
330 font.setLanguage(default_language);
335 // We are inserting into an existing document
336 users->text->breakParagraph(users);
337 first_par = users->text->firstParagraph();
340 // We don't want to adopt the parameters from the
341 // document we insert, so we skip until the text begins:
344 string const pretoken = lex.GetString();
345 if (pretoken == "\\layout") {
346 lex.pushToken(pretoken);
354 string const token = lex.GetString();
356 if (token.empty()) continue;
358 lyxerr[Debug::PARSER] << "Handling token: `"
359 << token << "'" << endl;
362 parseSingleLyXformat2Token(lex, par, first_par,
370 paragraph = first_par;
372 if (unknown_layouts > 0) {
373 string s = _("Couldn't set the layout for ");
374 if (unknown_layouts == 1) {
375 s += _("one paragraph");
377 s += tostr(unknown_layouts);
378 s += _(" paragraphs");
380 WriteAlert(_("Textclass Loading Error!"), s,
381 _("When reading " + fileName()));
388 void Buffer::insertErtContents(Paragraph * par, int & pos,
389 LyXFont const & font, bool set_inactive)
391 if (!ert_comp.contents.empty()) {
392 lyxerr[Debug::INSETS] << "ERT contents:\n"
393 << ert_comp.contents << endl;
394 Inset * inset = new InsetERT(ert_comp.contents, true);
395 par->insertInset(pos++, inset, font);
396 ert_comp.contents.erase();
399 ert_comp.active = false;
405 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
406 Paragraph *& first_par,
407 string const & token, int & pos,
408 Paragraph::depth_type & depth,
412 bool the_end_read = false;
413 #ifndef NO_PEXTRA_REALLY
414 // This is super temporary but is needed to get the compability
415 // mode for minipages work correctly together with new tabulars.
416 static int call_depth;
418 bool checkminipage = false;
419 static Paragraph * minipar;
420 static Paragraph * parBeforeMinipage;
423 if (token[0] != '\\') {
425 if (ert_comp.active) {
426 ert_comp.contents += token;
429 for (string::const_iterator cit = token.begin();
430 cit != token.end(); ++cit) {
431 par->insertChar(pos, (*cit), font);
437 } else if (token == "\\i") {
438 Inset * inset = new InsetLatexAccent;
439 inset->read(this, lex);
440 par->insertInset(pos, inset, font);
442 } else if (token == "\\layout") {
444 ert_comp.in_tabular = false;
446 insertErtContents(par, pos, font);
449 string const layoutname = lex.GetString();
450 pair<bool, LyXTextClass::LayoutList::size_type> pp
451 = textclasslist.NumberOfLayout(params.textclass,
455 if (compare_no_case(layoutname, "latex") == 0) {
456 ert_comp.active = true;
460 // The is the compability reading of layout caption.
461 // It can be removed in LyX version 1.3.0. (Lgb)
462 if (compare_no_case(layoutname, "caption") == 0) {
463 // We expect that the par we are now working on is
464 // really inside a InsetText inside a InsetFloat.
465 // We also know that captions can only be
466 // one paragraph. (Lgb)
468 // We should now read until the next "\layout"
470 // This is probably not good enough, what if the
471 // caption is the last par in the document (Lgb)
472 istream & ist = lex.getStream();
478 if (prefixIs(line, "\\layout")) {
482 if (prefixIs(line, "\\begin_inset"))
484 if (prefixIs(line, "\\end_inset")) {
495 // Now we should have the whole layout in ss
496 // we should now be able to give this to the
498 ss << "\\end_inset\n";
500 // This seems like a bug in stringstream.
501 // We really should be able to use ss
503 istringstream is(ss.str());
505 tmplex.setStream(is);
506 Inset * inset = new InsetCaption;
507 inset->Read(this, tmplex);
508 par->InsertInset(pos, inset, font);
515 par = new Paragraph(par);
519 par->layout = pp.second;
522 // use default layout "Standard" (0)
525 string const s = _("Layout had to be changed from\n")
526 + layoutname + _(" to ")
527 + textclasslist.NameOfLayout(params.textclass, par->layout);
528 InsetError * new_inset = new InsetError(s);
529 par->insertInset(0, new_inset);
531 // Test whether the layout is obsolete.
532 LyXLayout const & layout =
533 textclasslist.Style(params.textclass,
535 if (!layout.obsoleted_by().empty())
536 par->layout = textclasslist
537 .NumberOfLayout(params.textclass,
538 layout.obsoleted_by())
540 par->params().depth(depth);
541 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
542 if (file_format < 216
543 && params.language->lang() == "hebrew")
544 font.setLanguage(default_language);
549 } else if (token == "\\begin_float") {
550 insertErtContents(par, pos, font);
551 //insertErtContents(par, pos, font, false);
552 //ert_stack.push(ert_comp);
553 //ert_comp = ErtComp();
555 // This is the compability reader. It can be removed in
556 // LyX version 1.3.0. (Lgb)
558 string const tmptok = lex.GetString();
559 //lyxerr << "old float: " << tmptok << endl;
562 stringstream old_float;
564 if (tmptok == "footnote") {
565 inset = new InsetFoot;
566 } else if (tmptok == "margin") {
567 inset = new InsetMarginal;
568 } else if (tmptok == "fig") {
569 inset = new InsetFloat("figure");
570 old_float << "placement htbp\n"
572 } else if (tmptok == "tab") {
573 inset = new InsetFloat("table");
574 old_float << "placement htbp\n"
576 } else if (tmptok == "alg") {
577 inset = new InsetFloat("algorithm");
578 old_float << "placement htbp\n"
580 } else if (tmptok == "wide-fig") {
581 inset = new InsetFloat("figure");
582 //InsetFloat * tmp = new InsetFloat("figure");
585 old_float << "placement htbp\n"
587 } else if (tmptok == "wide-tab") {
588 inset = new InsetFloat("table");
589 //InsetFloat * tmp = new InsetFloat("table");
592 old_float << "placement htbp\n"
597 #ifndef NO_PEXTRA_REALLY
600 return false; // no end read yet
603 old_float << "collapsed true\n";
605 // Here we need to check for \end_deeper and handle that
606 // before we do the footnote parsing.
607 // This _is_ a hack! (Lgb)
610 string const tmp = lex.GetString();
611 if (tmp == "\\end_deeper") {
612 //lyxerr << "\\end_deeper caught!" << endl;
614 lex.printError("\\end_deeper: "
615 "depth is already null");
620 old_float << tmp << ' ';
625 old_float << lex.getLongString("\\end_float")
626 << "\n\\end_inset\n";
627 //lyxerr << "Float Body:\n" << old_float.str() << endl;
628 // That this does not work seems like a bug
629 // in stringstream. (Lgb)
630 istringstream istr(old_float.str());
632 nylex.setStream(istr);
633 inset->read(this, nylex);
634 par->insertInset(pos, inset, font);
636 insertErtContents(par, pos, font);
637 } else if (token == "\\begin_deeper") {
639 } else if (token == "\\end_deeper") {
641 lex.printError("\\end_deeper: "
642 "depth is already null");
646 } else if (token == "\\begin_preamble") {
647 params.readPreamble(lex);
648 } else if (token == "\\textclass") {
650 pair<bool, LyXTextClassList::size_type> pp =
651 textclasslist.NumberOfClass(lex.GetString());
653 params.textclass = pp.second;
655 WriteAlert(string(_("Textclass error")),
656 string(_("The document uses an unknown textclass \"")) +
657 lex.GetString() + string("\"."),
658 string(_("LyX will not be able to produce output correctly.")));
659 params.textclass = 0;
661 if (!textclasslist.Load(params.textclass)) {
662 // if the textclass wasn't loaded properly
663 // we need to either substitute another
664 // or stop loading the file.
665 // I can substitute but I don't see how I can
666 // stop loading... ideas?? ARRae980418
667 WriteAlert(_("Textclass Loading Error!"),
668 string(_("Can't load textclass ")) +
669 textclasslist.NameOfClass(params.textclass),
670 _("-- substituting default"));
671 params.textclass = 0;
673 } else if (token == "\\options") {
675 params.options = lex.GetString();
676 } else if (token == "\\language") {
677 params.readLanguage(lex);
678 } else if (token == "\\fontencoding") {
680 } else if (token == "\\inputencoding") {
682 params.inputenc = lex.GetString();
683 } else if (token == "\\graphics") {
684 params.readGraphicsDriver(lex);
685 } else if (token == "\\fontscheme") {
687 params.fonts = lex.GetString();
688 } else if (token == "\\noindent") {
689 par->params().noindent(true);
690 } else if (token == "\\fill_top") {
691 par->params().spaceTop(VSpace(VSpace::VFILL));
692 } else if (token == "\\fill_bottom") {
693 par->params().spaceBottom(VSpace(VSpace::VFILL));
694 } else if (token == "\\line_top") {
695 par->params().lineTop(true);
696 } else if (token == "\\line_bottom") {
697 par->params().lineBottom(true);
698 } else if (token == "\\pagebreak_top") {
699 par->params().pagebreakTop(true);
700 } else if (token == "\\pagebreak_bottom") {
701 par->params().pagebreakBottom(true);
702 } else if (token == "\\start_of_appendix") {
703 par->params().startOfAppendix(true);
704 } else if (token == "\\paragraph_separation") {
705 int tmpret = lex.FindToken(string_paragraph_separation);
706 if (tmpret == -1) ++tmpret;
707 if (tmpret != LYX_LAYOUT_DEFAULT)
708 params.paragraph_separation =
709 static_cast<BufferParams::PARSEP>(tmpret);
710 } else if (token == "\\defskip") {
712 params.defskip = VSpace(lex.GetString());
713 } else if (token == "\\epsfig") { // obsolete
714 // Indeed it is obsolete, but we HAVE to be backwards
715 // compatible until 0.14, because otherwise all figures
716 // in existing documents are irretrivably lost. (Asger)
717 params.readGraphicsDriver(lex);
718 } else if (token == "\\quotes_language") {
719 int tmpret = lex.FindToken(string_quotes_language);
720 if (tmpret == -1) ++tmpret;
721 if (tmpret != LYX_LAYOUT_DEFAULT) {
722 InsetQuotes::quote_language tmpl =
723 InsetQuotes::EnglishQ;
726 tmpl = InsetQuotes::EnglishQ;
729 tmpl = InsetQuotes::SwedishQ;
732 tmpl = InsetQuotes::GermanQ;
735 tmpl = InsetQuotes::PolishQ;
738 tmpl = InsetQuotes::FrenchQ;
741 tmpl = InsetQuotes::DanishQ;
744 params.quotes_language = tmpl;
746 } else if (token == "\\quotes_times") {
748 switch (lex.GetInteger()) {
750 params.quotes_times = InsetQuotes::SingleQ;
753 params.quotes_times = InsetQuotes::DoubleQ;
756 } else if (token == "\\papersize") {
757 int tmpret = lex.FindToken(string_papersize);
761 params.papersize2 = tmpret;
762 } else if (token == "\\paperpackage") {
763 int tmpret = lex.FindToken(string_paperpackages);
766 params.paperpackage = BufferParams::PACKAGE_NONE;
768 params.paperpackage = tmpret;
769 } else if (token == "\\use_geometry") {
771 params.use_geometry = lex.GetInteger();
772 } else if (token == "\\use_amsmath") {
774 params.use_amsmath = lex.GetInteger();
775 } else if (token == "\\use_natbib") {
777 params.use_natbib = lex.GetInteger();
778 } else if (token == "\\use_numerical_citations") {
780 params.use_numerical_citations = lex.GetInteger();
781 } else if (token == "\\paperorientation") {
782 int tmpret = lex.FindToken(string_orientation);
783 if (tmpret == -1) ++tmpret;
784 if (tmpret != LYX_LAYOUT_DEFAULT)
785 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
786 } else if (token == "\\paperwidth") {
788 params.paperwidth = lex.GetString();
789 } else if (token == "\\paperheight") {
791 params.paperheight = lex.GetString();
792 } else if (token == "\\leftmargin") {
794 params.leftmargin = lex.GetString();
795 } else if (token == "\\topmargin") {
797 params.topmargin = lex.GetString();
798 } else if (token == "\\rightmargin") {
800 params.rightmargin = lex.GetString();
801 } else if (token == "\\bottommargin") {
803 params.bottommargin = lex.GetString();
804 } else if (token == "\\headheight") {
806 params.headheight = lex.GetString();
807 } else if (token == "\\headsep") {
809 params.headsep = lex.GetString();
810 } else if (token == "\\footskip") {
812 params.footskip = lex.GetString();
813 } else if (token == "\\paperfontsize") {
815 params.fontsize = strip(lex.GetString());
816 } else if (token == "\\papercolumns") {
818 params.columns = lex.GetInteger();
819 } else if (token == "\\papersides") {
821 switch (lex.GetInteger()) {
823 case 1: params.sides = LyXTextClass::OneSide; break;
824 case 2: params.sides = LyXTextClass::TwoSides; break;
826 } else if (token == "\\paperpagestyle") {
828 params.pagestyle = strip(lex.GetString());
829 } else if (token == "\\bullet") {
831 int const index = lex.GetInteger();
833 int temp_int = lex.GetInteger();
834 params.user_defined_bullets[index].setFont(temp_int);
835 params.temp_bullets[index].setFont(temp_int);
837 temp_int = lex.GetInteger();
838 params.user_defined_bullets[index].setCharacter(temp_int);
839 params.temp_bullets[index].setCharacter(temp_int);
841 temp_int = lex.GetInteger();
842 params.user_defined_bullets[index].setSize(temp_int);
843 params.temp_bullets[index].setSize(temp_int);
845 string const temp_str = lex.GetString();
846 if (temp_str != "\\end_bullet") {
847 // this element isn't really necessary for
848 // parsing but is easier for humans
849 // to understand bullets. Put it back and
850 // set a debug message?
851 lex.printError("\\end_bullet expected, got" + temp_str);
852 //how can I put it back?
854 } else if (token == "\\bulletLaTeX") {
856 int const index = lex.GetInteger();
858 string temp_str = lex.GetString();
860 while (temp_str != "\\end_bullet") {
861 // this loop structure is needed when user
862 // enters an empty string since the first
863 // thing returned will be the \\end_bullet
865 // if the LaTeX entry has spaces. Each element
866 // therefore needs to be read in turn
869 temp_str = lex.GetString();
871 params.user_defined_bullets[index].setText(sum_str);
872 params.temp_bullets[index].setText(sum_str);
873 } else if (token == "\\secnumdepth") {
875 params.secnumdepth = lex.GetInteger();
876 } else if (token == "\\tocdepth") {
878 params.tocdepth = lex.GetInteger();
879 } else if (token == "\\spacing") {
881 string const tmp = strip(lex.GetString());
882 Spacing::Space tmp_space = Spacing::Default;
884 if (tmp == "single") {
885 tmp_space = Spacing::Single;
886 } else if (tmp == "onehalf") {
887 tmp_space = Spacing::Onehalf;
888 } else if (tmp == "double") {
889 tmp_space = Spacing::Double;
890 } else if (tmp == "other") {
892 tmp_space = Spacing::Other;
893 tmp_val = lex.GetFloat();
895 lex.printError("Unknown spacing token: '$$Token'");
897 // Small hack so that files written with klyx will be
900 par->params().spacing(Spacing(tmp_space, tmp_val));
902 params.spacing.set(tmp_space, tmp_val);
904 } else if (token == "\\paragraph_spacing") {
906 string const tmp = strip(lex.GetString());
907 if (tmp == "single") {
908 par->params().spacing(Spacing(Spacing::Single));
909 } else if (tmp == "onehalf") {
910 par->params().spacing(Spacing(Spacing::Onehalf));
911 } else if (tmp == "double") {
912 par->params().spacing(Spacing(Spacing::Double));
913 } else if (tmp == "other") {
915 par->params().spacing(Spacing(Spacing::Other,
918 lex.printError("Unknown spacing token: '$$Token'");
920 } else if (token == "\\float_placement") {
922 params.float_placement = lex.GetString();
923 } else if (token == "\\family") {
925 font.setLyXFamily(lex.GetString());
926 } else if (token == "\\series") {
928 font.setLyXSeries(lex.GetString());
929 } else if (token == "\\shape") {
931 font.setLyXShape(lex.GetString());
932 } else if (token == "\\size") {
934 font.setLyXSize(lex.GetString());
937 #warning compatability hack needed
939 } else if (token == "\\latex") {
941 string const tok = lex.GetString();
942 // This is dirty, but gone with LyX3. (Asger)
943 if (tok == "no_latex")
944 font.setLatex(LyXFont::OFF);
945 else if (tok == "latex")
946 font.setLatex(LyXFont::ON);
947 else if (tok == "default")
948 font.setLatex(LyXFont::INHERIT);
950 lex.printError("Unknown LaTeX font flag "
953 } else if (token == "\\latex") {
955 string const tok = lex.GetString();
956 if (tok == "no_latex") {
958 insertErtContents(par, pos, font);
959 } else if (tok == "latex") {
960 ert_comp.active = true;
961 } else if (tok == "default") {
963 insertErtContents(par, pos, font);
965 lex.printError("Unknown LaTeX font flag "
969 } else if (token == "\\lang") {
971 string const tok = lex.GetString();
972 Language const * lang = languages.getLanguage(tok);
974 font.setLanguage(lang);
976 font.setLanguage(params.language);
977 lex.printError("Unknown language `$$Token'");
979 } else if (token == "\\numeric") {
981 font.setNumber(font.setLyXMisc(lex.GetString()));
982 } else if (token == "\\emph") {
984 font.setEmph(font.setLyXMisc(lex.GetString()));
985 } else if (token == "\\bar") {
987 string const tok = lex.GetString();
988 // This is dirty, but gone with LyX3. (Asger)
990 font.setUnderbar(LyXFont::ON);
991 else if (tok == "no")
992 font.setUnderbar(LyXFont::OFF);
993 else if (tok == "default")
994 font.setUnderbar(LyXFont::INHERIT);
996 lex.printError("Unknown bar font flag "
998 } else if (token == "\\noun") {
1000 font.setNoun(font.setLyXMisc(lex.GetString()));
1001 } else if (token == "\\color") {
1003 font.setLyXColor(lex.GetString());
1004 } else if (token == "\\align") {
1005 int tmpret = lex.FindToken(string_align);
1006 if (tmpret == -1) ++tmpret;
1007 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1008 int const tmpret2 = int(pow(2.0, tmpret));
1009 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1010 par->params().align(LyXAlignment(tmpret2));
1012 } else if (token == "\\added_space_top") {
1014 par->params().spaceTop(VSpace(lex.GetString()));
1015 } else if (token == "\\added_space_bottom") {
1017 par->params().spaceBottom(VSpace(lex.GetString()));
1018 #ifndef NO_PEXTRA_REALLY
1019 } else if (token == "\\pextra_type") {
1021 par->params().pextraType(lex.GetInteger());
1022 } else if (token == "\\pextra_width") {
1024 par->params().pextraWidth(lex.GetString());
1025 } else if (token == "\\pextra_widthp") {
1027 par->params().pextraWidthp(lex.GetString());
1028 } else if (token == "\\pextra_alignment") {
1030 par->params().pextraAlignment(lex.GetInteger());
1031 } else if (token == "\\pextra_hfill") {
1033 par->params().pextraHfill(lex.GetInteger());
1034 } else if (token == "\\pextra_start_minipage") {
1036 par->params().pextraStartMinipage(lex.GetInteger());
1038 } else if (token == "\\labelwidthstring") {
1040 par->params().labelWidthString(lex.GetString());
1041 // do not delete this token, it is still needed!
1042 } else if (token == "\\end_inset") {
1043 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1044 << "Last inset read was: " << last_inset_read
1046 // Simply ignore this. The insets do not have
1048 // But insets should read it, it is a part of
1049 // the inset isn't it? Lgb.
1050 } else if (token == "\\begin_inset") {
1052 insertErtContents(par, pos, font, false);
1053 ert_stack.push(ert_comp);
1054 ert_comp = ErtComp();
1056 readInset(lex, par, pos, font);
1058 ert_comp = ert_stack.top();
1060 insertErtContents(par, pos, font);
1062 } else if (token == "\\SpecialChar") {
1063 LyXLayout const & layout =
1064 textclasslist.Style(params.textclass,
1067 // Insets don't make sense in a free-spacing context! ---Kayvan
1068 if (layout.free_spacing) {
1071 string next_token = lex.GetString();
1072 if (next_token == "\\-") {
1073 par->insertChar(pos, '-', font);
1074 } else if (next_token == "\\protected_separator"
1075 || next_token == "~") {
1076 par->insertChar(pos, ' ', font);
1078 lex.printError("Token `$$Token' "
1080 "paragraph layout!");
1085 Inset * inset = new InsetSpecialChar;
1086 inset->read(this, lex);
1087 par->insertInset(pos, inset, font);
1090 } else if (token == "\\newline") {
1093 if (!ert_comp.in_tabular && ert_comp.active) {
1094 ert_comp.contents += char(Paragraph::META_NEWLINE);
1096 // Since we cannot know it this is only a regular
1097 // newline or a tabular cell delimter we have to
1098 // handle the ERT here.
1099 insertErtContents(par, pos, font, false);
1101 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1105 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1108 } else if (token == "\\LyXTable") {
1110 ert_comp.in_tabular = true;
1112 Inset * inset = new InsetTabular(*this);
1113 inset->read(this, lex);
1114 par->insertInset(pos, inset, font);
1116 } else if (token == "\\hfill") {
1117 par->insertChar(pos, Paragraph::META_HFILL, font);
1119 } else if (token == "\\protected_separator") { // obsolete
1120 // This is a backward compability thingie. (Lgb)
1121 // Remove it later some time...introduced with fileformat
1123 LyXLayout const & layout =
1124 textclasslist.Style(params.textclass,
1127 if (layout.free_spacing) {
1128 par->insertChar(pos, ' ', font);
1130 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1131 par->insertInset(pos, inset, font);
1134 } else if (token == "\\bibitem") { // ale970302
1136 InsetCommandParams p("bibitem", "dummy");
1137 par->bibkey = new InsetBibKey(p);
1139 par->bibkey->read(this, lex);
1140 } else if (token == "\\backslash") {
1142 if (ert_comp.active) {
1143 ert_comp.contents += "\\";
1146 par->insertChar(pos, '\\', font);
1151 } else if (token == "\\the_end") {
1153 // If we still have some ert active here we have to insert
1154 // it so we don't loose it. (Lgb)
1155 insertErtContents(par, pos, font);
1157 the_end_read = true;
1158 #ifndef NO_PEXTRA_REALLY
1159 minipar = parBeforeMinipage = 0;
1163 if (ert_comp.active) {
1164 ert_comp.contents += token;
1167 // This should be insurance for the future: (Asger)
1168 lex.printError("Unknown token `$$Token'. "
1169 "Inserting as text.");
1170 string::const_iterator cit = token.begin();
1171 string::const_iterator end = token.end();
1172 for (; cit != end; ++cit) {
1173 par->insertChar(pos, (*cit), font);
1181 #ifndef NO_PEXTRA_REALLY
1182 // I wonder if we could use this blanket fix for all the
1183 // checkminipage cases...
1184 if (par && par->size()) {
1185 // It is possible that this will check to often,
1186 // but that should not be an correctness issue.
1187 // Only a speed issue.
1188 checkminipage = true;
1191 // now check if we have a minipage paragraph as at this
1192 // point we already read all the necessary data!
1193 // this cannot be done in layout because there we did
1194 // not read yet the paragraph PEXTRA-params (Jug)
1196 // BEGIN pextra_minipage compability
1197 // This should be removed in 1.3.x (Lgb)
1199 // This compability code is not perfect. In a couple
1200 // of rand cases it fails. When the minipage par is
1201 // the first par in the document, and when there are
1202 // none or only one regular paragraphs after the
1203 // minipage. Currently I am not investing any effort
1204 // in fixing those cases.
1206 //lyxerr << "Call depth: " << call_depth << endl;
1207 if (checkminipage && (call_depth == 1)) {
1208 checkminipage = false;
1209 if (minipar && (minipar != par) &&
1210 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1212 lyxerr << "minipages in a row" << endl;
1213 if (par->params().pextraStartMinipage()) {
1214 lyxerr << "start new minipage" << endl;
1215 // minipages in a row
1216 par->previous()->next(0);
1219 Paragraph * tmp = minipar;
1221 tmp->params().pextraType(0);
1222 tmp->params().pextraWidth(string());
1223 tmp->params().pextraWidthp(string());
1224 tmp->params().pextraAlignment(0);
1225 tmp->params().pextraHfill(false);
1226 tmp->params().pextraStartMinipage(false);
1229 // create a new paragraph to insert the
1230 // minipages in the following case
1231 if (par->params().pextraStartMinipage() &&
1232 !par->params().pextraHfill())
1234 Paragraph * p = new Paragraph;
1236 p->previous(parBeforeMinipage);
1237 parBeforeMinipage->next(p);
1239 p->params().depth(parBeforeMinipage->params().depth());
1240 parBeforeMinipage = p;
1242 InsetMinipage * mini = new InsetMinipage;
1243 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1244 mini->width(par->params().pextraWidth());
1245 if (!par->params().pextraWidthp().empty()) {
1246 lyxerr << "WP:" << mini->width() << endl;
1247 mini->width(tostr(par->params().pextraWidthp())+"%");
1249 mini->inset.paragraph(par);
1250 // Insert the minipage last in the
1251 // previous paragraph.
1252 if (par->params().pextraHfill()) {
1253 parBeforeMinipage->insertChar
1254 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1256 parBeforeMinipage->insertInset
1257 (parBeforeMinipage->size(), mini);
1261 lyxerr << "new minipage par" << endl;
1262 //nothing to do just continue reading
1265 } else if (minipar && (minipar != par)) {
1266 lyxerr << "last minipage par read" << endl;
1267 // The last paragraph read was not part of a
1268 // minipage but the par linked list is...
1269 // So we need to remove the last par from the
1271 if (par->previous())
1272 par->previous()->next(0);
1273 par->previous(parBeforeMinipage);
1274 parBeforeMinipage->next(par);
1275 Paragraph * tmp = minipar;
1277 tmp->params().pextraType(0);
1278 tmp->params().pextraWidth(string());
1279 tmp->params().pextraWidthp(string());
1280 tmp->params().pextraAlignment(0);
1281 tmp->params().pextraHfill(false);
1282 tmp->params().pextraStartMinipage(false);
1285 depth = parBeforeMinipage->params().depth();
1286 minipar = parBeforeMinipage = 0;
1287 } else if (!minipar &&
1288 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1290 // par is the first paragraph in a minipage
1291 lyxerr << "begin minipage" << endl;
1292 // To minimize problems for
1293 // the users we will insert
1294 // the first minipage in
1295 // a sequence of minipages
1296 // in its own paragraph.
1297 Paragraph * p = new Paragraph;
1299 p->previous(par->previous());
1301 p->params().depth(depth);
1302 par->params().depth(0);
1304 if (par->previous())
1305 par->previous()->next(p);
1307 parBeforeMinipage = p;
1309 if (!first_par || (first_par == par))
1312 InsetMinipage * mini = new InsetMinipage;
1313 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1314 mini->width(minipar->params().pextraWidth());
1315 if (!par->params().pextraWidthp().empty()) {
1316 lyxerr << "WP:" << mini->width() << endl;
1317 mini->width(tostr(par->params().pextraWidthp())+"%");
1319 mini->inset.paragraph(minipar);
1321 // Insert the minipage last in the
1322 // previous paragraph.
1323 if (minipar->params().pextraHfill()) {
1324 parBeforeMinipage->insertChar
1325 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1327 parBeforeMinipage->insertInset
1328 (parBeforeMinipage->size(), mini);
1331 // End of pextra_minipage compability
1334 return the_end_read;
1337 // needed to insert the selection
1338 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1339 LyXFont const & font,
1340 string const & str) const
1342 LyXLayout const & layout = textclasslist.Style(params.textclass,
1344 // insert the string, don't insert doublespace
1345 bool space_inserted = true;
1346 for(string::const_iterator cit = str.begin();
1347 cit != str.end(); ++cit) {
1349 if (par->size() || layout.keepempty) {
1350 par->breakParagraph(params, pos,
1351 layout.isEnvironment());
1354 space_inserted = true;
1358 // do not insert consecutive spaces if !free_spacing
1359 } else if ((*cit == ' ' || *cit == '\t')
1360 && space_inserted && !layout.free_spacing) {
1362 } else if (*cit == '\t') {
1363 if (!layout.free_spacing) {
1364 // tabs are like spaces here
1365 par->insertChar(pos, ' ', font);
1367 space_inserted = true;
1369 const Paragraph::value_type nb = 8 - pos % 8;
1370 for (Paragraph::size_type a = 0;
1372 par->insertChar(pos, ' ', font);
1375 space_inserted = true;
1377 } else if (!IsPrintable(*cit)) {
1378 // Ignore unprintables
1381 // just insert the character
1382 par->insertChar(pos, *cit, font);
1384 space_inserted = (*cit == ' ');
1391 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1392 int & pos, LyXFont & font)
1394 // consistency check
1395 if (lex.GetString() != "\\begin_inset") {
1396 lyxerr << "Buffer::readInset: Consistency check failed."
1403 string const tmptok = lex.GetString();
1404 last_inset_read = tmptok;
1406 // test the different insets
1407 if (tmptok == "LatexCommand") {
1408 InsetCommandParams inscmd;
1411 string const cmdName = inscmd.getCmdName();
1413 // This strange command allows LyX to recognize "natbib" style
1414 // citations: citet, citep, Citet etc.
1415 if (compare_no_case(cmdName, "cite", 4) == 0) {
1416 inset = new InsetCitation(inscmd);
1417 } else if (cmdName == "bibitem") {
1418 lex.printError("Wrong place for bibitem");
1419 inset = new InsetBibKey(inscmd);
1420 } else if (cmdName == "BibTeX") {
1421 inset = new InsetBibtex(inscmd);
1422 } else if (cmdName == "index") {
1423 inset = new InsetIndex(inscmd);
1424 } else if (cmdName == "include") {
1425 inset = new InsetInclude(inscmd, *this);
1426 } else if (cmdName == "label") {
1427 inset = new InsetLabel(inscmd);
1428 } else if (cmdName == "url"
1429 || cmdName == "htmlurl") {
1430 inset = new InsetUrl(inscmd);
1431 } else if (cmdName == "ref"
1432 || cmdName == "pageref"
1433 || cmdName == "vref"
1434 || cmdName == "vpageref"
1435 || cmdName == "prettyref") {
1436 if (!inscmd.getOptions().empty()
1437 || !inscmd.getContents().empty()) {
1438 inset = new InsetRef(inscmd, *this);
1440 } else if (cmdName == "tableofcontents") {
1441 inset = new InsetTOC(inscmd);
1442 } else if (cmdName == "listofalgorithms") {
1443 inset = new InsetFloatList("algorithm");
1444 } else if (cmdName == "listoffigures") {
1445 inset = new InsetFloatList("figure");
1446 } else if (cmdName == "listoftables") {
1447 inset = new InsetFloatList("table");
1448 } else if (cmdName == "printindex") {
1449 inset = new InsetPrintIndex(inscmd);
1450 } else if (cmdName == "lyxparent") {
1451 inset = new InsetParent(inscmd, *this);
1454 bool alreadyread = false;
1455 if (tmptok == "Quotes") {
1456 inset = new InsetQuotes;
1457 } else if (tmptok == "External") {
1458 inset = new InsetExternal;
1459 } else if (tmptok == "FormulaMacro") {
1460 inset = new InsetFormulaMacro;
1461 } else if (tmptok == "Formula") {
1462 inset = new InsetFormula;
1463 } else if (tmptok == "Figure") { // Backward compatibility
1464 inset = new InsetFig(100, 100, *this);
1465 //inset = new InsetGraphics;
1466 } else if (tmptok == "Graphics") {
1467 inset = new InsetGraphics;
1468 } else if (tmptok == "Info") {// backwards compatibility
1469 inset = new InsetNote(this,
1470 lex.getLongString("\\end_inset"),
1473 } else if (tmptok == "Note") {
1474 inset = new InsetNote;
1475 } else if (tmptok == "Include") {
1476 InsetCommandParams p( "Include" );
1477 inset = new InsetInclude(p, *this);
1478 } else if (tmptok == "ERT") {
1479 inset = new InsetERT;
1480 } else if (tmptok == "Tabular") {
1481 inset = new InsetTabular(*this);
1482 } else if (tmptok == "Text") {
1483 inset = new InsetText;
1484 } else if (tmptok == "Foot") {
1485 inset = new InsetFoot;
1486 } else if (tmptok == "Marginal") {
1487 inset = new InsetMarginal;
1488 } else if (tmptok == "Minipage") {
1489 inset = new InsetMinipage;
1490 } else if (tmptok == "Float") {
1492 string tmptok = lex.GetString();
1493 inset = new InsetFloat(tmptok);
1495 } else if (tmptok == "List") {
1496 inset = new InsetList;
1497 } else if (tmptok == "Theorem") {
1498 inset = new InsetList;
1500 } else if (tmptok == "Caption") {
1501 inset = new InsetCaption;
1502 } else if (tmptok == "FloatList") {
1503 inset = new InsetFloatList;
1506 if (inset && !alreadyread) inset->read(this, lex);
1510 par->insertInset(pos, inset, font);
1516 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1520 string const token(lex.GetString());
1521 if (token == "\\lyxformat") { // the first token _must_ be...
1523 string tmp_format = lex.GetString();
1524 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1525 // if present remove ".," from string.
1526 string::size_type dot = tmp_format.find_first_of(".,");
1527 //lyxerr << " dot found at " << dot << endl;
1528 if (dot != string::npos)
1529 tmp_format.erase(dot, 1);
1530 file_format = strToInt(tmp_format);
1531 if (file_format == LYX_FORMAT) {
1533 } else if (file_format > LYX_FORMAT) {
1535 WriteAlert(_("Warning!"),
1536 _("LyX file format is newer that what"),
1537 _("is supported in this LyX version. Expect some problems."));
1539 } else if (file_format < LYX_FORMAT) {
1541 if (file_format < 200) {
1542 WriteAlert(_("ERROR!"),
1543 _("Old LyX file format found. "
1544 "Use LyX 0.10.x to read this!"));
1548 bool the_end = readLyXformat2(lex, par);
1550 // the_end was added in 213
1551 if (file_format < 213)
1555 WriteAlert(_("Warning!"),
1556 _("Reading of document is not complete"),
1557 _("Maybe the document is truncated"));
1559 } else { // "\\lyxformat" not found
1560 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1563 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1568 // Should probably be moved to somewhere else: BufferView? LyXView?
1569 bool Buffer::save() const
1571 // We don't need autosaves in the immediate future. (Asger)
1572 resetAutosaveTimers();
1576 if (lyxrc.make_backup) {
1577 s = fileName() + '~';
1578 if (!lyxrc.backupdir_path.empty())
1579 s = AddName(lyxrc.backupdir_path,
1580 subst(os::slashify_path(s),'/','!'));
1582 // Rename is the wrong way of making a backup,
1583 // this is the correct way.
1584 /* truss cp fil fil2:
1585 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1586 stat("LyXVC.lyx", 0xEFFFF688) = 0
1587 open("LyXVC.lyx", O_RDONLY) = 3
1588 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1589 fstat(4, 0xEFFFF508) = 0
1590 fstat(3, 0xEFFFF508) = 0
1591 read(3, " # T h i s f i l e w".., 8192) = 5579
1592 write(4, " # T h i s f i l e w".., 5579) = 5579
1593 read(3, 0xEFFFD4A0, 8192) = 0
1596 chmod("LyXVC3.lyx", 0100644) = 0
1597 lseek(0, 0, SEEK_CUR) = 46440
1601 // Should probably have some more error checking here.
1602 // Should be cleaned up in 0.13, at least a bit.
1603 // Doing it this way, also makes the inodes stay the same.
1604 // This is still not a very good solution, in particular we
1605 // might loose the owner of the backup.
1606 FileInfo finfo(fileName());
1607 if (finfo.exist()) {
1608 mode_t fmode = finfo.getMode();
1609 struct utimbuf times = {
1610 finfo.getAccessTime(),
1611 finfo.getModificationTime() };
1613 ifstream ifs(fileName().c_str());
1614 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1619 ::chmod(s.c_str(), fmode);
1621 if (::utime(s.c_str(), ×)) {
1622 lyxerr << "utime error." << endl;
1625 lyxerr << "LyX was not able to make "
1626 "backup copy. Beware." << endl;
1631 if (writeFile(fileName(), false)) {
1633 removeAutosaveFile(fileName());
1635 // Saving failed, so backup is not backup
1636 if (lyxrc.make_backup) {
1637 lyx::rename(s, fileName());
1645 // Returns false if unsuccesful
1646 bool Buffer::writeFile(string const & fname, bool flag) const
1648 // if flag is false writeFile will not create any GUI
1649 // warnings, only cerr.
1650 // Needed for autosave in background or panic save (Matthias 120496)
1652 if (read_only && (fname == filename)) {
1653 // Here we should come with a question if we should
1654 // perform the write anyway.
1656 lyxerr << _("Error! Document is read-only: ")
1659 WriteAlert(_("Error! Document is read-only: "),
1664 FileInfo finfo(fname);
1665 if (finfo.exist() && !finfo.writable()) {
1666 // Here we should come with a question if we should
1667 // try to do the save anyway. (i.e. do a chmod first)
1669 lyxerr << _("Error! Cannot write file: ")
1672 WriteFSAlert(_("Error! Cannot write file: "),
1677 ofstream ofs(fname.c_str());
1680 lyxerr << _("Error! Cannot open file: ")
1683 WriteFSAlert(_("Error! Cannot open file: "),
1689 // Use the standard "C" locale for file output.
1690 ofs.imbue(std::locale::classic());
1693 // The top of the file should not be written by params.
1695 // write out a comment in the top of the file
1696 ofs << '#' << LYX_DOCVERSION
1697 << " created this file. For more info see http://www.lyx.org/\n"
1698 << "\\lyxformat " << LYX_FORMAT << "\n";
1700 // now write out the buffer paramters.
1701 params.writeFile(ofs);
1703 Paragraph::depth_type depth = 0;
1705 // this will write out all the paragraphs
1706 // using recursive descent.
1707 paragraph->writeFile(this, ofs, params, depth);
1709 // Write marker that shows file is complete
1710 ofs << "\n\\the_end" << endl;
1714 // how to check if close went ok?
1715 // Following is an attempt... (BE 20001011)
1717 // good() returns false if any error occured, including some
1718 // formatting error.
1719 // bad() returns true if something bad happened in the buffer,
1720 // which should include file system full errors.
1727 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1729 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1739 string const Buffer::asciiParagraph(Paragraph const * par,
1740 unsigned int linelen) const
1742 ostringstream buffer;
1743 Paragraph::depth_type depth = 0;
1745 Paragraph::depth_type ltype_depth = 0;
1746 unsigned int currlinelen = 0;
1747 bool ref_printed = false;
1751 if (!par->previous()) {
1752 // begins or ends a deeper area ?
1753 if (depth != par->params().depth()) {
1754 if (par->params().depth() > depth) {
1755 while (par->params().depth() > depth) {
1759 while (par->params().depth() < depth) {
1765 // First write the layout
1766 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1767 if (tmp == "Itemize") {
1769 ltype_depth = depth + 1;
1770 } else if (tmp == "Enumerate") {
1772 ltype_depth = depth + 1;
1773 } else if (contains(tmp, "ection")) {
1775 ltype_depth = depth + 1;
1776 } else if (contains(tmp, "aragraph")) {
1778 ltype_depth = depth + 1;
1779 } else if (tmp == "Description") {
1781 ltype_depth = depth + 1;
1782 } else if (tmp == "Abstract") {
1785 } else if (tmp == "Bibliography") {
1793 /* maybe some vertical spaces */
1795 /* the labelwidthstring used in lists */
1799 /* some pagebreaks? */
1803 /* what about the alignment */
1805 lyxerr << "Should this ever happen?" << endl;
1809 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1811 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1812 if (!i && !noparbreak) {
1815 for (Paragraph::depth_type j = 0; j < depth; ++j)
1817 currlinelen = depth * 2;
1820 case 4: // (Sub)Paragraph
1821 case 5: // Description
1825 buffer << "Abstract\n\n";
1827 buffer << "Abstract: ";
1829 case 7: // Bibliography
1832 buffer << "References\n\n";
1834 buffer << "References: ";
1839 buffer << par->params().labelString() << " ";
1842 if (ltype_depth > depth) {
1843 for (Paragraph::depth_type j = ltype_depth - 1;
1846 currlinelen += (ltype_depth-depth)*2;
1850 LyXFont const font2 = par->getFontSettings(params, i);
1851 if (font1.latex() != font2.latex()) {
1852 if (font2.latex() == LyXFont::OFF)
1861 char c = par->getUChar(params, i);
1865 case Paragraph::META_INSET:
1867 Inset const * inset = par->getInset(i);
1869 if (!inset->ascii(this, buffer)) {
1872 rsplit(buffer.str().c_str(),
1874 currlinelen += s.length();
1876 // to be sure it breaks paragraph
1877 currlinelen += linelen;
1883 case Paragraph::META_NEWLINE:
1886 for (Paragraph::depth_type j = 0;
1890 currlinelen = depth * 2;
1891 if (ltype_depth > depth) {
1892 for (Paragraph::depth_type j = ltype_depth;
1895 currlinelen += (ltype_depth - depth) * 2;
1899 case Paragraph::META_HFILL:
1908 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1909 (c == ' ') && ((i + 2) < par->size()))
1912 for (Paragraph::depth_type j = 0;
1915 currlinelen = depth * 2;
1916 if (ltype_depth > depth) {
1917 for (Paragraph::depth_type j = ltype_depth;
1920 currlinelen += (ltype_depth-depth)*2;
1922 } else if (c != '\0')
1925 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1930 return buffer.str().c_str();
1934 void Buffer::writeFileAscii(string const & fname, int linelen)
1936 ofstream ofs(fname.c_str());
1938 WriteFSAlert(_("Error: Cannot write file:"), fname);
1941 writeFileAscii(ofs, linelen);
1945 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1947 Paragraph * par = paragraph;
1949 ofs << asciiParagraph(par, linelen);
1957 void Buffer::makeLaTeXFile(string const & fname,
1958 string const & original_path,
1959 bool nice, bool only_body)
1961 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1963 niceFile = nice; // this will be used by Insetincludes.
1965 tex_code_break_column = lyxrc.ascii_linelen;
1967 LyXTextClass const & tclass =
1968 textclasslist.TextClass(params.textclass);
1970 ofstream ofs(fname.c_str());
1972 WriteFSAlert(_("Error: Cannot open file: "), fname);
1976 // validate the buffer.
1977 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1978 LaTeXFeatures features(params, tclass.numLayouts());
1980 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1983 // The starting paragraph of the coming rows is the
1984 // first paragraph of the document. (Asger)
1985 texrow.start(paragraph, 0);
1987 if (!only_body && nice) {
1988 ofs << "%% " LYX_DOCVERSION " created this file. "
1989 "For more info, see http://www.lyx.org/.\n"
1990 "%% Do not edit unless you really know what "
1995 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1996 // There are a few differences between nice LaTeX and usual files:
1997 // usual is \batchmode and has a
1998 // special input@path to allow the including of figures
1999 // with either \input or \includegraphics (what figinsets do).
2000 // batchmode is not set if there is a tex_code_break_column.
2001 // In this case somebody is interested in the generated LaTeX,
2002 // so this is OK. input@path is set when the actual parameter
2003 // original_path is set. This is done for usual tex-file, but not
2004 // for nice-latex-file. (Matthias 250696)
2007 // code for usual, NOT nice-latex-file
2008 ofs << "\\batchmode\n"; // changed
2009 // from \nonstopmode
2012 if (!original_path.empty()) {
2013 ofs << "\\makeatletter\n"
2014 << "\\def\\input@path{{"
2015 << os::external_path(original_path) << "/}}\n"
2016 << "\\makeatother\n";
2022 ofs << "\\documentclass";
2024 ostringstream options; // the document class options.
2026 if (tokenPos(tclass.opt_fontsize(),
2027 '|', params.fontsize) >= 0) {
2028 // only write if existing in list (and not default)
2029 options << params.fontsize << "pt,";
2033 if (!params.use_geometry &&
2034 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2035 switch (params.papersize) {
2036 case BufferParams::PAPER_A4PAPER:
2037 options << "a4paper,";
2039 case BufferParams::PAPER_USLETTER:
2040 options << "letterpaper,";
2042 case BufferParams::PAPER_A5PAPER:
2043 options << "a5paper,";
2045 case BufferParams::PAPER_B5PAPER:
2046 options << "b5paper,";
2048 case BufferParams::PAPER_EXECUTIVEPAPER:
2049 options << "executivepaper,";
2051 case BufferParams::PAPER_LEGALPAPER:
2052 options << "legalpaper,";
2058 if (params.sides != tclass.sides()) {
2059 switch (params.sides) {
2060 case LyXTextClass::OneSide:
2061 options << "oneside,";
2063 case LyXTextClass::TwoSides:
2064 options << "twoside,";
2070 if (params.columns != tclass.columns()) {
2071 if (params.columns == 2)
2072 options << "twocolumn,";
2074 options << "onecolumn,";
2077 if (!params.use_geometry
2078 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2079 options << "landscape,";
2081 // language should be a parameter to \documentclass
2083 ostringstream language_options;
2084 if (params.language->babel() == "hebrew"
2085 && default_language->babel() != "hebrew")
2086 // This seems necessary
2087 features.UsedLanguages.insert(default_language);
2089 if (lyxrc.language_use_babel ||
2090 params.language->lang() != lyxrc.default_language ||
2091 !features.UsedLanguages.empty()) {
2093 for (LaTeXFeatures::LanguageList::const_iterator cit =
2094 features.UsedLanguages.begin();
2095 cit != features.UsedLanguages.end(); ++cit)
2096 language_options << (*cit)->babel() << ',';
2097 language_options << params.language->babel();
2098 if (lyxrc.language_global_options)
2099 options << language_options.str() << ',';
2102 // the user-defined options
2103 if (!params.options.empty()) {
2104 options << params.options << ',';
2107 string strOptions(options.str().c_str());
2108 if (!strOptions.empty()){
2109 strOptions = strip(strOptions, ',');
2110 ofs << '[' << strOptions << ']';
2114 << textclasslist.LatexnameOfClass(params.textclass)
2117 // end of \documentclass defs
2119 // font selection must be done before loading fontenc.sty
2120 // The ae package is not needed when using OT1 font encoding.
2121 if (params.fonts != "default" &&
2122 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2123 ofs << "\\usepackage{" << params.fonts << "}\n";
2125 if (params.fonts == "ae") {
2126 ofs << "\\usepackage{aecompl}\n";
2130 // this one is not per buffer
2131 if (lyxrc.fontenc != "default") {
2132 ofs << "\\usepackage[" << lyxrc.fontenc
2137 if (params.inputenc == "auto") {
2138 string const doc_encoding =
2139 params.language->encoding()->LatexName();
2141 // Create a list with all the input encodings used
2143 set<string> encodings;
2144 for (LaTeXFeatures::LanguageList::const_iterator it =
2145 features.UsedLanguages.begin();
2146 it != features.UsedLanguages.end(); ++it)
2147 if ((*it)->encoding()->LatexName() != doc_encoding)
2148 encodings.insert((*it)->encoding()->LatexName());
2150 ofs << "\\usepackage[";
2151 std::copy(encodings.begin(), encodings.end(),
2152 std::ostream_iterator<string>(ofs, ","));
2153 ofs << doc_encoding << "]{inputenc}\n";
2155 } else if (params.inputenc != "default") {
2156 ofs << "\\usepackage[" << params.inputenc
2161 // At the very beginning the text parameters.
2162 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2163 switch (params.paperpackage) {
2164 case BufferParams::PACKAGE_A4:
2165 ofs << "\\usepackage{a4}\n";
2168 case BufferParams::PACKAGE_A4WIDE:
2169 ofs << "\\usepackage{a4wide}\n";
2172 case BufferParams::PACKAGE_WIDEMARGINSA4:
2173 ofs << "\\usepackage[widemargins]{a4}\n";
2178 if (params.use_geometry) {
2179 ofs << "\\usepackage{geometry}\n";
2181 ofs << "\\geometry{verbose";
2182 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2183 ofs << ",landscape";
2184 switch (params.papersize2) {
2185 case BufferParams::VM_PAPER_CUSTOM:
2186 if (!params.paperwidth.empty())
2187 ofs << ",paperwidth="
2188 << params.paperwidth;
2189 if (!params.paperheight.empty())
2190 ofs << ",paperheight="
2191 << params.paperheight;
2193 case BufferParams::VM_PAPER_USLETTER:
2194 ofs << ",letterpaper";
2196 case BufferParams::VM_PAPER_USLEGAL:
2197 ofs << ",legalpaper";
2199 case BufferParams::VM_PAPER_USEXECUTIVE:
2200 ofs << ",executivepaper";
2202 case BufferParams::VM_PAPER_A3:
2205 case BufferParams::VM_PAPER_A4:
2208 case BufferParams::VM_PAPER_A5:
2211 case BufferParams::VM_PAPER_B3:
2214 case BufferParams::VM_PAPER_B4:
2217 case BufferParams::VM_PAPER_B5:
2221 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2222 switch (lyxrc.default_papersize) {
2223 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2224 case BufferParams::PAPER_USLETTER:
2225 ofs << ",letterpaper";
2227 case BufferParams::PAPER_LEGALPAPER:
2228 ofs << ",legalpaper";
2230 case BufferParams::PAPER_EXECUTIVEPAPER:
2231 ofs << ",executivepaper";
2233 case BufferParams::PAPER_A3PAPER:
2236 case BufferParams::PAPER_A4PAPER:
2239 case BufferParams::PAPER_A5PAPER:
2242 case BufferParams::PAPER_B5PAPER:
2247 if (!params.topmargin.empty())
2248 ofs << ",tmargin=" << params.topmargin;
2249 if (!params.bottommargin.empty())
2250 ofs << ",bmargin=" << params.bottommargin;
2251 if (!params.leftmargin.empty())
2252 ofs << ",lmargin=" << params.leftmargin;
2253 if (!params.rightmargin.empty())
2254 ofs << ",rmargin=" << params.rightmargin;
2255 if (!params.headheight.empty())
2256 ofs << ",headheight=" << params.headheight;
2257 if (!params.headsep.empty())
2258 ofs << ",headsep=" << params.headsep;
2259 if (!params.footskip.empty())
2260 ofs << ",footskip=" << params.footskip;
2264 if (features.amsstyle
2265 && !tclass.provides(LyXTextClass::amsmath)) {
2266 ofs << "\\usepackage{amsmath}\n";
2270 if (tokenPos(tclass.opt_pagestyle(),
2271 '|', params.pagestyle) >= 0) {
2272 if (params.pagestyle == "fancy") {
2273 ofs << "\\usepackage{fancyhdr}\n";
2276 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2280 // We try to load babel late, in case it interferes
2281 // with other packages.
2283 string tmp = lyxrc.language_package;
2284 if (!lyxrc.language_global_options
2285 && tmp == "\\usepackage{babel}")
2286 tmp = string("\\usepackage[") +
2287 language_options.str().c_str() +
2293 if (params.secnumdepth != tclass.secnumdepth()) {
2294 ofs << "\\setcounter{secnumdepth}{"
2295 << params.secnumdepth
2299 if (params.tocdepth != tclass.tocdepth()) {
2300 ofs << "\\setcounter{tocdepth}{"
2306 if (params.paragraph_separation) {
2307 switch (params.defskip.kind()) {
2308 case VSpace::SMALLSKIP:
2309 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2311 case VSpace::MEDSKIP:
2312 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2314 case VSpace::BIGSKIP:
2315 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2317 case VSpace::LENGTH:
2318 ofs << "\\setlength\\parskip{"
2319 << params.defskip.length().asLatexString()
2322 default: // should never happen // Then delete it.
2323 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2328 ofs << "\\setlength\\parindent{0pt}\n";
2332 // Now insert the LyX specific LaTeX commands...
2334 // The optional packages;
2335 string preamble(features.getPackages());
2337 // this might be useful...
2338 preamble += "\n\\makeatletter\n";
2340 // Some macros LyX will need
2341 string tmppreamble(features.getMacros());
2343 if (!tmppreamble.empty()) {
2344 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2345 "LyX specific LaTeX commands.\n"
2346 + tmppreamble + '\n';
2349 // the text class specific preamble
2350 tmppreamble = features.getTClassPreamble();
2351 if (!tmppreamble.empty()) {
2352 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2353 "Textclass specific LaTeX commands.\n"
2354 + tmppreamble + '\n';
2357 /* the user-defined preamble */
2358 if (!params.preamble.empty()) {
2359 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2360 "User specified LaTeX commands.\n"
2361 + params.preamble + '\n';
2364 preamble += "\\makeatother\n";
2366 // Itemize bullet settings need to be last in case the user
2367 // defines their own bullets that use a package included
2368 // in the user-defined preamble -- ARRae
2369 // Actually it has to be done much later than that
2370 // since some packages like frenchb make modifications
2371 // at \begin{document} time -- JMarc
2373 for (int i = 0; i < 4; ++i) {
2374 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2375 if (bullets_def.empty())
2376 bullets_def="\\AtBeginDocument{\n";
2377 bullets_def += " \\renewcommand{\\labelitemi";
2379 // `i' is one less than the item to modify
2386 bullets_def += "ii";
2392 bullets_def += "}{" +
2393 params.user_defined_bullets[i].getText()
2398 if (!bullets_def.empty())
2399 preamble += bullets_def + "}\n\n";
2401 for (int j = countChar(preamble, '\n'); j-- ;) {
2408 ofs << "\\begin{document}\n";
2411 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2413 if (!lyxrc.language_auto_begin) {
2414 ofs << subst(lyxrc.language_command_begin, "$$lang",
2415 params.language->babel())
2420 latexParagraphs(ofs, paragraph, 0, texrow);
2422 // add this just in case after all the paragraphs
2426 if (!lyxrc.language_auto_end) {
2427 ofs << subst(lyxrc.language_command_end, "$$lang",
2428 params.language->babel())
2434 ofs << "\\end{document}\n";
2437 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2439 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2443 // Just to be sure. (Asger)
2446 // tex_code_break_column's value is used to decide
2447 // if we are in batchmode or not (within mathed_write()
2448 // in math_write.C) so we must set it to a non-zero
2449 // value when we leave otherwise we save incorrect .lyx files.
2450 tex_code_break_column = lyxrc.ascii_linelen;
2454 lyxerr << "File was not closed properly." << endl;
2457 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2462 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2464 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2465 Paragraph * endpar, TexRow & texrow) const
2467 bool was_title = false;
2468 bool already_title = false;
2471 while (par != endpar) {
2472 LyXLayout const & layout =
2473 textclasslist.Style(params.textclass,
2476 if (layout.intitle) {
2477 if (already_title) {
2478 lyxerr <<"Error in latexParagraphs: You"
2479 " should not mix title layouts"
2480 " with normal ones." << endl;
2483 } else if (was_title && !already_title) {
2484 ofs << "\\maketitle\n";
2486 already_title = true;
2490 if (layout.isEnvironment()) {
2491 par = par->TeXEnvironment(this, params, ofs, texrow);
2493 par = par->TeXOnePar(this, params, ofs, texrow, false);
2496 // It might be that we only have a title in this document
2497 if (was_title && !already_title) {
2498 ofs << "\\maketitle\n";
2504 bool Buffer::isLatex() const
2506 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2510 bool Buffer::isLinuxDoc() const
2512 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2516 bool Buffer::isLiterate() const
2518 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2522 bool Buffer::isDocBook() const
2524 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2528 bool Buffer::isSGML() const
2530 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2531 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2535 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2536 string const & latexname) const
2538 if (!latexname.empty() && latexname != "!-- --")
2539 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2540 //os << string(depth, ' ') << "<" << latexname << ">\n";
2544 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2545 string const & latexname) const
2547 if (!latexname.empty() && latexname != "!-- --")
2548 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2549 //os << string(depth, ' ') << "</" << latexname << ">\n";
2553 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2555 ofstream ofs(fname.c_str());
2558 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2562 niceFile = nice; // this will be used by included files.
2564 LyXTextClass const & tclass =
2565 textclasslist.TextClass(params.textclass);
2567 LaTeXFeatures features(params, tclass.numLayouts());
2572 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2575 string sgml_includedfiles=features.getIncludedFiles(fname);
2577 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2578 ofs << "<!doctype linuxdoc system>\n\n";
2580 ofs << "<!doctype linuxdoc system [ "
2581 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2584 if (params.options.empty())
2585 sgmlOpenTag(ofs, 0, top_element);
2587 string top = top_element;
2589 top += params.options;
2590 sgmlOpenTag(ofs, 0, top);
2594 ofs << "<!-- " << LYX_DOCVERSION
2595 << " created this file. For more info see http://www.lyx.org/"
2598 Paragraph::depth_type depth = 0; // paragraph depth
2599 Paragraph * par = paragraph;
2601 vector<string> environment_stack(5);
2604 LyXLayout const & style =
2605 textclasslist.Style(params.textclass,
2608 // treat <toc> as a special case for compatibility with old code
2609 if (par->getChar(0) == Paragraph::META_INSET) {
2610 Inset * inset = par->getInset(0);
2611 Inset::Code lyx_code = inset->lyxCode();
2612 if (lyx_code == Inset::TOC_CODE){
2613 string const temp = "toc";
2614 sgmlOpenTag(ofs, depth, temp);
2621 // environment tag closing
2622 for (; depth > par->params().depth(); --depth) {
2623 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2624 environment_stack[depth].erase();
2627 // write opening SGML tags
2628 switch (style.latextype) {
2629 case LATEX_PARAGRAPH:
2630 if (depth == par->params().depth()
2631 && !environment_stack[depth].empty()) {
2632 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2633 environment_stack[depth].erase();
2639 sgmlOpenTag(ofs, depth, style.latexname());
2644 linuxDocError(par, 0,
2645 _("Error : Wrong depth for"
2646 " LatexType Command.\n"));
2648 if (!environment_stack[depth].empty()){
2649 sgmlCloseTag(ofs, depth,
2650 environment_stack[depth]);
2654 environment_stack[depth].erase();
2655 sgmlOpenTag(ofs, depth, style.latexname());
2658 case LATEX_ENVIRONMENT:
2659 case LATEX_ITEM_ENVIRONMENT:
2660 if (depth == par->params().depth()
2661 && environment_stack[depth] != style.latexname()) {
2662 sgmlCloseTag(ofs, depth,
2663 environment_stack[depth]);
2664 environment_stack[depth].erase();
2666 if (depth < par->params().depth()) {
2667 depth = par->params().depth();
2668 environment_stack[depth].erase();
2670 if (environment_stack[depth] != style.latexname()) {
2672 sgmlOpenTag(ofs, depth, "p");
2674 sgmlOpenTag(ofs, depth, style.latexname());
2676 if (environment_stack.size() == depth + 1)
2677 environment_stack.push_back("!-- --");
2678 environment_stack[depth] = style.latexname();
2681 if (style.latexparam() == "CDATA")
2684 if (style.latextype == LATEX_ENVIRONMENT) break;
2686 if (style.labeltype == LABEL_MANUAL)
2691 sgmlOpenTag(ofs, depth + 1, item_name);
2694 sgmlOpenTag(ofs, depth, style.latexname());
2698 simpleLinuxDocOnePar(ofs, par, depth);
2703 // write closing SGML tags
2704 switch (style.latextype) {
2707 case LATEX_ENVIRONMENT:
2708 case LATEX_ITEM_ENVIRONMENT:
2709 if (style.latexparam() == "CDATA")
2713 sgmlCloseTag(ofs, depth, style.latexname());
2719 for (int i=depth; i >= 0; --i)
2720 sgmlCloseTag(ofs, depth, environment_stack[i]);
2724 sgmlCloseTag(ofs, 0, top_element);
2728 // How to check for successful close
2732 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2733 Paragraph::depth_type depth, int desc_on,
2736 Paragraph * tpar = par;
2738 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2740 tpar = tpar->next();
2743 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2744 "Caption").second) {
2745 sgmlOpenTag(os, depth + 1, inner_tag);
2747 simpleDocBookOnePar(os, extra_par, tpar,
2748 desc_on, depth + 2);
2749 sgmlCloseTag(os, depth+1, inner_tag);
2750 if (!extra_par.empty())
2756 // checks, if newcol chars should be put into this line
2757 // writes newline, if necessary.
2760 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2761 string::size_type newcol)
2764 if (colcount > lyxrc.ascii_linelen) {
2766 colcount = newcol; // assume write after this call
2781 string tag_name(PAR_TAG const & pt) {
2783 case NONE: return "!-- --";
2784 case TT: return "tt";
2785 case SF: return "sf";
2786 case BF: return "bf";
2787 case IT: return "it";
2788 case SL: return "sl";
2789 case EM: return "em";
2796 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2798 p1 = static_cast<PAR_TAG>(p1 | p2);
2803 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2805 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2813 // Handle internal paragraph parsing -- layout already processed.
2814 void Buffer::simpleLinuxDocOnePar(ostream & os,
2816 Paragraph::depth_type /*depth*/)
2818 LyXLayout const & style = textclasslist.Style(params.textclass,
2820 string::size_type char_line_count = 5; // Heuristic choice ;-)
2822 // gets paragraph main font
2825 if (style.labeltype == LABEL_MANUAL) {
2826 font_old = style.labelfont;
2829 font_old = style.font;
2833 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2834 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2835 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2838 stack < PAR_TAG > tag_state;
2839 // parsing main loop
2840 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2842 PAR_TAG tag_close = NONE;
2843 list < PAR_TAG > tag_open;
2845 LyXFont const font = par->getFont(params, i);
2847 if (font_old.family() != font.family()) {
2848 switch (family_type) {
2849 case LyXFont::SANS_FAMILY:
2852 case LyXFont::TYPEWRITER_FAMILY:
2859 family_type = font.family();
2861 switch (family_type) {
2862 case LyXFont::SANS_FAMILY:
2863 tag_open.push_back(SF);
2865 case LyXFont::TYPEWRITER_FAMILY:
2866 tag_open.push_back(TT);
2873 if (font_old.series() != font.series()) {
2874 switch (series_type) {
2875 case LyXFont::BOLD_SERIES:
2882 series_type = font.series();
2884 switch (series_type) {
2885 case LyXFont::BOLD_SERIES:
2886 tag_open.push_back(BF);
2894 if (font_old.shape() != font.shape()) {
2895 switch (shape_type) {
2896 case LyXFont::ITALIC_SHAPE:
2899 case LyXFont::SLANTED_SHAPE:
2906 shape_type = font.shape();
2908 switch (shape_type) {
2909 case LyXFont::ITALIC_SHAPE:
2910 tag_open.push_back(IT);
2912 case LyXFont::SLANTED_SHAPE:
2913 tag_open.push_back(SL);
2920 if (font_old.emph() != font.emph()) {
2921 if (font.emph() == LyXFont::ON) {
2922 tag_open.push_back(EM);
2931 list < PAR_TAG > temp;
2932 while(!tag_state.empty() && tag_close ) {
2933 PAR_TAG k = tag_state.top();
2935 os << "</" << tag_name(k) << ">";
2942 for(list< PAR_TAG >::const_iterator j = temp.begin();
2943 j != temp.end(); ++j) {
2945 os << "<" << tag_name(*j) << ">";
2948 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2949 j != tag_open.end(); ++j) {
2951 os << "<" << tag_name(*j) << ">";
2954 char c = par->getChar(i);
2956 if (c == Paragraph::META_INSET) {
2957 Inset * inset = par->getInset(i);
2958 inset->linuxdoc(this, os);
2965 font.latex() == LyXFont::ON ||
2967 style.latexparam() == "CDATA") {
2968 // "TeX"-Mode on == > SGML-Mode on.
2974 if (par->linuxDocConvertChar(c, sgml_string)
2975 && !style.free_spacing) {
2976 // in freespacing mode, spaces are
2977 // non-breaking characters
2978 if (desc_on) {// if char is ' ' then...
2981 linux_doc_line_break(os, char_line_count, 6);
2985 linux_doc_line_break(os, char_line_count, 1);
2990 char_line_count += sgml_string.length();
2996 while (!tag_state.empty()) {
2997 os << "</" << tag_name(tag_state.top()) << ">";
3001 // resets description flag correctly
3003 // <tag> not closed...
3004 linux_doc_line_break(os, char_line_count, 6);
3010 // Print an error message.
3011 void Buffer::linuxDocError(Paragraph * par, int pos,
3012 string const & message)
3014 // insert an error marker in text
3015 InsetError * new_inset = new InsetError(message);
3016 par->insertInset(pos, new_inset);
3020 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3022 ofstream ofs(fname.c_str());
3024 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3028 Paragraph * par = paragraph;
3030 niceFile = nice; // this will be used by Insetincludes.
3032 LyXTextClass const & tclass =
3033 textclasslist.TextClass(params.textclass);
3035 LaTeXFeatures features(params, tclass.numLayouts());
3040 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3043 string sgml_includedfiles = features.getIncludedFiles(fname);
3045 ofs << "<!doctype " << top_element
3046 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3048 if (params.preamble.empty() && sgml_includedfiles.empty())
3051 ofs << "\n [ " << params.preamble
3052 << sgml_includedfiles << " \n]>\n\n";
3055 string top = top_element;
3057 top += params.language->code();
3060 if (!params.options.empty()) {
3062 top += params.options;
3064 sgmlOpenTag(ofs, 0, top);
3066 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3067 << "\n See http://www.lyx.org/ for more information -->\n";
3069 vector<string> environment_stack(10);
3070 vector<string> environment_inner(10);
3071 vector<string> command_stack(10);
3073 bool command_flag = false;
3074 Paragraph::depth_type command_depth = 0;
3075 Paragraph::depth_type command_base = 0;
3076 Paragraph::depth_type cmd_depth = 0;
3077 Paragraph::depth_type depth = 0; // paragraph depth
3080 string command_name;
3086 int desc_on = 0; // description mode
3088 LyXLayout const & style =
3089 textclasslist.Style(params.textclass,
3092 // environment tag closing
3093 for (; depth > par->params().depth(); --depth) {
3094 if (environment_inner[depth] != "!-- --") {
3095 item_name = "listitem";
3096 sgmlCloseTag(ofs, command_depth + depth,
3098 if (environment_inner[depth] == "varlistentry")
3099 sgmlCloseTag(ofs, depth+command_depth,
3100 environment_inner[depth]);
3102 sgmlCloseTag(ofs, depth + command_depth,
3103 environment_stack[depth]);
3104 environment_stack[depth].erase();
3105 environment_inner[depth].erase();
3108 if (depth == par->params().depth()
3109 && environment_stack[depth] != style.latexname()
3110 && !environment_stack[depth].empty()) {
3111 if (environment_inner[depth] != "!-- --") {
3112 item_name= "listitem";
3113 sgmlCloseTag(ofs, command_depth+depth,
3115 if (environment_inner[depth] == "varlistentry")
3117 depth + command_depth,
3118 environment_inner[depth]);
3121 sgmlCloseTag(ofs, depth + command_depth,
3122 environment_stack[depth]);
3124 environment_stack[depth].erase();
3125 environment_inner[depth].erase();
3128 // Write opening SGML tags.
3129 switch (style.latextype) {
3130 case LATEX_PARAGRAPH:
3131 sgmlOpenTag(ofs, depth + command_depth,
3137 linuxDocError(par, 0,
3138 _("Error : Wrong depth for "
3139 "LatexType Command.\n"));
3141 command_name = style.latexname();
3143 sgmlparam = style.latexparam();
3144 c_params = split(sgmlparam, c_depth,'|');
3146 cmd_depth = lyx::atoi(c_depth);
3149 if (cmd_depth < command_base) {
3150 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3151 sgmlCloseTag(ofs, j, command_stack[j]);
3152 command_depth = command_base = cmd_depth;
3153 } else if (cmd_depth <= command_depth) {
3154 for (int j = command_depth; j >= int(cmd_depth); --j)
3155 sgmlCloseTag(ofs, j, command_stack[j]);
3156 command_depth = cmd_depth;
3158 command_depth = cmd_depth;
3160 command_depth = command_base = cmd_depth;
3161 command_flag = true;
3163 if (command_stack.size() == command_depth + 1)
3164 command_stack.push_back(string());
3165 command_stack[command_depth] = command_name;
3167 // treat label as a special case for
3168 // more WYSIWYM handling.
3169 if (par->getChar(0) == Paragraph::META_INSET) {
3170 Inset * inset = par->getInset(0);
3171 Inset::Code lyx_code = inset->lyxCode();
3172 if (lyx_code == Inset::LABEL_CODE){
3173 command_name += " id=\"";
3174 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3175 command_name += "\"";
3180 sgmlOpenTag(ofs, depth + command_depth, command_name);
3181 if (c_params.empty())
3182 item_name = "title";
3184 item_name = c_params;
3185 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3188 case LATEX_ENVIRONMENT:
3189 case LATEX_ITEM_ENVIRONMENT:
3190 if (depth < par->params().depth()) {
3191 depth = par->params().depth();
3192 environment_stack[depth].erase();
3195 if (environment_stack[depth] != style.latexname()) {
3196 if(environment_stack.size() == depth + 1) {
3197 environment_stack.push_back("!-- --");
3198 environment_inner.push_back("!-- --");
3200 environment_stack[depth] = style.latexname();
3201 environment_inner[depth] = "!-- --";
3202 sgmlOpenTag(ofs, depth + command_depth,
3203 environment_stack[depth]);
3205 if (environment_inner[depth] != "!-- --") {
3206 item_name= "listitem";
3208 command_depth + depth,
3210 if (environment_inner[depth] == "varlistentry")
3212 depth + command_depth,
3213 environment_inner[depth]);
3217 if (style.latextype == LATEX_ENVIRONMENT) {
3218 if (!style.latexparam().empty()) {
3219 if(style.latexparam() == "CDATA")
3222 sgmlOpenTag(ofs, depth + command_depth,
3223 style.latexparam());
3228 desc_on = (style.labeltype == LABEL_MANUAL);
3231 environment_inner[depth]= "varlistentry";
3233 environment_inner[depth]= "listitem";
3235 sgmlOpenTag(ofs, depth + 1 + command_depth,
3236 environment_inner[depth]);
3240 sgmlOpenTag(ofs, depth + 1 + command_depth,
3244 sgmlOpenTag(ofs, depth + 1 + command_depth,
3249 sgmlOpenTag(ofs, depth + command_depth,
3255 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3256 depth + 1 + command_depth);
3260 // write closing SGML tags
3261 switch (style.latextype) {
3263 if (c_params.empty())
3267 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3269 case LATEX_ENVIRONMENT:
3270 if (!style.latexparam().empty()) {
3271 if(style.latexparam() == "CDATA")
3274 sgmlCloseTag(ofs, depth + command_depth,
3275 style.latexparam());
3278 case LATEX_ITEM_ENVIRONMENT:
3279 if (desc_on == 1) break;
3281 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3283 case LATEX_PARAGRAPH:
3284 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3287 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3293 for (int d = depth; d >= 0; --d) {
3294 if (!environment_stack[depth].empty()) {
3295 if (environment_inner[depth] != "!-- --") {
3296 item_name = "listitem";
3297 sgmlCloseTag(ofs, command_depth + depth,
3299 if (environment_inner[depth] == "varlistentry")
3300 sgmlCloseTag(ofs, depth + command_depth,
3301 environment_inner[depth]);
3304 sgmlCloseTag(ofs, depth + command_depth,
3305 environment_stack[depth]);
3309 for (int j = command_depth; j >= 0 ; --j)
3310 if (!command_stack[j].empty())
3311 sgmlCloseTag(ofs, j, command_stack[j]);
3314 sgmlCloseTag(ofs, 0, top_element);
3317 // How to check for successful close
3321 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3322 Paragraph * par, int & desc_on,
3323 Paragraph::depth_type depth) const
3325 bool emph_flag = false;
3327 LyXLayout const & style = textclasslist.Style(params.textclass,
3330 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3332 int char_line_count = depth;
3333 //if (!style.free_spacing)
3334 // os << string(depth,' ');
3336 // parsing main loop
3337 for (Paragraph::size_type i = 0;
3338 i < par->size(); ++i) {
3339 LyXFont font = par->getFont(params, i);
3341 // handle <emphasis> tag
3342 if (font_old.emph() != font.emph()) {
3343 if (font.emph() == LyXFont::ON) {
3347 os << "</emphasis>";
3352 char c = par->getChar(i);
3354 if (c == Paragraph::META_INSET) {
3355 Inset * inset = par->getInset(i);
3357 inset->docBook(this, ost);
3358 string tmp_out = ost.str().c_str();
3361 // This code needs some explanation:
3362 // Two insets are treated specially
3363 // label if it is the first element in a command paragraph
3365 // graphics inside tables or figure floats can't go on
3366 // title (the equivalente in latex for this case is caption
3367 // and title should come first
3370 if (desc_on!= 3 || i!= 0) {
3371 if (!tmp_out.empty() && tmp_out[0] == '@') {
3373 extra += frontStrip(tmp_out, '@');
3375 os << frontStrip(tmp_out, '@');
3381 } else if (font.latex() == LyXFont::ON) {
3382 // "TeX"-Mode on ==> SGML-Mode on.
3389 if (par->linuxDocConvertChar(c, sgml_string)
3390 && !style.free_spacing) { // in freespacing
3392 // non-breaking characters
3396 os << "\n</term><listitem><para>";
3409 os << "</emphasis>";
3412 // resets description flag correctly
3414 // <term> not closed...
3417 if(style.free_spacing) os << '\n';
3421 // This should be enabled when the Chktex class is implemented. (Asger)
3422 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3423 // Other flags: -wall -v0 -x
3424 int Buffer::runChktex()
3426 if (!users->text) return 0;
3428 users->owner()->prohibitInput();
3430 // get LaTeX-Filename
3431 string const name = getLatexName();
3432 string path = OnlyPath(filename);
3434 string const org_path = path;
3435 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3439 Path p(path); // path to LaTeX file
3440 users->owner()->message(_("Running chktex..."));
3442 // Remove all error insets
3443 bool const removedErrorInsets = users->removeAutoInsets();
3445 // Generate the LaTeX file if neccessary
3446 makeLaTeXFile(name, org_path, false);
3449 Chktex chktex(lyxrc.chktex_command, name, filepath);
3450 int res = chktex.run(terr); // run chktex
3453 WriteAlert(_("chktex did not work!"),
3454 _("Could not run with file:"), name);
3455 } else if (res > 0) {
3456 // Insert all errors as errors boxes
3457 users->insertErrors(terr);
3460 // if we removed error insets before we ran chktex or if we inserted
3461 // error insets after we ran chktex, this must be run:
3462 if (removedErrorInsets || res){
3466 users->owner()->allowInput();
3472 void Buffer::validate(LaTeXFeatures & features) const
3474 Paragraph * par = paragraph;
3475 LyXTextClass const & tclass =
3476 textclasslist.TextClass(params.textclass);
3478 // AMS Style is at document level
3479 features.amsstyle = (params.use_amsmath ||
3480 tclass.provides(LyXTextClass::amsmath));
3483 // We don't use "lyxerr.debug" because of speed. (Asger)
3484 if (lyxerr.debugging(Debug::LATEX))
3485 lyxerr << "Paragraph: " << par << endl;
3487 // Now just follow the list of paragraphs and run
3488 // validate on each of them.
3489 par->validate(features);
3491 // and then the next paragraph
3495 // the bullet shapes are buffer level not paragraph level
3496 // so they are tested here
3497 for (int i = 0; i < 4; ++i) {
3498 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3499 int const font = params.user_defined_bullets[i].getFont();
3501 int const c = params
3502 .user_defined_bullets[i]
3509 features.latexsym = true;
3511 } else if (font == 1) {
3512 features.amssymb = true;
3513 } else if ((font >= 2 && font <= 5)) {
3514 features.pifont = true;
3519 if (lyxerr.debugging(Debug::LATEX)) {
3520 features.showStruct();
3525 void Buffer::setPaperStuff()
3527 params.papersize = BufferParams::PAPER_DEFAULT;
3528 char const c1 = params.paperpackage;
3529 if (c1 == BufferParams::PACKAGE_NONE) {
3530 char const c2 = params.papersize2;
3531 if (c2 == BufferParams::VM_PAPER_USLETTER)
3532 params.papersize = BufferParams::PAPER_USLETTER;
3533 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3534 params.papersize = BufferParams::PAPER_LEGALPAPER;
3535 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3536 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3537 else if (c2 == BufferParams::VM_PAPER_A3)
3538 params.papersize = BufferParams::PAPER_A3PAPER;
3539 else if (c2 == BufferParams::VM_PAPER_A4)
3540 params.papersize = BufferParams::PAPER_A4PAPER;
3541 else if (c2 == BufferParams::VM_PAPER_A5)
3542 params.papersize = BufferParams::PAPER_A5PAPER;
3543 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3544 (c2 == BufferParams::VM_PAPER_B5))
3545 params.papersize = BufferParams::PAPER_B5PAPER;
3546 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3547 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3548 params.papersize = BufferParams::PAPER_A4PAPER;
3552 // This function should be in Buffer because it's a buffer's property (ale)
3553 string const Buffer::getIncludeonlyList(char delim)
3556 for (inset_iterator it = inset_iterator_begin();
3557 it != inset_iterator_end(); ++it) {
3558 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3559 InsetInclude * insetinc =
3560 static_cast<InsetInclude *>(*it);
3561 if (insetinc->isIncludeOnly()) {
3564 lst += insetinc->getRelFileBaseName();
3568 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3573 vector<string> const Buffer::getLabelList()
3575 /// if this is a child document and the parent is already loaded
3576 /// Use the parent's list instead [ale990407]
3577 if (!params.parentname.empty()
3578 && bufferlist.exists(params.parentname)) {
3579 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3581 return tmp->getLabelList();
3584 vector<string> label_list;
3585 for (inset_iterator it = inset_iterator_begin();
3586 it != inset_iterator_end(); ++it) {
3587 vector<string> const l = (*it)->getLabelList();
3588 label_list.insert(label_list.end(), l.begin(), l.end());
3594 Buffer::Lists const Buffer::getLists() const
3597 Paragraph * par = paragraph;
3599 LyXTextClassList::size_type cap;
3600 boost::tie(found, cap) = textclasslist
3601 .NumberOfLayout(params.textclass, "Caption");
3604 char const labeltype =
3605 textclasslist.Style(params.textclass,
3606 par->getLayout()).labeltype;
3608 if (labeltype >= LABEL_COUNTER_CHAPTER
3609 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3610 // insert this into the table of contents
3611 SingleList & item = l["TOC"];
3614 textclasslist.TextClass(params.textclass).maxcounter());
3615 item.push_back(TocItem(par, depth, par->asString(this, true)));
3617 // For each paragrph, traverse its insets and look for
3621 Paragraph::inset_iterator it =
3622 par->inset_iterator_begin();
3623 Paragraph::inset_iterator end =
3624 par->inset_iterator_end();
3626 for (; it != end; ++it) {
3627 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3629 static_cast<InsetFloat*>(*it);
3631 string const type = il->type();
3633 // Now find the caption in the float...
3634 // We now tranverse the paragraphs of
3636 Paragraph * tmp = il->inset.paragraph();
3638 if (tmp->layout == cap) {
3639 SingleList & item = l[type];
3641 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3642 item.push_back(TocItem(tmp, 0 , str));
3649 lyxerr << "caption not found" << endl;
3658 // This is also a buffer property (ale)
3659 vector<pair<string, string> > const Buffer::getBibkeyList()
3661 /// if this is a child document and the parent is already loaded
3662 /// Use the parent's list instead [ale990412]
3663 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3664 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3666 return tmp->getBibkeyList();
3669 vector<pair<string, string> > keys;
3670 Paragraph * par = paragraph;
3673 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3674 par->asString(this, false)));
3678 // Might be either using bibtex or a child has bibliography
3680 for (inset_iterator it = inset_iterator_begin();
3681 it != inset_iterator_end(); ++it) {
3682 // Search for Bibtex or Include inset
3683 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3684 vector<pair<string,string> > tmp =
3685 static_cast<InsetBibtex*>(*it)->getKeys(this);
3686 keys.insert(keys.end(), tmp.begin(), tmp.end());
3687 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3688 vector<pair<string,string> > const tmp =
3689 static_cast<InsetInclude*>(*it)->getKeys();
3690 keys.insert(keys.end(), tmp.begin(), tmp.end());
3699 bool Buffer::isDepClean(string const & name) const
3701 DEPCLEAN * item = dep_clean;
3702 while (item && item->master != name)
3704 if (!item) return true;
3709 void Buffer::markDepClean(string const & name)
3712 dep_clean = new DEPCLEAN;
3713 dep_clean->clean = true;
3714 dep_clean->master = name;
3715 dep_clean->next = 0;
3717 DEPCLEAN * item = dep_clean;
3718 while (item && item->master != name)
3723 item = new DEPCLEAN;
3725 item->master = name;
3732 bool Buffer::dispatch(string const & command)
3734 // Split command string into command and argument
3736 string line = frontStrip(command);
3737 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3739 return dispatch(lyxaction.LookupFunc(cmd), arg);
3743 bool Buffer::dispatch(int action, string const & argument)
3745 bool dispatched = true;
3748 Exporter::Export(this, argument, false);
3758 void Buffer::resizeInsets(BufferView * bv)
3760 /// then remove all LyXText in text-insets
3761 Paragraph * par = paragraph;
3762 for (; par; par = par->next()) {
3763 par->resizeInsetsLyXText(bv);
3768 void Buffer::redraw()
3775 void Buffer::changeLanguage(Language const * from, Language const * to)
3778 Paragraph * par = paragraph;
3780 par->changeLanguage(params, from, to);
3786 bool Buffer::isMultiLingual()
3788 Paragraph * par = paragraph;
3790 if (par->isMultiLingual(params))
3798 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3799 Paragraph::size_type pos)
3802 it = par->InsetIterator(pos);
3803 if (it == par->inset_iterator_end()) {
3810 void Buffer::inset_iterator::setParagraph()
3813 it = par->inset_iterator_begin();
3814 if (it != par->inset_iterator_end())
3819 // We maintain an invariant that whenever par = 0 then it = 0
3823 Inset * Buffer::getInsetFromID(int id_arg) const
3825 for (inset_iterator it = inset_const_iterator_begin();
3826 it != inset_const_iterator_end(); ++it)
3828 if ((*it)->id() == id_arg)
3830 Inset * in = (*it)->getInsetFromID(id_arg);
3838 Paragraph * Buffer::getParFromID(int id) const
3840 if (id < 0) return 0;
3841 Paragraph * par = paragraph;
3843 if (par->id() == id) {
3846 Paragraph * tmp = par->getParFromID(id);