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) < 1))
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);
434 checkminipage = true;
438 } else if (token == "\\i") {
439 Inset * inset = new InsetLatexAccent;
440 inset->read(this, lex);
441 par->insertInset(pos, inset, font);
443 } else if (token == "\\layout") {
445 ert_comp.in_tabular = false;
447 insertErtContents(par, pos, font);
450 string const layoutname = lex.GetString();
451 pair<bool, LyXTextClass::LayoutList::size_type> pp
452 = textclasslist.NumberOfLayout(params.textclass,
456 if (compare_no_case(layoutname, "latex") == 0) {
457 ert_comp.active = true;
461 // The is the compability reading of layout caption.
462 // It can be removed in LyX version 1.3.0. (Lgb)
463 if (compare_no_case(layoutname, "caption") == 0) {
464 // We expect that the par we are now working on is
465 // really inside a InsetText inside a InsetFloat.
466 // We also know that captions can only be
467 // one paragraph. (Lgb)
469 // We should now read until the next "\layout"
471 // This is probably not good enough, what if the
472 // caption is the last par in the document (Lgb)
473 istream & ist = lex.getStream();
479 if (prefixIs(line, "\\layout")) {
483 if (prefixIs(line, "\\begin_inset"))
485 if (prefixIs(line, "\\end_inset")) {
496 // Now we should have the whole layout in ss
497 // we should now be able to give this to the
499 ss << "\\end_inset\n";
501 // This seems like a bug in stringstream.
502 // We really should be able to use ss
504 istringstream is(ss.str());
506 tmplex.setStream(is);
507 Inset * inset = new InsetCaption;
508 inset->Read(this, tmplex);
509 par->InsertInset(pos, inset, font);
516 par = new Paragraph(par);
520 par->layout = pp.second;
523 // use default layout "Standard" (0)
526 string const s = _("Layout had to be changed from\n")
527 + layoutname + _(" to ")
528 + textclasslist.NameOfLayout(params.textclass, par->layout);
529 InsetError * new_inset = new InsetError(s);
530 par->insertInset(0, new_inset);
532 // Test whether the layout is obsolete.
533 LyXLayout const & layout =
534 textclasslist.Style(params.textclass,
536 if (!layout.obsoleted_by().empty())
537 par->layout = textclasslist
538 .NumberOfLayout(params.textclass,
539 layout.obsoleted_by())
541 par->params().depth(depth);
542 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
543 if (file_format < 216
544 && params.language->lang() == "hebrew")
545 font.setLanguage(default_language);
550 } else if (token == "\\begin_float") {
551 // This is the compability reader. It can be removed in
552 // LyX version 1.3.0. (Lgb)
554 string const tmptok = lex.GetString();
555 //lyxerr << "old float: " << tmptok << endl;
558 stringstream old_float;
560 if (tmptok == "footnote") {
561 inset = new InsetFoot;
562 } else if (tmptok == "margin") {
563 inset = new InsetMarginal;
564 } else if (tmptok == "fig") {
565 inset = new InsetFloat("figure");
566 old_float << "placement htbp\n"
568 } else if (tmptok == "tab") {
569 inset = new InsetFloat("table");
570 old_float << "placement htbp\n"
572 } else if (tmptok == "alg") {
573 inset = new InsetFloat("algorithm");
574 old_float << "placement htbp\n"
576 } else if (tmptok == "wide-fig") {
577 inset = new InsetFloat("figure");
578 //InsetFloat * tmp = new InsetFloat("figure");
581 old_float << "placement htbp\n"
583 } else if (tmptok == "wide-tab") {
584 inset = new InsetFloat("table");
585 //InsetFloat * tmp = new InsetFloat("table");
588 old_float << "placement htbp\n"
594 return false; // no end read yet
597 old_float << "collapsed true\n";
599 // Here we need to check for \end_deeper and handle that
600 // before we do the footnote parsing.
601 // This _is_ a hack! (Lgb)
604 string const tmp = lex.GetString();
605 if (tmp == "\\end_deeper") {
606 //lyxerr << "\\end_deeper caught!" << endl;
608 lex.printError("\\end_deeper: "
609 "depth is already null");
614 old_float << tmp << ' ';
619 old_float << lex.getLongString("\\end_float")
620 << "\n\\end_inset\n";
621 //lyxerr << "Float Body:\n" << old_float.str() << endl;
622 // That this does not work seems like a bug
623 // in stringstream. (Lgb)
624 istringstream istr(old_float.str());
626 nylex.setStream(istr);
627 inset->read(this, nylex);
628 par->insertInset(pos, inset, font);
630 } else if (token == "\\begin_deeper") {
632 } else if (token == "\\end_deeper") {
634 lex.printError("\\end_deeper: "
635 "depth is already null");
639 } else if (token == "\\begin_preamble") {
640 params.readPreamble(lex);
641 } else if (token == "\\textclass") {
643 pair<bool, LyXTextClassList::size_type> pp =
644 textclasslist.NumberOfClass(lex.GetString());
646 params.textclass = pp.second;
648 WriteAlert(string(_("Textclass error")),
649 string(_("The document uses an unknown textclass \"")) +
650 lex.GetString() + string("\"."),
651 string(_("LyX will not be able to produce output correctly.")));
652 params.textclass = 0;
654 if (!textclasslist.Load(params.textclass)) {
655 // if the textclass wasn't loaded properly
656 // we need to either substitute another
657 // or stop loading the file.
658 // I can substitute but I don't see how I can
659 // stop loading... ideas?? ARRae980418
660 WriteAlert(_("Textclass Loading Error!"),
661 string(_("Can't load textclass ")) +
662 textclasslist.NameOfClass(params.textclass),
663 _("-- substituting default"));
664 params.textclass = 0;
666 } else if (token == "\\options") {
668 params.options = lex.GetString();
669 } else if (token == "\\language") {
670 params.readLanguage(lex);
671 } else if (token == "\\fontencoding") {
673 } else if (token == "\\inputencoding") {
675 params.inputenc = lex.GetString();
676 } else if (token == "\\graphics") {
677 params.readGraphicsDriver(lex);
678 } else if (token == "\\fontscheme") {
680 params.fonts = lex.GetString();
681 } else if (token == "\\noindent") {
682 par->params().noindent(true);
683 } else if (token == "\\fill_top") {
684 par->params().spaceTop(VSpace(VSpace::VFILL));
685 } else if (token == "\\fill_bottom") {
686 par->params().spaceBottom(VSpace(VSpace::VFILL));
687 } else if (token == "\\line_top") {
688 par->params().lineTop(true);
689 } else if (token == "\\line_bottom") {
690 par->params().lineBottom(true);
691 } else if (token == "\\pagebreak_top") {
692 par->params().pagebreakTop(true);
693 } else if (token == "\\pagebreak_bottom") {
694 par->params().pagebreakBottom(true);
695 } else if (token == "\\start_of_appendix") {
696 par->params().startOfAppendix(true);
697 } else if (token == "\\paragraph_separation") {
698 int tmpret = lex.FindToken(string_paragraph_separation);
699 if (tmpret == -1) ++tmpret;
700 if (tmpret != LYX_LAYOUT_DEFAULT)
701 params.paragraph_separation =
702 static_cast<BufferParams::PARSEP>(tmpret);
703 } else if (token == "\\defskip") {
705 params.defskip = VSpace(lex.GetString());
706 } else if (token == "\\epsfig") { // obsolete
707 // Indeed it is obsolete, but we HAVE to be backwards
708 // compatible until 0.14, because otherwise all figures
709 // in existing documents are irretrivably lost. (Asger)
710 params.readGraphicsDriver(lex);
711 } else if (token == "\\quotes_language") {
712 int tmpret = lex.FindToken(string_quotes_language);
713 if (tmpret == -1) ++tmpret;
714 if (tmpret != LYX_LAYOUT_DEFAULT) {
715 InsetQuotes::quote_language tmpl =
716 InsetQuotes::EnglishQ;
719 tmpl = InsetQuotes::EnglishQ;
722 tmpl = InsetQuotes::SwedishQ;
725 tmpl = InsetQuotes::GermanQ;
728 tmpl = InsetQuotes::PolishQ;
731 tmpl = InsetQuotes::FrenchQ;
734 tmpl = InsetQuotes::DanishQ;
737 params.quotes_language = tmpl;
739 } else if (token == "\\quotes_times") {
741 switch (lex.GetInteger()) {
743 params.quotes_times = InsetQuotes::SingleQ;
746 params.quotes_times = InsetQuotes::DoubleQ;
749 } else if (token == "\\papersize") {
750 int tmpret = lex.FindToken(string_papersize);
754 params.papersize2 = tmpret;
755 } else if (token == "\\paperpackage") {
756 int tmpret = lex.FindToken(string_paperpackages);
759 params.paperpackage = BufferParams::PACKAGE_NONE;
761 params.paperpackage = tmpret;
762 } else if (token == "\\use_geometry") {
764 params.use_geometry = lex.GetInteger();
765 } else if (token == "\\use_amsmath") {
767 params.use_amsmath = lex.GetInteger();
768 } else if (token == "\\use_natbib") {
770 params.use_natbib = lex.GetInteger();
771 } else if (token == "\\use_numerical_citations") {
773 params.use_numerical_citations = lex.GetInteger();
774 } else if (token == "\\paperorientation") {
775 int tmpret = lex.FindToken(string_orientation);
776 if (tmpret == -1) ++tmpret;
777 if (tmpret != LYX_LAYOUT_DEFAULT)
778 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
779 } else if (token == "\\paperwidth") {
781 params.paperwidth = lex.GetString();
782 } else if (token == "\\paperheight") {
784 params.paperheight = lex.GetString();
785 } else if (token == "\\leftmargin") {
787 params.leftmargin = lex.GetString();
788 } else if (token == "\\topmargin") {
790 params.topmargin = lex.GetString();
791 } else if (token == "\\rightmargin") {
793 params.rightmargin = lex.GetString();
794 } else if (token == "\\bottommargin") {
796 params.bottommargin = lex.GetString();
797 } else if (token == "\\headheight") {
799 params.headheight = lex.GetString();
800 } else if (token == "\\headsep") {
802 params.headsep = lex.GetString();
803 } else if (token == "\\footskip") {
805 params.footskip = lex.GetString();
806 } else if (token == "\\paperfontsize") {
808 params.fontsize = strip(lex.GetString());
809 } else if (token == "\\papercolumns") {
811 params.columns = lex.GetInteger();
812 } else if (token == "\\papersides") {
814 switch (lex.GetInteger()) {
816 case 1: params.sides = LyXTextClass::OneSide; break;
817 case 2: params.sides = LyXTextClass::TwoSides; break;
819 } else if (token == "\\paperpagestyle") {
821 params.pagestyle = strip(lex.GetString());
822 } else if (token == "\\bullet") {
824 int const index = lex.GetInteger();
826 int temp_int = lex.GetInteger();
827 params.user_defined_bullets[index].setFont(temp_int);
828 params.temp_bullets[index].setFont(temp_int);
830 temp_int = lex.GetInteger();
831 params.user_defined_bullets[index].setCharacter(temp_int);
832 params.temp_bullets[index].setCharacter(temp_int);
834 temp_int = lex.GetInteger();
835 params.user_defined_bullets[index].setSize(temp_int);
836 params.temp_bullets[index].setSize(temp_int);
838 string const temp_str = lex.GetString();
839 if (temp_str != "\\end_bullet") {
840 // this element isn't really necessary for
841 // parsing but is easier for humans
842 // to understand bullets. Put it back and
843 // set a debug message?
844 lex.printError("\\end_bullet expected, got" + temp_str);
845 //how can I put it back?
847 } else if (token == "\\bulletLaTeX") {
849 int const index = lex.GetInteger();
851 string temp_str = lex.GetString();
853 while (temp_str != "\\end_bullet") {
854 // this loop structure is needed when user
855 // enters an empty string since the first
856 // thing returned will be the \\end_bullet
858 // if the LaTeX entry has spaces. Each element
859 // therefore needs to be read in turn
862 temp_str = lex.GetString();
864 params.user_defined_bullets[index].setText(sum_str);
865 params.temp_bullets[index].setText(sum_str);
866 } else if (token == "\\secnumdepth") {
868 params.secnumdepth = lex.GetInteger();
869 } else if (token == "\\tocdepth") {
871 params.tocdepth = lex.GetInteger();
872 } else if (token == "\\spacing") {
874 string const tmp = strip(lex.GetString());
875 Spacing::Space tmp_space = Spacing::Default;
877 if (tmp == "single") {
878 tmp_space = Spacing::Single;
879 } else if (tmp == "onehalf") {
880 tmp_space = Spacing::Onehalf;
881 } else if (tmp == "double") {
882 tmp_space = Spacing::Double;
883 } else if (tmp == "other") {
885 tmp_space = Spacing::Other;
886 tmp_val = lex.GetFloat();
888 lex.printError("Unknown spacing token: '$$Token'");
890 // Small hack so that files written with klyx will be
893 par->params().spacing(Spacing(tmp_space, tmp_val));
895 params.spacing.set(tmp_space, tmp_val);
897 } else if (token == "\\paragraph_spacing") {
899 string const tmp = strip(lex.GetString());
900 if (tmp == "single") {
901 par->params().spacing(Spacing(Spacing::Single));
902 } else if (tmp == "onehalf") {
903 par->params().spacing(Spacing(Spacing::Onehalf));
904 } else if (tmp == "double") {
905 par->params().spacing(Spacing(Spacing::Double));
906 } else if (tmp == "other") {
908 par->params().spacing(Spacing(Spacing::Other,
911 lex.printError("Unknown spacing token: '$$Token'");
913 } else if (token == "\\float_placement") {
915 params.float_placement = lex.GetString();
916 } else if (token == "\\family") {
918 font.setLyXFamily(lex.GetString());
919 } else if (token == "\\series") {
921 font.setLyXSeries(lex.GetString());
922 } else if (token == "\\shape") {
924 font.setLyXShape(lex.GetString());
925 } else if (token == "\\size") {
927 font.setLyXSize(lex.GetString());
930 #warning compatability hack needed
932 } else if (token == "\\latex") {
934 string const tok = lex.GetString();
935 // This is dirty, but gone with LyX3. (Asger)
936 if (tok == "no_latex")
937 font.setLatex(LyXFont::OFF);
938 else if (tok == "latex")
939 font.setLatex(LyXFont::ON);
940 else if (tok == "default")
941 font.setLatex(LyXFont::INHERIT);
943 lex.printError("Unknown LaTeX font flag "
946 } else if (token == "\\latex") {
948 string const tok = lex.GetString();
949 if (tok == "no_latex") {
951 insertErtContents(par, pos, font);
952 } else if (tok == "latex") {
953 ert_comp.active = true;
954 } else if (tok == "default") {
956 insertErtContents(par, pos, font);
958 lex.printError("Unknown LaTeX font flag "
962 } else if (token == "\\lang") {
964 string const tok = lex.GetString();
965 Language const * lang = languages.getLanguage(tok);
967 font.setLanguage(lang);
969 font.setLanguage(params.language);
970 lex.printError("Unknown language `$$Token'");
972 } else if (token == "\\numeric") {
974 font.setNumber(font.setLyXMisc(lex.GetString()));
975 } else if (token == "\\emph") {
977 font.setEmph(font.setLyXMisc(lex.GetString()));
978 } else if (token == "\\bar") {
980 string const tok = lex.GetString();
981 // This is dirty, but gone with LyX3. (Asger)
983 font.setUnderbar(LyXFont::ON);
984 else if (tok == "no")
985 font.setUnderbar(LyXFont::OFF);
986 else if (tok == "default")
987 font.setUnderbar(LyXFont::INHERIT);
989 lex.printError("Unknown bar font flag "
991 } else if (token == "\\noun") {
993 font.setNoun(font.setLyXMisc(lex.GetString()));
994 } else if (token == "\\color") {
996 font.setLyXColor(lex.GetString());
997 } else if (token == "\\align") {
998 int tmpret = lex.FindToken(string_align);
999 if (tmpret == -1) ++tmpret;
1000 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1001 int const tmpret2 = int(pow(2.0, tmpret));
1002 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1003 par->params().align(LyXAlignment(tmpret2));
1005 } else if (token == "\\added_space_top") {
1007 par->params().spaceTop(VSpace(lex.GetString()));
1008 } else if (token == "\\added_space_bottom") {
1010 par->params().spaceBottom(VSpace(lex.GetString()));
1011 #ifndef NO_PEXTRA_REALLY
1012 } else if (token == "\\pextra_type") {
1014 par->params().pextraType(lex.GetInteger());
1015 } else if (token == "\\pextra_width") {
1017 par->params().pextraWidth(lex.GetString());
1018 } else if (token == "\\pextra_widthp") {
1020 par->params().pextraWidthp(lex.GetString());
1021 } else if (token == "\\pextra_alignment") {
1023 par->params().pextraAlignment(lex.GetInteger());
1024 } else if (token == "\\pextra_hfill") {
1026 par->params().pextraHfill(lex.GetInteger());
1027 } else if (token == "\\pextra_start_minipage") {
1029 par->params().pextraStartMinipage(lex.GetInteger());
1031 } else if (token == "\\labelwidthstring") {
1033 par->params().labelWidthString(lex.GetString());
1034 // do not delete this token, it is still needed!
1035 } else if (token == "\\end_inset") {
1036 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1037 << "Last inset read was: " << last_inset_read
1039 // Simply ignore this. The insets do not have
1041 // But insets should read it, it is a part of
1042 // the inset isn't it? Lgb.
1043 } else if (token == "\\begin_inset") {
1044 // Does this fix it? YES!
1045 checkminipage = true;
1048 insertErtContents(par, pos, font, false);
1049 ert_stack.push(ert_comp);
1050 ert_comp = ErtComp();
1052 readInset(lex, par, pos, font);
1054 ert_comp = ert_stack.top();
1057 } else if (token == "\\SpecialChar") {
1058 LyXLayout const & layout =
1059 textclasslist.Style(params.textclass,
1062 // Insets don't make sense in a free-spacing context! ---Kayvan
1063 if (layout.free_spacing) {
1066 string next_token = lex.GetString();
1067 if (next_token == "\\-") {
1068 par->insertChar(pos, '-', font);
1069 } else if (next_token == "\\protected_separator"
1070 || next_token == "~") {
1071 par->insertChar(pos, ' ', font);
1073 lex.printError("Token `$$Token' "
1075 "paragraph layout!");
1080 Inset * inset = new InsetSpecialChar;
1081 inset->read(this, lex);
1082 par->insertInset(pos, inset, font);
1085 } else if (token == "\\newline") {
1088 if (!ert_comp.in_tabular && ert_comp.active) {
1089 ert_comp.contents += char(Paragraph::META_NEWLINE);
1091 // Since we cannot know it this is only a regular
1092 // newline or a tabular cell delimter we have to
1093 // handle the ERT here.
1094 insertErtContents(par, pos, font, false);
1096 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1100 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1103 } else if (token == "\\LyXTable") {
1105 ert_comp.in_tabular = true;
1107 Inset * inset = new InsetTabular(*this);
1108 inset->read(this, lex);
1109 par->insertInset(pos, inset, font);
1111 // because of OLD_TABULAR_READ where tabulars have been
1113 checkminipage = true;
1114 } else if (token == "\\hfill") {
1115 par->insertChar(pos, Paragraph::META_HFILL, font);
1117 } else if (token == "\\protected_separator") { // obsolete
1118 // This is a backward compability thingie. (Lgb)
1119 // Remove it later some time...introduced with fileformat
1121 LyXLayout const & layout =
1122 textclasslist.Style(params.textclass,
1125 if (layout.free_spacing) {
1126 par->insertChar(pos, ' ', font);
1128 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1129 par->insertInset(pos, inset, font);
1132 } else if (token == "\\bibitem") { // ale970302
1134 InsetCommandParams p("bibitem", "dummy");
1135 par->bibkey = new InsetBibKey(p);
1137 par->bibkey->read(this, lex);
1138 } else if (token == "\\backslash") {
1140 if (ert_comp.active) {
1141 ert_comp.contents += "\\";
1144 par->insertChar(pos, '\\', font);
1149 } else if (token == "\\the_end") {
1151 // If we still have some ert active here we have to insert
1152 // it so we don't loose it. (Lgb)
1153 insertErtContents(par, pos, font);
1155 the_end_read = true;
1156 minipar = parBeforeMinipage = 0;
1159 if (ert_comp.active) {
1160 ert_comp.contents += token;
1163 // This should be insurance for the future: (Asger)
1164 lex.printError("Unknown token `$$Token'. "
1165 "Inserting as text.");
1166 string::const_iterator cit = token.begin();
1167 string::const_iterator end = token.end();
1168 for (; cit != end; ++cit) {
1169 par->insertChar(pos, (*cit), font);
1176 #ifndef NO_PEXTRA_REALLY
1177 // now check if we have a minipage paragraph as at this
1178 // point we already read all the necessary data!
1179 // this cannot be done in layout because there we did
1180 // not read yet the paragraph PEXTRA-params (Jug)
1182 // BEGIN pextra_minipage compability
1183 // This should be removed in 1.3.x (Lgb)
1185 // This compability code is not perfect. In a couple
1186 // of rand cases it fails. When the minipage par is
1187 // the first par in the document, and when there are
1188 // none or only one regular paragraphs after the
1189 // minipage. Currently I am not investing any effort
1190 // in fixing those cases.
1192 //lyxerr << "Call depth: " << call_depth << endl;
1193 if (checkminipage && (call_depth == 1)) {
1194 checkminipage = false;
1195 if (minipar && (minipar != par) &&
1196 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1198 lyxerr << "minipages in a row" << endl;
1199 if (par->params().pextraStartMinipage()) {
1200 lyxerr << "start new minipage" << endl;
1201 // minipages in a row
1202 par->previous()->next(0);
1205 Paragraph * tmp = minipar;
1207 tmp->params().pextraType(0);
1208 tmp->params().pextraWidth(string());
1209 tmp->params().pextraWidthp(string());
1210 tmp->params().pextraAlignment(0);
1211 tmp->params().pextraHfill(false);
1212 tmp->params().pextraStartMinipage(false);
1215 // create a new paragraph to insert the
1216 // minipages in the following case
1217 if (par->params().pextraStartMinipage() &&
1218 !par->params().pextraHfill())
1220 Paragraph * p = new Paragraph;
1222 p->previous(parBeforeMinipage);
1223 parBeforeMinipage->next(p);
1225 p->params().depth(parBeforeMinipage->params().depth());
1226 parBeforeMinipage = p;
1228 InsetMinipage * mini = new InsetMinipage;
1229 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1230 mini->width(par->params().pextraWidth());
1231 if (!par->params().pextraWidthp().empty()) {
1232 lyxerr << "WP:" << mini->width() << endl;
1233 mini->width(tostr(par->params().pextraWidthp())+"%");
1235 mini->inset.paragraph(par);
1236 // Insert the minipage last in the
1237 // previous paragraph.
1238 if (par->params().pextraHfill()) {
1239 parBeforeMinipage->insertChar
1240 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1242 parBeforeMinipage->insertInset
1243 (parBeforeMinipage->size(), mini);
1247 lyxerr << "new minipage par" << endl;
1248 //nothing to do just continue reading
1251 } else if (minipar && (minipar != par)) {
1252 lyxerr << "last minipage par read" << endl;
1253 // The last paragraph read was not part of a
1254 // minipage but the par linked list is...
1255 // So we need to remove the last par from the
1257 if (par->previous())
1258 par->previous()->next(0);
1259 par->previous(parBeforeMinipage);
1260 parBeforeMinipage->next(par);
1261 Paragraph * tmp = minipar;
1263 tmp->params().pextraType(0);
1264 tmp->params().pextraWidth(string());
1265 tmp->params().pextraWidthp(string());
1266 tmp->params().pextraAlignment(0);
1267 tmp->params().pextraHfill(false);
1268 tmp->params().pextraStartMinipage(false);
1271 depth = parBeforeMinipage->params().depth();
1272 minipar = parBeforeMinipage = 0;
1273 } else if (!minipar &&
1274 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1276 // par is the first paragraph in a minipage
1277 lyxerr << "begin minipage" << endl;
1278 // To minimize problems for
1279 // the users we will insert
1280 // the first minipage in
1281 // a sequence of minipages
1282 // in its own paragraph.
1283 Paragraph * p = new Paragraph;
1285 p->previous(par->previous());
1287 p->params().depth(depth);
1288 par->params().depth(0);
1290 if (par->previous())
1291 par->previous()->next(p);
1293 parBeforeMinipage = p;
1295 if (!first_par || (first_par == par))
1298 InsetMinipage * mini = new InsetMinipage;
1299 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1300 mini->width(minipar->params().pextraWidth());
1301 if (!par->params().pextraWidthp().empty()) {
1302 lyxerr << "WP:" << mini->width() << endl;
1303 mini->width(tostr(par->params().pextraWidthp())+"%");
1305 mini->inset.paragraph(minipar);
1307 // Insert the minipage last in the
1308 // previous paragraph.
1309 if (minipar->params().pextraHfill()) {
1310 parBeforeMinipage->insertChar
1311 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1313 parBeforeMinipage->insertInset
1314 (parBeforeMinipage->size(), mini);
1317 // End of pextra_minipage compability
1320 return the_end_read;
1323 // needed to insert the selection
1324 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1325 LyXFont const & font,
1326 string const & str) const
1328 LyXLayout const & layout = textclasslist.Style(params.textclass,
1330 // insert the string, don't insert doublespace
1331 bool space_inserted = true;
1332 for(string::const_iterator cit = str.begin();
1333 cit != str.end(); ++cit) {
1335 if (par->size() || layout.keepempty) {
1336 par->breakParagraph(params, pos,
1337 layout.isEnvironment());
1340 space_inserted = true;
1344 // do not insert consecutive spaces if !free_spacing
1345 } else if ((*cit == ' ' || *cit == '\t')
1346 && space_inserted && !layout.free_spacing) {
1348 } else if (*cit == '\t') {
1349 if (!layout.free_spacing) {
1350 // tabs are like spaces here
1351 par->insertChar(pos, ' ', font);
1353 space_inserted = true;
1355 const Paragraph::value_type nb = 8 - pos % 8;
1356 for (Paragraph::size_type a = 0;
1358 par->insertChar(pos, ' ', font);
1361 space_inserted = true;
1363 } else if (!IsPrintable(*cit)) {
1364 // Ignore unprintables
1367 // just insert the character
1368 par->insertChar(pos, *cit, font);
1370 space_inserted = (*cit == ' ');
1377 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1378 int & pos, LyXFont & font)
1380 // consistency check
1381 if (lex.GetString() != "\\begin_inset") {
1382 lyxerr << "Buffer::readInset: Consistency check failed."
1389 string const tmptok = lex.GetString();
1390 last_inset_read = tmptok;
1392 // test the different insets
1393 if (tmptok == "LatexCommand") {
1394 InsetCommandParams inscmd;
1397 string const cmdName = inscmd.getCmdName();
1399 // This strange command allows LyX to recognize "natbib" style
1400 // citations: citet, citep, Citet etc.
1401 if (compare_no_case(cmdName, "cite", 4) == 0) {
1402 inset = new InsetCitation(inscmd);
1403 } else if (cmdName == "bibitem") {
1404 lex.printError("Wrong place for bibitem");
1405 inset = new InsetBibKey(inscmd);
1406 } else if (cmdName == "BibTeX") {
1407 inset = new InsetBibtex(inscmd);
1408 } else if (cmdName == "index") {
1409 inset = new InsetIndex(inscmd);
1410 } else if (cmdName == "include") {
1411 inset = new InsetInclude(inscmd, *this);
1412 } else if (cmdName == "label") {
1413 inset = new InsetLabel(inscmd);
1414 } else if (cmdName == "url"
1415 || cmdName == "htmlurl") {
1416 inset = new InsetUrl(inscmd);
1417 } else if (cmdName == "ref"
1418 || cmdName == "pageref"
1419 || cmdName == "vref"
1420 || cmdName == "vpageref"
1421 || cmdName == "prettyref") {
1422 if (!inscmd.getOptions().empty()
1423 || !inscmd.getContents().empty()) {
1424 inset = new InsetRef(inscmd, *this);
1426 } else if (cmdName == "tableofcontents") {
1427 inset = new InsetTOC(inscmd);
1428 } else if (cmdName == "listofalgorithms") {
1429 inset = new InsetFloatList("algorithm");
1430 } else if (cmdName == "listoffigures") {
1431 inset = new InsetFloatList("figure");
1432 } else if (cmdName == "listoftables") {
1433 inset = new InsetFloatList("table");
1434 } else if (cmdName == "printindex") {
1435 inset = new InsetPrintIndex(inscmd);
1436 } else if (cmdName == "lyxparent") {
1437 inset = new InsetParent(inscmd, *this);
1440 bool alreadyread = false;
1441 if (tmptok == "Quotes") {
1442 inset = new InsetQuotes;
1443 } else if (tmptok == "External") {
1444 inset = new InsetExternal;
1445 } else if (tmptok == "FormulaMacro") {
1446 inset = new InsetFormulaMacro;
1447 } else if (tmptok == "Formula") {
1448 inset = new InsetFormula;
1449 } else if (tmptok == "Figure") {
1450 inset = new InsetFig(100, 100, *this);
1451 } else if (tmptok == "Info") {// backwards compatibility
1452 inset = new InsetNote(this,
1453 lex.getLongString("\\end_inset"),
1456 } else if (tmptok == "Note") {
1457 inset = new InsetNote;
1458 } else if (tmptok == "Include") {
1459 InsetCommandParams p( "Include" );
1460 inset = new InsetInclude(p, *this);
1461 } else if (tmptok == "ERT") {
1462 inset = new InsetERT;
1463 } else if (tmptok == "Tabular") {
1464 inset = new InsetTabular(*this);
1465 } else if (tmptok == "Text") {
1466 inset = new InsetText;
1467 } else if (tmptok == "Foot") {
1468 inset = new InsetFoot;
1469 } else if (tmptok == "Marginal") {
1470 inset = new InsetMarginal;
1471 } else if (tmptok == "Minipage") {
1472 inset = new InsetMinipage;
1473 } else if (tmptok == "Float") {
1475 string tmptok = lex.GetString();
1476 inset = new InsetFloat(tmptok);
1478 } else if (tmptok == "List") {
1479 inset = new InsetList;
1480 } else if (tmptok == "Theorem") {
1481 inset = new InsetList;
1483 } else if (tmptok == "Caption") {
1484 inset = new InsetCaption;
1485 } else if (tmptok == "GRAPHICS") {
1486 inset = new InsetGraphics;
1487 } else if (tmptok == "FloatList") {
1488 inset = new InsetFloatList;
1491 if (inset && !alreadyread) inset->read(this, lex);
1495 par->insertInset(pos, inset, font);
1501 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1505 string const token(lex.GetString());
1506 if (token == "\\lyxformat") { // the first token _must_ be...
1508 string tmp_format = lex.GetString();
1509 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1510 // if present remove ".," from string.
1511 string::size_type dot = tmp_format.find_first_of(".,");
1512 //lyxerr << " dot found at " << dot << endl;
1513 if (dot != string::npos)
1514 tmp_format.erase(dot, 1);
1515 file_format = strToInt(tmp_format);
1516 if (file_format == LYX_FORMAT) {
1518 } else if (file_format > LYX_FORMAT) {
1520 WriteAlert(_("Warning!"),
1521 _("LyX file format is newer that what"),
1522 _("is supported in this LyX version. Expect some problems."));
1524 } else if (file_format < LYX_FORMAT) {
1526 if (file_format < 200) {
1527 WriteAlert(_("ERROR!"),
1528 _("Old LyX file format found. "
1529 "Use LyX 0.10.x to read this!"));
1533 bool the_end = readLyXformat2(lex, par);
1535 // the_end was added in 213
1536 if (file_format < 213)
1540 WriteAlert(_("Warning!"),
1541 _("Reading of document is not complete"),
1542 _("Maybe the document is truncated"));
1544 } else { // "\\lyxformat" not found
1545 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1548 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1553 // Should probably be moved to somewhere else: BufferView? LyXView?
1554 bool Buffer::save() const
1556 // We don't need autosaves in the immediate future. (Asger)
1557 resetAutosaveTimers();
1561 if (lyxrc.make_backup) {
1562 s = fileName() + '~';
1563 if (!lyxrc.backupdir_path.empty())
1564 s = AddName(lyxrc.backupdir_path,
1565 subst(os::slashify_path(s),'/','!'));
1567 // Rename is the wrong way of making a backup,
1568 // this is the correct way.
1569 /* truss cp fil fil2:
1570 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1571 stat("LyXVC.lyx", 0xEFFFF688) = 0
1572 open("LyXVC.lyx", O_RDONLY) = 3
1573 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1574 fstat(4, 0xEFFFF508) = 0
1575 fstat(3, 0xEFFFF508) = 0
1576 read(3, " # T h i s f i l e w".., 8192) = 5579
1577 write(4, " # T h i s f i l e w".., 5579) = 5579
1578 read(3, 0xEFFFD4A0, 8192) = 0
1581 chmod("LyXVC3.lyx", 0100644) = 0
1582 lseek(0, 0, SEEK_CUR) = 46440
1586 // Should probably have some more error checking here.
1587 // Should be cleaned up in 0.13, at least a bit.
1588 // Doing it this way, also makes the inodes stay the same.
1589 // This is still not a very good solution, in particular we
1590 // might loose the owner of the backup.
1591 FileInfo finfo(fileName());
1592 if (finfo.exist()) {
1593 mode_t fmode = finfo.getMode();
1594 struct utimbuf times = {
1595 finfo.getAccessTime(),
1596 finfo.getModificationTime() };
1598 ifstream ifs(fileName().c_str());
1599 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1604 ::chmod(s.c_str(), fmode);
1606 if (::utime(s.c_str(), ×)) {
1607 lyxerr << "utime error." << endl;
1610 lyxerr << "LyX was not able to make "
1611 "backup copy. Beware." << endl;
1616 if (writeFile(fileName(), false)) {
1618 removeAutosaveFile(fileName());
1620 // Saving failed, so backup is not backup
1621 if (lyxrc.make_backup) {
1622 lyx::rename(s, fileName());
1630 // Returns false if unsuccesful
1631 bool Buffer::writeFile(string const & fname, bool flag) const
1633 // if flag is false writeFile will not create any GUI
1634 // warnings, only cerr.
1635 // Needed for autosave in background or panic save (Matthias 120496)
1637 if (read_only && (fname == filename)) {
1638 // Here we should come with a question if we should
1639 // perform the write anyway.
1641 lyxerr << _("Error! Document is read-only: ")
1644 WriteAlert(_("Error! Document is read-only: "),
1649 FileInfo finfo(fname);
1650 if (finfo.exist() && !finfo.writable()) {
1651 // Here we should come with a question if we should
1652 // try to do the save anyway. (i.e. do a chmod first)
1654 lyxerr << _("Error! Cannot write file: ")
1657 WriteFSAlert(_("Error! Cannot write file: "),
1662 ofstream ofs(fname.c_str());
1665 lyxerr << _("Error! Cannot open file: ")
1668 WriteFSAlert(_("Error! Cannot open file: "),
1674 // Use the standard "C" locale for file output.
1675 ofs.imbue(std::locale::classic());
1678 // The top of the file should not be written by params.
1680 // write out a comment in the top of the file
1681 ofs << '#' << LYX_DOCVERSION
1682 << " created this file. For more info see http://www.lyx.org/\n"
1683 << "\\lyxformat " << LYX_FORMAT << "\n";
1685 // now write out the buffer paramters.
1686 params.writeFile(ofs);
1688 Paragraph::depth_type depth = 0;
1690 // this will write out all the paragraphs
1691 // using recursive descent.
1692 paragraph->writeFile(this, ofs, params, depth);
1694 // Write marker that shows file is complete
1695 ofs << "\n\\the_end" << endl;
1699 // how to check if close went ok?
1700 // Following is an attempt... (BE 20001011)
1702 // good() returns false if any error occured, including some
1703 // formatting error.
1704 // bad() returns true if something bad happened in the buffer,
1705 // which should include file system full errors.
1712 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1714 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1724 string const Buffer::asciiParagraph(Paragraph const * par,
1725 unsigned int linelen) const
1727 ostringstream buffer;
1728 Paragraph::depth_type depth = 0;
1730 Paragraph::depth_type ltype_depth = 0;
1731 unsigned int currlinelen = 0;
1732 bool ref_printed = false;
1736 if (!par->previous()) {
1737 // begins or ends a deeper area ?
1738 if (depth != par->params().depth()) {
1739 if (par->params().depth() > depth) {
1740 while (par->params().depth() > depth) {
1744 while (par->params().depth() < depth) {
1750 // First write the layout
1751 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1752 if (tmp == "Itemize") {
1754 ltype_depth = depth + 1;
1755 } else if (tmp == "Enumerate") {
1757 ltype_depth = depth + 1;
1758 } else if (contains(tmp, "ection")) {
1760 ltype_depth = depth + 1;
1761 } else if (contains(tmp, "aragraph")) {
1763 ltype_depth = depth + 1;
1764 } else if (tmp == "Description") {
1766 ltype_depth = depth + 1;
1767 } else if (tmp == "Abstract") {
1770 } else if (tmp == "Bibliography") {
1778 /* maybe some vertical spaces */
1780 /* the labelwidthstring used in lists */
1784 /* some pagebreaks? */
1788 /* what about the alignment */
1790 lyxerr << "Should this ever happen?" << endl;
1794 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1796 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1797 if (!i && !noparbreak) {
1800 for (Paragraph::depth_type j = 0; j < depth; ++j)
1802 currlinelen = depth * 2;
1805 case 4: // (Sub)Paragraph
1806 case 5: // Description
1810 buffer << "Abstract\n\n";
1812 buffer << "Abstract: ";
1814 case 7: // Bibliography
1817 buffer << "References\n\n";
1819 buffer << "References: ";
1824 buffer << par->params().labelString() << " ";
1827 if (ltype_depth > depth) {
1828 for (Paragraph::depth_type j = ltype_depth - 1;
1831 currlinelen += (ltype_depth-depth)*2;
1835 LyXFont const font2 = par->getFontSettings(params, i);
1836 if (font1.latex() != font2.latex()) {
1837 if (font2.latex() == LyXFont::OFF)
1846 char c = par->getUChar(params, i);
1850 case Paragraph::META_INSET:
1852 Inset const * inset = par->getInset(i);
1854 if (!inset->ascii(this, buffer)) {
1857 rsplit(buffer.str().c_str(),
1859 currlinelen += s.length();
1861 // to be sure it breaks paragraph
1862 currlinelen += linelen;
1868 case Paragraph::META_NEWLINE:
1871 for (Paragraph::depth_type j = 0;
1875 currlinelen = depth * 2;
1876 if (ltype_depth > depth) {
1877 for (Paragraph::depth_type j = ltype_depth;
1880 currlinelen += (ltype_depth - depth) * 2;
1884 case Paragraph::META_HFILL:
1893 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1894 (c == ' ') && ((i + 2) < par->size()))
1897 for (Paragraph::depth_type j = 0;
1900 currlinelen = depth * 2;
1901 if (ltype_depth > depth) {
1902 for (Paragraph::depth_type j = ltype_depth;
1905 currlinelen += (ltype_depth-depth)*2;
1907 } else if (c != '\0')
1910 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1915 return buffer.str().c_str();
1919 void Buffer::writeFileAscii(string const & fname, int linelen)
1921 ofstream ofs(fname.c_str());
1923 WriteFSAlert(_("Error: Cannot write file:"), fname);
1926 writeFileAscii(ofs, linelen);
1930 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1932 Paragraph * par = paragraph;
1934 ofs << asciiParagraph(par, linelen);
1942 void Buffer::makeLaTeXFile(string const & fname,
1943 string const & original_path,
1944 bool nice, bool only_body)
1946 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1948 niceFile = nice; // this will be used by Insetincludes.
1950 tex_code_break_column = lyxrc.ascii_linelen;
1952 LyXTextClass const & tclass =
1953 textclasslist.TextClass(params.textclass);
1955 ofstream ofs(fname.c_str());
1957 WriteFSAlert(_("Error: Cannot open file: "), fname);
1961 // validate the buffer.
1962 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1963 LaTeXFeatures features(params, tclass.numLayouts());
1965 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1968 // The starting paragraph of the coming rows is the
1969 // first paragraph of the document. (Asger)
1970 texrow.start(paragraph, 0);
1972 if (!only_body && nice) {
1973 ofs << "%% " LYX_DOCVERSION " created this file. "
1974 "For more info, see http://www.lyx.org/.\n"
1975 "%% Do not edit unless you really know what "
1980 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1981 // There are a few differences between nice LaTeX and usual files:
1982 // usual is \batchmode and has a
1983 // special input@path to allow the including of figures
1984 // with either \input or \includegraphics (what figinsets do).
1985 // batchmode is not set if there is a tex_code_break_column.
1986 // In this case somebody is interested in the generated LaTeX,
1987 // so this is OK. input@path is set when the actual parameter
1988 // original_path is set. This is done for usual tex-file, but not
1989 // for nice-latex-file. (Matthias 250696)
1992 // code for usual, NOT nice-latex-file
1993 ofs << "\\batchmode\n"; // changed
1994 // from \nonstopmode
1997 if (!original_path.empty()) {
1998 ofs << "\\makeatletter\n"
1999 << "\\def\\input@path{{"
2000 << os::external_path(original_path) << "/}}\n"
2001 << "\\makeatother\n";
2007 ofs << "\\documentclass";
2009 ostringstream options; // the document class options.
2011 if (tokenPos(tclass.opt_fontsize(),
2012 '|', params.fontsize) >= 0) {
2013 // only write if existing in list (and not default)
2014 options << params.fontsize << "pt,";
2018 if (!params.use_geometry &&
2019 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2020 switch (params.papersize) {
2021 case BufferParams::PAPER_A4PAPER:
2022 options << "a4paper,";
2024 case BufferParams::PAPER_USLETTER:
2025 options << "letterpaper,";
2027 case BufferParams::PAPER_A5PAPER:
2028 options << "a5paper,";
2030 case BufferParams::PAPER_B5PAPER:
2031 options << "b5paper,";
2033 case BufferParams::PAPER_EXECUTIVEPAPER:
2034 options << "executivepaper,";
2036 case BufferParams::PAPER_LEGALPAPER:
2037 options << "legalpaper,";
2043 if (params.sides != tclass.sides()) {
2044 switch (params.sides) {
2045 case LyXTextClass::OneSide:
2046 options << "oneside,";
2048 case LyXTextClass::TwoSides:
2049 options << "twoside,";
2055 if (params.columns != tclass.columns()) {
2056 if (params.columns == 2)
2057 options << "twocolumn,";
2059 options << "onecolumn,";
2062 if (!params.use_geometry
2063 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2064 options << "landscape,";
2066 // language should be a parameter to \documentclass
2068 ostringstream language_options;
2069 if (params.language->babel() == "hebrew"
2070 && default_language->babel() != "hebrew")
2071 // This seems necessary
2072 features.UsedLanguages.insert(default_language);
2074 if (lyxrc.language_use_babel ||
2075 params.language->lang() != lyxrc.default_language ||
2076 !features.UsedLanguages.empty()) {
2078 for (LaTeXFeatures::LanguageList::const_iterator cit =
2079 features.UsedLanguages.begin();
2080 cit != features.UsedLanguages.end(); ++cit)
2081 language_options << (*cit)->babel() << ',';
2082 language_options << params.language->babel();
2083 if (lyxrc.language_global_options)
2084 options << language_options.str() << ',';
2087 // the user-defined options
2088 if (!params.options.empty()) {
2089 options << params.options << ',';
2092 string strOptions(options.str().c_str());
2093 if (!strOptions.empty()){
2094 strOptions = strip(strOptions, ',');
2095 ofs << '[' << strOptions << ']';
2099 << textclasslist.LatexnameOfClass(params.textclass)
2102 // end of \documentclass defs
2104 // font selection must be done before loading fontenc.sty
2105 // The ae package is not needed when using OT1 font encoding.
2106 if (params.fonts != "default" &&
2107 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2108 ofs << "\\usepackage{" << params.fonts << "}\n";
2110 if (params.fonts == "ae") {
2111 ofs << "\\usepackage{aecompl}\n";
2115 // this one is not per buffer
2116 if (lyxrc.fontenc != "default") {
2117 ofs << "\\usepackage[" << lyxrc.fontenc
2122 if (params.inputenc == "auto") {
2123 string const doc_encoding =
2124 params.language->encoding()->LatexName();
2126 // Create a list with all the input encodings used
2128 set<string> encodings;
2129 for (LaTeXFeatures::LanguageList::const_iterator it =
2130 features.UsedLanguages.begin();
2131 it != features.UsedLanguages.end(); ++it)
2132 if ((*it)->encoding()->LatexName() != doc_encoding)
2133 encodings.insert((*it)->encoding()->LatexName());
2135 ofs << "\\usepackage[";
2136 std::copy(encodings.begin(), encodings.end(),
2137 std::ostream_iterator<string>(ofs, ","));
2138 ofs << doc_encoding << "]{inputenc}\n";
2140 } else if (params.inputenc != "default") {
2141 ofs << "\\usepackage[" << params.inputenc
2146 // At the very beginning the text parameters.
2147 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2148 switch (params.paperpackage) {
2149 case BufferParams::PACKAGE_A4:
2150 ofs << "\\usepackage{a4}\n";
2153 case BufferParams::PACKAGE_A4WIDE:
2154 ofs << "\\usepackage{a4wide}\n";
2157 case BufferParams::PACKAGE_WIDEMARGINSA4:
2158 ofs << "\\usepackage[widemargins]{a4}\n";
2163 if (params.use_geometry) {
2164 ofs << "\\usepackage{geometry}\n";
2166 ofs << "\\geometry{verbose";
2167 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2168 ofs << ",landscape";
2169 switch (params.papersize2) {
2170 case BufferParams::VM_PAPER_CUSTOM:
2171 if (!params.paperwidth.empty())
2172 ofs << ",paperwidth="
2173 << params.paperwidth;
2174 if (!params.paperheight.empty())
2175 ofs << ",paperheight="
2176 << params.paperheight;
2178 case BufferParams::VM_PAPER_USLETTER:
2179 ofs << ",letterpaper";
2181 case BufferParams::VM_PAPER_USLEGAL:
2182 ofs << ",legalpaper";
2184 case BufferParams::VM_PAPER_USEXECUTIVE:
2185 ofs << ",executivepaper";
2187 case BufferParams::VM_PAPER_A3:
2190 case BufferParams::VM_PAPER_A4:
2193 case BufferParams::VM_PAPER_A5:
2196 case BufferParams::VM_PAPER_B3:
2199 case BufferParams::VM_PAPER_B4:
2202 case BufferParams::VM_PAPER_B5:
2206 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2207 switch (lyxrc.default_papersize) {
2208 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2209 case BufferParams::PAPER_USLETTER:
2210 ofs << ",letterpaper";
2212 case BufferParams::PAPER_LEGALPAPER:
2213 ofs << ",legalpaper";
2215 case BufferParams::PAPER_EXECUTIVEPAPER:
2216 ofs << ",executivepaper";
2218 case BufferParams::PAPER_A3PAPER:
2221 case BufferParams::PAPER_A4PAPER:
2224 case BufferParams::PAPER_A5PAPER:
2227 case BufferParams::PAPER_B5PAPER:
2232 if (!params.topmargin.empty())
2233 ofs << ",tmargin=" << params.topmargin;
2234 if (!params.bottommargin.empty())
2235 ofs << ",bmargin=" << params.bottommargin;
2236 if (!params.leftmargin.empty())
2237 ofs << ",lmargin=" << params.leftmargin;
2238 if (!params.rightmargin.empty())
2239 ofs << ",rmargin=" << params.rightmargin;
2240 if (!params.headheight.empty())
2241 ofs << ",headheight=" << params.headheight;
2242 if (!params.headsep.empty())
2243 ofs << ",headsep=" << params.headsep;
2244 if (!params.footskip.empty())
2245 ofs << ",footskip=" << params.footskip;
2249 if (features.amsstyle
2250 && !tclass.provides(LyXTextClass::amsmath)) {
2251 ofs << "\\usepackage{amsmath}\n";
2255 if (tokenPos(tclass.opt_pagestyle(),
2256 '|', params.pagestyle) >= 0) {
2257 if (params.pagestyle == "fancy") {
2258 ofs << "\\usepackage{fancyhdr}\n";
2261 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2265 // We try to load babel late, in case it interferes
2266 // with other packages.
2268 string tmp = lyxrc.language_package;
2269 if (!lyxrc.language_global_options
2270 && tmp == "\\usepackage{babel}")
2271 tmp = string("\\usepackage[") +
2272 language_options.str().c_str() +
2278 if (params.secnumdepth != tclass.secnumdepth()) {
2279 ofs << "\\setcounter{secnumdepth}{"
2280 << params.secnumdepth
2284 if (params.tocdepth != tclass.tocdepth()) {
2285 ofs << "\\setcounter{tocdepth}{"
2291 if (params.paragraph_separation) {
2292 switch (params.defskip.kind()) {
2293 case VSpace::SMALLSKIP:
2294 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2296 case VSpace::MEDSKIP:
2297 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2299 case VSpace::BIGSKIP:
2300 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2302 case VSpace::LENGTH:
2303 ofs << "\\setlength\\parskip{"
2304 << params.defskip.length().asLatexString()
2307 default: // should never happen // Then delete it.
2308 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2313 ofs << "\\setlength\\parindent{0pt}\n";
2317 // Now insert the LyX specific LaTeX commands...
2319 // The optional packages;
2320 string preamble(features.getPackages());
2322 // this might be useful...
2323 preamble += "\n\\makeatletter\n";
2325 // Some macros LyX will need
2326 string tmppreamble(features.getMacros());
2328 if (!tmppreamble.empty()) {
2329 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2330 "LyX specific LaTeX commands.\n"
2331 + tmppreamble + '\n';
2334 // the text class specific preamble
2335 tmppreamble = features.getTClassPreamble();
2336 if (!tmppreamble.empty()) {
2337 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2338 "Textclass specific LaTeX commands.\n"
2339 + tmppreamble + '\n';
2342 /* the user-defined preamble */
2343 if (!params.preamble.empty()) {
2344 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2345 "User specified LaTeX commands.\n"
2346 + params.preamble + '\n';
2349 preamble += "\\makeatother\n";
2351 // Itemize bullet settings need to be last in case the user
2352 // defines their own bullets that use a package included
2353 // in the user-defined preamble -- ARRae
2354 // Actually it has to be done much later than that
2355 // since some packages like frenchb make modifications
2356 // at \begin{document} time -- JMarc
2358 for (int i = 0; i < 4; ++i) {
2359 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2360 if (bullets_def.empty())
2361 bullets_def="\\AtBeginDocument{\n";
2362 bullets_def += " \\renewcommand{\\labelitemi";
2364 // `i' is one less than the item to modify
2371 bullets_def += "ii";
2377 bullets_def += "}{" +
2378 params.user_defined_bullets[i].getText()
2383 if (!bullets_def.empty())
2384 preamble += bullets_def + "}\n\n";
2386 for (int j = countChar(preamble, '\n'); j-- ;) {
2393 ofs << "\\begin{document}\n";
2396 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2398 if (!lyxrc.language_auto_begin) {
2399 ofs << subst(lyxrc.language_command_begin, "$$lang",
2400 params.language->babel())
2405 latexParagraphs(ofs, paragraph, 0, texrow);
2407 // add this just in case after all the paragraphs
2411 if (!lyxrc.language_auto_end) {
2412 ofs << subst(lyxrc.language_command_end, "$$lang",
2413 params.language->babel())
2419 ofs << "\\end{document}\n";
2422 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2424 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2428 // Just to be sure. (Asger)
2431 // tex_code_break_column's value is used to decide
2432 // if we are in batchmode or not (within mathed_write()
2433 // in math_write.C) so we must set it to a non-zero
2434 // value when we leave otherwise we save incorrect .lyx files.
2435 tex_code_break_column = lyxrc.ascii_linelen;
2439 lyxerr << "File was not closed properly." << endl;
2442 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2447 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2449 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2450 Paragraph * endpar, TexRow & texrow) const
2452 bool was_title = false;
2453 bool already_title = false;
2456 while (par != endpar) {
2457 LyXLayout const & layout =
2458 textclasslist.Style(params.textclass,
2461 if (layout.intitle) {
2462 if (already_title) {
2463 lyxerr <<"Error in latexParagraphs: You"
2464 " should not mix title layouts"
2465 " with normal ones." << endl;
2468 } else if (was_title && !already_title) {
2469 ofs << "\\maketitle\n";
2471 already_title = true;
2475 if (layout.isEnvironment()) {
2476 par = par->TeXEnvironment(this, params, ofs, texrow);
2478 par = par->TeXOnePar(this, params, ofs, texrow, false);
2481 // It might be that we only have a title in this document
2482 if (was_title && !already_title) {
2483 ofs << "\\maketitle\n";
2489 bool Buffer::isLatex() const
2491 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2495 bool Buffer::isLinuxDoc() const
2497 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2501 bool Buffer::isLiterate() const
2503 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2507 bool Buffer::isDocBook() const
2509 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2513 bool Buffer::isSGML() const
2515 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2516 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2520 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2521 string const & latexname) const
2523 if (!latexname.empty() && latexname != "!-- --")
2524 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2525 //os << string(depth, ' ') << "<" << latexname << ">\n";
2529 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2530 string const & latexname) const
2532 if (!latexname.empty() && latexname != "!-- --")
2533 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2534 //os << string(depth, ' ') << "</" << latexname << ">\n";
2538 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2540 ofstream ofs(fname.c_str());
2543 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2547 niceFile = nice; // this will be used by included files.
2549 LyXTextClass const & tclass =
2550 textclasslist.TextClass(params.textclass);
2552 LaTeXFeatures features(params, tclass.numLayouts());
2557 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2560 string sgml_includedfiles=features.getIncludedFiles(fname);
2562 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2563 ofs << "<!doctype linuxdoc system>\n\n";
2565 ofs << "<!doctype linuxdoc system [ "
2566 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2569 if (params.options.empty())
2570 sgmlOpenTag(ofs, 0, top_element);
2572 string top = top_element;
2574 top += params.options;
2575 sgmlOpenTag(ofs, 0, top);
2579 ofs << "<!-- " << LYX_DOCVERSION
2580 << " created this file. For more info see http://www.lyx.org/"
2583 Paragraph::depth_type depth = 0; // paragraph depth
2584 Paragraph * par = paragraph;
2586 vector<string> environment_stack(5);
2589 LyXLayout const & style =
2590 textclasslist.Style(params.textclass,
2593 // treat <toc> as a special case for compatibility with old code
2594 if (par->getChar(0) == Paragraph::META_INSET) {
2595 Inset * inset = par->getInset(0);
2596 Inset::Code lyx_code = inset->lyxCode();
2597 if (lyx_code == Inset::TOC_CODE){
2598 string const temp = "toc";
2599 sgmlOpenTag(ofs, depth, temp);
2606 // environment tag closing
2607 for (; depth > par->params().depth(); --depth) {
2608 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2609 environment_stack[depth].erase();
2612 // write opening SGML tags
2613 switch (style.latextype) {
2614 case LATEX_PARAGRAPH:
2615 if (depth == par->params().depth()
2616 && !environment_stack[depth].empty()) {
2617 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2618 environment_stack[depth].erase();
2624 sgmlOpenTag(ofs, depth, style.latexname());
2629 linuxDocError(par, 0,
2630 _("Error : Wrong depth for"
2631 " LatexType Command.\n"));
2633 if (!environment_stack[depth].empty()){
2634 sgmlCloseTag(ofs, depth,
2635 environment_stack[depth]);
2639 environment_stack[depth].erase();
2640 sgmlOpenTag(ofs, depth, style.latexname());
2643 case LATEX_ENVIRONMENT:
2644 case LATEX_ITEM_ENVIRONMENT:
2645 if (depth == par->params().depth()
2646 && environment_stack[depth] != style.latexname()) {
2647 sgmlCloseTag(ofs, depth,
2648 environment_stack[depth]);
2649 environment_stack[depth].erase();
2651 if (depth < par->params().depth()) {
2652 depth = par->params().depth();
2653 environment_stack[depth].erase();
2655 if (environment_stack[depth] != style.latexname()) {
2657 sgmlOpenTag(ofs, depth, "p");
2659 sgmlOpenTag(ofs, depth, style.latexname());
2661 if (environment_stack.size() == depth + 1)
2662 environment_stack.push_back("!-- --");
2663 environment_stack[depth] = style.latexname();
2666 if (style.latexparam() == "CDATA")
2669 if (style.latextype == LATEX_ENVIRONMENT) break;
2671 if (style.labeltype == LABEL_MANUAL)
2676 sgmlOpenTag(ofs, depth + 1, item_name);
2679 sgmlOpenTag(ofs, depth, style.latexname());
2683 simpleLinuxDocOnePar(ofs, par, depth);
2688 // write closing SGML tags
2689 switch (style.latextype) {
2692 case LATEX_ENVIRONMENT:
2693 case LATEX_ITEM_ENVIRONMENT:
2694 if (style.latexparam() == "CDATA")
2698 sgmlCloseTag(ofs, depth, style.latexname());
2704 for (int i=depth; i >= 0; --i)
2705 sgmlCloseTag(ofs, depth, environment_stack[i]);
2709 sgmlCloseTag(ofs, 0, top_element);
2713 // How to check for successful close
2717 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2718 Paragraph::depth_type depth, int desc_on,
2721 Paragraph * tpar = par;
2723 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2725 tpar = tpar->next();
2728 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2729 "Caption").second) {
2730 sgmlOpenTag(os, depth + 1, inner_tag);
2732 simpleDocBookOnePar(os, extra_par, tpar,
2733 desc_on, depth + 2);
2734 sgmlCloseTag(os, depth+1, inner_tag);
2735 if (!extra_par.empty())
2741 // checks, if newcol chars should be put into this line
2742 // writes newline, if necessary.
2745 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2746 string::size_type newcol)
2749 if (colcount > lyxrc.ascii_linelen) {
2751 colcount = newcol; // assume write after this call
2766 string tag_name(PAR_TAG const & pt) {
2768 case NONE: return "!-- --";
2769 case TT: return "tt";
2770 case SF: return "sf";
2771 case BF: return "bf";
2772 case IT: return "it";
2773 case SL: return "sl";
2774 case EM: return "em";
2781 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2783 p1 = static_cast<PAR_TAG>(p1 | p2);
2788 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2790 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2798 // Handle internal paragraph parsing -- layout already processed.
2799 void Buffer::simpleLinuxDocOnePar(ostream & os,
2801 Paragraph::depth_type /*depth*/)
2803 LyXLayout const & style = textclasslist.Style(params.textclass,
2805 string::size_type char_line_count = 5; // Heuristic choice ;-)
2807 // gets paragraph main font
2810 if (style.labeltype == LABEL_MANUAL) {
2811 font_old = style.labelfont;
2814 font_old = style.font;
2818 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2819 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2820 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2823 stack < PAR_TAG > tag_state;
2824 // parsing main loop
2825 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2827 PAR_TAG tag_close = NONE;
2828 list < PAR_TAG > tag_open;
2830 LyXFont const font = par->getFont(params, i);
2832 if (font_old.family() != font.family()) {
2833 switch (family_type) {
2834 case LyXFont::SANS_FAMILY:
2837 case LyXFont::TYPEWRITER_FAMILY:
2844 family_type = font.family();
2846 switch (family_type) {
2847 case LyXFont::SANS_FAMILY:
2848 tag_open.push_back(SF);
2850 case LyXFont::TYPEWRITER_FAMILY:
2851 tag_open.push_back(TT);
2858 if (font_old.series() != font.series()) {
2859 switch (series_type) {
2860 case LyXFont::BOLD_SERIES:
2867 series_type = font.series();
2869 switch (series_type) {
2870 case LyXFont::BOLD_SERIES:
2871 tag_open.push_back(BF);
2879 if (font_old.shape() != font.shape()) {
2880 switch (shape_type) {
2881 case LyXFont::ITALIC_SHAPE:
2884 case LyXFont::SLANTED_SHAPE:
2891 shape_type = font.shape();
2893 switch (shape_type) {
2894 case LyXFont::ITALIC_SHAPE:
2895 tag_open.push_back(IT);
2897 case LyXFont::SLANTED_SHAPE:
2898 tag_open.push_back(SL);
2905 if (font_old.emph() != font.emph()) {
2906 if (font.emph() == LyXFont::ON) {
2907 tag_open.push_back(EM);
2916 list < PAR_TAG > temp;
2917 while(!tag_state.empty() && tag_close ) {
2918 PAR_TAG k = tag_state.top();
2920 os << "</" << tag_name(k) << ">";
2927 for(list< PAR_TAG >::const_iterator j = temp.begin();
2928 j != temp.end(); ++j) {
2930 os << "<" << tag_name(*j) << ">";
2933 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2934 j != tag_open.end(); ++j) {
2936 os << "<" << tag_name(*j) << ">";
2939 char c = par->getChar(i);
2941 if (c == Paragraph::META_INSET) {
2942 Inset * inset = par->getInset(i);
2943 inset->linuxdoc(this, os);
2950 font.latex() == LyXFont::ON ||
2952 style.latexparam() == "CDATA") {
2953 // "TeX"-Mode on == > SGML-Mode on.
2959 if (par->linuxDocConvertChar(c, sgml_string)
2960 && !style.free_spacing) {
2961 // in freespacing mode, spaces are
2962 // non-breaking characters
2963 if (desc_on) {// if char is ' ' then...
2966 linux_doc_line_break(os, char_line_count, 6);
2970 linux_doc_line_break(os, char_line_count, 1);
2975 char_line_count += sgml_string.length();
2981 while (!tag_state.empty()) {
2982 os << "</" << tag_name(tag_state.top()) << ">";
2986 // resets description flag correctly
2988 // <tag> not closed...
2989 linux_doc_line_break(os, char_line_count, 6);
2995 // Print an error message.
2996 void Buffer::linuxDocError(Paragraph * par, int pos,
2997 string const & message)
2999 // insert an error marker in text
3000 InsetError * new_inset = new InsetError(message);
3001 par->insertInset(pos, new_inset);
3005 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3007 ofstream ofs(fname.c_str());
3009 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3013 Paragraph * par = paragraph;
3015 niceFile = nice; // this will be used by Insetincludes.
3017 LyXTextClass const & tclass =
3018 textclasslist.TextClass(params.textclass);
3020 LaTeXFeatures features(params, tclass.numLayouts());
3025 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3028 string sgml_includedfiles = features.getIncludedFiles(fname);
3030 ofs << "<!doctype " << top_element
3031 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3033 if (params.preamble.empty() && sgml_includedfiles.empty())
3036 ofs << "\n [ " << params.preamble
3037 << sgml_includedfiles << " \n]>\n\n";
3040 string top = top_element;
3042 top += params.language->code();
3045 if (!params.options.empty()) {
3047 top += params.options;
3049 sgmlOpenTag(ofs, 0, top);
3051 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3052 << "\n See http://www.lyx.org/ for more information -->\n";
3054 vector<string> environment_stack(10);
3055 vector<string> environment_inner(10);
3056 vector<string> command_stack(10);
3058 bool command_flag = false;
3059 Paragraph::depth_type command_depth = 0;
3060 Paragraph::depth_type command_base = 0;
3061 Paragraph::depth_type cmd_depth = 0;
3062 Paragraph::depth_type depth = 0; // paragraph depth
3065 string command_name;
3071 int desc_on = 0; // description mode
3073 LyXLayout const & style =
3074 textclasslist.Style(params.textclass,
3077 // environment tag closing
3078 for (; depth > par->params().depth(); --depth) {
3079 if (environment_inner[depth] != "!-- --") {
3080 item_name = "listitem";
3081 sgmlCloseTag(ofs, command_depth + depth,
3083 if (environment_inner[depth] == "varlistentry")
3084 sgmlCloseTag(ofs, depth+command_depth,
3085 environment_inner[depth]);
3087 sgmlCloseTag(ofs, depth + command_depth,
3088 environment_stack[depth]);
3089 environment_stack[depth].erase();
3090 environment_inner[depth].erase();
3093 if (depth == par->params().depth()
3094 && environment_stack[depth] != style.latexname()
3095 && !environment_stack[depth].empty()) {
3096 if (environment_inner[depth] != "!-- --") {
3097 item_name= "listitem";
3098 sgmlCloseTag(ofs, command_depth+depth,
3100 if (environment_inner[depth] == "varlistentry")
3102 depth + command_depth,
3103 environment_inner[depth]);
3106 sgmlCloseTag(ofs, depth + command_depth,
3107 environment_stack[depth]);
3109 environment_stack[depth].erase();
3110 environment_inner[depth].erase();
3113 // Write opening SGML tags.
3114 switch (style.latextype) {
3115 case LATEX_PARAGRAPH:
3116 sgmlOpenTag(ofs, depth + command_depth,
3122 linuxDocError(par, 0,
3123 _("Error : Wrong depth for "
3124 "LatexType Command.\n"));
3126 command_name = style.latexname();
3128 sgmlparam = style.latexparam();
3129 c_params = split(sgmlparam, c_depth,'|');
3131 cmd_depth = lyx::atoi(c_depth);
3134 if (cmd_depth < command_base) {
3135 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3136 sgmlCloseTag(ofs, j, command_stack[j]);
3137 command_depth = command_base = cmd_depth;
3138 } else if (cmd_depth <= command_depth) {
3139 for (int j = command_depth; j >= int(cmd_depth); --j)
3140 sgmlCloseTag(ofs, j, command_stack[j]);
3141 command_depth = cmd_depth;
3143 command_depth = cmd_depth;
3145 command_depth = command_base = cmd_depth;
3146 command_flag = true;
3148 if (command_stack.size() == command_depth + 1)
3149 command_stack.push_back(string());
3150 command_stack[command_depth] = command_name;
3152 // treat label as a special case for
3153 // more WYSIWYM handling.
3154 if (par->getChar(0) == Paragraph::META_INSET) {
3155 Inset * inset = par->getInset(0);
3156 Inset::Code lyx_code = inset->lyxCode();
3157 if (lyx_code == Inset::LABEL_CODE){
3158 command_name += " id=\"";
3159 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3160 command_name += "\"";
3165 sgmlOpenTag(ofs, depth + command_depth, command_name);
3166 if (c_params.empty())
3167 item_name = "title";
3169 item_name = c_params;
3170 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3173 case LATEX_ENVIRONMENT:
3174 case LATEX_ITEM_ENVIRONMENT:
3175 if (depth < par->params().depth()) {
3176 depth = par->params().depth();
3177 environment_stack[depth].erase();
3180 if (environment_stack[depth] != style.latexname()) {
3181 if(environment_stack.size() == depth + 1) {
3182 environment_stack.push_back("!-- --");
3183 environment_inner.push_back("!-- --");
3185 environment_stack[depth] = style.latexname();
3186 environment_inner[depth] = "!-- --";
3187 sgmlOpenTag(ofs, depth + command_depth,
3188 environment_stack[depth]);
3190 if (environment_inner[depth] != "!-- --") {
3191 item_name= "listitem";
3193 command_depth + depth,
3195 if (environment_inner[depth] == "varlistentry")
3197 depth + command_depth,
3198 environment_inner[depth]);
3202 if (style.latextype == LATEX_ENVIRONMENT) {
3203 if (!style.latexparam().empty()) {
3204 if(style.latexparam() == "CDATA")
3207 sgmlOpenTag(ofs, depth + command_depth,
3208 style.latexparam());
3213 desc_on = (style.labeltype == LABEL_MANUAL);
3216 environment_inner[depth]= "varlistentry";
3218 environment_inner[depth]= "listitem";
3220 sgmlOpenTag(ofs, depth + 1 + command_depth,
3221 environment_inner[depth]);
3225 sgmlOpenTag(ofs, depth + 1 + command_depth,
3229 sgmlOpenTag(ofs, depth + 1 + command_depth,
3234 sgmlOpenTag(ofs, depth + command_depth,
3240 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3241 depth + 1 + command_depth);
3245 // write closing SGML tags
3246 switch (style.latextype) {
3248 if (c_params.empty())
3252 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3254 case LATEX_ENVIRONMENT:
3255 if (!style.latexparam().empty()) {
3256 if(style.latexparam() == "CDATA")
3259 sgmlCloseTag(ofs, depth + command_depth,
3260 style.latexparam());
3263 case LATEX_ITEM_ENVIRONMENT:
3264 if (desc_on == 1) break;
3266 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3268 case LATEX_PARAGRAPH:
3269 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3272 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3278 for (int d = depth; d >= 0; --d) {
3279 if (!environment_stack[depth].empty()) {
3280 if (environment_inner[depth] != "!-- --") {
3281 item_name = "listitem";
3282 sgmlCloseTag(ofs, command_depth + depth,
3284 if (environment_inner[depth] == "varlistentry")
3285 sgmlCloseTag(ofs, depth + command_depth,
3286 environment_inner[depth]);
3289 sgmlCloseTag(ofs, depth + command_depth,
3290 environment_stack[depth]);
3294 for (int j = command_depth; j >= 0 ; --j)
3295 if (!command_stack[j].empty())
3296 sgmlCloseTag(ofs, j, command_stack[j]);
3299 sgmlCloseTag(ofs, 0, top_element);
3302 // How to check for successful close
3306 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3307 Paragraph * par, int & desc_on,
3308 Paragraph::depth_type depth) const
3310 bool emph_flag = false;
3312 LyXLayout const & style = textclasslist.Style(params.textclass,
3315 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3317 int char_line_count = depth;
3318 //if (!style.free_spacing)
3319 // os << string(depth,' ');
3321 // parsing main loop
3322 for (Paragraph::size_type i = 0;
3323 i < par->size(); ++i) {
3324 LyXFont font = par->getFont(params, i);
3326 // handle <emphasis> tag
3327 if (font_old.emph() != font.emph()) {
3328 if (font.emph() == LyXFont::ON) {
3332 os << "</emphasis>";
3337 char c = par->getChar(i);
3339 if (c == Paragraph::META_INSET) {
3340 Inset * inset = par->getInset(i);
3342 inset->docBook(this, ost);
3343 string tmp_out = ost.str().c_str();
3346 // This code needs some explanation:
3347 // Two insets are treated specially
3348 // label if it is the first element in a command paragraph
3350 // graphics inside tables or figure floats can't go on
3351 // title (the equivalente in latex for this case is caption
3352 // and title should come first
3355 if (desc_on!= 3 || i!= 0) {
3356 if (!tmp_out.empty() && tmp_out[0] == '@') {
3358 extra += frontStrip(tmp_out, '@');
3360 os << frontStrip(tmp_out, '@');
3366 } else if (font.latex() == LyXFont::ON) {
3367 // "TeX"-Mode on ==> SGML-Mode on.
3374 if (par->linuxDocConvertChar(c, sgml_string)
3375 && !style.free_spacing) { // in freespacing
3377 // non-breaking characters
3381 os << "\n</term><listitem><para>";
3394 os << "</emphasis>";
3397 // resets description flag correctly
3399 // <term> not closed...
3402 if(style.free_spacing) os << '\n';
3406 // This should be enabled when the Chktex class is implemented. (Asger)
3407 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3408 // Other flags: -wall -v0 -x
3409 int Buffer::runChktex()
3411 if (!users->text) return 0;
3413 users->owner()->prohibitInput();
3415 // get LaTeX-Filename
3416 string const name = getLatexName();
3417 string path = OnlyPath(filename);
3419 string const org_path = path;
3420 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3424 Path p(path); // path to LaTeX file
3425 users->owner()->message(_("Running chktex..."));
3427 // Remove all error insets
3428 bool const removedErrorInsets = users->removeAutoInsets();
3430 // Generate the LaTeX file if neccessary
3431 makeLaTeXFile(name, org_path, false);
3434 Chktex chktex(lyxrc.chktex_command, name, filepath);
3435 int res = chktex.run(terr); // run chktex
3438 WriteAlert(_("chktex did not work!"),
3439 _("Could not run with file:"), name);
3440 } else if (res > 0) {
3441 // Insert all errors as errors boxes
3442 users->insertErrors(terr);
3445 // if we removed error insets before we ran chktex or if we inserted
3446 // error insets after we ran chktex, this must be run:
3447 if (removedErrorInsets || res){
3449 users->fitCursor(users->text);
3451 users->owner()->allowInput();
3457 void Buffer::validate(LaTeXFeatures & features) const
3459 Paragraph * par = paragraph;
3460 LyXTextClass const & tclass =
3461 textclasslist.TextClass(params.textclass);
3463 // AMS Style is at document level
3464 features.amsstyle = (params.use_amsmath ||
3465 tclass.provides(LyXTextClass::amsmath));
3468 // We don't use "lyxerr.debug" because of speed. (Asger)
3469 if (lyxerr.debugging(Debug::LATEX))
3470 lyxerr << "Paragraph: " << par << endl;
3472 // Now just follow the list of paragraphs and run
3473 // validate on each of them.
3474 par->validate(features);
3476 // and then the next paragraph
3480 // the bullet shapes are buffer level not paragraph level
3481 // so they are tested here
3482 for (int i = 0; i < 4; ++i) {
3483 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3484 int const font = params.user_defined_bullets[i].getFont();
3486 int const c = params
3487 .user_defined_bullets[i]
3494 features.latexsym = true;
3496 } else if (font == 1) {
3497 features.amssymb = true;
3498 } else if ((font >= 2 && font <= 5)) {
3499 features.pifont = true;
3504 if (lyxerr.debugging(Debug::LATEX)) {
3505 features.showStruct();
3510 void Buffer::setPaperStuff()
3512 params.papersize = BufferParams::PAPER_DEFAULT;
3513 char const c1 = params.paperpackage;
3514 if (c1 == BufferParams::PACKAGE_NONE) {
3515 char const c2 = params.papersize2;
3516 if (c2 == BufferParams::VM_PAPER_USLETTER)
3517 params.papersize = BufferParams::PAPER_USLETTER;
3518 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3519 params.papersize = BufferParams::PAPER_LEGALPAPER;
3520 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3521 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3522 else if (c2 == BufferParams::VM_PAPER_A3)
3523 params.papersize = BufferParams::PAPER_A3PAPER;
3524 else if (c2 == BufferParams::VM_PAPER_A4)
3525 params.papersize = BufferParams::PAPER_A4PAPER;
3526 else if (c2 == BufferParams::VM_PAPER_A5)
3527 params.papersize = BufferParams::PAPER_A5PAPER;
3528 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3529 (c2 == BufferParams::VM_PAPER_B5))
3530 params.papersize = BufferParams::PAPER_B5PAPER;
3531 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3532 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3533 params.papersize = BufferParams::PAPER_A4PAPER;
3537 // This function should be in Buffer because it's a buffer's property (ale)
3538 string const Buffer::getIncludeonlyList(char delim)
3541 for (inset_iterator it = inset_iterator_begin();
3542 it != inset_iterator_end(); ++it) {
3543 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3544 InsetInclude * insetinc =
3545 static_cast<InsetInclude *>(*it);
3546 if (insetinc->isIncludeOnly()) {
3549 lst += insetinc->getRelFileBaseName();
3553 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3558 vector<string> const Buffer::getLabelList()
3560 /// if this is a child document and the parent is already loaded
3561 /// Use the parent's list instead [ale990407]
3562 if (!params.parentname.empty()
3563 && bufferlist.exists(params.parentname)) {
3564 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3566 return tmp->getLabelList();
3569 vector<string> label_list;
3570 for (inset_iterator it = inset_iterator_begin();
3571 it != inset_iterator_end(); ++it) {
3572 vector<string> const l = (*it)->getLabelList();
3573 label_list.insert(label_list.end(), l.begin(), l.end());
3579 Buffer::Lists const Buffer::getLists() const
3582 Paragraph * par = paragraph;
3584 LyXTextClassList::size_type cap;
3585 boost::tie(found, cap) = textclasslist
3586 .NumberOfLayout(params.textclass, "Caption");
3589 char const labeltype =
3590 textclasslist.Style(params.textclass,
3591 par->getLayout()).labeltype;
3593 if (labeltype >= LABEL_COUNTER_CHAPTER
3594 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3595 // insert this into the table of contents
3596 SingleList & item = l["TOC"];
3599 textclasslist.TextClass(params.textclass).maxcounter());
3600 item.push_back(TocItem(par, depth, par->asString(this, true)));
3602 // For each paragrph, traverse its insets and look for
3606 Paragraph::inset_iterator it =
3607 par->inset_iterator_begin();
3608 Paragraph::inset_iterator end =
3609 par->inset_iterator_end();
3611 for (; it != end; ++it) {
3612 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3614 static_cast<InsetFloat*>(*it);
3616 string const type = il->type();
3618 // Now find the caption in the float...
3619 // We now tranverse the paragraphs of
3621 Paragraph * tmp = il->inset.paragraph();
3623 if (tmp->layout == cap) {
3624 SingleList & item = l[type];
3626 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3627 item.push_back(TocItem(tmp, 0 , str));
3634 lyxerr << "caption not found" << endl;
3643 // This is also a buffer property (ale)
3644 vector<pair<string, string> > const Buffer::getBibkeyList()
3646 /// if this is a child document and the parent is already loaded
3647 /// Use the parent's list instead [ale990412]
3648 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3649 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3651 return tmp->getBibkeyList();
3654 vector<pair<string, string> > keys;
3655 Paragraph * par = paragraph;
3658 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3659 par->asString(this, false)));
3663 // Might be either using bibtex or a child has bibliography
3665 for (inset_iterator it = inset_iterator_begin();
3666 it != inset_iterator_end(); ++it) {
3667 // Search for Bibtex or Include inset
3668 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3669 vector<pair<string,string> > tmp =
3670 static_cast<InsetBibtex*>(*it)->getKeys(this);
3671 keys.insert(keys.end(), tmp.begin(), tmp.end());
3672 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3673 vector<pair<string,string> > const tmp =
3674 static_cast<InsetInclude*>(*it)->getKeys();
3675 keys.insert(keys.end(), tmp.begin(), tmp.end());
3684 bool Buffer::isDepClean(string const & name) const
3686 DEPCLEAN * item = dep_clean;
3687 while (item && item->master != name)
3689 if (!item) return true;
3694 void Buffer::markDepClean(string const & name)
3697 dep_clean = new DEPCLEAN;
3698 dep_clean->clean = true;
3699 dep_clean->master = name;
3700 dep_clean->next = 0;
3702 DEPCLEAN * item = dep_clean;
3703 while (item && item->master != name)
3708 item = new DEPCLEAN;
3710 item->master = name;
3717 bool Buffer::dispatch(string const & command)
3719 // Split command string into command and argument
3721 string line = frontStrip(command);
3722 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3724 return dispatch(lyxaction.LookupFunc(cmd), arg);
3728 bool Buffer::dispatch(int action, string const & argument)
3730 bool dispatched = true;
3733 Exporter::Export(this, argument, false);
3743 void Buffer::resizeInsets(BufferView * bv)
3745 /// then remove all LyXText in text-insets
3746 Paragraph * par = paragraph;
3747 for (; par; par = par->next()) {
3748 par->resizeInsetsLyXText(bv);
3753 void Buffer::redraw()
3756 users->fitCursor(users->text);
3760 void Buffer::changeLanguage(Language const * from, Language const * to)
3763 Paragraph * par = paragraph;
3765 par->changeLanguage(params, from, to);
3771 bool Buffer::isMultiLingual()
3773 Paragraph * par = paragraph;
3775 if (par->isMultiLingual(params))
3783 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3784 Paragraph::size_type pos)
3787 it = par->InsetIterator(pos);
3788 if (it == par->inset_iterator_end()) {
3795 void Buffer::inset_iterator::setParagraph()
3798 it = par->inset_iterator_begin();
3799 if (it != par->inset_iterator_end())
3804 // We maintain an invariant that whenever par = 0 then it = 0
3808 Inset * Buffer::getInsetFromID(int id_arg) const
3810 for (inset_iterator it = inset_const_iterator_begin();
3811 it != inset_const_iterator_end(); ++it)
3813 if ((*it)->id() == id_arg)
3815 Inset * in = (*it)->getInsetFromID(id_arg);
3823 Paragraph * Buffer::getParFromID(int id) const
3825 if (id < 0) return 0;
3826 Paragraph * par = paragraph;
3828 if (par->id() == id) {
3831 Paragraph * tmp = par->getParFromID(id);