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;
301 set<string> unknown_layouts;
303 // candidate for move to BufferView
304 // (at least some parts in the beginning of the func)
307 // changed to be public and have one parameter
308 // if par = 0 normal behavior
309 // else insert behavior
310 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
311 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
313 unknown_layouts.clear();
315 ert_comp.contents.erase();
316 ert_comp.active = false;
317 ert_comp.in_tabular = false;
321 Paragraph::depth_type depth = 0;
322 bool the_end_read = false;
324 Paragraph * first_par = 0;
325 LyXFont font(LyXFont::ALL_INHERIT, params.language);
326 if (file_format < 216 && params.language->lang() == "hebrew")
327 font.setLanguage(default_language);
332 // We are inserting into an existing document
333 users->text->breakParagraph(users);
334 first_par = users->text->firstParagraph();
337 // We don't want to adopt the parameters from the
338 // document we insert, so we skip until the text begins:
341 string const pretoken = lex.GetString();
342 if (pretoken == "\\layout") {
343 lex.pushToken(pretoken);
351 string const token = lex.GetString();
353 if (token.empty()) continue;
355 lyxerr[Debug::PARSER] << "Handling token: `"
356 << token << "'" << endl;
359 parseSingleLyXformat2Token(lex, par, first_par,
367 paragraph = first_par;
369 if (!unknown_layouts.empty()) {
371 for (set<string>::const_iterator it = unknown_layouts.begin();
372 it != unknown_layouts.end(); ++it) {
373 if (it != unknown_layouts.begin())
377 WriteAlert(_("Textclass Loading Error!"),
378 _("The following layouts are undefined:"),
386 void Buffer::insertErtContents(Paragraph * par, int & pos,
387 LyXFont const & font, bool set_inactive)
389 if (!ert_comp.contents.empty()) {
390 lyxerr[Debug::INSETS] << "ERT contents:\n"
391 << ert_comp.contents << endl;
392 Inset * inset = new InsetERT(ert_comp.contents);
393 par->insertInset(pos++, inset, font);
394 ert_comp.contents.erase();
397 ert_comp.active = false;
403 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
404 Paragraph *& first_par,
405 string const & token, int & pos,
406 Paragraph::depth_type & depth,
410 bool the_end_read = false;
411 #ifndef NO_PEXTRA_REALLY
412 // This is super temporary but is needed to get the compability
413 // mode for minipages work correctly together with new tabulars.
414 static int call_depth;
416 bool checkminipage = false;
417 static Paragraph * minipar;
418 static Paragraph * parBeforeMinipage;
421 if (token[0] != '\\') {
423 if (ert_comp.active) {
424 ert_comp.contents += token;
427 for (string::const_iterator cit = token.begin();
428 cit != token.end(); ++cit) {
429 par->insertChar(pos, (*cit), font);
432 checkminipage = true;
436 } else if (token == "\\i") {
437 Inset * inset = new InsetLatexAccent;
438 inset->read(this, lex);
439 par->insertInset(pos, inset, font);
441 } else if (token == "\\layout") {
443 ert_comp.in_tabular = false;
445 insertErtContents(par, pos, font);
448 string const layoutname = lex.GetString();
449 pair<bool, LyXTextClass::LayoutList::size_type> pp
450 = textclasslist.NumberOfLayout(params.textclass,
454 if (compare_no_case(layoutname, "latex") == 0) {
455 ert_comp.active = true;
459 // The is the compability reading of layout caption.
460 // It can be removed in LyX version 1.3.0. (Lgb)
461 if (compare_no_case(layoutname, "caption") == 0) {
462 // We expect that the par we are now working on is
463 // really inside a InsetText inside a InsetFloat.
464 // We also know that captions can only be
465 // one paragraph. (Lgb)
467 // We should now read until the next "\layout"
469 // This is probably not good enough, what if the
470 // caption is the last par in the document (Lgb)
471 istream & ist = lex.getStream();
477 if (prefixIs(line, "\\layout")) {
481 if (prefixIs(line, "\\begin_inset"))
483 if (prefixIs(line, "\\end_inset")) {
494 // Now we should have the whole layout in ss
495 // we should now be able to give this to the
497 ss << "\\end_inset\n";
499 // This seems like a bug in stringstream.
500 // We really should be able to use ss
502 istringstream is(ss.str());
504 tmplex.setStream(is);
505 Inset * inset = new InsetCaption;
506 inset->Read(this, tmplex);
507 par->InsertInset(pos, inset, font);
514 par = new Paragraph(par);
518 par->layout = pp.second;
521 // use default layout "Standard" (0)
523 unknown_layouts.insert(layoutname);
525 // Test whether the layout is obsolete.
526 LyXLayout const & layout =
527 textclasslist.Style(params.textclass,
529 if (!layout.obsoleted_by().empty())
530 par->layout = textclasslist
531 .NumberOfLayout(params.textclass,
532 layout.obsoleted_by())
534 par->params().depth(depth);
535 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
536 if (file_format < 216
537 && params.language->lang() == "hebrew")
538 font.setLanguage(default_language);
543 } else if (token == "\\begin_float") {
544 // This is the compability reader. It can be removed in
545 // LyX version 1.3.0. (Lgb)
547 string const tmptok = lex.GetString();
548 //lyxerr << "old float: " << tmptok << endl;
551 stringstream old_float;
553 if (tmptok == "footnote") {
554 inset = new InsetFoot;
555 } else if (tmptok == "margin") {
556 inset = new InsetMarginal;
557 } else if (tmptok == "fig") {
558 inset = new InsetFloat("figure");
559 old_float << "placement htbp\n"
561 } else if (tmptok == "tab") {
562 inset = new InsetFloat("table");
563 old_float << "placement htbp\n"
565 } else if (tmptok == "alg") {
566 inset = new InsetFloat("algorithm");
567 old_float << "placement htbp\n"
569 } else if (tmptok == "wide-fig") {
570 inset = new InsetFloat("figure");
571 //InsetFloat * tmp = new InsetFloat("figure");
574 old_float << "placement htbp\n"
576 } else if (tmptok == "wide-tab") {
577 inset = new InsetFloat("table");
578 //InsetFloat * tmp = new InsetFloat("table");
581 old_float << "placement htbp\n"
587 return false; // no end read yet
590 old_float << "collapsed true\n";
592 // Here we need to check for \end_deeper and handle that
593 // before we do the footnote parsing.
594 // This _is_ a hack! (Lgb)
597 string const tmp = lex.GetString();
598 if (tmp == "\\end_deeper") {
599 //lyxerr << "\\end_deeper caught!" << endl;
601 lex.printError("\\end_deeper: "
602 "depth is already null");
607 old_float << tmp << ' ';
612 old_float << lex.getLongString("\\end_float")
613 << "\n\\end_inset\n";
614 //lyxerr << "Float Body:\n" << old_float.str() << endl;
615 // That this does not work seems like a bug
616 // in stringstream. (Lgb)
617 istringstream istr(old_float.str());
619 nylex.setStream(istr);
620 inset->read(this, nylex);
621 par->insertInset(pos, inset, font);
623 } else if (token == "\\begin_deeper") {
625 } else if (token == "\\end_deeper") {
627 lex.printError("\\end_deeper: "
628 "depth is already null");
632 } else if (token == "\\begin_preamble") {
633 params.readPreamble(lex);
634 } else if (token == "\\textclass") {
636 pair<bool, LyXTextClassList::size_type> pp =
637 textclasslist.NumberOfClass(lex.GetString());
639 params.textclass = pp.second;
641 WriteAlert(string(_("Textclass error")),
642 string(_("The document uses an unknown textclass \"")) +
643 lex.GetString() + string("\"."),
644 string(_("LyX will not be able to produce output correctly.")));
645 params.textclass = 0;
647 if (!textclasslist.Load(params.textclass)) {
648 // if the textclass wasn't loaded properly
649 // we need to either substitute another
650 // or stop loading the file.
651 // I can substitute but I don't see how I can
652 // stop loading... ideas?? ARRae980418
653 WriteAlert(_("Textclass Loading Error!"),
654 string(_("Can't load textclass ")) +
655 textclasslist.NameOfClass(params.textclass),
656 _("-- substituting default"));
657 params.textclass = 0;
659 } else if (token == "\\options") {
661 params.options = lex.GetString();
662 } else if (token == "\\language") {
663 params.readLanguage(lex);
664 } else if (token == "\\fontencoding") {
666 } else if (token == "\\inputencoding") {
668 params.inputenc = lex.GetString();
669 } else if (token == "\\graphics") {
670 params.readGraphicsDriver(lex);
671 } else if (token == "\\fontscheme") {
673 params.fonts = lex.GetString();
674 } else if (token == "\\noindent") {
675 par->params().noindent(true);
676 } else if (token == "\\fill_top") {
677 par->params().spaceTop(VSpace(VSpace::VFILL));
678 } else if (token == "\\fill_bottom") {
679 par->params().spaceBottom(VSpace(VSpace::VFILL));
680 } else if (token == "\\line_top") {
681 par->params().lineTop(true);
682 } else if (token == "\\line_bottom") {
683 par->params().lineBottom(true);
684 } else if (token == "\\pagebreak_top") {
685 par->params().pagebreakTop(true);
686 } else if (token == "\\pagebreak_bottom") {
687 par->params().pagebreakBottom(true);
688 } else if (token == "\\start_of_appendix") {
689 par->params().startOfAppendix(true);
690 } else if (token == "\\paragraph_separation") {
691 int tmpret = lex.FindToken(string_paragraph_separation);
692 if (tmpret == -1) ++tmpret;
693 if (tmpret != LYX_LAYOUT_DEFAULT)
694 params.paragraph_separation =
695 static_cast<BufferParams::PARSEP>(tmpret);
696 } else if (token == "\\defskip") {
698 params.defskip = VSpace(lex.GetString());
699 } else if (token == "\\epsfig") { // obsolete
700 // Indeed it is obsolete, but we HAVE to be backwards
701 // compatible until 0.14, because otherwise all figures
702 // in existing documents are irretrivably lost. (Asger)
703 params.readGraphicsDriver(lex);
704 } else if (token == "\\quotes_language") {
705 int tmpret = lex.FindToken(string_quotes_language);
706 if (tmpret == -1) ++tmpret;
707 if (tmpret != LYX_LAYOUT_DEFAULT) {
708 InsetQuotes::quote_language tmpl =
709 InsetQuotes::EnglishQ;
712 tmpl = InsetQuotes::EnglishQ;
715 tmpl = InsetQuotes::SwedishQ;
718 tmpl = InsetQuotes::GermanQ;
721 tmpl = InsetQuotes::PolishQ;
724 tmpl = InsetQuotes::FrenchQ;
727 tmpl = InsetQuotes::DanishQ;
730 params.quotes_language = tmpl;
732 } else if (token == "\\quotes_times") {
734 switch (lex.GetInteger()) {
736 params.quotes_times = InsetQuotes::SingleQ;
739 params.quotes_times = InsetQuotes::DoubleQ;
742 } else if (token == "\\papersize") {
743 int tmpret = lex.FindToken(string_papersize);
747 params.papersize2 = tmpret;
748 } else if (token == "\\paperpackage") {
749 int tmpret = lex.FindToken(string_paperpackages);
752 params.paperpackage = BufferParams::PACKAGE_NONE;
754 params.paperpackage = tmpret;
755 } else if (token == "\\use_geometry") {
757 params.use_geometry = lex.GetInteger();
758 } else if (token == "\\use_amsmath") {
760 params.use_amsmath = lex.GetInteger();
761 } else if (token == "\\paperorientation") {
762 int tmpret = lex.FindToken(string_orientation);
763 if (tmpret == -1) ++tmpret;
764 if (tmpret != LYX_LAYOUT_DEFAULT)
765 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
766 } else if (token == "\\paperwidth") {
768 params.paperwidth = lex.GetString();
769 } else if (token == "\\paperheight") {
771 params.paperheight = lex.GetString();
772 } else if (token == "\\leftmargin") {
774 params.leftmargin = lex.GetString();
775 } else if (token == "\\topmargin") {
777 params.topmargin = lex.GetString();
778 } else if (token == "\\rightmargin") {
780 params.rightmargin = lex.GetString();
781 } else if (token == "\\bottommargin") {
783 params.bottommargin = lex.GetString();
784 } else if (token == "\\headheight") {
786 params.headheight = lex.GetString();
787 } else if (token == "\\headsep") {
789 params.headsep = lex.GetString();
790 } else if (token == "\\footskip") {
792 params.footskip = lex.GetString();
793 } else if (token == "\\paperfontsize") {
795 params.fontsize = strip(lex.GetString());
796 } else if (token == "\\papercolumns") {
798 params.columns = lex.GetInteger();
799 } else if (token == "\\papersides") {
801 switch (lex.GetInteger()) {
803 case 1: params.sides = LyXTextClass::OneSide; break;
804 case 2: params.sides = LyXTextClass::TwoSides; break;
806 } else if (token == "\\paperpagestyle") {
808 params.pagestyle = strip(lex.GetString());
809 } else if (token == "\\bullet") {
811 int const index = lex.GetInteger();
813 int temp_int = lex.GetInteger();
814 params.user_defined_bullets[index].setFont(temp_int);
815 params.temp_bullets[index].setFont(temp_int);
817 temp_int = lex.GetInteger();
818 params.user_defined_bullets[index].setCharacter(temp_int);
819 params.temp_bullets[index].setCharacter(temp_int);
821 temp_int = lex.GetInteger();
822 params.user_defined_bullets[index].setSize(temp_int);
823 params.temp_bullets[index].setSize(temp_int);
825 string const temp_str = lex.GetString();
826 if (temp_str != "\\end_bullet") {
827 // this element isn't really necessary for
828 // parsing but is easier for humans
829 // to understand bullets. Put it back and
830 // set a debug message?
831 lex.printError("\\end_bullet expected, got" + temp_str);
832 //how can I put it back?
834 } else if (token == "\\bulletLaTeX") {
836 int const index = lex.GetInteger();
838 string temp_str = lex.GetString();
840 while (temp_str != "\\end_bullet") {
841 // this loop structure is needed when user
842 // enters an empty string since the first
843 // thing returned will be the \\end_bullet
845 // if the LaTeX entry has spaces. Each element
846 // therefore needs to be read in turn
849 temp_str = lex.GetString();
851 params.user_defined_bullets[index].setText(sum_str);
852 params.temp_bullets[index].setText(sum_str);
853 } else if (token == "\\secnumdepth") {
855 params.secnumdepth = lex.GetInteger();
856 } else if (token == "\\tocdepth") {
858 params.tocdepth = lex.GetInteger();
859 } else if (token == "\\spacing") {
861 string const tmp = strip(lex.GetString());
862 Spacing::Space tmp_space = Spacing::Default;
864 if (tmp == "single") {
865 tmp_space = Spacing::Single;
866 } else if (tmp == "onehalf") {
867 tmp_space = Spacing::Onehalf;
868 } else if (tmp == "double") {
869 tmp_space = Spacing::Double;
870 } else if (tmp == "other") {
872 tmp_space = Spacing::Other;
873 tmp_val = lex.GetFloat();
875 lex.printError("Unknown spacing token: '$$Token'");
877 // Small hack so that files written with klyx will be
880 par->params().spacing(Spacing(tmp_space, tmp_val));
882 params.spacing.set(tmp_space, tmp_val);
884 } else if (token == "\\paragraph_spacing") {
886 string const tmp = strip(lex.GetString());
887 if (tmp == "single") {
888 par->params().spacing(Spacing(Spacing::Single));
889 } else if (tmp == "onehalf") {
890 par->params().spacing(Spacing(Spacing::Onehalf));
891 } else if (tmp == "double") {
892 par->params().spacing(Spacing(Spacing::Double));
893 } else if (tmp == "other") {
895 par->params().spacing(Spacing(Spacing::Other,
898 lex.printError("Unknown spacing token: '$$Token'");
900 } else if (token == "\\float_placement") {
902 params.float_placement = lex.GetString();
903 } else if (token == "\\family") {
905 font.setLyXFamily(lex.GetString());
906 } else if (token == "\\series") {
908 font.setLyXSeries(lex.GetString());
909 } else if (token == "\\shape") {
911 font.setLyXShape(lex.GetString());
912 } else if (token == "\\size") {
914 font.setLyXSize(lex.GetString());
917 #warning compatability hack needed
919 } else if (token == "\\latex") {
921 string const tok = lex.GetString();
922 // This is dirty, but gone with LyX3. (Asger)
923 if (tok == "no_latex")
924 font.setLatex(LyXFont::OFF);
925 else if (tok == "latex")
926 font.setLatex(LyXFont::ON);
927 else if (tok == "default")
928 font.setLatex(LyXFont::INHERIT);
930 lex.printError("Unknown LaTeX font flag "
933 } else if (token == "\\latex") {
935 string const tok = lex.GetString();
936 if (tok == "no_latex") {
938 insertErtContents(par, pos, font);
939 } else if (tok == "latex") {
940 ert_comp.active = true;
941 } else if (tok == "default") {
943 insertErtContents(par, pos, font);
945 lex.printError("Unknown LaTeX font flag "
949 } else if (token == "\\lang") {
951 string const tok = lex.GetString();
952 Language const * lang = languages.getLanguage(tok);
954 font.setLanguage(lang);
956 font.setLanguage(params.language);
957 lex.printError("Unknown language `$$Token'");
959 } else if (token == "\\numeric") {
961 font.setNumber(font.setLyXMisc(lex.GetString()));
962 } else if (token == "\\emph") {
964 font.setEmph(font.setLyXMisc(lex.GetString()));
965 } else if (token == "\\bar") {
967 string const tok = lex.GetString();
968 // This is dirty, but gone with LyX3. (Asger)
970 font.setUnderbar(LyXFont::ON);
971 else if (tok == "no")
972 font.setUnderbar(LyXFont::OFF);
973 else if (tok == "default")
974 font.setUnderbar(LyXFont::INHERIT);
976 lex.printError("Unknown bar font flag "
978 } else if (token == "\\noun") {
980 font.setNoun(font.setLyXMisc(lex.GetString()));
981 } else if (token == "\\color") {
983 font.setLyXColor(lex.GetString());
984 } else if (token == "\\align") {
985 int tmpret = lex.FindToken(string_align);
986 if (tmpret == -1) ++tmpret;
987 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
988 int const tmpret2 = int(pow(2.0, tmpret));
989 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
990 par->params().align(LyXAlignment(tmpret2));
992 } else if (token == "\\added_space_top") {
994 par->params().spaceTop(VSpace(lex.GetString()));
995 } else if (token == "\\added_space_bottom") {
997 par->params().spaceBottom(VSpace(lex.GetString()));
998 #ifndef NO_PEXTRA_REALLY
999 } else if (token == "\\pextra_type") {
1001 par->params().pextraType(lex.GetInteger());
1002 } else if (token == "\\pextra_width") {
1004 par->params().pextraWidth(lex.GetString());
1005 } else if (token == "\\pextra_widthp") {
1007 par->params().pextraWidthp(lex.GetString());
1008 } else if (token == "\\pextra_alignment") {
1010 par->params().pextraAlignment(lex.GetInteger());
1011 } else if (token == "\\pextra_hfill") {
1013 par->params().pextraHfill(lex.GetInteger());
1014 } else if (token == "\\pextra_start_minipage") {
1016 par->params().pextraStartMinipage(lex.GetInteger());
1018 } else if (token == "\\labelwidthstring") {
1020 par->params().labelWidthString(lex.GetString());
1021 // do not delete this token, it is still needed!
1022 } else if (token == "\\end_inset") {
1023 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1024 << "Last inset read was: " << last_inset_read
1026 // Simply ignore this. The insets do not have
1028 // But insets should read it, it is a part of
1029 // the inset isn't it? Lgb.
1030 } else if (token == "\\begin_inset") {
1032 insertErtContents(par, pos, font, false);
1033 ert_stack.push(ert_comp);
1034 ert_comp = ErtComp();
1036 readInset(lex, par, pos, font);
1038 ert_comp = ert_stack.top();
1041 } else if (token == "\\SpecialChar") {
1042 LyXLayout const & layout =
1043 textclasslist.Style(params.textclass,
1046 // Insets don't make sense in a free-spacing context! ---Kayvan
1047 if (layout.free_spacing) {
1050 string next_token = lex.GetString();
1051 if (next_token == "\\-") {
1052 par->insertChar(pos, '-', font);
1053 } else if (next_token == "\\protected_separator"
1054 || next_token == "~") {
1055 par->insertChar(pos, ' ', font);
1057 lex.printError("Token `$$Token' "
1059 "paragraph layout!");
1064 Inset * inset = new InsetSpecialChar;
1065 inset->read(this, lex);
1066 par->insertInset(pos, inset, font);
1069 } else if (token == "\\newline") {
1072 if (!ert_comp.in_tabular && ert_comp.active) {
1073 ert_comp.contents += char(Paragraph::META_NEWLINE);
1075 // Since we cannot know it this is only a regular
1076 // newline or a tabular cell delimter we have to
1077 // handle the ERT here.
1078 insertErtContents(par, pos, font, false);
1080 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1084 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1087 } else if (token == "\\LyXTable") {
1089 ert_comp.in_tabular = true;
1091 Inset * inset = new InsetTabular(*this);
1092 inset->read(this, lex);
1093 par->insertInset(pos, inset, font);
1095 // because of OLD_TABULAR_READ where tabulars have been
1097 checkminipage = true;
1098 } else if (token == "\\hfill") {
1099 par->insertChar(pos, Paragraph::META_HFILL, font);
1101 } else if (token == "\\protected_separator") { // obsolete
1102 // This is a backward compability thingie. (Lgb)
1103 // Remove it later some time...introduced with fileformat
1105 LyXLayout const & layout =
1106 textclasslist.Style(params.textclass,
1109 if (layout.free_spacing) {
1110 par->insertChar(pos, ' ', font);
1112 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1113 par->insertInset(pos, inset, font);
1116 } else if (token == "\\bibitem") { // ale970302
1118 InsetCommandParams p("bibitem", "dummy");
1119 par->bibkey = new InsetBibKey(p);
1121 par->bibkey->read(this, lex);
1122 } else if (token == "\\backslash") {
1124 if (ert_comp.active) {
1125 ert_comp.contents += "\\";
1128 par->insertChar(pos, '\\', font);
1133 } else if (token == "\\the_end") {
1135 // If we still have some ert active here we have to insert
1136 // it so we don't loose it. (Lgb)
1137 insertErtContents(par, pos, font);
1139 the_end_read = true;
1140 minipar = parBeforeMinipage = 0;
1143 if (ert_comp.active) {
1144 ert_comp.contents += token;
1147 // This should be insurance for the future: (Asger)
1148 lex.printError("Unknown token `$$Token'. "
1149 "Inserting as text.");
1150 string::const_iterator cit = token.begin();
1151 string::const_iterator end = token.end();
1152 for (; cit != end; ++cit) {
1153 par->insertChar(pos, (*cit), font);
1160 #ifndef NO_PEXTRA_REALLY
1161 // now check if we have a minipage paragraph as at this
1162 // point we already read all the necessary data!
1163 // this cannot be done in layout because there we did
1164 // not read yet the paragraph PEXTRA-params (Jug)
1166 // BEGIN pextra_minipage compability
1167 // This should be removed in 1.3.x (Lgb)
1169 // This compability code is not perfect. In a couple
1170 // of rand cases it fails. When the minipage par is
1171 // the first par in the document, and when there are
1172 // none or only one regular paragraphs after the
1173 // minipage. Currently I am not investing any effort
1174 // in fixing those cases.
1176 //lyxerr << "Call depth: " << call_depth << endl;
1177 if (checkminipage && (call_depth == 1)) {
1178 checkminipage = false;
1179 if (minipar && (minipar != par) &&
1180 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1182 lyxerr << "minipages in a row" << endl;
1183 if (par->params().pextraStartMinipage()) {
1184 lyxerr << "start new minipage" << endl;
1185 // minipages in a row
1186 par->previous()->next(0);
1189 Paragraph * tmp = minipar;
1191 tmp->params().pextraType(0);
1192 tmp->params().pextraWidth(string());
1193 tmp->params().pextraWidthp(string());
1194 tmp->params().pextraAlignment(0);
1195 tmp->params().pextraHfill(false);
1196 tmp->params().pextraStartMinipage(false);
1199 // create a new paragraph to insert the
1200 // minipages in the following case
1201 if (par->params().pextraStartMinipage() &&
1202 !par->params().pextraHfill())
1204 Paragraph * p = new Paragraph;
1206 p->previous(parBeforeMinipage);
1207 parBeforeMinipage->next(p);
1209 p->params().depth(parBeforeMinipage->params().depth());
1210 parBeforeMinipage = p;
1212 InsetMinipage * mini = new InsetMinipage;
1213 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1214 mini->width(par->params().pextraWidth());
1215 if (!par->params().pextraWidthp().empty()) {
1216 lyxerr << "WP:" << mini->width() << endl;
1217 mini->width(tostr(par->params().pextraWidthp())+"%");
1219 mini->inset.paragraph(par);
1220 // Insert the minipage last in the
1221 // previous paragraph.
1222 if (par->params().pextraHfill()) {
1223 parBeforeMinipage->insertChar
1224 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1226 parBeforeMinipage->insertInset
1227 (parBeforeMinipage->size(), mini);
1231 lyxerr << "new minipage par" << endl;
1232 //nothing to do just continue reading
1235 } else if (minipar && (minipar != par)) {
1236 lyxerr << "last minipage par read" << endl;
1237 // The last paragraph read was not part of a
1238 // minipage but the par linked list is...
1239 // So we need to remove the last par from the
1241 if (par->previous())
1242 par->previous()->next(0);
1243 par->previous(parBeforeMinipage);
1244 parBeforeMinipage->next(par);
1245 Paragraph * tmp = minipar;
1247 tmp->params().pextraType(0);
1248 tmp->params().pextraWidth(string());
1249 tmp->params().pextraWidthp(string());
1250 tmp->params().pextraAlignment(0);
1251 tmp->params().pextraHfill(false);
1252 tmp->params().pextraStartMinipage(false);
1255 depth = parBeforeMinipage->params().depth();
1256 minipar = parBeforeMinipage = 0;
1257 } else if (!minipar &&
1258 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1260 // par is the first paragraph in a minipage
1261 lyxerr << "begin minipage" << endl;
1262 // To minimize problems for
1263 // the users we will insert
1264 // the first minipage in
1265 // a sequence of minipages
1266 // in its own paragraph.
1267 Paragraph * p = new Paragraph;
1269 p->previous(par->previous());
1271 p->params().depth(depth);
1272 par->params().depth(0);
1274 if (par->previous())
1275 par->previous()->next(p);
1277 parBeforeMinipage = p;
1279 if (!first_par || (first_par == par))
1282 InsetMinipage * mini = new InsetMinipage;
1283 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1284 mini->width(minipar->params().pextraWidth());
1285 if (!par->params().pextraWidthp().empty()) {
1286 lyxerr << "WP:" << mini->width() << endl;
1287 mini->width(tostr(par->params().pextraWidthp())+"%");
1289 mini->inset.paragraph(minipar);
1291 // Insert the minipage last in the
1292 // previous paragraph.
1293 if (minipar->params().pextraHfill()) {
1294 parBeforeMinipage->insertChar
1295 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1297 parBeforeMinipage->insertInset
1298 (parBeforeMinipage->size(), mini);
1301 // End of pextra_minipage compability
1304 return the_end_read;
1308 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1309 int & pos, LyXFont & font)
1311 // consistency check
1312 if (lex.GetString() != "\\begin_inset") {
1313 lyxerr << "Buffer::readInset: Consistency check failed."
1320 string const tmptok = lex.GetString();
1321 last_inset_read = tmptok;
1323 // test the different insets
1324 if (tmptok == "LatexCommand") {
1325 InsetCommandParams inscmd;
1328 string const cmdName = inscmd.getCmdName();
1330 if (cmdName == "cite") {
1331 inset = new InsetCitation(inscmd);
1332 } else if (cmdName == "bibitem") {
1333 lex.printError("Wrong place for bibitem");
1334 inset = new InsetBibKey(inscmd);
1335 } else if (cmdName == "BibTeX") {
1336 inset = new InsetBibtex(inscmd);
1337 } else if (cmdName == "index") {
1338 inset = new InsetIndex(inscmd);
1339 } else if (cmdName == "include") {
1340 inset = new InsetInclude(inscmd, *this);
1341 } else if (cmdName == "label") {
1342 inset = new InsetLabel(inscmd);
1343 } else if (cmdName == "url"
1344 || cmdName == "htmlurl") {
1345 inset = new InsetUrl(inscmd);
1346 } else if (cmdName == "ref"
1347 || cmdName == "pageref"
1348 || cmdName == "vref"
1349 || cmdName == "vpageref"
1350 || cmdName == "prettyref") {
1351 if (!inscmd.getOptions().empty()
1352 || !inscmd.getContents().empty()) {
1353 inset = new InsetRef(inscmd, *this);
1355 } else if (cmdName == "tableofcontents") {
1356 inset = new InsetTOC(inscmd);
1357 } else if (cmdName == "listofalgorithms") {
1358 inset = new InsetFloatList("algorithm");
1359 } else if (cmdName == "listoffigures") {
1360 inset = new InsetFloatList("figure");
1361 } else if (cmdName == "listoftables") {
1362 inset = new InsetFloatList("table");
1363 } else if (cmdName == "printindex") {
1364 inset = new InsetPrintIndex(inscmd);
1365 } else if (cmdName == "lyxparent") {
1366 inset = new InsetParent(inscmd, *this);
1369 if (tmptok == "Quotes") {
1370 inset = new InsetQuotes;
1371 } else if (tmptok == "External") {
1372 inset = new InsetExternal;
1373 } else if (tmptok == "FormulaMacro") {
1374 inset = new InsetFormulaMacro;
1375 } else if (tmptok == "Formula") {
1376 inset = new InsetFormula;
1377 } else if (tmptok == "Figure") {
1378 inset = new InsetFig(100, 100, *this);
1379 } else if (tmptok == "Info") {
1380 inset = new InsetInfo;
1381 } else if (tmptok == "Include") {
1382 InsetCommandParams p( "Include" );
1383 inset = new InsetInclude(p, *this);
1384 } else if (tmptok == "ERT") {
1385 inset = new InsetERT;
1386 } else if (tmptok == "Tabular") {
1387 inset = new InsetTabular(*this);
1388 } else if (tmptok == "Text") {
1389 inset = new InsetText;
1390 } else if (tmptok == "Foot") {
1391 inset = new InsetFoot;
1392 } else if (tmptok == "Marginal") {
1393 inset = new InsetMarginal;
1394 } else if (tmptok == "Minipage") {
1395 inset = new InsetMinipage;
1396 } else if (tmptok == "Float") {
1398 string tmptok = lex.GetString();
1399 inset = new InsetFloat(tmptok);
1400 } else if (tmptok == "List") {
1401 inset = new InsetList;
1402 } else if (tmptok == "Theorem") {
1403 inset = new InsetList;
1404 } else if (tmptok == "Caption") {
1405 inset = new InsetCaption;
1406 } else if (tmptok == "GRAPHICS") {
1407 inset = new InsetGraphics;
1408 } else if (tmptok == "FloatList") {
1409 inset = new InsetFloatList;
1412 if (inset) inset->read(this, lex);
1416 par->insertInset(pos, inset, font);
1422 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1426 string const token(lex.GetString());
1427 if (token == "\\lyxformat") { // the first token _must_ be...
1429 string tmp_format = lex.GetString();
1430 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1431 // if present remove ".," from string.
1432 string::size_type dot = tmp_format.find_first_of(".,");
1433 //lyxerr << " dot found at " << dot << endl;
1434 if (dot != string::npos)
1435 tmp_format.erase(dot, 1);
1436 file_format = strToInt(tmp_format);
1437 if (file_format == LYX_FORMAT) {
1439 } else if (file_format > LYX_FORMAT) {
1441 WriteAlert(_("Warning!"),
1442 _("LyX file format is newer that what"),
1443 _("is supported in this LyX version. Expect some problems."));
1445 } else if (file_format < LYX_FORMAT) {
1447 if (file_format < 200) {
1448 WriteAlert(_("ERROR!"),
1449 _("Old LyX file format found. "
1450 "Use LyX 0.10.x to read this!"));
1454 bool the_end = readLyXformat2(lex, par);
1456 // the_end was added in 213
1457 if (file_format < 213)
1461 WriteAlert(_("Warning!"),
1462 _("Reading of document is not complete"),
1463 _("Maybe the document is truncated"));
1465 } else { // "\\lyxformat" not found
1466 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1469 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1474 // Should probably be moved to somewhere else: BufferView? LyXView?
1475 bool Buffer::save() const
1477 // We don't need autosaves in the immediate future. (Asger)
1478 resetAutosaveTimers();
1482 if (lyxrc.make_backup) {
1483 s = fileName() + '~';
1484 if (!lyxrc.backupdir_path.empty())
1485 s = AddName(lyxrc.backupdir_path,
1486 subst(os::slashify_path(s),'/','!'));
1488 // Rename is the wrong way of making a backup,
1489 // this is the correct way.
1490 /* truss cp fil fil2:
1491 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1492 stat("LyXVC.lyx", 0xEFFFF688) = 0
1493 open("LyXVC.lyx", O_RDONLY) = 3
1494 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1495 fstat(4, 0xEFFFF508) = 0
1496 fstat(3, 0xEFFFF508) = 0
1497 read(3, " # T h i s f i l e w".., 8192) = 5579
1498 write(4, " # T h i s f i l e w".., 5579) = 5579
1499 read(3, 0xEFFFD4A0, 8192) = 0
1502 chmod("LyXVC3.lyx", 0100644) = 0
1503 lseek(0, 0, SEEK_CUR) = 46440
1507 // Should probably have some more error checking here.
1508 // Should be cleaned up in 0.13, at least a bit.
1509 // Doing it this way, also makes the inodes stay the same.
1510 // This is still not a very good solution, in particular we
1511 // might loose the owner of the backup.
1512 FileInfo finfo(fileName());
1513 if (finfo.exist()) {
1514 mode_t fmode = finfo.getMode();
1515 struct utimbuf times = {
1516 finfo.getAccessTime(),
1517 finfo.getModificationTime() };
1519 ifstream ifs(fileName().c_str());
1520 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1525 ::chmod(s.c_str(), fmode);
1527 if (::utime(s.c_str(), ×)) {
1528 lyxerr << "utime error." << endl;
1531 lyxerr << "LyX was not able to make "
1532 "backup copy. Beware." << endl;
1537 if (writeFile(fileName(), false)) {
1539 removeAutosaveFile(fileName());
1541 // Saving failed, so backup is not backup
1542 if (lyxrc.make_backup) {
1543 lyx::rename(s, fileName());
1551 // Returns false if unsuccesful
1552 bool Buffer::writeFile(string const & fname, bool flag) const
1554 // if flag is false writeFile will not create any GUI
1555 // warnings, only cerr.
1556 // Needed for autosave in background or panic save (Matthias 120496)
1558 if (read_only && (fname == filename)) {
1559 // Here we should come with a question if we should
1560 // perform the write anyway.
1562 lyxerr << _("Error! Document is read-only: ")
1565 WriteAlert(_("Error! Document is read-only: "),
1570 FileInfo finfo(fname);
1571 if (finfo.exist() && !finfo.writable()) {
1572 // Here we should come with a question if we should
1573 // try to do the save anyway. (i.e. do a chmod first)
1575 lyxerr << _("Error! Cannot write file: ")
1578 WriteFSAlert(_("Error! Cannot write file: "),
1583 ofstream ofs(fname.c_str());
1586 lyxerr << _("Error! Cannot open file: ")
1589 WriteFSAlert(_("Error! Cannot open file: "),
1595 // Use the standard "C" locale for file output.
1596 ofs.imbue(std::locale::classic());
1599 // The top of the file should not be written by params.
1601 // write out a comment in the top of the file
1602 ofs << '#' << LYX_DOCVERSION
1603 << " created this file. For more info see http://www.lyx.org/\n"
1604 << "\\lyxformat " << LYX_FORMAT << "\n";
1606 // now write out the buffer paramters.
1607 params.writeFile(ofs);
1609 Paragraph::depth_type depth = 0;
1611 // this will write out all the paragraphs
1612 // using recursive descent.
1613 paragraph->writeFile(this, ofs, params, depth);
1615 // Write marker that shows file is complete
1616 ofs << "\n\\the_end" << endl;
1620 // how to check if close went ok?
1621 // Following is an attempt... (BE 20001011)
1623 // good() returns false if any error occured, including some
1624 // formatting error.
1625 // bad() returns true if something bad happened in the buffer,
1626 // which should include file system full errors.
1633 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1635 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1645 string const Buffer::asciiParagraph(Paragraph const * par,
1646 unsigned int linelen) const
1648 ostringstream buffer;
1649 Paragraph::depth_type depth = 0;
1651 Paragraph::depth_type ltype_depth = 0;
1652 unsigned int currlinelen = 0;
1653 bool ref_printed = false;
1657 if (!par->previous()) {
1658 // begins or ends a deeper area ?
1659 if (depth != par->params().depth()) {
1660 if (par->params().depth() > depth) {
1661 while (par->params().depth() > depth) {
1665 while (par->params().depth() < depth) {
1671 // First write the layout
1672 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1673 if (tmp == "Itemize") {
1675 ltype_depth = depth + 1;
1676 } else if (tmp == "Enumerate") {
1678 ltype_depth = depth + 1;
1679 } else if (contains(tmp, "ection")) {
1681 ltype_depth = depth + 1;
1682 } else if (contains(tmp, "aragraph")) {
1684 ltype_depth = depth + 1;
1685 } else if (tmp == "Description") {
1687 ltype_depth = depth + 1;
1688 } else if (tmp == "Abstract") {
1691 } else if (tmp == "Bibliography") {
1699 /* maybe some vertical spaces */
1701 /* the labelwidthstring used in lists */
1705 /* some pagebreaks? */
1709 /* what about the alignment */
1711 lyxerr << "Should this ever happen?" << endl;
1715 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1717 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1718 if (!i && !noparbreak) {
1721 for (Paragraph::depth_type j = 0; j < depth; ++j)
1723 currlinelen = depth * 2;
1726 case 4: // (Sub)Paragraph
1727 case 5: // Description
1731 buffer << "Abstract\n\n";
1733 buffer << "Abstract: ";
1735 case 7: // Bibliography
1738 buffer << "References\n\n";
1740 buffer << "References: ";
1745 buffer << par->params().labelString() << " ";
1748 if (ltype_depth > depth) {
1749 for (Paragraph::depth_type j = ltype_depth - 1;
1752 currlinelen += (ltype_depth-depth)*2;
1756 LyXFont const font2 = par->getFontSettings(params, i);
1757 if (font1.latex() != font2.latex()) {
1758 if (font2.latex() == LyXFont::OFF)
1767 char c = par->getUChar(params, i);
1771 case Paragraph::META_INSET:
1773 Inset const * inset = par->getInset(i);
1775 if (!inset->ascii(this, buffer)) {
1778 rsplit(buffer.str().c_str(),
1780 currlinelen += s.length();
1782 // to be sure it breaks paragraph
1783 currlinelen += linelen;
1789 case Paragraph::META_NEWLINE:
1792 for (Paragraph::depth_type j = 0;
1796 currlinelen = depth * 2;
1797 if (ltype_depth > depth) {
1798 for (Paragraph::depth_type j = ltype_depth;
1801 currlinelen += (ltype_depth - depth) * 2;
1805 case Paragraph::META_HFILL:
1814 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1815 (c == ' ') && ((i + 2) < par->size()))
1818 for (Paragraph::depth_type j = 0;
1821 currlinelen = depth * 2;
1822 if (ltype_depth > depth) {
1823 for (Paragraph::depth_type j = ltype_depth;
1826 currlinelen += (ltype_depth-depth)*2;
1828 } else if (c != '\0')
1831 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1836 return buffer.str().c_str();
1840 void Buffer::writeFileAscii(string const & fname, int linelen)
1842 ofstream ofs(fname.c_str());
1844 WriteFSAlert(_("Error: Cannot write file:"), fname);
1847 writeFileAscii(ofs, linelen);
1851 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1853 Paragraph * par = paragraph;
1855 ofs << asciiParagraph(par, linelen);
1863 void Buffer::makeLaTeXFile(string const & fname,
1864 string const & original_path,
1865 bool nice, bool only_body)
1867 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1869 niceFile = nice; // this will be used by Insetincludes.
1871 tex_code_break_column = lyxrc.ascii_linelen;
1873 LyXTextClass const & tclass =
1874 textclasslist.TextClass(params.textclass);
1876 ofstream ofs(fname.c_str());
1878 WriteFSAlert(_("Error: Cannot open file: "), fname);
1882 // validate the buffer.
1883 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1884 LaTeXFeatures features(params, tclass.numLayouts());
1886 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1889 // The starting paragraph of the coming rows is the
1890 // first paragraph of the document. (Asger)
1891 texrow.start(paragraph, 0);
1893 if (!only_body && nice) {
1894 ofs << "%% " LYX_DOCVERSION " created this file. "
1895 "For more info, see http://www.lyx.org/.\n"
1896 "%% Do not edit unless you really know what "
1901 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1902 // There are a few differences between nice LaTeX and usual files:
1903 // usual is \batchmode and has a
1904 // special input@path to allow the including of figures
1905 // with either \input or \includegraphics (what figinsets do).
1906 // batchmode is not set if there is a tex_code_break_column.
1907 // In this case somebody is interested in the generated LaTeX,
1908 // so this is OK. input@path is set when the actual parameter
1909 // original_path is set. This is done for usual tex-file, but not
1910 // for nice-latex-file. (Matthias 250696)
1913 // code for usual, NOT nice-latex-file
1914 ofs << "\\batchmode\n"; // changed
1915 // from \nonstopmode
1918 if (!original_path.empty()) {
1919 ofs << "\\makeatletter\n"
1920 << "\\def\\input@path{{"
1921 << os::external_path(original_path) << "/}}\n"
1922 << "\\makeatother\n";
1928 ofs << "\\documentclass";
1930 ostringstream options; // the document class options.
1932 if (tokenPos(tclass.opt_fontsize(),
1933 '|', params.fontsize) >= 0) {
1934 // only write if existing in list (and not default)
1935 options << params.fontsize << "pt,";
1939 if (!params.use_geometry &&
1940 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1941 switch (params.papersize) {
1942 case BufferParams::PAPER_A4PAPER:
1943 options << "a4paper,";
1945 case BufferParams::PAPER_USLETTER:
1946 options << "letterpaper,";
1948 case BufferParams::PAPER_A5PAPER:
1949 options << "a5paper,";
1951 case BufferParams::PAPER_B5PAPER:
1952 options << "b5paper,";
1954 case BufferParams::PAPER_EXECUTIVEPAPER:
1955 options << "executivepaper,";
1957 case BufferParams::PAPER_LEGALPAPER:
1958 options << "legalpaper,";
1964 if (params.sides != tclass.sides()) {
1965 switch (params.sides) {
1966 case LyXTextClass::OneSide:
1967 options << "oneside,";
1969 case LyXTextClass::TwoSides:
1970 options << "twoside,";
1976 if (params.columns != tclass.columns()) {
1977 if (params.columns == 2)
1978 options << "twocolumn,";
1980 options << "onecolumn,";
1983 if (!params.use_geometry
1984 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1985 options << "landscape,";
1987 // language should be a parameter to \documentclass
1989 ostringstream language_options;
1990 if (params.language->babel() == "hebrew"
1991 && default_language->babel() != "hebrew")
1992 // This seems necessary
1993 features.UsedLanguages.insert(default_language);
1995 if (lyxrc.language_use_babel ||
1996 params.language->lang() != lyxrc.default_language ||
1997 !features.UsedLanguages.empty()) {
1999 for (LaTeXFeatures::LanguageList::const_iterator cit =
2000 features.UsedLanguages.begin();
2001 cit != features.UsedLanguages.end(); ++cit)
2002 language_options << (*cit)->babel() << ',';
2003 language_options << params.language->babel();
2004 if (lyxrc.language_global_options)
2005 options << language_options.str() << ',';
2008 // the user-defined options
2009 if (!params.options.empty()) {
2010 options << params.options << ',';
2013 string strOptions(options.str().c_str());
2014 if (!strOptions.empty()){
2015 strOptions = strip(strOptions, ',');
2016 ofs << '[' << strOptions << ']';
2020 << textclasslist.LatexnameOfClass(params.textclass)
2023 // end of \documentclass defs
2025 // font selection must be done before loading fontenc.sty
2026 // The ae package is not needed when using OT1 font encoding.
2027 if (params.fonts != "default" &&
2028 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2029 ofs << "\\usepackage{" << params.fonts << "}\n";
2031 if (params.fonts == "ae") {
2032 ofs << "\\usepackage{aecompl}\n";
2036 // this one is not per buffer
2037 if (lyxrc.fontenc != "default") {
2038 ofs << "\\usepackage[" << lyxrc.fontenc
2043 if (params.inputenc == "auto") {
2044 string const doc_encoding =
2045 params.language->encoding()->LatexName();
2047 // Create a list with all the input encodings used
2049 set<string> encodings;
2050 for (LaTeXFeatures::LanguageList::const_iterator it =
2051 features.UsedLanguages.begin();
2052 it != features.UsedLanguages.end(); ++it)
2053 if ((*it)->encoding()->LatexName() != doc_encoding)
2054 encodings.insert((*it)->encoding()->LatexName());
2056 ofs << "\\usepackage[";
2057 std::copy(encodings.begin(), encodings.end(),
2058 std::ostream_iterator<string>(ofs, ","));
2059 ofs << doc_encoding << "]{inputenc}\n";
2061 } else if (params.inputenc != "default") {
2062 ofs << "\\usepackage[" << params.inputenc
2067 // At the very beginning the text parameters.
2068 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2069 switch (params.paperpackage) {
2070 case BufferParams::PACKAGE_A4:
2071 ofs << "\\usepackage{a4}\n";
2074 case BufferParams::PACKAGE_A4WIDE:
2075 ofs << "\\usepackage{a4wide}\n";
2078 case BufferParams::PACKAGE_WIDEMARGINSA4:
2079 ofs << "\\usepackage[widemargins]{a4}\n";
2084 if (params.use_geometry) {
2085 ofs << "\\usepackage{geometry}\n";
2087 ofs << "\\geometry{verbose";
2088 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2089 ofs << ",landscape";
2090 switch (params.papersize2) {
2091 case BufferParams::VM_PAPER_CUSTOM:
2092 if (!params.paperwidth.empty())
2093 ofs << ",paperwidth="
2094 << params.paperwidth;
2095 if (!params.paperheight.empty())
2096 ofs << ",paperheight="
2097 << params.paperheight;
2099 case BufferParams::VM_PAPER_USLETTER:
2100 ofs << ",letterpaper";
2102 case BufferParams::VM_PAPER_USLEGAL:
2103 ofs << ",legalpaper";
2105 case BufferParams::VM_PAPER_USEXECUTIVE:
2106 ofs << ",executivepaper";
2108 case BufferParams::VM_PAPER_A3:
2111 case BufferParams::VM_PAPER_A4:
2114 case BufferParams::VM_PAPER_A5:
2117 case BufferParams::VM_PAPER_B3:
2120 case BufferParams::VM_PAPER_B4:
2123 case BufferParams::VM_PAPER_B5:
2127 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2128 switch (lyxrc.default_papersize) {
2129 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2130 case BufferParams::PAPER_USLETTER:
2131 ofs << ",letterpaper";
2133 case BufferParams::PAPER_LEGALPAPER:
2134 ofs << ",legalpaper";
2136 case BufferParams::PAPER_EXECUTIVEPAPER:
2137 ofs << ",executivepaper";
2139 case BufferParams::PAPER_A3PAPER:
2142 case BufferParams::PAPER_A4PAPER:
2145 case BufferParams::PAPER_A5PAPER:
2148 case BufferParams::PAPER_B5PAPER:
2153 if (!params.topmargin.empty())
2154 ofs << ",tmargin=" << params.topmargin;
2155 if (!params.bottommargin.empty())
2156 ofs << ",bmargin=" << params.bottommargin;
2157 if (!params.leftmargin.empty())
2158 ofs << ",lmargin=" << params.leftmargin;
2159 if (!params.rightmargin.empty())
2160 ofs << ",rmargin=" << params.rightmargin;
2161 if (!params.headheight.empty())
2162 ofs << ",headheight=" << params.headheight;
2163 if (!params.headsep.empty())
2164 ofs << ",headsep=" << params.headsep;
2165 if (!params.footskip.empty())
2166 ofs << ",footskip=" << params.footskip;
2170 if (features.amsstyle
2171 && !tclass.provides(LyXTextClass::amsmath)) {
2172 ofs << "\\usepackage{amsmath}\n";
2176 if (tokenPos(tclass.opt_pagestyle(),
2177 '|', params.pagestyle) >= 0) {
2178 if (params.pagestyle == "fancy") {
2179 ofs << "\\usepackage{fancyhdr}\n";
2182 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2186 // We try to load babel late, in case it interferes
2187 // with other packages.
2189 string tmp = lyxrc.language_package;
2190 if (!lyxrc.language_global_options
2191 && tmp == "\\usepackage{babel}")
2192 tmp = string("\\usepackage[") +
2193 language_options.str().c_str() +
2199 if (params.secnumdepth != tclass.secnumdepth()) {
2200 ofs << "\\setcounter{secnumdepth}{"
2201 << params.secnumdepth
2205 if (params.tocdepth != tclass.tocdepth()) {
2206 ofs << "\\setcounter{tocdepth}{"
2212 if (params.paragraph_separation) {
2213 switch (params.defskip.kind()) {
2214 case VSpace::SMALLSKIP:
2215 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2217 case VSpace::MEDSKIP:
2218 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2220 case VSpace::BIGSKIP:
2221 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2223 case VSpace::LENGTH:
2224 ofs << "\\setlength\\parskip{"
2225 << params.defskip.length().asLatexString()
2228 default: // should never happen // Then delete it.
2229 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2234 ofs << "\\setlength\\parindent{0pt}\n";
2238 // Now insert the LyX specific LaTeX commands...
2240 // The optional packages;
2241 string preamble(features.getPackages());
2243 // this might be useful...
2244 preamble += "\n\\makeatletter\n";
2246 // Some macros LyX will need
2247 string tmppreamble(features.getMacros());
2249 if (!tmppreamble.empty()) {
2250 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2251 "LyX specific LaTeX commands.\n"
2252 + tmppreamble + '\n';
2255 // the text class specific preamble
2256 tmppreamble = features.getTClassPreamble();
2257 if (!tmppreamble.empty()) {
2258 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2259 "Textclass specific LaTeX commands.\n"
2260 + tmppreamble + '\n';
2263 /* the user-defined preamble */
2264 if (!params.preamble.empty()) {
2265 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2266 "User specified LaTeX commands.\n"
2267 + params.preamble + '\n';
2270 preamble += "\\makeatother\n";
2272 // Itemize bullet settings need to be last in case the user
2273 // defines their own bullets that use a package included
2274 // in the user-defined preamble -- ARRae
2275 // Actually it has to be done much later than that
2276 // since some packages like frenchb make modifications
2277 // at \begin{document} time -- JMarc
2279 for (int i = 0; i < 4; ++i) {
2280 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2281 if (bullets_def.empty())
2282 bullets_def="\\AtBeginDocument{\n";
2283 bullets_def += " \\renewcommand{\\labelitemi";
2285 // `i' is one less than the item to modify
2292 bullets_def += "ii";
2298 bullets_def += "}{" +
2299 params.user_defined_bullets[i].getText()
2304 if (!bullets_def.empty())
2305 preamble += bullets_def + "}\n\n";
2307 for (int j = countChar(preamble, '\n'); j-- ;) {
2314 ofs << "\\begin{document}\n";
2317 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2319 if (!lyxrc.language_auto_begin) {
2320 ofs << subst(lyxrc.language_command_begin, "$$lang",
2321 params.language->babel())
2326 latexParagraphs(ofs, paragraph, 0, texrow);
2328 // add this just in case after all the paragraphs
2332 if (!lyxrc.language_auto_end) {
2333 ofs << subst(lyxrc.language_command_end, "$$lang",
2334 params.language->babel())
2340 ofs << "\\end{document}\n";
2343 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2345 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2349 // Just to be sure. (Asger)
2352 // tex_code_break_column's value is used to decide
2353 // if we are in batchmode or not (within mathed_write()
2354 // in math_write.C) so we must set it to a non-zero
2355 // value when we leave otherwise we save incorrect .lyx files.
2356 tex_code_break_column = lyxrc.ascii_linelen;
2360 lyxerr << "File was not closed properly." << endl;
2363 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2368 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2370 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2371 Paragraph * endpar, TexRow & texrow) const
2373 bool was_title = false;
2374 bool already_title = false;
2377 while (par != endpar) {
2378 LyXLayout const & layout =
2379 textclasslist.Style(params.textclass,
2382 if (layout.intitle) {
2383 if (already_title) {
2384 lyxerr <<"Error in latexParagraphs: You"
2385 " should not mix title layouts"
2386 " with normal ones." << endl;
2389 } else if (was_title && !already_title) {
2390 ofs << "\\maketitle\n";
2392 already_title = true;
2396 if (layout.isEnvironment()) {
2397 par = par->TeXEnvironment(this, params, ofs, texrow);
2399 par = par->TeXOnePar(this, params, ofs, texrow, false);
2402 // It might be that we only have a title in this document
2403 if (was_title && !already_title) {
2404 ofs << "\\maketitle\n";
2410 bool Buffer::isLatex() const
2412 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2416 bool Buffer::isLinuxDoc() const
2418 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2422 bool Buffer::isLiterate() const
2424 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2428 bool Buffer::isDocBook() const
2430 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2434 bool Buffer::isSGML() const
2436 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2437 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2441 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2442 string const & latexname) const
2444 if (!latexname.empty() && latexname != "!-- --")
2445 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2446 //os << string(depth, ' ') << "<" << latexname << ">\n";
2450 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2451 string const & latexname) const
2453 if (!latexname.empty() && latexname != "!-- --")
2454 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2455 //os << string(depth, ' ') << "</" << latexname << ">\n";
2459 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2461 ofstream ofs(fname.c_str());
2464 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2468 niceFile = nice; // this will be used by included files.
2470 LyXTextClass const & tclass =
2471 textclasslist.TextClass(params.textclass);
2473 LaTeXFeatures features(params, tclass.numLayouts());
2478 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2481 string sgml_includedfiles=features.getIncludedFiles(fname);
2483 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2484 ofs << "<!doctype linuxdoc system>\n\n";
2486 ofs << "<!doctype linuxdoc system [ "
2487 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2490 if (params.options.empty())
2491 sgmlOpenTag(ofs, 0, top_element);
2493 string top = top_element;
2495 top += params.options;
2496 sgmlOpenTag(ofs, 0, top);
2500 ofs << "<!-- " << LYX_DOCVERSION
2501 << " created this file. For more info see http://www.lyx.org/"
2504 Paragraph::depth_type depth = 0; // paragraph depth
2505 Paragraph * par = paragraph;
2507 vector<string> environment_stack(5);
2510 LyXLayout const & style =
2511 textclasslist.Style(params.textclass,
2514 // treat <toc> as a special case for compatibility with old code
2515 if (par->getChar(0) == Paragraph::META_INSET) {
2516 Inset * inset = par->getInset(0);
2517 Inset::Code lyx_code = inset->lyxCode();
2518 if (lyx_code == Inset::TOC_CODE){
2519 string const temp = "toc";
2520 sgmlOpenTag(ofs, depth, temp);
2527 // environment tag closing
2528 for (; depth > par->params().depth(); --depth) {
2529 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2530 environment_stack[depth].erase();
2533 // write opening SGML tags
2534 switch (style.latextype) {
2535 case LATEX_PARAGRAPH:
2536 if (depth == par->params().depth()
2537 && !environment_stack[depth].empty()) {
2538 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2539 environment_stack[depth].erase();
2545 sgmlOpenTag(ofs, depth, style.latexname());
2550 linuxDocError(par, 0,
2551 _("Error : Wrong depth for"
2552 " LatexType Command.\n"));
2554 if (!environment_stack[depth].empty()){
2555 sgmlCloseTag(ofs, depth,
2556 environment_stack[depth]);
2560 environment_stack[depth].erase();
2561 sgmlOpenTag(ofs, depth, style.latexname());
2564 case LATEX_ENVIRONMENT:
2565 case LATEX_ITEM_ENVIRONMENT:
2566 if (depth == par->params().depth()
2567 && environment_stack[depth] != style.latexname()) {
2568 sgmlCloseTag(ofs, depth,
2569 environment_stack[depth]);
2570 environment_stack[depth].erase();
2572 if (depth < par->params().depth()) {
2573 depth = par->params().depth();
2574 environment_stack[depth].erase();
2576 if (environment_stack[depth] != style.latexname()) {
2578 sgmlOpenTag(ofs, depth, "p");
2580 sgmlOpenTag(ofs, depth, style.latexname());
2582 if (environment_stack.size() == depth + 1)
2583 environment_stack.push_back("!-- --");
2584 environment_stack[depth] = style.latexname();
2587 if (style.latexparam() == "CDATA")
2590 if (style.latextype == LATEX_ENVIRONMENT) break;
2592 if (style.labeltype == LABEL_MANUAL)
2597 sgmlOpenTag(ofs, depth + 1, item_name);
2600 sgmlOpenTag(ofs, depth, style.latexname());
2604 simpleLinuxDocOnePar(ofs, par, depth);
2609 // write closing SGML tags
2610 switch (style.latextype) {
2613 case LATEX_ENVIRONMENT:
2614 case LATEX_ITEM_ENVIRONMENT:
2615 if (style.latexparam() == "CDATA")
2619 sgmlCloseTag(ofs, depth, style.latexname());
2625 for (int i=depth; i >= 0; --i)
2626 sgmlCloseTag(ofs, depth, environment_stack[i]);
2630 sgmlCloseTag(ofs, 0, top_element);
2634 // How to check for successful close
2638 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2639 Paragraph::depth_type depth, int desc_on,
2642 Paragraph * tpar = par;
2644 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2646 tpar = tpar->next();
2649 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2650 "Caption").second) {
2651 sgmlOpenTag(os, depth + 1, inner_tag);
2653 simpleDocBookOnePar(os, extra_par, tpar,
2654 desc_on, depth + 2);
2655 sgmlCloseTag(os, depth+1, inner_tag);
2656 if (!extra_par.empty())
2662 // checks, if newcol chars should be put into this line
2663 // writes newline, if necessary.
2666 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2667 string::size_type newcol)
2670 if (colcount > lyxrc.ascii_linelen) {
2672 colcount = newcol; // assume write after this call
2687 string tag_name(PAR_TAG const & pt) {
2689 case NONE: return "!-- --";
2690 case TT: return "tt";
2691 case SF: return "sf";
2692 case BF: return "bf";
2693 case IT: return "it";
2694 case SL: return "sl";
2695 case EM: return "em";
2702 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2704 p1 = static_cast<PAR_TAG>(p1 | p2);
2709 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2711 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2719 // Handle internal paragraph parsing -- layout already processed.
2720 void Buffer::simpleLinuxDocOnePar(ostream & os,
2722 Paragraph::depth_type /*depth*/)
2724 LyXLayout const & style = textclasslist.Style(params.textclass,
2726 string::size_type char_line_count = 5; // Heuristic choice ;-)
2728 // gets paragraph main font
2731 if (style.labeltype == LABEL_MANUAL) {
2732 font_old = style.labelfont;
2735 font_old = style.font;
2739 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2740 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2741 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2744 stack < PAR_TAG > tag_state;
2745 // parsing main loop
2746 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2748 PAR_TAG tag_close = NONE;
2749 list < PAR_TAG > tag_open;
2751 LyXFont const font = par->getFont(params, i);
2753 if (font_old.family() != font.family()) {
2754 switch (family_type) {
2755 case LyXFont::SANS_FAMILY:
2758 case LyXFont::TYPEWRITER_FAMILY:
2765 family_type = font.family();
2767 switch (family_type) {
2768 case LyXFont::SANS_FAMILY:
2769 tag_open.push_back(SF);
2771 case LyXFont::TYPEWRITER_FAMILY:
2772 tag_open.push_back(TT);
2779 if (font_old.series() != font.series()) {
2780 switch (series_type) {
2781 case LyXFont::BOLD_SERIES:
2788 series_type = font.series();
2790 switch (series_type) {
2791 case LyXFont::BOLD_SERIES:
2792 tag_open.push_back(BF);
2800 if (font_old.shape() != font.shape()) {
2801 switch (shape_type) {
2802 case LyXFont::ITALIC_SHAPE:
2805 case LyXFont::SLANTED_SHAPE:
2812 shape_type = font.shape();
2814 switch (shape_type) {
2815 case LyXFont::ITALIC_SHAPE:
2816 tag_open.push_back(IT);
2818 case LyXFont::SLANTED_SHAPE:
2819 tag_open.push_back(SL);
2826 if (font_old.emph() != font.emph()) {
2827 if (font.emph() == LyXFont::ON) {
2828 tag_open.push_back(EM);
2837 list < PAR_TAG > temp;
2838 while(!tag_state.empty() && tag_close ) {
2839 PAR_TAG k = tag_state.top();
2841 os << "</" << tag_name(k) << ">";
2848 for(list< PAR_TAG >::const_iterator j = temp.begin();
2849 j != temp.end(); ++j) {
2851 os << "<" << tag_name(*j) << ">";
2854 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2855 j != tag_open.end(); ++j) {
2857 os << "<" << tag_name(*j) << ">";
2860 char c = par->getChar(i);
2862 if (c == Paragraph::META_INSET) {
2863 Inset * inset = par->getInset(i);
2864 inset->linuxdoc(this, os);
2871 font.latex() == LyXFont::ON ||
2873 style.latexparam() == "CDATA") {
2874 // "TeX"-Mode on == > SGML-Mode on.
2880 if (par->linuxDocConvertChar(c, sgml_string)
2881 && !style.free_spacing) {
2882 // in freespacing mode, spaces are
2883 // non-breaking characters
2884 if (desc_on) {// if char is ' ' then...
2887 linux_doc_line_break(os, char_line_count, 6);
2891 linux_doc_line_break(os, char_line_count, 1);
2896 char_line_count += sgml_string.length();
2902 while (!tag_state.empty()) {
2903 os << "</" << tag_name(tag_state.top()) << ">";
2907 // resets description flag correctly
2909 // <tag> not closed...
2910 linux_doc_line_break(os, char_line_count, 6);
2916 // Print an error message.
2917 void Buffer::linuxDocError(Paragraph * par, int pos,
2918 string const & message)
2920 // insert an error marker in text
2921 InsetError * new_inset = new InsetError(message);
2922 par->insertInset(pos, new_inset);
2926 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2928 ofstream ofs(fname.c_str());
2930 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2934 Paragraph * par = paragraph;
2936 niceFile = nice; // this will be used by Insetincludes.
2938 LyXTextClass const & tclass =
2939 textclasslist.TextClass(params.textclass);
2941 LaTeXFeatures features(params, tclass.numLayouts());
2946 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2949 string sgml_includedfiles = features.getIncludedFiles(fname);
2951 ofs << "<!doctype " << top_element
2952 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2954 if (params.preamble.empty() && sgml_includedfiles.empty())
2957 ofs << "\n [ " << params.preamble
2958 << sgml_includedfiles << " \n]>\n\n";
2961 string top = top_element;
2963 top += params.language->code();
2966 if (!params.options.empty()) {
2968 top += params.options;
2970 sgmlOpenTag(ofs, 0, top);
2972 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2973 << "\n See http://www.lyx.org/ for more information -->\n";
2975 vector<string> environment_stack(10);
2976 vector<string> environment_inner(10);
2977 vector<string> command_stack(10);
2979 bool command_flag = false;
2980 Paragraph::depth_type command_depth = 0;
2981 Paragraph::depth_type command_base = 0;
2982 Paragraph::depth_type cmd_depth = 0;
2983 Paragraph::depth_type depth = 0; // paragraph depth
2986 string command_name;
2992 int desc_on = 0; // description mode
2994 LyXLayout const & style =
2995 textclasslist.Style(params.textclass,
2998 // environment tag closing
2999 for (; depth > par->params().depth(); --depth) {
3000 if (environment_inner[depth] != "!-- --") {
3001 item_name = "listitem";
3002 sgmlCloseTag(ofs, command_depth + depth,
3004 if (environment_inner[depth] == "varlistentry")
3005 sgmlCloseTag(ofs, depth+command_depth,
3006 environment_inner[depth]);
3008 sgmlCloseTag(ofs, depth + command_depth,
3009 environment_stack[depth]);
3010 environment_stack[depth].erase();
3011 environment_inner[depth].erase();
3014 if (depth == par->params().depth()
3015 && environment_stack[depth] != style.latexname()
3016 && !environment_stack[depth].empty()) {
3017 if (environment_inner[depth] != "!-- --") {
3018 item_name= "listitem";
3019 sgmlCloseTag(ofs, command_depth+depth,
3021 if (environment_inner[depth] == "varlistentry")
3023 depth + command_depth,
3024 environment_inner[depth]);
3027 sgmlCloseTag(ofs, depth + command_depth,
3028 environment_stack[depth]);
3030 environment_stack[depth].erase();
3031 environment_inner[depth].erase();
3034 // Write opening SGML tags.
3035 switch (style.latextype) {
3036 case LATEX_PARAGRAPH:
3037 sgmlOpenTag(ofs, depth + command_depth,
3043 linuxDocError(par, 0,
3044 _("Error : Wrong depth for "
3045 "LatexType Command.\n"));
3047 command_name = style.latexname();
3049 sgmlparam = style.latexparam();
3050 c_params = split(sgmlparam, c_depth,'|');
3052 cmd_depth = lyx::atoi(c_depth);
3055 if (cmd_depth < command_base) {
3056 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3057 sgmlCloseTag(ofs, j, command_stack[j]);
3058 command_depth = command_base = cmd_depth;
3059 } else if (cmd_depth <= command_depth) {
3060 for (int j = command_depth; j >= int(cmd_depth); --j)
3061 sgmlCloseTag(ofs, j, command_stack[j]);
3062 command_depth = cmd_depth;
3064 command_depth = cmd_depth;
3066 command_depth = command_base = cmd_depth;
3067 command_flag = true;
3069 if (command_stack.size() == command_depth + 1)
3070 command_stack.push_back(string());
3071 command_stack[command_depth] = command_name;
3073 // treat label as a special case for
3074 // more WYSIWYM handling.
3075 if (par->getChar(0) == Paragraph::META_INSET) {
3076 Inset * inset = par->getInset(0);
3077 Inset::Code lyx_code = inset->lyxCode();
3078 if (lyx_code == Inset::LABEL_CODE){
3079 command_name += " id=\"";
3080 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3081 command_name += "\"";
3086 sgmlOpenTag(ofs, depth + command_depth, command_name);
3087 if (c_params.empty())
3088 item_name = "title";
3090 item_name = c_params;
3091 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3094 case LATEX_ENVIRONMENT:
3095 case LATEX_ITEM_ENVIRONMENT:
3096 if (depth < par->params().depth()) {
3097 depth = par->params().depth();
3098 environment_stack[depth].erase();
3101 if (environment_stack[depth] != style.latexname()) {
3102 if(environment_stack.size() == depth + 1) {
3103 environment_stack.push_back("!-- --");
3104 environment_inner.push_back("!-- --");
3106 environment_stack[depth] = style.latexname();
3107 environment_inner[depth] = "!-- --";
3108 sgmlOpenTag(ofs, depth + command_depth,
3109 environment_stack[depth]);
3111 if (environment_inner[depth] != "!-- --") {
3112 item_name= "listitem";
3114 command_depth + depth,
3116 if (environment_inner[depth] == "varlistentry")
3118 depth + command_depth,
3119 environment_inner[depth]);
3123 if (style.latextype == LATEX_ENVIRONMENT) {
3124 if (!style.latexparam().empty()) {
3125 if(style.latexparam() == "CDATA")
3128 sgmlOpenTag(ofs, depth + command_depth,
3129 style.latexparam());
3134 desc_on = (style.labeltype == LABEL_MANUAL);
3137 environment_inner[depth]= "varlistentry";
3139 environment_inner[depth]= "listitem";
3141 sgmlOpenTag(ofs, depth + 1 + command_depth,
3142 environment_inner[depth]);
3146 sgmlOpenTag(ofs, depth + 1 + command_depth,
3150 sgmlOpenTag(ofs, depth + 1 + command_depth,
3155 sgmlOpenTag(ofs, depth + command_depth,
3161 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3162 depth + 1 + command_depth);
3166 // write closing SGML tags
3167 switch (style.latextype) {
3169 if (c_params.empty())
3173 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3175 case LATEX_ENVIRONMENT:
3176 if (!style.latexparam().empty()) {
3177 if(style.latexparam() == "CDATA")
3180 sgmlCloseTag(ofs, depth + command_depth,
3181 style.latexparam());
3184 case LATEX_ITEM_ENVIRONMENT:
3185 if (desc_on == 1) break;
3187 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3189 case LATEX_PARAGRAPH:
3190 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3193 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3199 for (int d = depth; d >= 0; --d) {
3200 if (!environment_stack[depth].empty()) {
3201 if (environment_inner[depth] != "!-- --") {
3202 item_name = "listitem";
3203 sgmlCloseTag(ofs, command_depth + depth,
3205 if (environment_inner[depth] == "varlistentry")
3206 sgmlCloseTag(ofs, depth + command_depth,
3207 environment_inner[depth]);
3210 sgmlCloseTag(ofs, depth + command_depth,
3211 environment_stack[depth]);
3215 for (int j = command_depth; j >= 0 ; --j)
3216 if (!command_stack[j].empty())
3217 sgmlCloseTag(ofs, j, command_stack[j]);
3220 sgmlCloseTag(ofs, 0, top_element);
3223 // How to check for successful close
3227 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3228 Paragraph * par, int & desc_on,
3229 Paragraph::depth_type depth) const
3231 bool emph_flag = false;
3233 LyXLayout const & style = textclasslist.Style(params.textclass,
3236 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3238 int char_line_count = depth;
3239 //if (!style.free_spacing)
3240 // os << string(depth,' ');
3242 // parsing main loop
3243 for (Paragraph::size_type i = 0;
3244 i < par->size(); ++i) {
3245 LyXFont font = par->getFont(params, i);
3247 // handle <emphasis> tag
3248 if (font_old.emph() != font.emph()) {
3249 if (font.emph() == LyXFont::ON) {
3253 os << "</emphasis>";
3258 char c = par->getChar(i);
3260 if (c == Paragraph::META_INSET) {
3261 Inset * inset = par->getInset(i);
3263 inset->docBook(this, ost);
3264 string tmp_out = ost.str().c_str();
3267 // This code needs some explanation:
3268 // Two insets are treated specially
3269 // label if it is the first element in a command paragraph
3271 // graphics inside tables or figure floats can't go on
3272 // title (the equivalente in latex for this case is caption
3273 // and title should come first
3276 if (desc_on!= 3 || i!= 0) {
3277 if (!tmp_out.empty() && tmp_out[0] == '@') {
3279 extra += frontStrip(tmp_out, '@');
3281 os << frontStrip(tmp_out, '@');
3287 } else if (font.latex() == LyXFont::ON) {
3288 // "TeX"-Mode on ==> SGML-Mode on.
3295 if (par->linuxDocConvertChar(c, sgml_string)
3296 && !style.free_spacing) { // in freespacing
3298 // non-breaking characters
3302 os << "\n</term><listitem><para>";
3315 os << "</emphasis>";
3318 // resets description flag correctly
3320 // <term> not closed...
3323 if(style.free_spacing) os << '\n';
3327 // This should be enabled when the Chktex class is implemented. (Asger)
3328 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3329 // Other flags: -wall -v0 -x
3330 int Buffer::runChktex()
3332 if (!users->text) return 0;
3334 users->owner()->prohibitInput();
3336 // get LaTeX-Filename
3337 string const name = getLatexName();
3338 string path = OnlyPath(filename);
3340 string const org_path = path;
3341 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3345 Path p(path); // path to LaTeX file
3346 users->owner()->message(_("Running chktex..."));
3348 // Remove all error insets
3349 bool const removedErrorInsets = users->removeAutoInsets();
3351 // Generate the LaTeX file if neccessary
3352 makeLaTeXFile(name, org_path, false);
3355 Chktex chktex(lyxrc.chktex_command, name, filepath);
3356 int res = chktex.run(terr); // run chktex
3359 WriteAlert(_("chktex did not work!"),
3360 _("Could not run with file:"), name);
3361 } else if (res > 0) {
3362 // Insert all errors as errors boxes
3363 users->insertErrors(terr);
3366 // if we removed error insets before we ran chktex or if we inserted
3367 // error insets after we ran chktex, this must be run:
3368 if (removedErrorInsets || res){
3370 users->fitCursor(users->text);
3372 users->owner()->allowInput();
3378 void Buffer::validate(LaTeXFeatures & features) const
3380 Paragraph * par = paragraph;
3381 LyXTextClass const & tclass =
3382 textclasslist.TextClass(params.textclass);
3384 // AMS Style is at document level
3386 features.amsstyle = (params.use_amsmath ||
3387 tclass.provides(LyXTextClass::amsmath));
3390 // We don't use "lyxerr.debug" because of speed. (Asger)
3391 if (lyxerr.debugging(Debug::LATEX))
3392 lyxerr << "Paragraph: " << par << endl;
3394 // Now just follow the list of paragraphs and run
3395 // validate on each of them.
3396 par->validate(features);
3398 // and then the next paragraph
3402 // the bullet shapes are buffer level not paragraph level
3403 // so they are tested here
3404 for (int i = 0; i < 4; ++i) {
3405 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3406 int const font = params.user_defined_bullets[i].getFont();
3408 int const c = params
3409 .user_defined_bullets[i]
3416 features.latexsym = true;
3418 } else if (font == 1) {
3419 features.amssymb = true;
3420 } else if ((font >= 2 && font <= 5)) {
3421 features.pifont = true;
3426 if (lyxerr.debugging(Debug::LATEX)) {
3427 features.showStruct();
3432 void Buffer::setPaperStuff()
3434 params.papersize = BufferParams::PAPER_DEFAULT;
3435 char const c1 = params.paperpackage;
3436 if (c1 == BufferParams::PACKAGE_NONE) {
3437 char const c2 = params.papersize2;
3438 if (c2 == BufferParams::VM_PAPER_USLETTER)
3439 params.papersize = BufferParams::PAPER_USLETTER;
3440 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3441 params.papersize = BufferParams::PAPER_LEGALPAPER;
3442 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3443 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3444 else if (c2 == BufferParams::VM_PAPER_A3)
3445 params.papersize = BufferParams::PAPER_A3PAPER;
3446 else if (c2 == BufferParams::VM_PAPER_A4)
3447 params.papersize = BufferParams::PAPER_A4PAPER;
3448 else if (c2 == BufferParams::VM_PAPER_A5)
3449 params.papersize = BufferParams::PAPER_A5PAPER;
3450 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3451 (c2 == BufferParams::VM_PAPER_B5))
3452 params.papersize = BufferParams::PAPER_B5PAPER;
3453 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3454 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3455 params.papersize = BufferParams::PAPER_A4PAPER;
3459 // This function should be in Buffer because it's a buffer's property (ale)
3460 string const Buffer::getIncludeonlyList(char delim)
3463 for (inset_iterator it = inset_iterator_begin();
3464 it != inset_iterator_end(); ++it) {
3465 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3466 InsetInclude * insetinc =
3467 static_cast<InsetInclude *>(*it);
3468 if (insetinc->isIncludeOnly()) {
3471 lst += insetinc->getRelFileBaseName();
3475 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3480 vector<string> const Buffer::getLabelList()
3482 /// if this is a child document and the parent is already loaded
3483 /// Use the parent's list instead [ale990407]
3484 if (!params.parentname.empty()
3485 && bufferlist.exists(params.parentname)) {
3486 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3488 return tmp->getLabelList();
3491 vector<string> label_list;
3492 for (inset_iterator it = inset_iterator_begin();
3493 it != inset_iterator_end(); ++it) {
3494 vector<string> const l = (*it)->getLabelList();
3495 label_list.insert(label_list.end(), l.begin(), l.end());
3501 Buffer::Lists const Buffer::getLists() const
3504 Paragraph * par = paragraph;
3506 LyXTextClassList::size_type cap;
3507 boost::tie(found, cap) = textclasslist
3508 .NumberOfLayout(params.textclass, "Caption");
3511 char const labeltype =
3512 textclasslist.Style(params.textclass,
3513 par->getLayout()).labeltype;
3515 if (labeltype >= LABEL_COUNTER_CHAPTER
3516 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3517 // insert this into the table of contents
3518 SingleList & item = l["TOC"];
3521 textclasslist.TextClass(params.textclass).maxcounter());
3522 item.push_back(TocItem(par, depth, par->asString(this, true)));
3524 // For each paragrph, traverse its insets and look for
3528 Paragraph::inset_iterator it =
3529 par->inset_iterator_begin();
3530 Paragraph::inset_iterator end =
3531 par->inset_iterator_end();
3533 for (; it != end; ++it) {
3534 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3536 static_cast<InsetFloat*>(*it);
3538 string const type = il->type();
3540 // Now find the caption in the float...
3541 // We now tranverse the paragraphs of
3543 Paragraph * tmp = il->inset.paragraph();
3545 if (tmp->layout == cap) {
3546 SingleList & item = l[type];
3548 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3549 item.push_back(TocItem(tmp, 0 , str));
3556 lyxerr << "caption not found" << endl;
3565 // This is also a buffer property (ale)
3566 vector<pair<string, string> > const Buffer::getBibkeyList()
3568 /// if this is a child document and the parent is already loaded
3569 /// Use the parent's list instead [ale990412]
3570 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3571 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3573 return tmp->getBibkeyList();
3576 vector<pair<string, string> > keys;
3577 Paragraph * par = paragraph;
3580 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3581 par->asString(this, false)));
3585 // Might be either using bibtex or a child has bibliography
3587 for (inset_iterator it = inset_iterator_begin();
3588 it != inset_iterator_end(); ++it) {
3589 // Search for Bibtex or Include inset
3590 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3591 vector<pair<string,string> > tmp =
3592 static_cast<InsetBibtex*>(*it)->getKeys(this);
3593 keys.insert(keys.end(), tmp.begin(), tmp.end());
3594 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3595 vector<pair<string,string> > const tmp =
3596 static_cast<InsetInclude*>(*it)->getKeys();
3597 keys.insert(keys.end(), tmp.begin(), tmp.end());
3606 bool Buffer::isDepClean(string const & name) const
3608 DEPCLEAN * item = dep_clean;
3609 while (item && item->master != name)
3611 if (!item) return true;
3616 void Buffer::markDepClean(string const & name)
3619 dep_clean = new DEPCLEAN;
3620 dep_clean->clean = true;
3621 dep_clean->master = name;
3622 dep_clean->next = 0;
3624 DEPCLEAN * item = dep_clean;
3625 while (item && item->master != name)
3630 item = new DEPCLEAN;
3632 item->master = name;
3639 bool Buffer::dispatch(string const & command)
3641 // Split command string into command and argument
3643 string line = frontStrip(command);
3644 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3646 return dispatch(lyxaction.LookupFunc(cmd), arg);
3650 bool Buffer::dispatch(int action, string const & argument)
3652 bool dispatched = true;
3655 Exporter::Export(this, argument, false);
3665 void Buffer::resizeInsets(BufferView * bv)
3667 /// then remove all LyXText in text-insets
3668 Paragraph * par = paragraph;
3669 for (; par; par = par->next()) {
3670 par->resizeInsetsLyXText(bv);
3675 void Buffer::redraw()
3678 users->fitCursor(users->text);
3682 void Buffer::changeLanguage(Language const * from, Language const * to)
3685 Paragraph * par = paragraph;
3687 par->changeLanguage(params, from, to);
3693 bool Buffer::isMultiLingual()
3695 Paragraph * par = paragraph;
3697 if (par->isMultiLingual(params))
3705 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3706 Paragraph::size_type pos)
3709 it = par->InsetIterator(pos);
3710 if (it == par->inset_iterator_end()) {
3717 void Buffer::inset_iterator::setParagraph()
3720 it = par->inset_iterator_begin();
3721 if (it != par->inset_iterator_end())
3726 // We maintain an invariant that whenever par = 0 then it = 0
3730 Inset * Buffer::getInsetFromID(int id_arg) const
3732 for (inset_iterator it = inset_const_iterator_begin();
3733 it != inset_const_iterator_end(); ++it)
3735 if ((*it)->id() == id_arg)
3737 Inset * in = (*it)->getInsetFromID(id_arg);
3745 Paragraph * Buffer::getParFromID(int id) const
3747 if (id < 0) return 0;
3748 Paragraph * par = paragraph;
3750 if (par->id() == id) {
3753 Paragraph * tmp = par->getParFromID(id);