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/insetinfo.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/insetlist.h"
78 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
82 #include "support/filetools.h"
83 #include "support/path.h"
84 #include "support/os.h"
89 #include "LaTeXFeatures.h"
90 #include "support/syscall.h"
91 #include "support/lyxlib.h"
92 #include "support/FileInfo.h"
93 #include "support/lyxmanip.h"
97 #include "lyx_gui_misc.h" // WarnReadonly()
98 #include "frontends/Dialogs.h"
100 #include "exporter.h"
101 #include "Lsstream.h"
102 #include "converter.h"
103 #include "BufferView.h"
104 #include "ParagraphParameters.h"
114 using std::make_pair;
122 // all these externs should eventually be removed.
123 extern BufferList bufferlist;
125 extern LyXAction lyxaction;
129 const int LYX_FORMAT = 220;
133 extern int tex_code_break_column;
136 Buffer::Buffer(string const & file, bool ronly)
138 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
140 filepath = OnlyPath(file);
149 if (read_only || (lyxrc.use_tempdir)) {
150 tmppath = CreateBufferTmpDir();
151 } else tmppath.erase();
157 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
158 // here the buffer should take care that it is
159 // saved properly, before it goes into the void.
161 // make sure that views using this buffer
166 if (!tmppath.empty()) {
167 DestroyBufferTmpDir(tmppath);
170 Paragraph * par = paragraph;
173 tmppar = par->next();
181 string const Buffer::getLatexName(bool no_path) const
183 string name = ChangeExtension(MakeLatexName(filename), ".tex");
185 return OnlyFilename(name);
191 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
193 string const filename = getLatexName(false);
195 if (filename.empty())
196 return make_pair(Buffer::latexlog, string());
198 string path = OnlyPath(filename);
200 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
203 string const fname = AddName(path,
204 OnlyFilename(ChangeExtension(filename,
207 AddName(path, OnlyFilename(
208 ChangeExtension(filename,
209 formats.Extension("literate") + ".out")));
211 // If no Latex log or Build log is newer, show Build log
213 FileInfo const f_fi(fname);
214 FileInfo const b_fi(bname);
217 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
218 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
219 return make_pair(Buffer::buildlog, bname);
221 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
222 return make_pair(Buffer::latexlog, fname);
226 void Buffer::setReadonly(bool flag)
228 if (read_only != flag) {
231 users->owner()->getDialogs()->updateBufferDependent(false);
234 WarnReadonly(filename);
239 bool Buffer::saveParamsAsDefaults() // const
241 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
243 Buffer defaults = Buffer(fname);
245 // Use the current buffer's parameters as default
246 defaults.params = params;
248 // add an empty paragraph. Is this enough?
249 defaults.paragraph = new Paragraph;
251 return defaults.writeFile(defaults.filename, false);
255 /// Update window titles of all users
256 // Should work on a list
257 void Buffer::updateTitles() const
259 if (users) users->owner()->updateWindowTitle();
263 /// Reset autosave timer of all users
264 // Should work on a list
265 void Buffer::resetAutosaveTimers() const
267 if (users) users->owner()->resetAutosaveTimer();
271 void Buffer::setFileName(string const & newfile)
273 filename = MakeAbsPath(newfile);
274 filepath = OnlyPath(filename);
275 setReadonly(IsFileWriteable(filename) == 0);
280 // We'll remove this later. (Lgb)
283 string last_inset_read;
287 ErtComp() : active(false), in_tabular(false) {
294 std::stack<ErtComp> ert_stack;
302 // candidate for move to BufferView
303 // (at least some parts in the beginning of the func)
306 // changed to be public and have one parameter
307 // if par = 0 normal behavior
308 // else insert behavior
309 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
310 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
313 ert_comp.contents.erase();
314 ert_comp.active = false;
315 ert_comp.in_tabular = false;
319 Paragraph::depth_type depth = 0;
320 bool the_end_read = false;
322 Paragraph * first_par = 0;
323 LyXFont font(LyXFont::ALL_INHERIT, params.language);
324 if (file_format < 216 && params.language->lang() == "hebrew")
325 font.setLanguage(default_language);
330 // We are inserting into an existing document
331 users->text->breakParagraph(users);
332 first_par = users->text->firstParagraph();
335 // We don't want to adopt the parameters from the
336 // document we insert, so we skip until the text begins:
339 string const pretoken = lex.GetString();
340 if (pretoken == "\\layout") {
341 lex.pushToken(pretoken);
349 string const token = lex.GetString();
351 if (token.empty()) continue;
353 lyxerr[Debug::PARSER] << "Handling token: `"
354 << token << "'" << endl;
357 parseSingleLyXformat2Token(lex, par, first_par,
365 paragraph = first_par;
371 void Buffer::insertErtContents(Paragraph * par, int & pos,
372 LyXFont const & font, bool set_inactive)
374 if (!ert_comp.contents.empty()) {
375 lyxerr[Debug::INSETS] << "ERT contents:\n"
376 << ert_comp.contents << endl;
377 Inset * inset = new InsetERT(ert_comp.contents);
378 par->insertInset(pos++, inset, font);
379 ert_comp.contents.erase();
382 ert_comp.active = false;
388 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
389 Paragraph *& first_par,
390 string const & token, int & pos,
391 Paragraph::depth_type & depth,
395 bool the_end_read = false;
396 #ifndef NO_PEXTRA_REALLY
397 // This is super temporary but is needed to get the compability
398 // mode for minipages work correctly together with new tabulars.
399 static int call_depth;
401 bool checkminipage = false;
402 static Paragraph * minipar;
403 static Paragraph * parBeforeMinipage;
406 if (token[0] != '\\') {
408 if (ert_comp.active) {
409 ert_comp.contents += token;
412 for (string::const_iterator cit = token.begin();
413 cit != token.end(); ++cit) {
414 par->insertChar(pos, (*cit), font);
417 checkminipage = true;
421 } else if (token == "\\i") {
422 Inset * inset = new InsetLatexAccent;
423 inset->read(this, lex);
424 par->insertInset(pos, inset, font);
426 } else if (token == "\\layout") {
428 ert_comp.in_tabular = false;
430 insertErtContents(par, pos, font);
433 string const layoutname = lex.GetString();
434 pair<bool, LyXTextClass::LayoutList::size_type> pp
435 = textclasslist.NumberOfLayout(params.textclass,
439 if (compare_no_case(layoutname, "latex") == 0) {
440 ert_comp.active = true;
444 // The is the compability reading of layout caption.
445 // It can be removed in LyX version 1.3.0. (Lgb)
446 if (compare_no_case(layoutname, "caption") == 0) {
447 // We expect that the par we are now working on is
448 // really inside a InsetText inside a InsetFloat.
449 // We also know that captions can only be
450 // one paragraph. (Lgb)
452 // We should now read until the next "\layout"
454 // This is probably not good enough, what if the
455 // caption is the last par in the document (Lgb)
456 istream & ist = lex.getStream();
462 if (prefixIs(line, "\\layout")) {
466 if (prefixIs(line, "\\begin_inset"))
468 if (prefixIs(line, "\\end_inset")) {
479 // Now we should have the whole layout in ss
480 // we should now be able to give this to the
482 ss << "\\end_inset\n";
484 // This seems like a bug in stringstream.
485 // We really should be able to use ss
487 istringstream is(ss.str());
489 tmplex.setStream(is);
490 Inset * inset = new InsetCaption;
491 inset->Read(this, tmplex);
492 par->InsertInset(pos, inset, font);
499 par = new Paragraph(par);
503 par->layout = pp.second;
506 // use default layout "Standard" (0)
509 // Test whether the layout is obsolete.
510 LyXLayout const & layout =
511 textclasslist.Style(params.textclass,
513 if (!layout.obsoleted_by().empty())
514 par->layout = textclasslist
515 .NumberOfLayout(params.textclass,
516 layout.obsoleted_by())
518 par->params().depth(depth);
519 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
520 if (file_format < 216
521 && params.language->lang() == "hebrew")
522 font.setLanguage(default_language);
527 } else if (token == "\\begin_float") {
528 // This is the compability reader. It can be removed in
529 // LyX version 1.3.0. (Lgb)
531 string const tmptok = lex.GetString();
532 //lyxerr << "old float: " << tmptok << endl;
535 stringstream old_float;
537 if (tmptok == "footnote") {
538 inset = new InsetFoot;
539 } else if (tmptok == "margin") {
540 inset = new InsetMarginal;
541 } else if (tmptok == "fig") {
542 inset = new InsetFloat("figure");
543 old_float << "placement htbp\n"
545 } else if (tmptok == "tab") {
546 inset = new InsetFloat("table");
547 old_float << "placement htbp\n"
549 } else if (tmptok == "alg") {
550 inset = new InsetFloat("algorithm");
551 old_float << "placement htbp\n"
553 } else if (tmptok == "wide-fig") {
554 inset = new InsetFloat("figure");
555 //InsetFloat * tmp = new InsetFloat("figure");
558 old_float << "placement htbp\n"
560 } else if (tmptok == "wide-tab") {
561 inset = new InsetFloat("table");
562 //InsetFloat * tmp = new InsetFloat("table");
565 old_float << "placement htbp\n"
571 return false; // no end read yet
574 old_float << "collapsed true\n";
576 // Here we need to check for \end_deeper and handle that
577 // before we do the footnote parsing.
578 // This _is_ a hack! (Lgb)
581 string const tmp = lex.GetString();
582 if (tmp == "\\end_deeper") {
583 //lyxerr << "\\end_deeper caught!" << endl;
585 lex.printError("\\end_deeper: "
586 "depth is already null");
591 old_float << tmp << ' ';
596 old_float << lex.getLongString("\\end_float")
597 << "\n\\end_inset\n";
598 //lyxerr << "Float Body:\n" << old_float.str() << endl;
599 // That this does not work seems like a bug
600 // in stringstream. (Lgb)
601 istringstream istr(old_float.str());
603 nylex.setStream(istr);
604 inset->read(this, nylex);
605 par->insertInset(pos, inset, font);
607 } else if (token == "\\begin_deeper") {
609 } else if (token == "\\end_deeper") {
611 lex.printError("\\end_deeper: "
612 "depth is already null");
616 } else if (token == "\\begin_preamble") {
617 params.readPreamble(lex);
618 } else if (token == "\\textclass") {
620 pair<bool, LyXTextClassList::size_type> pp =
621 textclasslist.NumberOfClass(lex.GetString());
623 params.textclass = pp.second;
625 WriteAlert(string(_("Textclass error")),
626 string(_("The document uses an unknown textclass \"")) +
627 lex.GetString() + string("\"."),
628 string(_("LyX will not be able to produce output correctly.")));
629 params.textclass = 0;
631 if (!textclasslist.Load(params.textclass)) {
632 // if the textclass wasn't loaded properly
633 // we need to either substitute another
634 // or stop loading the file.
635 // I can substitute but I don't see how I can
636 // stop loading... ideas?? ARRae980418
637 WriteAlert(_("Textclass Loading Error!"),
638 string(_("Can't load textclass ")) +
639 textclasslist.NameOfClass(params.textclass),
640 _("-- substituting default"));
641 params.textclass = 0;
643 } else if (token == "\\options") {
645 params.options = lex.GetString();
646 } else if (token == "\\language") {
647 params.readLanguage(lex);
648 } else if (token == "\\fontencoding") {
650 } else if (token == "\\inputencoding") {
652 params.inputenc = lex.GetString();
653 } else if (token == "\\graphics") {
654 params.readGraphicsDriver(lex);
655 } else if (token == "\\fontscheme") {
657 params.fonts = lex.GetString();
658 } else if (token == "\\noindent") {
659 par->params().noindent(true);
660 } else if (token == "\\fill_top") {
661 par->params().spaceTop(VSpace(VSpace::VFILL));
662 } else if (token == "\\fill_bottom") {
663 par->params().spaceBottom(VSpace(VSpace::VFILL));
664 } else if (token == "\\line_top") {
665 par->params().lineTop(true);
666 } else if (token == "\\line_bottom") {
667 par->params().lineBottom(true);
668 } else if (token == "\\pagebreak_top") {
669 par->params().pagebreakTop(true);
670 } else if (token == "\\pagebreak_bottom") {
671 par->params().pagebreakBottom(true);
672 } else if (token == "\\start_of_appendix") {
673 par->params().startOfAppendix(true);
674 } else if (token == "\\paragraph_separation") {
675 int tmpret = lex.FindToken(string_paragraph_separation);
676 if (tmpret == -1) ++tmpret;
677 if (tmpret != LYX_LAYOUT_DEFAULT)
678 params.paragraph_separation =
679 static_cast<BufferParams::PARSEP>(tmpret);
680 } else if (token == "\\defskip") {
682 params.defskip = VSpace(lex.GetString());
683 } else if (token == "\\epsfig") { // obsolete
684 // Indeed it is obsolete, but we HAVE to be backwards
685 // compatible until 0.14, because otherwise all figures
686 // in existing documents are irretrivably lost. (Asger)
687 params.readGraphicsDriver(lex);
688 } else if (token == "\\quotes_language") {
689 int tmpret = lex.FindToken(string_quotes_language);
690 if (tmpret == -1) ++tmpret;
691 if (tmpret != LYX_LAYOUT_DEFAULT) {
692 InsetQuotes::quote_language tmpl =
693 InsetQuotes::EnglishQ;
696 tmpl = InsetQuotes::EnglishQ;
699 tmpl = InsetQuotes::SwedishQ;
702 tmpl = InsetQuotes::GermanQ;
705 tmpl = InsetQuotes::PolishQ;
708 tmpl = InsetQuotes::FrenchQ;
711 tmpl = InsetQuotes::DanishQ;
714 params.quotes_language = tmpl;
716 } else if (token == "\\quotes_times") {
718 switch (lex.GetInteger()) {
720 params.quotes_times = InsetQuotes::SingleQ;
723 params.quotes_times = InsetQuotes::DoubleQ;
726 } else if (token == "\\papersize") {
727 int tmpret = lex.FindToken(string_papersize);
731 params.papersize2 = tmpret;
732 } else if (token == "\\paperpackage") {
733 int tmpret = lex.FindToken(string_paperpackages);
736 params.paperpackage = BufferParams::PACKAGE_NONE;
738 params.paperpackage = tmpret;
739 } else if (token == "\\use_geometry") {
741 params.use_geometry = lex.GetInteger();
742 } else if (token == "\\use_amsmath") {
744 params.use_amsmath = lex.GetInteger();
745 } else if (token == "\\paperorientation") {
746 int tmpret = lex.FindToken(string_orientation);
747 if (tmpret == -1) ++tmpret;
748 if (tmpret != LYX_LAYOUT_DEFAULT)
749 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
750 } else if (token == "\\paperwidth") {
752 params.paperwidth = lex.GetString();
753 } else if (token == "\\paperheight") {
755 params.paperheight = lex.GetString();
756 } else if (token == "\\leftmargin") {
758 params.leftmargin = lex.GetString();
759 } else if (token == "\\topmargin") {
761 params.topmargin = lex.GetString();
762 } else if (token == "\\rightmargin") {
764 params.rightmargin = lex.GetString();
765 } else if (token == "\\bottommargin") {
767 params.bottommargin = lex.GetString();
768 } else if (token == "\\headheight") {
770 params.headheight = lex.GetString();
771 } else if (token == "\\headsep") {
773 params.headsep = lex.GetString();
774 } else if (token == "\\footskip") {
776 params.footskip = lex.GetString();
777 } else if (token == "\\paperfontsize") {
779 params.fontsize = strip(lex.GetString());
780 } else if (token == "\\papercolumns") {
782 params.columns = lex.GetInteger();
783 } else if (token == "\\papersides") {
785 switch (lex.GetInteger()) {
787 case 1: params.sides = LyXTextClass::OneSide; break;
788 case 2: params.sides = LyXTextClass::TwoSides; break;
790 } else if (token == "\\paperpagestyle") {
792 params.pagestyle = strip(lex.GetString());
793 } else if (token == "\\bullet") {
795 int const index = lex.GetInteger();
797 int temp_int = lex.GetInteger();
798 params.user_defined_bullets[index].setFont(temp_int);
799 params.temp_bullets[index].setFont(temp_int);
801 temp_int = lex.GetInteger();
802 params.user_defined_bullets[index].setCharacter(temp_int);
803 params.temp_bullets[index].setCharacter(temp_int);
805 temp_int = lex.GetInteger();
806 params.user_defined_bullets[index].setSize(temp_int);
807 params.temp_bullets[index].setSize(temp_int);
809 string const temp_str = lex.GetString();
810 if (temp_str != "\\end_bullet") {
811 // this element isn't really necessary for
812 // parsing but is easier for humans
813 // to understand bullets. Put it back and
814 // set a debug message?
815 lex.printError("\\end_bullet expected, got" + temp_str);
816 //how can I put it back?
818 } else if (token == "\\bulletLaTeX") {
820 int const index = lex.GetInteger();
822 string temp_str = lex.GetString();
824 while (temp_str != "\\end_bullet") {
825 // this loop structure is needed when user
826 // enters an empty string since the first
827 // thing returned will be the \\end_bullet
829 // if the LaTeX entry has spaces. Each element
830 // therefore needs to be read in turn
833 temp_str = lex.GetString();
835 params.user_defined_bullets[index].setText(sum_str);
836 params.temp_bullets[index].setText(sum_str);
837 } else if (token == "\\secnumdepth") {
839 params.secnumdepth = lex.GetInteger();
840 } else if (token == "\\tocdepth") {
842 params.tocdepth = lex.GetInteger();
843 } else if (token == "\\spacing") {
845 string const tmp = strip(lex.GetString());
846 Spacing::Space tmp_space = Spacing::Default;
848 if (tmp == "single") {
849 tmp_space = Spacing::Single;
850 } else if (tmp == "onehalf") {
851 tmp_space = Spacing::Onehalf;
852 } else if (tmp == "double") {
853 tmp_space = Spacing::Double;
854 } else if (tmp == "other") {
856 tmp_space = Spacing::Other;
857 tmp_val = lex.GetFloat();
859 lex.printError("Unknown spacing token: '$$Token'");
861 // Small hack so that files written with klyx will be
864 par->params().spacing(Spacing(tmp_space, tmp_val));
866 params.spacing.set(tmp_space, tmp_val);
868 } else if (token == "\\paragraph_spacing") {
870 string const tmp = strip(lex.GetString());
871 if (tmp == "single") {
872 par->params().spacing(Spacing(Spacing::Single));
873 } else if (tmp == "onehalf") {
874 par->params().spacing(Spacing(Spacing::Onehalf));
875 } else if (tmp == "double") {
876 par->params().spacing(Spacing(Spacing::Double));
877 } else if (tmp == "other") {
879 par->params().spacing(Spacing(Spacing::Other,
882 lex.printError("Unknown spacing token: '$$Token'");
884 } else if (token == "\\float_placement") {
886 params.float_placement = lex.GetString();
887 } else if (token == "\\family") {
889 font.setLyXFamily(lex.GetString());
890 } else if (token == "\\series") {
892 font.setLyXSeries(lex.GetString());
893 } else if (token == "\\shape") {
895 font.setLyXShape(lex.GetString());
896 } else if (token == "\\size") {
898 font.setLyXSize(lex.GetString());
901 #warning compatability hack needed
903 } else if (token == "\\latex") {
905 string const tok = lex.GetString();
906 // This is dirty, but gone with LyX3. (Asger)
907 if (tok == "no_latex")
908 font.setLatex(LyXFont::OFF);
909 else if (tok == "latex")
910 font.setLatex(LyXFont::ON);
911 else if (tok == "default")
912 font.setLatex(LyXFont::INHERIT);
914 lex.printError("Unknown LaTeX font flag "
917 } else if (token == "\\latex") {
919 string const tok = lex.GetString();
920 if (tok == "no_latex") {
922 insertErtContents(par, pos, font);
923 } else if (tok == "latex") {
924 ert_comp.active = true;
925 } else if (tok == "default") {
927 insertErtContents(par, pos, font);
929 lex.printError("Unknown LaTeX font flag "
933 } else if (token == "\\lang") {
935 string const tok = lex.GetString();
936 Language const * lang = languages.getLanguage(tok);
938 font.setLanguage(lang);
940 font.setLanguage(params.language);
941 lex.printError("Unknown language `$$Token'");
943 } else if (token == "\\numeric") {
945 font.setNumber(font.setLyXMisc(lex.GetString()));
946 } else if (token == "\\emph") {
948 font.setEmph(font.setLyXMisc(lex.GetString()));
949 } else if (token == "\\bar") {
951 string const tok = lex.GetString();
952 // This is dirty, but gone with LyX3. (Asger)
954 font.setUnderbar(LyXFont::ON);
955 else if (tok == "no")
956 font.setUnderbar(LyXFont::OFF);
957 else if (tok == "default")
958 font.setUnderbar(LyXFont::INHERIT);
960 lex.printError("Unknown bar font flag "
962 } else if (token == "\\noun") {
964 font.setNoun(font.setLyXMisc(lex.GetString()));
965 } else if (token == "\\color") {
967 font.setLyXColor(lex.GetString());
968 } else if (token == "\\align") {
969 int tmpret = lex.FindToken(string_align);
970 if (tmpret == -1) ++tmpret;
971 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
972 int const tmpret2 = int(pow(2.0, tmpret));
973 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
974 par->params().align(LyXAlignment(tmpret2));
976 } else if (token == "\\added_space_top") {
978 par->params().spaceTop(VSpace(lex.GetString()));
979 } else if (token == "\\added_space_bottom") {
981 par->params().spaceBottom(VSpace(lex.GetString()));
982 #ifndef NO_PEXTRA_REALLY
983 } else if (token == "\\pextra_type") {
985 par->params().pextraType(lex.GetInteger());
986 } else if (token == "\\pextra_width") {
988 par->params().pextraWidth(lex.GetString());
989 } else if (token == "\\pextra_widthp") {
991 par->params().pextraWidthp(lex.GetString());
992 } else if (token == "\\pextra_alignment") {
994 par->params().pextraAlignment(lex.GetInteger());
995 } else if (token == "\\pextra_hfill") {
997 par->params().pextraHfill(lex.GetInteger());
998 } else if (token == "\\pextra_start_minipage") {
1000 par->params().pextraStartMinipage(lex.GetInteger());
1002 } else if (token == "\\labelwidthstring") {
1004 par->params().labelWidthString(lex.GetString());
1005 // do not delete this token, it is still needed!
1006 } else if (token == "\\end_inset") {
1007 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1008 << "Last inset read was: " << last_inset_read
1010 // Simply ignore this. The insets do not have
1012 // But insets should read it, it is a part of
1013 // the inset isn't it? Lgb.
1014 } else if (token == "\\begin_inset") {
1016 insertErtContents(par, pos, font, false);
1017 ert_stack.push(ert_comp);
1018 ert_comp = ErtComp();
1020 readInset(lex, par, pos, font);
1022 ert_comp = ert_stack.top();
1025 } else if (token == "\\SpecialChar") {
1026 LyXLayout const & layout =
1027 textclasslist.Style(params.textclass,
1030 // Insets don't make sense in a free-spacing context! ---Kayvan
1031 if (layout.free_spacing) {
1034 string next_token = lex.GetString();
1035 if (next_token == "\\-") {
1036 par->insertChar(pos, '-', font);
1037 } else if (next_token == "\\protected_separator"
1038 || next_token == "~") {
1039 par->insertChar(pos, ' ', font);
1041 lex.printError("Token `$$Token' "
1043 "paragraph layout!");
1048 Inset * inset = new InsetSpecialChar;
1049 inset->read(this, lex);
1050 par->insertInset(pos, inset, font);
1053 } else if (token == "\\newline") {
1056 if (!ert_comp.in_tabular && ert_comp.active) {
1057 ert_comp.contents += char(Paragraph::META_NEWLINE);
1059 // Since we cannot know it this is only a regular
1060 // newline or a tabular cell delimter we have to
1061 // handle the ERT here.
1062 insertErtContents(par, pos, font, false);
1064 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1068 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1071 } else if (token == "\\LyXTable") {
1073 ert_comp.in_tabular = true;
1075 Inset * inset = new InsetTabular(*this);
1076 inset->read(this, lex);
1077 par->insertInset(pos, inset, font);
1079 // because of OLD_TABULAR_READ where tabulars have been
1081 checkminipage = true;
1082 } else if (token == "\\hfill") {
1083 par->insertChar(pos, Paragraph::META_HFILL, font);
1085 } else if (token == "\\protected_separator") { // obsolete
1086 // This is a backward compability thingie. (Lgb)
1087 // Remove it later some time...introduced with fileformat
1089 LyXLayout const & layout =
1090 textclasslist.Style(params.textclass,
1093 if (layout.free_spacing) {
1094 par->insertChar(pos, ' ', font);
1096 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1097 par->insertInset(pos, inset, font);
1100 } else if (token == "\\bibitem") { // ale970302
1102 InsetCommandParams p("bibitem", "dummy");
1103 par->bibkey = new InsetBibKey(p);
1105 par->bibkey->read(this, lex);
1106 } else if (token == "\\backslash") {
1108 if (ert_comp.active) {
1109 ert_comp.contents += "\\";
1112 par->insertChar(pos, '\\', font);
1117 } else if (token == "\\the_end") {
1119 // If we still have some ert active here we have to insert
1120 // it so we don't loose it. (Lgb)
1121 insertErtContents(par, pos, font);
1123 the_end_read = true;
1124 minipar = parBeforeMinipage = 0;
1127 if (ert_comp.active) {
1128 ert_comp.contents += token;
1131 // This should be insurance for the future: (Asger)
1132 lex.printError("Unknown token `$$Token'. "
1133 "Inserting as text.");
1134 string::const_iterator cit = token.begin();
1135 string::const_iterator end = token.end();
1136 for (; cit != end; ++cit) {
1137 par->insertChar(pos, (*cit), font);
1144 #ifndef NO_PEXTRA_REALLY
1145 // now check if we have a minipage paragraph as at this
1146 // point we already read all the necessary data!
1147 // this cannot be done in layout because there we did
1148 // not read yet the paragraph PEXTRA-params (Jug)
1150 // BEGIN pextra_minipage compability
1151 // This should be removed in 1.3.x (Lgb)
1153 // This compability code is not perfect. In a couple
1154 // of rand cases it fails. When the minipage par is
1155 // the first par in the document, and when there are
1156 // none or only one regular paragraphs after the
1157 // minipage. Currently I am not investing any effort
1158 // in fixing those cases.
1160 //lyxerr << "Call depth: " << call_depth << endl;
1161 if (checkminipage && (call_depth == 1)) {
1162 checkminipage = false;
1163 if (minipar && (minipar != par) &&
1164 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1166 lyxerr << "minipages in a row" << endl;
1167 if (par->params().pextraStartMinipage()) {
1168 lyxerr << "start new minipage" << endl;
1169 // minipages in a row
1170 par->previous()->next(0);
1173 Paragraph * tmp = minipar;
1175 tmp->params().pextraType(0);
1176 tmp->params().pextraWidth(string());
1177 tmp->params().pextraWidthp(string());
1178 tmp->params().pextraAlignment(0);
1179 tmp->params().pextraHfill(false);
1180 tmp->params().pextraStartMinipage(false);
1183 // create a new paragraph to insert the
1184 // minipages in the following case
1185 if (par->params().pextraStartMinipage() &&
1186 !par->params().pextraHfill())
1188 Paragraph * p = new Paragraph;
1190 p->previous(parBeforeMinipage);
1191 parBeforeMinipage->next(p);
1193 p->params().depth(parBeforeMinipage->params().depth());
1194 parBeforeMinipage = p;
1196 InsetMinipage * mini = new InsetMinipage;
1197 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1198 mini->width(par->params().pextraWidth());
1199 if (!par->params().pextraWidthp().empty()) {
1200 lyxerr << "WP:" << mini->width() << endl;
1201 mini->width(tostr(par->params().pextraWidthp())+"%");
1203 mini->inset.paragraph(par);
1204 // Insert the minipage last in the
1205 // previous paragraph.
1206 if (par->params().pextraHfill()) {
1207 parBeforeMinipage->insertChar
1208 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1210 parBeforeMinipage->insertInset
1211 (parBeforeMinipage->size(), mini);
1215 lyxerr << "new minipage par" << endl;
1216 //nothing to do just continue reading
1219 } else if (minipar && (minipar != par)) {
1220 lyxerr << "last minipage par read" << endl;
1221 // The last paragraph read was not part of a
1222 // minipage but the par linked list is...
1223 // So we need to remove the last par from the
1225 if (par->previous())
1226 par->previous()->next(0);
1227 par->previous(parBeforeMinipage);
1228 parBeforeMinipage->next(par);
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 depth = parBeforeMinipage->params().depth();
1240 minipar = parBeforeMinipage = 0;
1241 } else if (!minipar &&
1242 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1244 // par is the first paragraph in a minipage
1245 lyxerr << "begin minipage" << endl;
1246 // To minimize problems for
1247 // the users we will insert
1248 // the first minipage in
1249 // a sequence of minipages
1250 // in its own paragraph.
1251 Paragraph * p = new Paragraph;
1253 p->previous(par->previous());
1255 p->params().depth(depth);
1256 par->params().depth(0);
1258 if (par->previous())
1259 par->previous()->next(p);
1261 parBeforeMinipage = p;
1263 if (!first_par || (first_par == par))
1266 InsetMinipage * mini = new InsetMinipage;
1267 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1268 mini->width(minipar->params().pextraWidth());
1269 if (!par->params().pextraWidthp().empty()) {
1270 lyxerr << "WP:" << mini->width() << endl;
1271 mini->width(tostr(par->params().pextraWidthp())+"%");
1273 mini->inset.paragraph(minipar);
1275 // Insert the minipage last in the
1276 // previous paragraph.
1277 if (minipar->params().pextraHfill()) {
1278 parBeforeMinipage->insertChar
1279 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1281 parBeforeMinipage->insertInset
1282 (parBeforeMinipage->size(), mini);
1285 // End of pextra_minipage compability
1288 return the_end_read;
1292 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1293 int & pos, LyXFont & font)
1295 // consistency check
1296 if (lex.GetString() != "\\begin_inset") {
1297 lyxerr << "Buffer::readInset: Consistency check failed."
1304 string const tmptok = lex.GetString();
1305 last_inset_read = tmptok;
1307 // test the different insets
1308 if (tmptok == "LatexCommand") {
1309 InsetCommandParams inscmd;
1312 string const cmdName = inscmd.getCmdName();
1314 if (cmdName == "cite") {
1315 inset = new InsetCitation(inscmd);
1316 } else if (cmdName == "bibitem") {
1317 lex.printError("Wrong place for bibitem");
1318 inset = new InsetBibKey(inscmd);
1319 } else if (cmdName == "BibTeX") {
1320 inset = new InsetBibtex(inscmd);
1321 } else if (cmdName == "index") {
1322 inset = new InsetIndex(inscmd);
1323 } else if (cmdName == "include") {
1324 inset = new InsetInclude(inscmd, *this);
1325 } else if (cmdName == "label") {
1326 inset = new InsetLabel(inscmd);
1327 } else if (cmdName == "url"
1328 || cmdName == "htmlurl") {
1329 inset = new InsetUrl(inscmd);
1330 } else if (cmdName == "ref"
1331 || cmdName == "pageref"
1332 || cmdName == "vref"
1333 || cmdName == "vpageref"
1334 || cmdName == "prettyref") {
1335 if (!inscmd.getOptions().empty()
1336 || !inscmd.getContents().empty()) {
1337 inset = new InsetRef(inscmd, *this);
1339 } else if (cmdName == "tableofcontents") {
1340 inset = new InsetTOC(inscmd);
1341 } else if (cmdName == "listofalgorithms") {
1342 inset = new InsetFloatList("algorithm");
1343 } else if (cmdName == "listoffigures") {
1344 inset = new InsetFloatList("figure");
1345 } else if (cmdName == "listoftables") {
1346 inset = new InsetFloatList("table");
1347 } else if (cmdName == "printindex") {
1348 inset = new InsetPrintIndex(inscmd);
1349 } else if (cmdName == "lyxparent") {
1350 inset = new InsetParent(inscmd, *this);
1353 if (tmptok == "Quotes") {
1354 inset = new InsetQuotes;
1355 } else if (tmptok == "External") {
1356 inset = new InsetExternal;
1357 } else if (tmptok == "FormulaMacro") {
1358 inset = new InsetFormulaMacro;
1359 } else if (tmptok == "Formula") {
1360 inset = new InsetFormula;
1361 } else if (tmptok == "Figure") {
1362 inset = new InsetFig(100, 100, *this);
1363 } else if (tmptok == "Info") {
1364 inset = new InsetInfo;
1365 } else if (tmptok == "Include") {
1366 InsetCommandParams p( "Include" );
1367 inset = new InsetInclude(p, *this);
1368 } else if (tmptok == "ERT") {
1369 inset = new InsetERT;
1370 } else if (tmptok == "Tabular") {
1371 inset = new InsetTabular(*this);
1372 } else if (tmptok == "Text") {
1373 inset = new InsetText;
1374 } else if (tmptok == "Foot") {
1375 inset = new InsetFoot;
1376 } else if (tmptok == "Marginal") {
1377 inset = new InsetMarginal;
1378 } else if (tmptok == "Minipage") {
1379 inset = new InsetMinipage;
1380 } else if (tmptok == "Float") {
1382 string tmptok = lex.GetString();
1383 inset = new InsetFloat(tmptok);
1384 } else if (tmptok == "List") {
1385 inset = new InsetList;
1386 } else if (tmptok == "Theorem") {
1387 inset = new InsetList;
1388 } else if (tmptok == "Caption") {
1389 inset = new InsetCaption;
1390 } else if (tmptok == "GRAPHICS") {
1391 inset = new InsetGraphics;
1392 } else if (tmptok == "FloatList") {
1393 inset = new InsetFloatList;
1396 if (inset) inset->read(this, lex);
1400 par->insertInset(pos, inset, font);
1406 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1410 string const token(lex.GetString());
1411 if (token == "\\lyxformat") { // the first token _must_ be...
1413 string tmp_format = lex.GetString();
1414 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1415 // if present remove ".," from string.
1416 string::size_type dot = tmp_format.find_first_of(".,");
1417 //lyxerr << " dot found at " << dot << endl;
1418 if (dot != string::npos)
1419 tmp_format.erase(dot, 1);
1420 file_format = strToInt(tmp_format);
1421 if (file_format == LYX_FORMAT) {
1423 } else if (file_format > LYX_FORMAT) {
1425 WriteAlert(_("Warning!"),
1426 _("LyX file format is newer that what"),
1427 _("is supported in this LyX version. Expect some problems."));
1429 } else if (file_format < LYX_FORMAT) {
1431 if (file_format < 200) {
1432 WriteAlert(_("ERROR!"),
1433 _("Old LyX file format found. "
1434 "Use LyX 0.10.x to read this!"));
1438 bool the_end = readLyXformat2(lex, par);
1440 // the_end was added in 213
1441 if (file_format < 213)
1445 WriteAlert(_("Warning!"),
1446 _("Reading of document is not complete"),
1447 _("Maybe the document is truncated"));
1449 } else { // "\\lyxformat" not found
1450 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1453 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1458 // Should probably be moved to somewhere else: BufferView? LyXView?
1459 bool Buffer::save() const
1461 // We don't need autosaves in the immediate future. (Asger)
1462 resetAutosaveTimers();
1466 if (lyxrc.make_backup) {
1467 s = fileName() + '~';
1468 if (!lyxrc.backupdir_path.empty())
1469 s = AddName(lyxrc.backupdir_path,
1470 subst(os::slashify_path(s),'/','!'));
1472 // Rename is the wrong way of making a backup,
1473 // this is the correct way.
1474 /* truss cp fil fil2:
1475 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1476 stat("LyXVC.lyx", 0xEFFFF688) = 0
1477 open("LyXVC.lyx", O_RDONLY) = 3
1478 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1479 fstat(4, 0xEFFFF508) = 0
1480 fstat(3, 0xEFFFF508) = 0
1481 read(3, " # T h i s f i l e w".., 8192) = 5579
1482 write(4, " # T h i s f i l e w".., 5579) = 5579
1483 read(3, 0xEFFFD4A0, 8192) = 0
1486 chmod("LyXVC3.lyx", 0100644) = 0
1487 lseek(0, 0, SEEK_CUR) = 46440
1491 // Should probably have some more error checking here.
1492 // Should be cleaned up in 0.13, at least a bit.
1493 // Doing it this way, also makes the inodes stay the same.
1494 // This is still not a very good solution, in particular we
1495 // might loose the owner of the backup.
1496 FileInfo finfo(fileName());
1497 if (finfo.exist()) {
1498 mode_t fmode = finfo.getMode();
1499 struct utimbuf times = {
1500 finfo.getAccessTime(),
1501 finfo.getModificationTime() };
1503 ifstream ifs(fileName().c_str());
1504 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1509 ::chmod(s.c_str(), fmode);
1511 if (::utime(s.c_str(), ×)) {
1512 lyxerr << "utime error." << endl;
1515 lyxerr << "LyX was not able to make "
1516 "backup copy. Beware." << endl;
1521 if (writeFile(fileName(), false)) {
1523 removeAutosaveFile(fileName());
1525 // Saving failed, so backup is not backup
1526 if (lyxrc.make_backup) {
1527 lyx::rename(s, fileName());
1535 // Returns false if unsuccesful
1536 bool Buffer::writeFile(string const & fname, bool flag) const
1538 // if flag is false writeFile will not create any GUI
1539 // warnings, only cerr.
1540 // Needed for autosave in background or panic save (Matthias 120496)
1542 if (read_only && (fname == filename)) {
1543 // Here we should come with a question if we should
1544 // perform the write anyway.
1546 lyxerr << _("Error! Document is read-only: ")
1549 WriteAlert(_("Error! Document is read-only: "),
1554 FileInfo finfo(fname);
1555 if (finfo.exist() && !finfo.writable()) {
1556 // Here we should come with a question if we should
1557 // try to do the save anyway. (i.e. do a chmod first)
1559 lyxerr << _("Error! Cannot write file: ")
1562 WriteFSAlert(_("Error! Cannot write file: "),
1567 ofstream ofs(fname.c_str());
1570 lyxerr << _("Error! Cannot open file: ")
1573 WriteFSAlert(_("Error! Cannot open file: "),
1579 // Use the standard "C" locale for file output.
1580 ofs.imbue(std::locale::classic());
1583 // The top of the file should not be written by params.
1585 // write out a comment in the top of the file
1586 ofs << '#' << LYX_DOCVERSION
1587 << " created this file. For more info see http://www.lyx.org/\n"
1588 << "\\lyxformat " << LYX_FORMAT << "\n";
1590 // now write out the buffer paramters.
1591 params.writeFile(ofs);
1593 Paragraph::depth_type depth = 0;
1595 // this will write out all the paragraphs
1596 // using recursive descent.
1597 paragraph->writeFile(this, ofs, params, depth);
1599 // Write marker that shows file is complete
1600 ofs << "\n\\the_end" << endl;
1604 // how to check if close went ok?
1605 // Following is an attempt... (BE 20001011)
1607 // good() returns false if any error occured, including some
1608 // formatting error.
1609 // bad() returns true if something bad happened in the buffer,
1610 // which should include file system full errors.
1617 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1619 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1629 string const Buffer::asciiParagraph(Paragraph const * par,
1630 unsigned int linelen) const
1632 ostringstream buffer;
1633 Paragraph::depth_type depth = 0;
1635 Paragraph::depth_type ltype_depth = 0;
1636 unsigned int currlinelen = 0;
1637 bool ref_printed = false;
1641 if (!par->previous()) {
1642 // begins or ends a deeper area ?
1643 if (depth != par->params().depth()) {
1644 if (par->params().depth() > depth) {
1645 while (par->params().depth() > depth) {
1649 while (par->params().depth() < depth) {
1655 // First write the layout
1656 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1657 if (tmp == "Itemize") {
1659 ltype_depth = depth + 1;
1660 } else if (tmp == "Enumerate") {
1662 ltype_depth = depth + 1;
1663 } else if (contains(tmp, "ection")) {
1665 ltype_depth = depth + 1;
1666 } else if (contains(tmp, "aragraph")) {
1668 ltype_depth = depth + 1;
1669 } else if (tmp == "Description") {
1671 ltype_depth = depth + 1;
1672 } else if (tmp == "Abstract") {
1675 } else if (tmp == "Bibliography") {
1683 /* maybe some vertical spaces */
1685 /* the labelwidthstring used in lists */
1689 /* some pagebreaks? */
1693 /* what about the alignment */
1695 lyxerr << "Should this ever happen?" << endl;
1699 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1701 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1702 if (!i && !noparbreak) {
1705 for (Paragraph::depth_type j = 0; j < depth; ++j)
1707 currlinelen = depth * 2;
1710 case 4: // (Sub)Paragraph
1711 case 5: // Description
1715 buffer << "Abstract\n\n";
1717 buffer << "Abstract: ";
1719 case 7: // Bibliography
1722 buffer << "References\n\n";
1724 buffer << "References: ";
1729 buffer << par->params().labelString() << " ";
1732 if (ltype_depth > depth) {
1733 for (Paragraph::depth_type j = ltype_depth - 1;
1736 currlinelen += (ltype_depth-depth)*2;
1740 LyXFont const font2 = par->getFontSettings(params, i);
1741 if (font1.latex() != font2.latex()) {
1742 if (font2.latex() == LyXFont::OFF)
1751 char c = par->getUChar(params, i);
1755 case Paragraph::META_INSET:
1757 Inset const * inset = par->getInset(i);
1759 if (!inset->ascii(this, buffer)) {
1762 rsplit(buffer.str().c_str(),
1764 currlinelen += s.length();
1766 // to be sure it breaks paragraph
1767 currlinelen += linelen;
1773 case Paragraph::META_NEWLINE:
1776 for (Paragraph::depth_type j = 0;
1780 currlinelen = depth * 2;
1781 if (ltype_depth > depth) {
1782 for (Paragraph::depth_type j = ltype_depth;
1785 currlinelen += (ltype_depth - depth) * 2;
1789 case Paragraph::META_HFILL:
1798 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1799 (c == ' ') && ((i + 2) < par->size()))
1802 for (Paragraph::depth_type j = 0;
1805 currlinelen = depth * 2;
1806 if (ltype_depth > depth) {
1807 for (Paragraph::depth_type j = ltype_depth;
1810 currlinelen += (ltype_depth-depth)*2;
1812 } else if (c != '\0')
1815 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1820 return buffer.str().c_str();
1824 void Buffer::writeFileAscii(string const & fname, int linelen)
1826 ofstream ofs(fname.c_str());
1828 WriteFSAlert(_("Error: Cannot write file:"), fname);
1831 writeFileAscii(ofs, linelen);
1835 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1837 Paragraph * par = paragraph;
1839 ofs << asciiParagraph(par, linelen);
1847 void Buffer::makeLaTeXFile(string const & fname,
1848 string const & original_path,
1849 bool nice, bool only_body)
1851 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1853 niceFile = nice; // this will be used by Insetincludes.
1855 tex_code_break_column = lyxrc.ascii_linelen;
1857 LyXTextClass const & tclass =
1858 textclasslist.TextClass(params.textclass);
1860 ofstream ofs(fname.c_str());
1862 WriteFSAlert(_("Error: Cannot open file: "), fname);
1866 // validate the buffer.
1867 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1868 LaTeXFeatures features(params, tclass.numLayouts());
1870 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1873 // The starting paragraph of the coming rows is the
1874 // first paragraph of the document. (Asger)
1875 texrow.start(paragraph, 0);
1877 if (!only_body && nice) {
1878 ofs << "%% " LYX_DOCVERSION " created this file. "
1879 "For more info, see http://www.lyx.org/.\n"
1880 "%% Do not edit unless you really know what "
1885 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1886 // There are a few differences between nice LaTeX and usual files:
1887 // usual is \batchmode and has a
1888 // special input@path to allow the including of figures
1889 // with either \input or \includegraphics (what figinsets do).
1890 // batchmode is not set if there is a tex_code_break_column.
1891 // In this case somebody is interested in the generated LaTeX,
1892 // so this is OK. input@path is set when the actual parameter
1893 // original_path is set. This is done for usual tex-file, but not
1894 // for nice-latex-file. (Matthias 250696)
1897 // code for usual, NOT nice-latex-file
1898 ofs << "\\batchmode\n"; // changed
1899 // from \nonstopmode
1902 if (!original_path.empty()) {
1903 ofs << "\\makeatletter\n"
1904 << "\\def\\input@path{{"
1905 << os::external_path(original_path) << "/}}\n"
1906 << "\\makeatother\n";
1912 ofs << "\\documentclass";
1914 ostringstream options; // the document class options.
1916 if (tokenPos(tclass.opt_fontsize(),
1917 '|', params.fontsize) >= 0) {
1918 // only write if existing in list (and not default)
1919 options << params.fontsize << "pt,";
1923 if (!params.use_geometry &&
1924 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1925 switch (params.papersize) {
1926 case BufferParams::PAPER_A4PAPER:
1927 options << "a4paper,";
1929 case BufferParams::PAPER_USLETTER:
1930 options << "letterpaper,";
1932 case BufferParams::PAPER_A5PAPER:
1933 options << "a5paper,";
1935 case BufferParams::PAPER_B5PAPER:
1936 options << "b5paper,";
1938 case BufferParams::PAPER_EXECUTIVEPAPER:
1939 options << "executivepaper,";
1941 case BufferParams::PAPER_LEGALPAPER:
1942 options << "legalpaper,";
1948 if (params.sides != tclass.sides()) {
1949 switch (params.sides) {
1950 case LyXTextClass::OneSide:
1951 options << "oneside,";
1953 case LyXTextClass::TwoSides:
1954 options << "twoside,";
1960 if (params.columns != tclass.columns()) {
1961 if (params.columns == 2)
1962 options << "twocolumn,";
1964 options << "onecolumn,";
1967 if (!params.use_geometry
1968 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1969 options << "landscape,";
1971 // language should be a parameter to \documentclass
1973 ostringstream language_options;
1974 if (params.language->babel() == "hebrew"
1975 && default_language->babel() != "hebrew")
1976 // This seems necessary
1977 features.UsedLanguages.insert(default_language);
1979 if (lyxrc.language_use_babel ||
1980 params.language->lang() != lyxrc.default_language ||
1981 !features.UsedLanguages.empty()) {
1983 for (LaTeXFeatures::LanguageList::const_iterator cit =
1984 features.UsedLanguages.begin();
1985 cit != features.UsedLanguages.end(); ++cit)
1986 language_options << (*cit)->babel() << ',';
1987 language_options << params.language->babel();
1988 if (lyxrc.language_global_options)
1989 options << language_options.str() << ',';
1992 // the user-defined options
1993 if (!params.options.empty()) {
1994 options << params.options << ',';
1997 string strOptions(options.str().c_str());
1998 if (!strOptions.empty()){
1999 strOptions = strip(strOptions, ',');
2000 ofs << '[' << strOptions << ']';
2004 << textclasslist.LatexnameOfClass(params.textclass)
2007 // end of \documentclass defs
2009 // font selection must be done before loading fontenc.sty
2010 // The ae package is not needed when using OT1 font encoding.
2011 if (params.fonts != "default" &&
2012 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2013 ofs << "\\usepackage{" << params.fonts << "}\n";
2015 if (params.fonts == "ae") {
2016 ofs << "\\usepackage{aecompl}\n";
2020 // this one is not per buffer
2021 if (lyxrc.fontenc != "default") {
2022 ofs << "\\usepackage[" << lyxrc.fontenc
2027 if (params.inputenc == "auto") {
2028 string const doc_encoding =
2029 params.language->encoding()->LatexName();
2031 // Create a list with all the input encodings used
2033 set<string> encodings;
2034 for (LaTeXFeatures::LanguageList::const_iterator it =
2035 features.UsedLanguages.begin();
2036 it != features.UsedLanguages.end(); ++it)
2037 if ((*it)->encoding()->LatexName() != doc_encoding)
2038 encodings.insert((*it)->encoding()->LatexName());
2040 ofs << "\\usepackage[";
2041 std::copy(encodings.begin(), encodings.end(),
2042 std::ostream_iterator<string>(ofs, ","));
2043 ofs << doc_encoding << "]{inputenc}\n";
2045 } else if (params.inputenc != "default") {
2046 ofs << "\\usepackage[" << params.inputenc
2051 // At the very beginning the text parameters.
2052 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2053 switch (params.paperpackage) {
2054 case BufferParams::PACKAGE_A4:
2055 ofs << "\\usepackage{a4}\n";
2058 case BufferParams::PACKAGE_A4WIDE:
2059 ofs << "\\usepackage{a4wide}\n";
2062 case BufferParams::PACKAGE_WIDEMARGINSA4:
2063 ofs << "\\usepackage[widemargins]{a4}\n";
2068 if (params.use_geometry) {
2069 ofs << "\\usepackage{geometry}\n";
2071 ofs << "\\geometry{verbose";
2072 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2073 ofs << ",landscape";
2074 switch (params.papersize2) {
2075 case BufferParams::VM_PAPER_CUSTOM:
2076 if (!params.paperwidth.empty())
2077 ofs << ",paperwidth="
2078 << params.paperwidth;
2079 if (!params.paperheight.empty())
2080 ofs << ",paperheight="
2081 << params.paperheight;
2083 case BufferParams::VM_PAPER_USLETTER:
2084 ofs << ",letterpaper";
2086 case BufferParams::VM_PAPER_USLEGAL:
2087 ofs << ",legalpaper";
2089 case BufferParams::VM_PAPER_USEXECUTIVE:
2090 ofs << ",executivepaper";
2092 case BufferParams::VM_PAPER_A3:
2095 case BufferParams::VM_PAPER_A4:
2098 case BufferParams::VM_PAPER_A5:
2101 case BufferParams::VM_PAPER_B3:
2104 case BufferParams::VM_PAPER_B4:
2107 case BufferParams::VM_PAPER_B5:
2111 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2112 switch (lyxrc.default_papersize) {
2113 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2114 case BufferParams::PAPER_USLETTER:
2115 ofs << ",letterpaper";
2117 case BufferParams::PAPER_LEGALPAPER:
2118 ofs << ",legalpaper";
2120 case BufferParams::PAPER_EXECUTIVEPAPER:
2121 ofs << ",executivepaper";
2123 case BufferParams::PAPER_A3PAPER:
2126 case BufferParams::PAPER_A4PAPER:
2129 case BufferParams::PAPER_A5PAPER:
2132 case BufferParams::PAPER_B5PAPER:
2137 if (!params.topmargin.empty())
2138 ofs << ",tmargin=" << params.topmargin;
2139 if (!params.bottommargin.empty())
2140 ofs << ",bmargin=" << params.bottommargin;
2141 if (!params.leftmargin.empty())
2142 ofs << ",lmargin=" << params.leftmargin;
2143 if (!params.rightmargin.empty())
2144 ofs << ",rmargin=" << params.rightmargin;
2145 if (!params.headheight.empty())
2146 ofs << ",headheight=" << params.headheight;
2147 if (!params.headsep.empty())
2148 ofs << ",headsep=" << params.headsep;
2149 if (!params.footskip.empty())
2150 ofs << ",footskip=" << params.footskip;
2154 if (features.amsstyle
2155 && !tclass.provides(LyXTextClass::amsmath)) {
2156 ofs << "\\usepackage{amsmath}\n";
2160 if (tokenPos(tclass.opt_pagestyle(),
2161 '|', params.pagestyle) >= 0) {
2162 if (params.pagestyle == "fancy") {
2163 ofs << "\\usepackage{fancyhdr}\n";
2166 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2170 // We try to load babel late, in case it interferes
2171 // with other packages.
2173 string tmp = lyxrc.language_package;
2174 if (!lyxrc.language_global_options
2175 && tmp == "\\usepackage{babel}")
2176 tmp = string("\\usepackage[") +
2177 language_options.str().c_str() +
2183 if (params.secnumdepth != tclass.secnumdepth()) {
2184 ofs << "\\setcounter{secnumdepth}{"
2185 << params.secnumdepth
2189 if (params.tocdepth != tclass.tocdepth()) {
2190 ofs << "\\setcounter{tocdepth}{"
2196 if (params.paragraph_separation) {
2197 switch (params.defskip.kind()) {
2198 case VSpace::SMALLSKIP:
2199 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2201 case VSpace::MEDSKIP:
2202 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2204 case VSpace::BIGSKIP:
2205 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2207 case VSpace::LENGTH:
2208 ofs << "\\setlength\\parskip{"
2209 << params.defskip.length().asLatexString()
2212 default: // should never happen // Then delete it.
2213 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2218 ofs << "\\setlength\\parindent{0pt}\n";
2222 // Now insert the LyX specific LaTeX commands...
2224 // The optional packages;
2225 string preamble(features.getPackages());
2227 // this might be useful...
2228 preamble += "\n\\makeatletter\n";
2230 // Some macros LyX will need
2231 string tmppreamble(features.getMacros());
2233 if (!tmppreamble.empty()) {
2234 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2235 "LyX specific LaTeX commands.\n"
2236 + tmppreamble + '\n';
2239 // the text class specific preamble
2240 tmppreamble = features.getTClassPreamble();
2241 if (!tmppreamble.empty()) {
2242 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2243 "Textclass specific LaTeX commands.\n"
2244 + tmppreamble + '\n';
2247 /* the user-defined preamble */
2248 if (!params.preamble.empty()) {
2249 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2250 "User specified LaTeX commands.\n"
2251 + params.preamble + '\n';
2254 preamble += "\\makeatother\n";
2256 // Itemize bullet settings need to be last in case the user
2257 // defines their own bullets that use a package included
2258 // in the user-defined preamble -- ARRae
2259 // Actually it has to be done much later than that
2260 // since some packages like frenchb make modifications
2261 // at \begin{document} time -- JMarc
2263 for (int i = 0; i < 4; ++i) {
2264 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2265 if (bullets_def.empty())
2266 bullets_def="\\AtBeginDocument{\n";
2267 bullets_def += " \\renewcommand{\\labelitemi";
2269 // `i' is one less than the item to modify
2276 bullets_def += "ii";
2282 bullets_def += "}{" +
2283 params.user_defined_bullets[i].getText()
2288 if (!bullets_def.empty())
2289 preamble += bullets_def + "}\n\n";
2291 for (int j = countChar(preamble, '\n'); j-- ;) {
2298 ofs << "\\begin{document}\n";
2301 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2303 if (!lyxrc.language_auto_begin) {
2304 ofs << subst(lyxrc.language_command_begin, "$$lang",
2305 params.language->babel())
2310 latexParagraphs(ofs, paragraph, 0, texrow);
2312 // add this just in case after all the paragraphs
2316 if (!lyxrc.language_auto_end) {
2317 ofs << subst(lyxrc.language_command_end, "$$lang",
2318 params.language->babel())
2324 ofs << "\\end{document}\n";
2327 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2329 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2333 // Just to be sure. (Asger)
2336 // tex_code_break_column's value is used to decide
2337 // if we are in batchmode or not (within mathed_write()
2338 // in math_write.C) so we must set it to a non-zero
2339 // value when we leave otherwise we save incorrect .lyx files.
2340 tex_code_break_column = lyxrc.ascii_linelen;
2344 lyxerr << "File was not closed properly." << endl;
2347 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2352 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2354 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2355 Paragraph * endpar, TexRow & texrow) const
2357 bool was_title = false;
2358 bool already_title = false;
2361 while (par != endpar) {
2362 LyXLayout const & layout =
2363 textclasslist.Style(params.textclass,
2366 if (layout.intitle) {
2367 if (already_title) {
2368 lyxerr <<"Error in latexParagraphs: You"
2369 " should not mix title layouts"
2370 " with normal ones." << endl;
2373 } else if (was_title && !already_title) {
2374 ofs << "\\maketitle\n";
2376 already_title = true;
2380 if (layout.isEnvironment()) {
2381 par = par->TeXEnvironment(this, params, ofs, texrow);
2383 par = par->TeXOnePar(this, params, ofs, texrow, false);
2386 // It might be that we only have a title in this document
2387 if (was_title && !already_title) {
2388 ofs << "\\maketitle\n";
2394 bool Buffer::isLatex() const
2396 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2400 bool Buffer::isLinuxDoc() const
2402 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2406 bool Buffer::isLiterate() const
2408 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2412 bool Buffer::isDocBook() const
2414 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2418 bool Buffer::isSGML() const
2420 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2421 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2425 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2426 string const & latexname) const
2428 if (!latexname.empty() && latexname != "!-- --")
2429 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2430 //os << string(depth, ' ') << "<" << latexname << ">\n";
2434 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2435 string const & latexname) const
2437 if (!latexname.empty() && latexname != "!-- --")
2438 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2439 //os << string(depth, ' ') << "</" << latexname << ">\n";
2443 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2445 ofstream ofs(fname.c_str());
2448 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2452 niceFile = nice; // this will be used by included files.
2454 LyXTextClass const & tclass =
2455 textclasslist.TextClass(params.textclass);
2457 LaTeXFeatures features(params, tclass.numLayouts());
2462 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2465 string sgml_includedfiles=features.getIncludedFiles(fname);
2467 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2468 ofs << "<!doctype linuxdoc system>\n\n";
2470 ofs << "<!doctype linuxdoc system [ "
2471 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2474 if (params.options.empty())
2475 sgmlOpenTag(ofs, 0, top_element);
2477 string top = top_element;
2479 top += params.options;
2480 sgmlOpenTag(ofs, 0, top);
2484 ofs << "<!-- " << LYX_DOCVERSION
2485 << " created this file. For more info see http://www.lyx.org/"
2488 Paragraph::depth_type depth = 0; // paragraph depth
2489 Paragraph * par = paragraph;
2491 vector<string> environment_stack(5);
2494 LyXLayout const & style =
2495 textclasslist.Style(params.textclass,
2498 // treat <toc> as a special case for compatibility with old code
2499 if (par->getChar(0) == Paragraph::META_INSET) {
2500 Inset * inset = par->getInset(0);
2501 Inset::Code lyx_code = inset->lyxCode();
2502 if (lyx_code == Inset::TOC_CODE){
2503 string const temp = "toc";
2504 sgmlOpenTag(ofs, depth, temp);
2511 // environment tag closing
2512 for (; depth > par->params().depth(); --depth) {
2513 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2514 environment_stack[depth].erase();
2517 // write opening SGML tags
2518 switch (style.latextype) {
2519 case LATEX_PARAGRAPH:
2520 if (depth == par->params().depth()
2521 && !environment_stack[depth].empty()) {
2522 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2523 environment_stack[depth].erase();
2529 sgmlOpenTag(ofs, depth, style.latexname());
2534 linuxDocError(par, 0,
2535 _("Error : Wrong depth for"
2536 " LatexType Command.\n"));
2538 if (!environment_stack[depth].empty()){
2539 sgmlCloseTag(ofs, depth,
2540 environment_stack[depth]);
2544 environment_stack[depth].erase();
2545 sgmlOpenTag(ofs, depth, style.latexname());
2548 case LATEX_ENVIRONMENT:
2549 case LATEX_ITEM_ENVIRONMENT:
2550 if (depth == par->params().depth()
2551 && environment_stack[depth] != style.latexname()) {
2552 sgmlCloseTag(ofs, depth,
2553 environment_stack[depth]);
2554 environment_stack[depth].erase();
2556 if (depth < par->params().depth()) {
2557 depth = par->params().depth();
2558 environment_stack[depth].erase();
2560 if (environment_stack[depth] != style.latexname()) {
2562 sgmlOpenTag(ofs, depth, "p");
2564 sgmlOpenTag(ofs, depth, style.latexname());
2566 if (environment_stack.size() == depth + 1)
2567 environment_stack.push_back("!-- --");
2568 environment_stack[depth] = style.latexname();
2571 if (style.latexparam() == "CDATA")
2574 if (style.latextype == LATEX_ENVIRONMENT) break;
2576 if (style.labeltype == LABEL_MANUAL)
2581 sgmlOpenTag(ofs, depth + 1, item_name);
2584 sgmlOpenTag(ofs, depth, style.latexname());
2588 simpleLinuxDocOnePar(ofs, par, depth);
2593 // write closing SGML tags
2594 switch (style.latextype) {
2597 case LATEX_ENVIRONMENT:
2598 case LATEX_ITEM_ENVIRONMENT:
2599 if (style.latexparam() == "CDATA")
2603 sgmlCloseTag(ofs, depth, style.latexname());
2609 for (int i=depth; i >= 0; --i)
2610 sgmlCloseTag(ofs, depth, environment_stack[i]);
2614 sgmlCloseTag(ofs, 0, top_element);
2618 // How to check for successful close
2622 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2623 Paragraph::depth_type depth, int desc_on,
2626 Paragraph * tpar = par;
2628 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2630 tpar = tpar->next();
2633 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2634 "Caption").second) {
2635 sgmlOpenTag(os, depth + 1, inner_tag);
2637 simpleDocBookOnePar(os, extra_par, tpar,
2638 desc_on, depth + 2);
2639 sgmlCloseTag(os, depth+1, inner_tag);
2640 if (!extra_par.empty())
2646 // checks, if newcol chars should be put into this line
2647 // writes newline, if necessary.
2650 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2651 string::size_type newcol)
2654 if (colcount > lyxrc.ascii_linelen) {
2656 colcount = newcol; // assume write after this call
2671 string tag_name(PAR_TAG const & pt) {
2673 case NONE: return "!-- --";
2674 case TT: return "tt";
2675 case SF: return "sf";
2676 case BF: return "bf";
2677 case IT: return "it";
2678 case SL: return "sl";
2679 case EM: return "em";
2686 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2688 p1 = static_cast<PAR_TAG>(p1 | p2);
2693 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2695 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2703 // Handle internal paragraph parsing -- layout already processed.
2704 void Buffer::simpleLinuxDocOnePar(ostream & os,
2706 Paragraph::depth_type /*depth*/)
2708 LyXLayout const & style = textclasslist.Style(params.textclass,
2710 string::size_type char_line_count = 5; // Heuristic choice ;-)
2712 // gets paragraph main font
2715 if (style.labeltype == LABEL_MANUAL) {
2716 font_old = style.labelfont;
2719 font_old = style.font;
2723 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2724 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2725 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2728 stack < PAR_TAG > tag_state;
2729 // parsing main loop
2730 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2732 PAR_TAG tag_close = NONE;
2733 list < PAR_TAG > tag_open;
2735 LyXFont const font = par->getFont(params, i);
2737 if (font_old.family() != font.family()) {
2738 switch (family_type) {
2739 case LyXFont::SANS_FAMILY:
2742 case LyXFont::TYPEWRITER_FAMILY:
2749 family_type = font.family();
2751 switch (family_type) {
2752 case LyXFont::SANS_FAMILY:
2753 tag_open.push_back(SF);
2755 case LyXFont::TYPEWRITER_FAMILY:
2756 tag_open.push_back(TT);
2763 if (font_old.series() != font.series()) {
2764 switch (series_type) {
2765 case LyXFont::BOLD_SERIES:
2772 series_type = font.series();
2774 switch (series_type) {
2775 case LyXFont::BOLD_SERIES:
2776 tag_open.push_back(BF);
2784 if (font_old.shape() != font.shape()) {
2785 switch (shape_type) {
2786 case LyXFont::ITALIC_SHAPE:
2789 case LyXFont::SLANTED_SHAPE:
2796 shape_type = font.shape();
2798 switch (shape_type) {
2799 case LyXFont::ITALIC_SHAPE:
2800 tag_open.push_back(IT);
2802 case LyXFont::SLANTED_SHAPE:
2803 tag_open.push_back(SL);
2810 if (font_old.emph() != font.emph()) {
2811 if (font.emph() == LyXFont::ON) {
2812 tag_open.push_back(EM);
2821 list < PAR_TAG > temp;
2822 while(!tag_state.empty() && tag_close ) {
2823 PAR_TAG k = tag_state.top();
2825 os << "</" << tag_name(k) << ">";
2832 for(list< PAR_TAG >::const_iterator j = temp.begin();
2833 j != temp.end(); ++j) {
2835 os << "<" << tag_name(*j) << ">";
2838 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2839 j != tag_open.end(); ++j) {
2841 os << "<" << tag_name(*j) << ">";
2844 char c = par->getChar(i);
2846 if (c == Paragraph::META_INSET) {
2847 Inset * inset = par->getInset(i);
2848 inset->linuxdoc(this, os);
2855 font.latex() == LyXFont::ON ||
2857 style.latexparam() == "CDATA") {
2858 // "TeX"-Mode on == > SGML-Mode on.
2864 if (par->linuxDocConvertChar(c, sgml_string)
2865 && !style.free_spacing) {
2866 // in freespacing mode, spaces are
2867 // non-breaking characters
2868 if (desc_on) {// if char is ' ' then...
2871 linux_doc_line_break(os, char_line_count, 6);
2875 linux_doc_line_break(os, char_line_count, 1);
2880 char_line_count += sgml_string.length();
2886 while (!tag_state.empty()) {
2887 os << "</" << tag_name(tag_state.top()) << ">";
2891 // resets description flag correctly
2893 // <tag> not closed...
2894 linux_doc_line_break(os, char_line_count, 6);
2900 // Print an error message.
2901 void Buffer::linuxDocError(Paragraph * par, int pos,
2902 string const & message)
2904 // insert an error marker in text
2905 InsetError * new_inset = new InsetError(message);
2906 par->insertInset(pos, new_inset);
2910 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2912 ofstream ofs(fname.c_str());
2914 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2918 Paragraph * par = paragraph;
2920 niceFile = nice; // this will be used by Insetincludes.
2922 LyXTextClass const & tclass =
2923 textclasslist.TextClass(params.textclass);
2925 LaTeXFeatures features(params, tclass.numLayouts());
2930 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2933 string sgml_includedfiles = features.getIncludedFiles(fname);
2935 ofs << "<!doctype " << top_element
2936 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2938 if (params.preamble.empty() && sgml_includedfiles.empty())
2941 ofs << "\n [ " << params.preamble
2942 << sgml_includedfiles << " \n]>\n\n";
2945 string top = top_element;
2947 top += params.language->code();
2950 if (!params.options.empty()) {
2952 top += params.options;
2954 sgmlOpenTag(ofs, 0, top);
2956 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2957 << "\n See http://www.lyx.org/ for more information -->\n";
2959 vector<string> environment_stack(10);
2960 vector<string> environment_inner(10);
2961 vector<string> command_stack(10);
2963 bool command_flag = false;
2964 Paragraph::depth_type command_depth = 0;
2965 Paragraph::depth_type command_base = 0;
2966 Paragraph::depth_type cmd_depth = 0;
2967 Paragraph::depth_type depth = 0; // paragraph depth
2970 string command_name;
2976 int desc_on = 0; // description mode
2978 LyXLayout const & style =
2979 textclasslist.Style(params.textclass,
2982 // environment tag closing
2983 for (; depth > par->params().depth(); --depth) {
2984 if (environment_inner[depth] != "!-- --") {
2985 item_name = "listitem";
2986 sgmlCloseTag(ofs, command_depth + depth,
2988 if (environment_inner[depth] == "varlistentry")
2989 sgmlCloseTag(ofs, depth+command_depth,
2990 environment_inner[depth]);
2992 sgmlCloseTag(ofs, depth + command_depth,
2993 environment_stack[depth]);
2994 environment_stack[depth].erase();
2995 environment_inner[depth].erase();
2998 if (depth == par->params().depth()
2999 && environment_stack[depth] != style.latexname()
3000 && !environment_stack[depth].empty()) {
3001 if (environment_inner[depth] != "!-- --") {
3002 item_name= "listitem";
3003 sgmlCloseTag(ofs, command_depth+depth,
3005 if (environment_inner[depth] == "varlistentry")
3007 depth + command_depth,
3008 environment_inner[depth]);
3011 sgmlCloseTag(ofs, depth + command_depth,
3012 environment_stack[depth]);
3014 environment_stack[depth].erase();
3015 environment_inner[depth].erase();
3018 // Write opening SGML tags.
3019 switch (style.latextype) {
3020 case LATEX_PARAGRAPH:
3021 sgmlOpenTag(ofs, depth + command_depth,
3027 linuxDocError(par, 0,
3028 _("Error : Wrong depth for "
3029 "LatexType Command.\n"));
3031 command_name = style.latexname();
3033 sgmlparam = style.latexparam();
3034 c_params = split(sgmlparam, c_depth,'|');
3036 cmd_depth = lyx::atoi(c_depth);
3039 if (cmd_depth < command_base) {
3040 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3041 sgmlCloseTag(ofs, j, command_stack[j]);
3042 command_depth = command_base = cmd_depth;
3043 } else if (cmd_depth <= command_depth) {
3044 for (int j = command_depth; j >= int(cmd_depth); --j)
3045 sgmlCloseTag(ofs, j, command_stack[j]);
3046 command_depth = cmd_depth;
3048 command_depth = cmd_depth;
3050 command_depth = command_base = cmd_depth;
3051 command_flag = true;
3053 if (command_stack.size() == command_depth + 1)
3054 command_stack.push_back(string());
3055 command_stack[command_depth] = command_name;
3057 // treat label as a special case for
3058 // more WYSIWYM handling.
3059 if (par->getChar(0) == Paragraph::META_INSET) {
3060 Inset * inset = par->getInset(0);
3061 Inset::Code lyx_code = inset->lyxCode();
3062 if (lyx_code == Inset::LABEL_CODE){
3063 command_name += " id=\"";
3064 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3065 command_name += "\"";
3070 sgmlOpenTag(ofs, depth + command_depth, command_name);
3071 if (c_params.empty())
3072 item_name = "title";
3074 item_name = c_params;
3075 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3078 case LATEX_ENVIRONMENT:
3079 case LATEX_ITEM_ENVIRONMENT:
3080 if (depth < par->params().depth()) {
3081 depth = par->params().depth();
3082 environment_stack[depth].erase();
3085 if (environment_stack[depth] != style.latexname()) {
3086 if(environment_stack.size() == depth + 1) {
3087 environment_stack.push_back("!-- --");
3088 environment_inner.push_back("!-- --");
3090 environment_stack[depth] = style.latexname();
3091 environment_inner[depth] = "!-- --";
3092 sgmlOpenTag(ofs, depth + command_depth,
3093 environment_stack[depth]);
3095 if (environment_inner[depth] != "!-- --") {
3096 item_name= "listitem";
3098 command_depth + depth,
3100 if (environment_inner[depth] == "varlistentry")
3102 depth + command_depth,
3103 environment_inner[depth]);
3107 if (style.latextype == LATEX_ENVIRONMENT) {
3108 if (!style.latexparam().empty()) {
3109 if(style.latexparam() == "CDATA")
3112 sgmlOpenTag(ofs, depth + command_depth,
3113 style.latexparam());
3118 desc_on = (style.labeltype == LABEL_MANUAL);
3121 environment_inner[depth]= "varlistentry";
3123 environment_inner[depth]= "listitem";
3125 sgmlOpenTag(ofs, depth + 1 + command_depth,
3126 environment_inner[depth]);
3130 sgmlOpenTag(ofs, depth + 1 + command_depth,
3134 sgmlOpenTag(ofs, depth + 1 + command_depth,
3139 sgmlOpenTag(ofs, depth + command_depth,
3145 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3146 depth + 1 + command_depth);
3150 // write closing SGML tags
3151 switch (style.latextype) {
3153 if (c_params.empty())
3157 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3159 case LATEX_ENVIRONMENT:
3160 if (!style.latexparam().empty()) {
3161 if(style.latexparam() == "CDATA")
3164 sgmlCloseTag(ofs, depth + command_depth,
3165 style.latexparam());
3168 case LATEX_ITEM_ENVIRONMENT:
3169 if (desc_on == 1) break;
3171 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3173 case LATEX_PARAGRAPH:
3174 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3177 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3183 for (int d = depth; d >= 0; --d) {
3184 if (!environment_stack[depth].empty()) {
3185 if (environment_inner[depth] != "!-- --") {
3186 item_name = "listitem";
3187 sgmlCloseTag(ofs, command_depth + depth,
3189 if (environment_inner[depth] == "varlistentry")
3190 sgmlCloseTag(ofs, depth + command_depth,
3191 environment_inner[depth]);
3194 sgmlCloseTag(ofs, depth + command_depth,
3195 environment_stack[depth]);
3199 for (int j = command_depth; j >= 0 ; --j)
3200 if (!command_stack[j].empty())
3201 sgmlCloseTag(ofs, j, command_stack[j]);
3204 sgmlCloseTag(ofs, 0, top_element);
3207 // How to check for successful close
3211 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3212 Paragraph * par, int & desc_on,
3213 Paragraph::depth_type depth) const
3215 bool emph_flag = false;
3217 LyXLayout const & style = textclasslist.Style(params.textclass,
3220 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3222 int char_line_count = depth;
3223 //if (!style.free_spacing)
3224 // os << string(depth,' ');
3226 // parsing main loop
3227 for (Paragraph::size_type i = 0;
3228 i < par->size(); ++i) {
3229 LyXFont font = par->getFont(params, i);
3231 // handle <emphasis> tag
3232 if (font_old.emph() != font.emph()) {
3233 if (font.emph() == LyXFont::ON) {
3237 os << "</emphasis>";
3242 char c = par->getChar(i);
3244 if (c == Paragraph::META_INSET) {
3245 Inset * inset = par->getInset(i);
3247 inset->docBook(this, ost);
3248 string tmp_out = ost.str().c_str();
3251 // This code needs some explanation:
3252 // Two insets are treated specially
3253 // label if it is the first element in a command paragraph
3255 // graphics inside tables or figure floats can't go on
3256 // title (the equivalente in latex for this case is caption
3257 // and title should come first
3260 if (desc_on!= 3 || i!= 0) {
3261 if (!tmp_out.empty() && tmp_out[0] == '@') {
3263 extra += frontStrip(tmp_out, '@');
3265 os << frontStrip(tmp_out, '@');
3271 } else if (font.latex() == LyXFont::ON) {
3272 // "TeX"-Mode on ==> SGML-Mode on.
3279 if (par->linuxDocConvertChar(c, sgml_string)
3280 && !style.free_spacing) { // in freespacing
3282 // non-breaking characters
3286 os << "\n</term><listitem><para>";
3299 os << "</emphasis>";
3302 // resets description flag correctly
3304 // <term> not closed...
3307 if(style.free_spacing) os << '\n';
3311 // This should be enabled when the Chktex class is implemented. (Asger)
3312 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3313 // Other flags: -wall -v0 -x
3314 int Buffer::runChktex()
3316 if (!users->text) return 0;
3318 users->owner()->prohibitInput();
3320 // get LaTeX-Filename
3321 string const name = getLatexName();
3322 string path = OnlyPath(filename);
3324 string const org_path = path;
3325 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3329 Path p(path); // path to LaTeX file
3330 users->owner()->message(_("Running chktex..."));
3332 // Remove all error insets
3333 bool const removedErrorInsets = users->removeAutoInsets();
3335 // Generate the LaTeX file if neccessary
3336 makeLaTeXFile(name, org_path, false);
3339 Chktex chktex(lyxrc.chktex_command, name, filepath);
3340 int res = chktex.run(terr); // run chktex
3343 WriteAlert(_("chktex did not work!"),
3344 _("Could not run with file:"), name);
3345 } else if (res > 0) {
3346 // Insert all errors as errors boxes
3347 users->insertErrors(terr);
3350 // if we removed error insets before we ran chktex or if we inserted
3351 // error insets after we ran chktex, this must be run:
3352 if (removedErrorInsets || res){
3354 users->fitCursor(users->text);
3356 users->owner()->allowInput();
3362 void Buffer::validate(LaTeXFeatures & features) const
3364 Paragraph * par = paragraph;
3365 LyXTextClass const & tclass =
3366 textclasslist.TextClass(params.textclass);
3368 // AMS Style is at document level
3370 features.amsstyle = (params.use_amsmath ||
3371 tclass.provides(LyXTextClass::amsmath));
3374 // We don't use "lyxerr.debug" because of speed. (Asger)
3375 if (lyxerr.debugging(Debug::LATEX))
3376 lyxerr << "Paragraph: " << par << endl;
3378 // Now just follow the list of paragraphs and run
3379 // validate on each of them.
3380 par->validate(features);
3382 // and then the next paragraph
3386 // the bullet shapes are buffer level not paragraph level
3387 // so they are tested here
3388 for (int i = 0; i < 4; ++i) {
3389 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3390 int const font = params.user_defined_bullets[i].getFont();
3392 int const c = params
3393 .user_defined_bullets[i]
3400 features.latexsym = true;
3402 } else if (font == 1) {
3403 features.amssymb = true;
3404 } else if ((font >= 2 && font <= 5)) {
3405 features.pifont = true;
3410 if (lyxerr.debugging(Debug::LATEX)) {
3411 features.showStruct();
3416 void Buffer::setPaperStuff()
3418 params.papersize = BufferParams::PAPER_DEFAULT;
3419 char const c1 = params.paperpackage;
3420 if (c1 == BufferParams::PACKAGE_NONE) {
3421 char const c2 = params.papersize2;
3422 if (c2 == BufferParams::VM_PAPER_USLETTER)
3423 params.papersize = BufferParams::PAPER_USLETTER;
3424 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3425 params.papersize = BufferParams::PAPER_LEGALPAPER;
3426 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3427 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3428 else if (c2 == BufferParams::VM_PAPER_A3)
3429 params.papersize = BufferParams::PAPER_A3PAPER;
3430 else if (c2 == BufferParams::VM_PAPER_A4)
3431 params.papersize = BufferParams::PAPER_A4PAPER;
3432 else if (c2 == BufferParams::VM_PAPER_A5)
3433 params.papersize = BufferParams::PAPER_A5PAPER;
3434 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3435 (c2 == BufferParams::VM_PAPER_B5))
3436 params.papersize = BufferParams::PAPER_B5PAPER;
3437 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3438 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3439 params.papersize = BufferParams::PAPER_A4PAPER;
3443 // This function should be in Buffer because it's a buffer's property (ale)
3444 string const Buffer::getIncludeonlyList(char delim)
3447 for (inset_iterator it = inset_iterator_begin();
3448 it != inset_iterator_end(); ++it) {
3449 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3450 InsetInclude * insetinc =
3451 static_cast<InsetInclude *>(*it);
3452 if (insetinc->isIncludeOnly()) {
3455 lst += insetinc->getRelFileBaseName();
3459 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3464 vector<string> const Buffer::getLabelList()
3466 /// if this is a child document and the parent is already loaded
3467 /// Use the parent's list instead [ale990407]
3468 if (!params.parentname.empty()
3469 && bufferlist.exists(params.parentname)) {
3470 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3472 return tmp->getLabelList();
3475 vector<string> label_list;
3476 for (inset_iterator it = inset_iterator_begin();
3477 it != inset_iterator_end(); ++it) {
3478 vector<string> const l = (*it)->getLabelList();
3479 label_list.insert(label_list.end(), l.begin(), l.end());
3485 Buffer::Lists const Buffer::getLists() const
3488 Paragraph * par = paragraph;
3490 LyXTextClassList::size_type cap;
3491 boost::tie(found, cap) = textclasslist
3492 .NumberOfLayout(params.textclass, "Caption");
3495 char const labeltype =
3496 textclasslist.Style(params.textclass,
3497 par->getLayout()).labeltype;
3499 if (labeltype >= LABEL_COUNTER_CHAPTER
3500 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3501 // insert this into the table of contents
3502 SingleList & item = l["TOC"];
3505 textclasslist.TextClass(params.textclass).maxcounter());
3506 item.push_back(TocItem(par, depth, par->asString(this, true)));
3508 // For each paragrph, traverse its insets and look for
3512 Paragraph::inset_iterator it =
3513 par->inset_iterator_begin();
3514 Paragraph::inset_iterator end =
3515 par->inset_iterator_end();
3517 for (; it != end; ++it) {
3518 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3520 static_cast<InsetFloat*>(*it);
3522 string const type = il->type();
3524 // Now find the caption in the float...
3525 // We now tranverse the paragraphs of
3527 Paragraph * tmp = il->inset.paragraph();
3529 if (tmp->layout == cap) {
3530 SingleList & item = l[type];
3532 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3533 item.push_back(TocItem(tmp, 0 , str));
3540 lyxerr << "caption not found" << endl;
3549 // This is also a buffer property (ale)
3550 vector<pair<string, string> > const Buffer::getBibkeyList()
3552 /// if this is a child document and the parent is already loaded
3553 /// Use the parent's list instead [ale990412]
3554 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3555 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3557 return tmp->getBibkeyList();
3560 vector<pair<string, string> > keys;
3561 Paragraph * par = paragraph;
3564 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3565 par->asString(this, false)));
3569 // Might be either using bibtex or a child has bibliography
3571 for (inset_iterator it = inset_iterator_begin();
3572 it != inset_iterator_end(); ++it) {
3573 // Search for Bibtex or Include inset
3574 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3575 vector<pair<string,string> > tmp =
3576 static_cast<InsetBibtex*>(*it)->getKeys(this);
3577 keys.insert(keys.end(), tmp.begin(), tmp.end());
3578 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3579 vector<pair<string,string> > const tmp =
3580 static_cast<InsetInclude*>(*it)->getKeys();
3581 keys.insert(keys.end(), tmp.begin(), tmp.end());
3590 bool Buffer::isDepClean(string const & name) const
3592 DEPCLEAN * item = dep_clean;
3593 while (item && item->master != name)
3595 if (!item) return true;
3600 void Buffer::markDepClean(string const & name)
3603 dep_clean = new DEPCLEAN;
3604 dep_clean->clean = true;
3605 dep_clean->master = name;
3606 dep_clean->next = 0;
3608 DEPCLEAN * item = dep_clean;
3609 while (item && item->master != name)
3614 item = new DEPCLEAN;
3616 item->master = name;
3623 bool Buffer::dispatch(string const & command)
3625 // Split command string into command and argument
3627 string line = frontStrip(command);
3628 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3630 return dispatch(lyxaction.LookupFunc(cmd), arg);
3634 bool Buffer::dispatch(int action, string const & argument)
3636 bool dispatched = true;
3639 Exporter::Export(this, argument, false);
3649 void Buffer::resizeInsets(BufferView * bv)
3651 /// then remove all LyXText in text-insets
3652 Paragraph * par = paragraph;
3653 for (; par; par = par->next()) {
3654 par->resizeInsetsLyXText(bv);
3659 void Buffer::redraw()
3662 users->fitCursor(users->text);
3666 void Buffer::changeLanguage(Language const * from, Language const * to)
3669 Paragraph * par = paragraph;
3671 par->changeLanguage(params, from, to);
3677 bool Buffer::isMultiLingual()
3679 Paragraph * par = paragraph;
3681 if (par->isMultiLingual(params))
3689 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3690 Paragraph::size_type pos)
3693 it = par->InsetIterator(pos);
3694 if (it == par->inset_iterator_end()) {
3701 void Buffer::inset_iterator::setParagraph()
3704 it = par->inset_iterator_begin();
3705 if (it != par->inset_iterator_end())
3710 // We maintain an invariant that whenever par = 0 then it = 0
3714 Inset * Buffer::getInsetFromID(int id_arg) const
3716 for (inset_iterator it = inset_const_iterator_begin();
3717 it != inset_const_iterator_end(); ++it)
3719 if ((*it)->id() == id_arg)
3721 Inset * in = (*it)->getInsetFromID(id_arg);
3729 Paragraph * Buffer::getParFromID(int id) const
3731 if (id < 0) return 0;
3732 Paragraph * par = paragraph;
3734 if (par->id() == id) {
3737 Paragraph * tmp = par->getParFromID(id);