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);
437 } else if (token == "\\i") {
438 Inset * inset = new InsetLatexAccent;
439 inset->read(this, lex);
440 par->insertInset(pos, inset, font);
442 } else if (token == "\\layout") {
444 ert_comp.in_tabular = false;
446 insertErtContents(par, pos, font);
449 string const layoutname = lex.GetString();
450 pair<bool, LyXTextClass::LayoutList::size_type> pp
451 = textclasslist.NumberOfLayout(params.textclass,
455 if (compare_no_case(layoutname, "latex") == 0) {
456 ert_comp.active = true;
460 // The is the compability reading of layout caption.
461 // It can be removed in LyX version 1.3.0. (Lgb)
462 if (compare_no_case(layoutname, "caption") == 0) {
463 // We expect that the par we are now working on is
464 // really inside a InsetText inside a InsetFloat.
465 // We also know that captions can only be
466 // one paragraph. (Lgb)
468 // We should now read until the next "\layout"
470 // This is probably not good enough, what if the
471 // caption is the last par in the document (Lgb)
472 istream & ist = lex.getStream();
478 if (prefixIs(line, "\\layout")) {
482 if (prefixIs(line, "\\begin_inset"))
484 if (prefixIs(line, "\\end_inset")) {
495 // Now we should have the whole layout in ss
496 // we should now be able to give this to the
498 ss << "\\end_inset\n";
500 // This seems like a bug in stringstream.
501 // We really should be able to use ss
503 istringstream is(ss.str());
505 tmplex.setStream(is);
506 Inset * inset = new InsetCaption;
507 inset->Read(this, tmplex);
508 par->InsertInset(pos, inset, font);
515 par = new Paragraph(par);
519 par->layout = pp.second;
522 // use default layout "Standard" (0)
525 string const s = _("Layout had to be changed from\n")
526 + layoutname + _(" to ")
527 + textclasslist.NameOfLayout(params.textclass, par->layout);
528 InsetError * new_inset = new InsetError(s);
529 par->insertInset(0, new_inset);
531 // Test whether the layout is obsolete.
532 LyXLayout const & layout =
533 textclasslist.Style(params.textclass,
535 if (!layout.obsoleted_by().empty())
536 par->layout = textclasslist
537 .NumberOfLayout(params.textclass,
538 layout.obsoleted_by())
540 par->params().depth(depth);
541 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
542 if (file_format < 216
543 && params.language->lang() == "hebrew")
544 font.setLanguage(default_language);
549 } else if (token == "\\begin_float") {
550 // This is the compability reader. It can be removed in
551 // LyX version 1.3.0. (Lgb)
553 string const tmptok = lex.GetString();
554 //lyxerr << "old float: " << tmptok << endl;
557 stringstream old_float;
559 if (tmptok == "footnote") {
560 inset = new InsetFoot;
561 } else if (tmptok == "margin") {
562 inset = new InsetMarginal;
563 } else if (tmptok == "fig") {
564 inset = new InsetFloat("figure");
565 old_float << "placement htbp\n"
567 } else if (tmptok == "tab") {
568 inset = new InsetFloat("table");
569 old_float << "placement htbp\n"
571 } else if (tmptok == "alg") {
572 inset = new InsetFloat("algorithm");
573 old_float << "placement htbp\n"
575 } else if (tmptok == "wide-fig") {
576 inset = new InsetFloat("figure");
577 //InsetFloat * tmp = new InsetFloat("figure");
580 old_float << "placement htbp\n"
582 } else if (tmptok == "wide-tab") {
583 inset = new InsetFloat("table");
584 //InsetFloat * tmp = new InsetFloat("table");
587 old_float << "placement htbp\n"
592 #ifndef NO_PEXTRA_REALLY
595 return false; // no end read yet
598 old_float << "collapsed true\n";
600 // Here we need to check for \end_deeper and handle that
601 // before we do the footnote parsing.
602 // This _is_ a hack! (Lgb)
605 string const tmp = lex.GetString();
606 if (tmp == "\\end_deeper") {
607 //lyxerr << "\\end_deeper caught!" << endl;
609 lex.printError("\\end_deeper: "
610 "depth is already null");
615 old_float << tmp << ' ';
620 old_float << lex.getLongString("\\end_float")
621 << "\n\\end_inset\n";
622 //lyxerr << "Float Body:\n" << old_float.str() << endl;
623 // That this does not work seems like a bug
624 // in stringstream. (Lgb)
625 istringstream istr(old_float.str());
627 nylex.setStream(istr);
628 inset->read(this, nylex);
629 par->insertInset(pos, inset, font);
631 } else if (token == "\\begin_deeper") {
633 } else if (token == "\\end_deeper") {
635 lex.printError("\\end_deeper: "
636 "depth is already null");
640 } else if (token == "\\begin_preamble") {
641 params.readPreamble(lex);
642 } else if (token == "\\textclass") {
644 pair<bool, LyXTextClassList::size_type> pp =
645 textclasslist.NumberOfClass(lex.GetString());
647 params.textclass = pp.second;
649 WriteAlert(string(_("Textclass error")),
650 string(_("The document uses an unknown textclass \"")) +
651 lex.GetString() + string("\"."),
652 string(_("LyX will not be able to produce output correctly.")));
653 params.textclass = 0;
655 if (!textclasslist.Load(params.textclass)) {
656 // if the textclass wasn't loaded properly
657 // we need to either substitute another
658 // or stop loading the file.
659 // I can substitute but I don't see how I can
660 // stop loading... ideas?? ARRae980418
661 WriteAlert(_("Textclass Loading Error!"),
662 string(_("Can't load textclass ")) +
663 textclasslist.NameOfClass(params.textclass),
664 _("-- substituting default"));
665 params.textclass = 0;
667 } else if (token == "\\options") {
669 params.options = lex.GetString();
670 } else if (token == "\\language") {
671 params.readLanguage(lex);
672 } else if (token == "\\fontencoding") {
674 } else if (token == "\\inputencoding") {
676 params.inputenc = lex.GetString();
677 } else if (token == "\\graphics") {
678 params.readGraphicsDriver(lex);
679 } else if (token == "\\fontscheme") {
681 params.fonts = lex.GetString();
682 } else if (token == "\\noindent") {
683 par->params().noindent(true);
684 } else if (token == "\\fill_top") {
685 par->params().spaceTop(VSpace(VSpace::VFILL));
686 } else if (token == "\\fill_bottom") {
687 par->params().spaceBottom(VSpace(VSpace::VFILL));
688 } else if (token == "\\line_top") {
689 par->params().lineTop(true);
690 } else if (token == "\\line_bottom") {
691 par->params().lineBottom(true);
692 } else if (token == "\\pagebreak_top") {
693 par->params().pagebreakTop(true);
694 } else if (token == "\\pagebreak_bottom") {
695 par->params().pagebreakBottom(true);
696 } else if (token == "\\start_of_appendix") {
697 par->params().startOfAppendix(true);
698 } else if (token == "\\paragraph_separation") {
699 int tmpret = lex.FindToken(string_paragraph_separation);
700 if (tmpret == -1) ++tmpret;
701 if (tmpret != LYX_LAYOUT_DEFAULT)
702 params.paragraph_separation =
703 static_cast<BufferParams::PARSEP>(tmpret);
704 } else if (token == "\\defskip") {
706 params.defskip = VSpace(lex.GetString());
707 } else if (token == "\\epsfig") { // obsolete
708 // Indeed it is obsolete, but we HAVE to be backwards
709 // compatible until 0.14, because otherwise all figures
710 // in existing documents are irretrivably lost. (Asger)
711 params.readGraphicsDriver(lex);
712 } else if (token == "\\quotes_language") {
713 int tmpret = lex.FindToken(string_quotes_language);
714 if (tmpret == -1) ++tmpret;
715 if (tmpret != LYX_LAYOUT_DEFAULT) {
716 InsetQuotes::quote_language tmpl =
717 InsetQuotes::EnglishQ;
720 tmpl = InsetQuotes::EnglishQ;
723 tmpl = InsetQuotes::SwedishQ;
726 tmpl = InsetQuotes::GermanQ;
729 tmpl = InsetQuotes::PolishQ;
732 tmpl = InsetQuotes::FrenchQ;
735 tmpl = InsetQuotes::DanishQ;
738 params.quotes_language = tmpl;
740 } else if (token == "\\quotes_times") {
742 switch (lex.GetInteger()) {
744 params.quotes_times = InsetQuotes::SingleQ;
747 params.quotes_times = InsetQuotes::DoubleQ;
750 } else if (token == "\\papersize") {
751 int tmpret = lex.FindToken(string_papersize);
755 params.papersize2 = tmpret;
756 } else if (token == "\\paperpackage") {
757 int tmpret = lex.FindToken(string_paperpackages);
760 params.paperpackage = BufferParams::PACKAGE_NONE;
762 params.paperpackage = tmpret;
763 } else if (token == "\\use_geometry") {
765 params.use_geometry = lex.GetInteger();
766 } else if (token == "\\use_amsmath") {
768 params.use_amsmath = lex.GetInteger();
769 } else if (token == "\\use_natbib") {
771 params.use_natbib = lex.GetInteger();
772 } else if (token == "\\use_numerical_citations") {
774 params.use_numerical_citations = lex.GetInteger();
775 } else if (token == "\\paperorientation") {
776 int tmpret = lex.FindToken(string_orientation);
777 if (tmpret == -1) ++tmpret;
778 if (tmpret != LYX_LAYOUT_DEFAULT)
779 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
780 } else if (token == "\\paperwidth") {
782 params.paperwidth = lex.GetString();
783 } else if (token == "\\paperheight") {
785 params.paperheight = lex.GetString();
786 } else if (token == "\\leftmargin") {
788 params.leftmargin = lex.GetString();
789 } else if (token == "\\topmargin") {
791 params.topmargin = lex.GetString();
792 } else if (token == "\\rightmargin") {
794 params.rightmargin = lex.GetString();
795 } else if (token == "\\bottommargin") {
797 params.bottommargin = lex.GetString();
798 } else if (token == "\\headheight") {
800 params.headheight = lex.GetString();
801 } else if (token == "\\headsep") {
803 params.headsep = lex.GetString();
804 } else if (token == "\\footskip") {
806 params.footskip = lex.GetString();
807 } else if (token == "\\paperfontsize") {
809 params.fontsize = strip(lex.GetString());
810 } else if (token == "\\papercolumns") {
812 params.columns = lex.GetInteger();
813 } else if (token == "\\papersides") {
815 switch (lex.GetInteger()) {
817 case 1: params.sides = LyXTextClass::OneSide; break;
818 case 2: params.sides = LyXTextClass::TwoSides; break;
820 } else if (token == "\\paperpagestyle") {
822 params.pagestyle = strip(lex.GetString());
823 } else if (token == "\\bullet") {
825 int const index = lex.GetInteger();
827 int temp_int = lex.GetInteger();
828 params.user_defined_bullets[index].setFont(temp_int);
829 params.temp_bullets[index].setFont(temp_int);
831 temp_int = lex.GetInteger();
832 params.user_defined_bullets[index].setCharacter(temp_int);
833 params.temp_bullets[index].setCharacter(temp_int);
835 temp_int = lex.GetInteger();
836 params.user_defined_bullets[index].setSize(temp_int);
837 params.temp_bullets[index].setSize(temp_int);
839 string const temp_str = lex.GetString();
840 if (temp_str != "\\end_bullet") {
841 // this element isn't really necessary for
842 // parsing but is easier for humans
843 // to understand bullets. Put it back and
844 // set a debug message?
845 lex.printError("\\end_bullet expected, got" + temp_str);
846 //how can I put it back?
848 } else if (token == "\\bulletLaTeX") {
850 int const index = lex.GetInteger();
852 string temp_str = lex.GetString();
854 while (temp_str != "\\end_bullet") {
855 // this loop structure is needed when user
856 // enters an empty string since the first
857 // thing returned will be the \\end_bullet
859 // if the LaTeX entry has spaces. Each element
860 // therefore needs to be read in turn
863 temp_str = lex.GetString();
865 params.user_defined_bullets[index].setText(sum_str);
866 params.temp_bullets[index].setText(sum_str);
867 } else if (token == "\\secnumdepth") {
869 params.secnumdepth = lex.GetInteger();
870 } else if (token == "\\tocdepth") {
872 params.tocdepth = lex.GetInteger();
873 } else if (token == "\\spacing") {
875 string const tmp = strip(lex.GetString());
876 Spacing::Space tmp_space = Spacing::Default;
878 if (tmp == "single") {
879 tmp_space = Spacing::Single;
880 } else if (tmp == "onehalf") {
881 tmp_space = Spacing::Onehalf;
882 } else if (tmp == "double") {
883 tmp_space = Spacing::Double;
884 } else if (tmp == "other") {
886 tmp_space = Spacing::Other;
887 tmp_val = lex.GetFloat();
889 lex.printError("Unknown spacing token: '$$Token'");
891 // Small hack so that files written with klyx will be
894 par->params().spacing(Spacing(tmp_space, tmp_val));
896 params.spacing.set(tmp_space, tmp_val);
898 } else if (token == "\\paragraph_spacing") {
900 string const tmp = strip(lex.GetString());
901 if (tmp == "single") {
902 par->params().spacing(Spacing(Spacing::Single));
903 } else if (tmp == "onehalf") {
904 par->params().spacing(Spacing(Spacing::Onehalf));
905 } else if (tmp == "double") {
906 par->params().spacing(Spacing(Spacing::Double));
907 } else if (tmp == "other") {
909 par->params().spacing(Spacing(Spacing::Other,
912 lex.printError("Unknown spacing token: '$$Token'");
914 } else if (token == "\\float_placement") {
916 params.float_placement = lex.GetString();
917 } else if (token == "\\family") {
919 font.setLyXFamily(lex.GetString());
920 } else if (token == "\\series") {
922 font.setLyXSeries(lex.GetString());
923 } else if (token == "\\shape") {
925 font.setLyXShape(lex.GetString());
926 } else if (token == "\\size") {
928 font.setLyXSize(lex.GetString());
931 #warning compatability hack needed
933 } else if (token == "\\latex") {
935 string const tok = lex.GetString();
936 // This is dirty, but gone with LyX3. (Asger)
937 if (tok == "no_latex")
938 font.setLatex(LyXFont::OFF);
939 else if (tok == "latex")
940 font.setLatex(LyXFont::ON);
941 else if (tok == "default")
942 font.setLatex(LyXFont::INHERIT);
944 lex.printError("Unknown LaTeX font flag "
947 } else if (token == "\\latex") {
949 string const tok = lex.GetString();
950 if (tok == "no_latex") {
952 insertErtContents(par, pos, font);
953 } else if (tok == "latex") {
954 ert_comp.active = true;
955 } else if (tok == "default") {
957 insertErtContents(par, pos, font);
959 lex.printError("Unknown LaTeX font flag "
963 } else if (token == "\\lang") {
965 string const tok = lex.GetString();
966 Language const * lang = languages.getLanguage(tok);
968 font.setLanguage(lang);
970 font.setLanguage(params.language);
971 lex.printError("Unknown language `$$Token'");
973 } else if (token == "\\numeric") {
975 font.setNumber(font.setLyXMisc(lex.GetString()));
976 } else if (token == "\\emph") {
978 font.setEmph(font.setLyXMisc(lex.GetString()));
979 } else if (token == "\\bar") {
981 string const tok = lex.GetString();
982 // This is dirty, but gone with LyX3. (Asger)
984 font.setUnderbar(LyXFont::ON);
985 else if (tok == "no")
986 font.setUnderbar(LyXFont::OFF);
987 else if (tok == "default")
988 font.setUnderbar(LyXFont::INHERIT);
990 lex.printError("Unknown bar font flag "
992 } else if (token == "\\noun") {
994 font.setNoun(font.setLyXMisc(lex.GetString()));
995 } else if (token == "\\color") {
997 font.setLyXColor(lex.GetString());
998 } else if (token == "\\align") {
999 int tmpret = lex.FindToken(string_align);
1000 if (tmpret == -1) ++tmpret;
1001 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1002 int const tmpret2 = int(pow(2.0, tmpret));
1003 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1004 par->params().align(LyXAlignment(tmpret2));
1006 } else if (token == "\\added_space_top") {
1008 par->params().spaceTop(VSpace(lex.GetString()));
1009 } else if (token == "\\added_space_bottom") {
1011 par->params().spaceBottom(VSpace(lex.GetString()));
1012 #ifndef NO_PEXTRA_REALLY
1013 } else if (token == "\\pextra_type") {
1015 par->params().pextraType(lex.GetInteger());
1016 } else if (token == "\\pextra_width") {
1018 par->params().pextraWidth(lex.GetString());
1019 } else if (token == "\\pextra_widthp") {
1021 par->params().pextraWidthp(lex.GetString());
1022 } else if (token == "\\pextra_alignment") {
1024 par->params().pextraAlignment(lex.GetInteger());
1025 } else if (token == "\\pextra_hfill") {
1027 par->params().pextraHfill(lex.GetInteger());
1028 } else if (token == "\\pextra_start_minipage") {
1030 par->params().pextraStartMinipage(lex.GetInteger());
1032 } else if (token == "\\labelwidthstring") {
1034 par->params().labelWidthString(lex.GetString());
1035 // do not delete this token, it is still needed!
1036 } else if (token == "\\end_inset") {
1037 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1038 << "Last inset read was: " << last_inset_read
1040 // Simply ignore this. The insets do not have
1042 // But insets should read it, it is a part of
1043 // the inset isn't it? Lgb.
1044 } else if (token == "\\begin_inset") {
1046 insertErtContents(par, pos, font, false);
1047 ert_stack.push(ert_comp);
1048 ert_comp = ErtComp();
1050 readInset(lex, par, pos, font);
1052 ert_comp = ert_stack.top();
1055 } else if (token == "\\SpecialChar") {
1056 LyXLayout const & layout =
1057 textclasslist.Style(params.textclass,
1060 // Insets don't make sense in a free-spacing context! ---Kayvan
1061 if (layout.free_spacing) {
1064 string next_token = lex.GetString();
1065 if (next_token == "\\-") {
1066 par->insertChar(pos, '-', font);
1067 } else if (next_token == "\\protected_separator"
1068 || next_token == "~") {
1069 par->insertChar(pos, ' ', font);
1071 lex.printError("Token `$$Token' "
1073 "paragraph layout!");
1078 Inset * inset = new InsetSpecialChar;
1079 inset->read(this, lex);
1080 par->insertInset(pos, inset, font);
1083 } else if (token == "\\newline") {
1086 if (!ert_comp.in_tabular && ert_comp.active) {
1087 ert_comp.contents += char(Paragraph::META_NEWLINE);
1089 // Since we cannot know it this is only a regular
1090 // newline or a tabular cell delimter we have to
1091 // handle the ERT here.
1092 insertErtContents(par, pos, font, false);
1094 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1098 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1101 } else if (token == "\\LyXTable") {
1103 ert_comp.in_tabular = true;
1105 Inset * inset = new InsetTabular(*this);
1106 inset->read(this, lex);
1107 par->insertInset(pos, inset, font);
1109 } else if (token == "\\hfill") {
1110 par->insertChar(pos, Paragraph::META_HFILL, font);
1112 } else if (token == "\\protected_separator") { // obsolete
1113 // This is a backward compability thingie. (Lgb)
1114 // Remove it later some time...introduced with fileformat
1116 LyXLayout const & layout =
1117 textclasslist.Style(params.textclass,
1120 if (layout.free_spacing) {
1121 par->insertChar(pos, ' ', font);
1123 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1124 par->insertInset(pos, inset, font);
1127 } else if (token == "\\bibitem") { // ale970302
1129 InsetCommandParams p("bibitem", "dummy");
1130 par->bibkey = new InsetBibKey(p);
1132 par->bibkey->read(this, lex);
1133 } else if (token == "\\backslash") {
1135 if (ert_comp.active) {
1136 ert_comp.contents += "\\";
1139 par->insertChar(pos, '\\', font);
1144 } else if (token == "\\the_end") {
1146 // If we still have some ert active here we have to insert
1147 // it so we don't loose it. (Lgb)
1148 insertErtContents(par, pos, font);
1150 the_end_read = true;
1151 #ifndef NO_PEXTRA_REALLY
1152 minipar = parBeforeMinipage = 0;
1156 if (ert_comp.active) {
1157 ert_comp.contents += token;
1160 // This should be insurance for the future: (Asger)
1161 lex.printError("Unknown token `$$Token'. "
1162 "Inserting as text.");
1163 string::const_iterator cit = token.begin();
1164 string::const_iterator end = token.end();
1165 for (; cit != end; ++cit) {
1166 par->insertChar(pos, (*cit), font);
1174 #ifndef NO_PEXTRA_REALLY
1175 // I wonder if we could use this blanket fix for all the
1176 // checkminipage cases...
1177 if (par && par->size()) {
1178 // It is possible that this will check to often,
1179 // but that should not be an correctness issue.
1180 // Only a speed issue.
1181 checkminipage = true;
1184 // now check if we have a minipage paragraph as at this
1185 // point we already read all the necessary data!
1186 // this cannot be done in layout because there we did
1187 // not read yet the paragraph PEXTRA-params (Jug)
1189 // BEGIN pextra_minipage compability
1190 // This should be removed in 1.3.x (Lgb)
1192 // This compability code is not perfect. In a couple
1193 // of rand cases it fails. When the minipage par is
1194 // the first par in the document, and when there are
1195 // none or only one regular paragraphs after the
1196 // minipage. Currently I am not investing any effort
1197 // in fixing those cases.
1199 //lyxerr << "Call depth: " << call_depth << endl;
1200 if (checkminipage && (call_depth == 1)) {
1201 checkminipage = false;
1202 if (minipar && (minipar != par) &&
1203 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1205 lyxerr << "minipages in a row" << endl;
1206 if (par->params().pextraStartMinipage()) {
1207 lyxerr << "start new minipage" << endl;
1208 // minipages in a row
1209 par->previous()->next(0);
1212 Paragraph * tmp = minipar;
1214 tmp->params().pextraType(0);
1215 tmp->params().pextraWidth(string());
1216 tmp->params().pextraWidthp(string());
1217 tmp->params().pextraAlignment(0);
1218 tmp->params().pextraHfill(false);
1219 tmp->params().pextraStartMinipage(false);
1222 // create a new paragraph to insert the
1223 // minipages in the following case
1224 if (par->params().pextraStartMinipage() &&
1225 !par->params().pextraHfill())
1227 Paragraph * p = new Paragraph;
1229 p->previous(parBeforeMinipage);
1230 parBeforeMinipage->next(p);
1232 p->params().depth(parBeforeMinipage->params().depth());
1233 parBeforeMinipage = p;
1235 InsetMinipage * mini = new InsetMinipage;
1236 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1237 mini->width(par->params().pextraWidth());
1238 if (!par->params().pextraWidthp().empty()) {
1239 lyxerr << "WP:" << mini->width() << endl;
1240 mini->width(tostr(par->params().pextraWidthp())+"%");
1242 mini->inset.paragraph(par);
1243 // Insert the minipage last in the
1244 // previous paragraph.
1245 if (par->params().pextraHfill()) {
1246 parBeforeMinipage->insertChar
1247 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1249 parBeforeMinipage->insertInset
1250 (parBeforeMinipage->size(), mini);
1254 lyxerr << "new minipage par" << endl;
1255 //nothing to do just continue reading
1258 } else if (minipar && (minipar != par)) {
1259 lyxerr << "last minipage par read" << endl;
1260 // The last paragraph read was not part of a
1261 // minipage but the par linked list is...
1262 // So we need to remove the last par from the
1264 if (par->previous())
1265 par->previous()->next(0);
1266 par->previous(parBeforeMinipage);
1267 parBeforeMinipage->next(par);
1268 Paragraph * tmp = minipar;
1270 tmp->params().pextraType(0);
1271 tmp->params().pextraWidth(string());
1272 tmp->params().pextraWidthp(string());
1273 tmp->params().pextraAlignment(0);
1274 tmp->params().pextraHfill(false);
1275 tmp->params().pextraStartMinipage(false);
1278 depth = parBeforeMinipage->params().depth();
1279 minipar = parBeforeMinipage = 0;
1280 } else if (!minipar &&
1281 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1283 // par is the first paragraph in a minipage
1284 lyxerr << "begin minipage" << endl;
1285 // To minimize problems for
1286 // the users we will insert
1287 // the first minipage in
1288 // a sequence of minipages
1289 // in its own paragraph.
1290 Paragraph * p = new Paragraph;
1292 p->previous(par->previous());
1294 p->params().depth(depth);
1295 par->params().depth(0);
1297 if (par->previous())
1298 par->previous()->next(p);
1300 parBeforeMinipage = p;
1302 if (!first_par || (first_par == par))
1305 InsetMinipage * mini = new InsetMinipage;
1306 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1307 mini->width(minipar->params().pextraWidth());
1308 if (!par->params().pextraWidthp().empty()) {
1309 lyxerr << "WP:" << mini->width() << endl;
1310 mini->width(tostr(par->params().pextraWidthp())+"%");
1312 mini->inset.paragraph(minipar);
1314 // Insert the minipage last in the
1315 // previous paragraph.
1316 if (minipar->params().pextraHfill()) {
1317 parBeforeMinipage->insertChar
1318 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1320 parBeforeMinipage->insertInset
1321 (parBeforeMinipage->size(), mini);
1324 // End of pextra_minipage compability
1327 return the_end_read;
1330 // needed to insert the selection
1331 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1332 LyXFont const & font,
1333 string const & str) const
1335 LyXLayout const & layout = textclasslist.Style(params.textclass,
1337 // insert the string, don't insert doublespace
1338 bool space_inserted = true;
1339 for(string::const_iterator cit = str.begin();
1340 cit != str.end(); ++cit) {
1342 if (par->size() || layout.keepempty) {
1343 par->breakParagraph(params, pos,
1344 layout.isEnvironment());
1347 space_inserted = true;
1351 // do not insert consecutive spaces if !free_spacing
1352 } else if ((*cit == ' ' || *cit == '\t')
1353 && space_inserted && !layout.free_spacing) {
1355 } else if (*cit == '\t') {
1356 if (!layout.free_spacing) {
1357 // tabs are like spaces here
1358 par->insertChar(pos, ' ', font);
1360 space_inserted = true;
1362 const Paragraph::value_type nb = 8 - pos % 8;
1363 for (Paragraph::size_type a = 0;
1365 par->insertChar(pos, ' ', font);
1368 space_inserted = true;
1370 } else if (!IsPrintable(*cit)) {
1371 // Ignore unprintables
1374 // just insert the character
1375 par->insertChar(pos, *cit, font);
1377 space_inserted = (*cit == ' ');
1384 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1385 int & pos, LyXFont & font)
1387 // consistency check
1388 if (lex.GetString() != "\\begin_inset") {
1389 lyxerr << "Buffer::readInset: Consistency check failed."
1396 string const tmptok = lex.GetString();
1397 last_inset_read = tmptok;
1399 // test the different insets
1400 if (tmptok == "LatexCommand") {
1401 InsetCommandParams inscmd;
1404 string const cmdName = inscmd.getCmdName();
1406 // This strange command allows LyX to recognize "natbib" style
1407 // citations: citet, citep, Citet etc.
1408 if (compare_no_case(cmdName, "cite", 4) == 0) {
1409 inset = new InsetCitation(inscmd);
1410 } else if (cmdName == "bibitem") {
1411 lex.printError("Wrong place for bibitem");
1412 inset = new InsetBibKey(inscmd);
1413 } else if (cmdName == "BibTeX") {
1414 inset = new InsetBibtex(inscmd);
1415 } else if (cmdName == "index") {
1416 inset = new InsetIndex(inscmd);
1417 } else if (cmdName == "include") {
1418 inset = new InsetInclude(inscmd, *this);
1419 } else if (cmdName == "label") {
1420 inset = new InsetLabel(inscmd);
1421 } else if (cmdName == "url"
1422 || cmdName == "htmlurl") {
1423 inset = new InsetUrl(inscmd);
1424 } else if (cmdName == "ref"
1425 || cmdName == "pageref"
1426 || cmdName == "vref"
1427 || cmdName == "vpageref"
1428 || cmdName == "prettyref") {
1429 if (!inscmd.getOptions().empty()
1430 || !inscmd.getContents().empty()) {
1431 inset = new InsetRef(inscmd, *this);
1433 } else if (cmdName == "tableofcontents") {
1434 inset = new InsetTOC(inscmd);
1435 } else if (cmdName == "listofalgorithms") {
1436 inset = new InsetFloatList("algorithm");
1437 } else if (cmdName == "listoffigures") {
1438 inset = new InsetFloatList("figure");
1439 } else if (cmdName == "listoftables") {
1440 inset = new InsetFloatList("table");
1441 } else if (cmdName == "printindex") {
1442 inset = new InsetPrintIndex(inscmd);
1443 } else if (cmdName == "lyxparent") {
1444 inset = new InsetParent(inscmd, *this);
1447 bool alreadyread = false;
1448 if (tmptok == "Quotes") {
1449 inset = new InsetQuotes;
1450 } else if (tmptok == "External") {
1451 inset = new InsetExternal;
1452 } else if (tmptok == "FormulaMacro") {
1453 inset = new InsetFormulaMacro;
1454 } else if (tmptok == "Formula") {
1455 inset = new InsetFormula;
1456 } else if (tmptok == "Figure") {
1457 inset = new InsetFig(100, 100, *this);
1458 } else if (tmptok == "Info") {// backwards compatibility
1459 inset = new InsetNote(this,
1460 lex.getLongString("\\end_inset"),
1463 } else if (tmptok == "Note") {
1464 inset = new InsetNote;
1465 } else if (tmptok == "Include") {
1466 InsetCommandParams p( "Include" );
1467 inset = new InsetInclude(p, *this);
1468 } else if (tmptok == "ERT") {
1469 inset = new InsetERT;
1470 } else if (tmptok == "Tabular") {
1471 inset = new InsetTabular(*this);
1472 } else if (tmptok == "Text") {
1473 inset = new InsetText;
1474 } else if (tmptok == "Foot") {
1475 inset = new InsetFoot;
1476 } else if (tmptok == "Marginal") {
1477 inset = new InsetMarginal;
1478 } else if (tmptok == "Minipage") {
1479 inset = new InsetMinipage;
1480 } else if (tmptok == "Float") {
1482 string tmptok = lex.GetString();
1483 inset = new InsetFloat(tmptok);
1485 } else if (tmptok == "List") {
1486 inset = new InsetList;
1487 } else if (tmptok == "Theorem") {
1488 inset = new InsetList;
1490 } else if (tmptok == "Caption") {
1491 inset = new InsetCaption;
1492 } else if (tmptok == "GRAPHICS") {
1493 inset = new InsetGraphics;
1494 } else if (tmptok == "FloatList") {
1495 inset = new InsetFloatList;
1498 if (inset && !alreadyread) inset->read(this, lex);
1502 par->insertInset(pos, inset, font);
1508 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1512 string const token(lex.GetString());
1513 if (token == "\\lyxformat") { // the first token _must_ be...
1515 string tmp_format = lex.GetString();
1516 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1517 // if present remove ".," from string.
1518 string::size_type dot = tmp_format.find_first_of(".,");
1519 //lyxerr << " dot found at " << dot << endl;
1520 if (dot != string::npos)
1521 tmp_format.erase(dot, 1);
1522 file_format = strToInt(tmp_format);
1523 if (file_format == LYX_FORMAT) {
1525 } else if (file_format > LYX_FORMAT) {
1527 WriteAlert(_("Warning!"),
1528 _("LyX file format is newer that what"),
1529 _("is supported in this LyX version. Expect some problems."));
1531 } else if (file_format < LYX_FORMAT) {
1533 if (file_format < 200) {
1534 WriteAlert(_("ERROR!"),
1535 _("Old LyX file format found. "
1536 "Use LyX 0.10.x to read this!"));
1540 bool the_end = readLyXformat2(lex, par);
1542 // the_end was added in 213
1543 if (file_format < 213)
1547 WriteAlert(_("Warning!"),
1548 _("Reading of document is not complete"),
1549 _("Maybe the document is truncated"));
1551 } else { // "\\lyxformat" not found
1552 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1555 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1560 // Should probably be moved to somewhere else: BufferView? LyXView?
1561 bool Buffer::save() const
1563 // We don't need autosaves in the immediate future. (Asger)
1564 resetAutosaveTimers();
1568 if (lyxrc.make_backup) {
1569 s = fileName() + '~';
1570 if (!lyxrc.backupdir_path.empty())
1571 s = AddName(lyxrc.backupdir_path,
1572 subst(os::slashify_path(s),'/','!'));
1574 // Rename is the wrong way of making a backup,
1575 // this is the correct way.
1576 /* truss cp fil fil2:
1577 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1578 stat("LyXVC.lyx", 0xEFFFF688) = 0
1579 open("LyXVC.lyx", O_RDONLY) = 3
1580 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1581 fstat(4, 0xEFFFF508) = 0
1582 fstat(3, 0xEFFFF508) = 0
1583 read(3, " # T h i s f i l e w".., 8192) = 5579
1584 write(4, " # T h i s f i l e w".., 5579) = 5579
1585 read(3, 0xEFFFD4A0, 8192) = 0
1588 chmod("LyXVC3.lyx", 0100644) = 0
1589 lseek(0, 0, SEEK_CUR) = 46440
1593 // Should probably have some more error checking here.
1594 // Should be cleaned up in 0.13, at least a bit.
1595 // Doing it this way, also makes the inodes stay the same.
1596 // This is still not a very good solution, in particular we
1597 // might loose the owner of the backup.
1598 FileInfo finfo(fileName());
1599 if (finfo.exist()) {
1600 mode_t fmode = finfo.getMode();
1601 struct utimbuf times = {
1602 finfo.getAccessTime(),
1603 finfo.getModificationTime() };
1605 ifstream ifs(fileName().c_str());
1606 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1611 ::chmod(s.c_str(), fmode);
1613 if (::utime(s.c_str(), ×)) {
1614 lyxerr << "utime error." << endl;
1617 lyxerr << "LyX was not able to make "
1618 "backup copy. Beware." << endl;
1623 if (writeFile(fileName(), false)) {
1625 removeAutosaveFile(fileName());
1627 // Saving failed, so backup is not backup
1628 if (lyxrc.make_backup) {
1629 lyx::rename(s, fileName());
1637 // Returns false if unsuccesful
1638 bool Buffer::writeFile(string const & fname, bool flag) const
1640 // if flag is false writeFile will not create any GUI
1641 // warnings, only cerr.
1642 // Needed for autosave in background or panic save (Matthias 120496)
1644 if (read_only && (fname == filename)) {
1645 // Here we should come with a question if we should
1646 // perform the write anyway.
1648 lyxerr << _("Error! Document is read-only: ")
1651 WriteAlert(_("Error! Document is read-only: "),
1656 FileInfo finfo(fname);
1657 if (finfo.exist() && !finfo.writable()) {
1658 // Here we should come with a question if we should
1659 // try to do the save anyway. (i.e. do a chmod first)
1661 lyxerr << _("Error! Cannot write file: ")
1664 WriteFSAlert(_("Error! Cannot write file: "),
1669 ofstream ofs(fname.c_str());
1672 lyxerr << _("Error! Cannot open file: ")
1675 WriteFSAlert(_("Error! Cannot open file: "),
1681 // Use the standard "C" locale for file output.
1682 ofs.imbue(std::locale::classic());
1685 // The top of the file should not be written by params.
1687 // write out a comment in the top of the file
1688 ofs << '#' << LYX_DOCVERSION
1689 << " created this file. For more info see http://www.lyx.org/\n"
1690 << "\\lyxformat " << LYX_FORMAT << "\n";
1692 // now write out the buffer paramters.
1693 params.writeFile(ofs);
1695 Paragraph::depth_type depth = 0;
1697 // this will write out all the paragraphs
1698 // using recursive descent.
1699 paragraph->writeFile(this, ofs, params, depth);
1701 // Write marker that shows file is complete
1702 ofs << "\n\\the_end" << endl;
1706 // how to check if close went ok?
1707 // Following is an attempt... (BE 20001011)
1709 // good() returns false if any error occured, including some
1710 // formatting error.
1711 // bad() returns true if something bad happened in the buffer,
1712 // which should include file system full errors.
1719 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1721 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1731 string const Buffer::asciiParagraph(Paragraph const * par,
1732 unsigned int linelen) const
1734 ostringstream buffer;
1735 Paragraph::depth_type depth = 0;
1737 Paragraph::depth_type ltype_depth = 0;
1738 unsigned int currlinelen = 0;
1739 bool ref_printed = false;
1743 if (!par->previous()) {
1744 // begins or ends a deeper area ?
1745 if (depth != par->params().depth()) {
1746 if (par->params().depth() > depth) {
1747 while (par->params().depth() > depth) {
1751 while (par->params().depth() < depth) {
1757 // First write the layout
1758 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1759 if (tmp == "Itemize") {
1761 ltype_depth = depth + 1;
1762 } else if (tmp == "Enumerate") {
1764 ltype_depth = depth + 1;
1765 } else if (contains(tmp, "ection")) {
1767 ltype_depth = depth + 1;
1768 } else if (contains(tmp, "aragraph")) {
1770 ltype_depth = depth + 1;
1771 } else if (tmp == "Description") {
1773 ltype_depth = depth + 1;
1774 } else if (tmp == "Abstract") {
1777 } else if (tmp == "Bibliography") {
1785 /* maybe some vertical spaces */
1787 /* the labelwidthstring used in lists */
1791 /* some pagebreaks? */
1795 /* what about the alignment */
1797 lyxerr << "Should this ever happen?" << endl;
1801 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1803 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1804 if (!i && !noparbreak) {
1807 for (Paragraph::depth_type j = 0; j < depth; ++j)
1809 currlinelen = depth * 2;
1812 case 4: // (Sub)Paragraph
1813 case 5: // Description
1817 buffer << "Abstract\n\n";
1819 buffer << "Abstract: ";
1821 case 7: // Bibliography
1824 buffer << "References\n\n";
1826 buffer << "References: ";
1831 buffer << par->params().labelString() << " ";
1834 if (ltype_depth > depth) {
1835 for (Paragraph::depth_type j = ltype_depth - 1;
1838 currlinelen += (ltype_depth-depth)*2;
1842 LyXFont const font2 = par->getFontSettings(params, i);
1843 if (font1.latex() != font2.latex()) {
1844 if (font2.latex() == LyXFont::OFF)
1853 char c = par->getUChar(params, i);
1857 case Paragraph::META_INSET:
1859 Inset const * inset = par->getInset(i);
1861 if (!inset->ascii(this, buffer)) {
1864 rsplit(buffer.str().c_str(),
1866 currlinelen += s.length();
1868 // to be sure it breaks paragraph
1869 currlinelen += linelen;
1875 case Paragraph::META_NEWLINE:
1878 for (Paragraph::depth_type j = 0;
1882 currlinelen = depth * 2;
1883 if (ltype_depth > depth) {
1884 for (Paragraph::depth_type j = ltype_depth;
1887 currlinelen += (ltype_depth - depth) * 2;
1891 case Paragraph::META_HFILL:
1900 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1901 (c == ' ') && ((i + 2) < par->size()))
1904 for (Paragraph::depth_type j = 0;
1907 currlinelen = depth * 2;
1908 if (ltype_depth > depth) {
1909 for (Paragraph::depth_type j = ltype_depth;
1912 currlinelen += (ltype_depth-depth)*2;
1914 } else if (c != '\0')
1917 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1922 return buffer.str().c_str();
1926 void Buffer::writeFileAscii(string const & fname, int linelen)
1928 ofstream ofs(fname.c_str());
1930 WriteFSAlert(_("Error: Cannot write file:"), fname);
1933 writeFileAscii(ofs, linelen);
1937 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1939 Paragraph * par = paragraph;
1941 ofs << asciiParagraph(par, linelen);
1949 void Buffer::makeLaTeXFile(string const & fname,
1950 string const & original_path,
1951 bool nice, bool only_body)
1953 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1955 niceFile = nice; // this will be used by Insetincludes.
1957 tex_code_break_column = lyxrc.ascii_linelen;
1959 LyXTextClass const & tclass =
1960 textclasslist.TextClass(params.textclass);
1962 ofstream ofs(fname.c_str());
1964 WriteFSAlert(_("Error: Cannot open file: "), fname);
1968 // validate the buffer.
1969 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1970 LaTeXFeatures features(params, tclass.numLayouts());
1972 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1975 // The starting paragraph of the coming rows is the
1976 // first paragraph of the document. (Asger)
1977 texrow.start(paragraph, 0);
1979 if (!only_body && nice) {
1980 ofs << "%% " LYX_DOCVERSION " created this file. "
1981 "For more info, see http://www.lyx.org/.\n"
1982 "%% Do not edit unless you really know what "
1987 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1988 // There are a few differences between nice LaTeX and usual files:
1989 // usual is \batchmode and has a
1990 // special input@path to allow the including of figures
1991 // with either \input or \includegraphics (what figinsets do).
1992 // batchmode is not set if there is a tex_code_break_column.
1993 // In this case somebody is interested in the generated LaTeX,
1994 // so this is OK. input@path is set when the actual parameter
1995 // original_path is set. This is done for usual tex-file, but not
1996 // for nice-latex-file. (Matthias 250696)
1999 // code for usual, NOT nice-latex-file
2000 ofs << "\\batchmode\n"; // changed
2001 // from \nonstopmode
2004 if (!original_path.empty()) {
2005 ofs << "\\makeatletter\n"
2006 << "\\def\\input@path{{"
2007 << os::external_path(original_path) << "/}}\n"
2008 << "\\makeatother\n";
2014 ofs << "\\documentclass";
2016 ostringstream options; // the document class options.
2018 if (tokenPos(tclass.opt_fontsize(),
2019 '|', params.fontsize) >= 0) {
2020 // only write if existing in list (and not default)
2021 options << params.fontsize << "pt,";
2025 if (!params.use_geometry &&
2026 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2027 switch (params.papersize) {
2028 case BufferParams::PAPER_A4PAPER:
2029 options << "a4paper,";
2031 case BufferParams::PAPER_USLETTER:
2032 options << "letterpaper,";
2034 case BufferParams::PAPER_A5PAPER:
2035 options << "a5paper,";
2037 case BufferParams::PAPER_B5PAPER:
2038 options << "b5paper,";
2040 case BufferParams::PAPER_EXECUTIVEPAPER:
2041 options << "executivepaper,";
2043 case BufferParams::PAPER_LEGALPAPER:
2044 options << "legalpaper,";
2050 if (params.sides != tclass.sides()) {
2051 switch (params.sides) {
2052 case LyXTextClass::OneSide:
2053 options << "oneside,";
2055 case LyXTextClass::TwoSides:
2056 options << "twoside,";
2062 if (params.columns != tclass.columns()) {
2063 if (params.columns == 2)
2064 options << "twocolumn,";
2066 options << "onecolumn,";
2069 if (!params.use_geometry
2070 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2071 options << "landscape,";
2073 // language should be a parameter to \documentclass
2075 ostringstream language_options;
2076 if (params.language->babel() == "hebrew"
2077 && default_language->babel() != "hebrew")
2078 // This seems necessary
2079 features.UsedLanguages.insert(default_language);
2081 if (lyxrc.language_use_babel ||
2082 params.language->lang() != lyxrc.default_language ||
2083 !features.UsedLanguages.empty()) {
2085 for (LaTeXFeatures::LanguageList::const_iterator cit =
2086 features.UsedLanguages.begin();
2087 cit != features.UsedLanguages.end(); ++cit)
2088 language_options << (*cit)->babel() << ',';
2089 language_options << params.language->babel();
2090 if (lyxrc.language_global_options)
2091 options << language_options.str() << ',';
2094 // the user-defined options
2095 if (!params.options.empty()) {
2096 options << params.options << ',';
2099 string strOptions(options.str().c_str());
2100 if (!strOptions.empty()){
2101 strOptions = strip(strOptions, ',');
2102 ofs << '[' << strOptions << ']';
2106 << textclasslist.LatexnameOfClass(params.textclass)
2109 // end of \documentclass defs
2111 // font selection must be done before loading fontenc.sty
2112 // The ae package is not needed when using OT1 font encoding.
2113 if (params.fonts != "default" &&
2114 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2115 ofs << "\\usepackage{" << params.fonts << "}\n";
2117 if (params.fonts == "ae") {
2118 ofs << "\\usepackage{aecompl}\n";
2122 // this one is not per buffer
2123 if (lyxrc.fontenc != "default") {
2124 ofs << "\\usepackage[" << lyxrc.fontenc
2129 if (params.inputenc == "auto") {
2130 string const doc_encoding =
2131 params.language->encoding()->LatexName();
2133 // Create a list with all the input encodings used
2135 set<string> encodings;
2136 for (LaTeXFeatures::LanguageList::const_iterator it =
2137 features.UsedLanguages.begin();
2138 it != features.UsedLanguages.end(); ++it)
2139 if ((*it)->encoding()->LatexName() != doc_encoding)
2140 encodings.insert((*it)->encoding()->LatexName());
2142 ofs << "\\usepackage[";
2143 std::copy(encodings.begin(), encodings.end(),
2144 std::ostream_iterator<string>(ofs, ","));
2145 ofs << doc_encoding << "]{inputenc}\n";
2147 } else if (params.inputenc != "default") {
2148 ofs << "\\usepackage[" << params.inputenc
2153 // At the very beginning the text parameters.
2154 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2155 switch (params.paperpackage) {
2156 case BufferParams::PACKAGE_A4:
2157 ofs << "\\usepackage{a4}\n";
2160 case BufferParams::PACKAGE_A4WIDE:
2161 ofs << "\\usepackage{a4wide}\n";
2164 case BufferParams::PACKAGE_WIDEMARGINSA4:
2165 ofs << "\\usepackage[widemargins]{a4}\n";
2170 if (params.use_geometry) {
2171 ofs << "\\usepackage{geometry}\n";
2173 ofs << "\\geometry{verbose";
2174 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2175 ofs << ",landscape";
2176 switch (params.papersize2) {
2177 case BufferParams::VM_PAPER_CUSTOM:
2178 if (!params.paperwidth.empty())
2179 ofs << ",paperwidth="
2180 << params.paperwidth;
2181 if (!params.paperheight.empty())
2182 ofs << ",paperheight="
2183 << params.paperheight;
2185 case BufferParams::VM_PAPER_USLETTER:
2186 ofs << ",letterpaper";
2188 case BufferParams::VM_PAPER_USLEGAL:
2189 ofs << ",legalpaper";
2191 case BufferParams::VM_PAPER_USEXECUTIVE:
2192 ofs << ",executivepaper";
2194 case BufferParams::VM_PAPER_A3:
2197 case BufferParams::VM_PAPER_A4:
2200 case BufferParams::VM_PAPER_A5:
2203 case BufferParams::VM_PAPER_B3:
2206 case BufferParams::VM_PAPER_B4:
2209 case BufferParams::VM_PAPER_B5:
2213 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2214 switch (lyxrc.default_papersize) {
2215 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2216 case BufferParams::PAPER_USLETTER:
2217 ofs << ",letterpaper";
2219 case BufferParams::PAPER_LEGALPAPER:
2220 ofs << ",legalpaper";
2222 case BufferParams::PAPER_EXECUTIVEPAPER:
2223 ofs << ",executivepaper";
2225 case BufferParams::PAPER_A3PAPER:
2228 case BufferParams::PAPER_A4PAPER:
2231 case BufferParams::PAPER_A5PAPER:
2234 case BufferParams::PAPER_B5PAPER:
2239 if (!params.topmargin.empty())
2240 ofs << ",tmargin=" << params.topmargin;
2241 if (!params.bottommargin.empty())
2242 ofs << ",bmargin=" << params.bottommargin;
2243 if (!params.leftmargin.empty())
2244 ofs << ",lmargin=" << params.leftmargin;
2245 if (!params.rightmargin.empty())
2246 ofs << ",rmargin=" << params.rightmargin;
2247 if (!params.headheight.empty())
2248 ofs << ",headheight=" << params.headheight;
2249 if (!params.headsep.empty())
2250 ofs << ",headsep=" << params.headsep;
2251 if (!params.footskip.empty())
2252 ofs << ",footskip=" << params.footskip;
2256 if (features.amsstyle
2257 && !tclass.provides(LyXTextClass::amsmath)) {
2258 ofs << "\\usepackage{amsmath}\n";
2262 if (tokenPos(tclass.opt_pagestyle(),
2263 '|', params.pagestyle) >= 0) {
2264 if (params.pagestyle == "fancy") {
2265 ofs << "\\usepackage{fancyhdr}\n";
2268 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2272 // We try to load babel late, in case it interferes
2273 // with other packages.
2275 string tmp = lyxrc.language_package;
2276 if (!lyxrc.language_global_options
2277 && tmp == "\\usepackage{babel}")
2278 tmp = string("\\usepackage[") +
2279 language_options.str().c_str() +
2285 if (params.secnumdepth != tclass.secnumdepth()) {
2286 ofs << "\\setcounter{secnumdepth}{"
2287 << params.secnumdepth
2291 if (params.tocdepth != tclass.tocdepth()) {
2292 ofs << "\\setcounter{tocdepth}{"
2298 if (params.paragraph_separation) {
2299 switch (params.defskip.kind()) {
2300 case VSpace::SMALLSKIP:
2301 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2303 case VSpace::MEDSKIP:
2304 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2306 case VSpace::BIGSKIP:
2307 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2309 case VSpace::LENGTH:
2310 ofs << "\\setlength\\parskip{"
2311 << params.defskip.length().asLatexString()
2314 default: // should never happen // Then delete it.
2315 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2320 ofs << "\\setlength\\parindent{0pt}\n";
2324 // Now insert the LyX specific LaTeX commands...
2326 // The optional packages;
2327 string preamble(features.getPackages());
2329 // this might be useful...
2330 preamble += "\n\\makeatletter\n";
2332 // Some macros LyX will need
2333 string tmppreamble(features.getMacros());
2335 if (!tmppreamble.empty()) {
2336 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2337 "LyX specific LaTeX commands.\n"
2338 + tmppreamble + '\n';
2341 // the text class specific preamble
2342 tmppreamble = features.getTClassPreamble();
2343 if (!tmppreamble.empty()) {
2344 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2345 "Textclass specific LaTeX commands.\n"
2346 + tmppreamble + '\n';
2349 /* the user-defined preamble */
2350 if (!params.preamble.empty()) {
2351 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2352 "User specified LaTeX commands.\n"
2353 + params.preamble + '\n';
2356 preamble += "\\makeatother\n";
2358 // Itemize bullet settings need to be last in case the user
2359 // defines their own bullets that use a package included
2360 // in the user-defined preamble -- ARRae
2361 // Actually it has to be done much later than that
2362 // since some packages like frenchb make modifications
2363 // at \begin{document} time -- JMarc
2365 for (int i = 0; i < 4; ++i) {
2366 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2367 if (bullets_def.empty())
2368 bullets_def="\\AtBeginDocument{\n";
2369 bullets_def += " \\renewcommand{\\labelitemi";
2371 // `i' is one less than the item to modify
2378 bullets_def += "ii";
2384 bullets_def += "}{" +
2385 params.user_defined_bullets[i].getText()
2390 if (!bullets_def.empty())
2391 preamble += bullets_def + "}\n\n";
2393 for (int j = countChar(preamble, '\n'); j-- ;) {
2400 ofs << "\\begin{document}\n";
2403 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2405 if (!lyxrc.language_auto_begin) {
2406 ofs << subst(lyxrc.language_command_begin, "$$lang",
2407 params.language->babel())
2412 latexParagraphs(ofs, paragraph, 0, texrow);
2414 // add this just in case after all the paragraphs
2418 if (!lyxrc.language_auto_end) {
2419 ofs << subst(lyxrc.language_command_end, "$$lang",
2420 params.language->babel())
2426 ofs << "\\end{document}\n";
2429 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2431 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2435 // Just to be sure. (Asger)
2438 // tex_code_break_column's value is used to decide
2439 // if we are in batchmode or not (within mathed_write()
2440 // in math_write.C) so we must set it to a non-zero
2441 // value when we leave otherwise we save incorrect .lyx files.
2442 tex_code_break_column = lyxrc.ascii_linelen;
2446 lyxerr << "File was not closed properly." << endl;
2449 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2454 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2456 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2457 Paragraph * endpar, TexRow & texrow) const
2459 bool was_title = false;
2460 bool already_title = false;
2463 while (par != endpar) {
2464 LyXLayout const & layout =
2465 textclasslist.Style(params.textclass,
2468 if (layout.intitle) {
2469 if (already_title) {
2470 lyxerr <<"Error in latexParagraphs: You"
2471 " should not mix title layouts"
2472 " with normal ones." << endl;
2475 } else if (was_title && !already_title) {
2476 ofs << "\\maketitle\n";
2478 already_title = true;
2482 if (layout.isEnvironment()) {
2483 par = par->TeXEnvironment(this, params, ofs, texrow);
2485 par = par->TeXOnePar(this, params, ofs, texrow, false);
2488 // It might be that we only have a title in this document
2489 if (was_title && !already_title) {
2490 ofs << "\\maketitle\n";
2496 bool Buffer::isLatex() const
2498 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2502 bool Buffer::isLinuxDoc() const
2504 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2508 bool Buffer::isLiterate() const
2510 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2514 bool Buffer::isDocBook() const
2516 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2520 bool Buffer::isSGML() const
2522 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2523 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2527 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2528 string const & latexname) const
2530 if (!latexname.empty() && latexname != "!-- --")
2531 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2532 //os << string(depth, ' ') << "<" << latexname << ">\n";
2536 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2537 string const & latexname) const
2539 if (!latexname.empty() && latexname != "!-- --")
2540 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2541 //os << string(depth, ' ') << "</" << latexname << ">\n";
2545 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2547 ofstream ofs(fname.c_str());
2550 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2554 niceFile = nice; // this will be used by included files.
2556 LyXTextClass const & tclass =
2557 textclasslist.TextClass(params.textclass);
2559 LaTeXFeatures features(params, tclass.numLayouts());
2564 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2567 string sgml_includedfiles=features.getIncludedFiles(fname);
2569 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2570 ofs << "<!doctype linuxdoc system>\n\n";
2572 ofs << "<!doctype linuxdoc system [ "
2573 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2576 if (params.options.empty())
2577 sgmlOpenTag(ofs, 0, top_element);
2579 string top = top_element;
2581 top += params.options;
2582 sgmlOpenTag(ofs, 0, top);
2586 ofs << "<!-- " << LYX_DOCVERSION
2587 << " created this file. For more info see http://www.lyx.org/"
2590 Paragraph::depth_type depth = 0; // paragraph depth
2591 Paragraph * par = paragraph;
2593 vector<string> environment_stack(5);
2596 LyXLayout const & style =
2597 textclasslist.Style(params.textclass,
2600 // treat <toc> as a special case for compatibility with old code
2601 if (par->getChar(0) == Paragraph::META_INSET) {
2602 Inset * inset = par->getInset(0);
2603 Inset::Code lyx_code = inset->lyxCode();
2604 if (lyx_code == Inset::TOC_CODE){
2605 string const temp = "toc";
2606 sgmlOpenTag(ofs, depth, temp);
2613 // environment tag closing
2614 for (; depth > par->params().depth(); --depth) {
2615 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2616 environment_stack[depth].erase();
2619 // write opening SGML tags
2620 switch (style.latextype) {
2621 case LATEX_PARAGRAPH:
2622 if (depth == par->params().depth()
2623 && !environment_stack[depth].empty()) {
2624 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2625 environment_stack[depth].erase();
2631 sgmlOpenTag(ofs, depth, style.latexname());
2636 linuxDocError(par, 0,
2637 _("Error : Wrong depth for"
2638 " LatexType Command.\n"));
2640 if (!environment_stack[depth].empty()){
2641 sgmlCloseTag(ofs, depth,
2642 environment_stack[depth]);
2646 environment_stack[depth].erase();
2647 sgmlOpenTag(ofs, depth, style.latexname());
2650 case LATEX_ENVIRONMENT:
2651 case LATEX_ITEM_ENVIRONMENT:
2652 if (depth == par->params().depth()
2653 && environment_stack[depth] != style.latexname()) {
2654 sgmlCloseTag(ofs, depth,
2655 environment_stack[depth]);
2656 environment_stack[depth].erase();
2658 if (depth < par->params().depth()) {
2659 depth = par->params().depth();
2660 environment_stack[depth].erase();
2662 if (environment_stack[depth] != style.latexname()) {
2664 sgmlOpenTag(ofs, depth, "p");
2666 sgmlOpenTag(ofs, depth, style.latexname());
2668 if (environment_stack.size() == depth + 1)
2669 environment_stack.push_back("!-- --");
2670 environment_stack[depth] = style.latexname();
2673 if (style.latexparam() == "CDATA")
2676 if (style.latextype == LATEX_ENVIRONMENT) break;
2678 if (style.labeltype == LABEL_MANUAL)
2683 sgmlOpenTag(ofs, depth + 1, item_name);
2686 sgmlOpenTag(ofs, depth, style.latexname());
2690 simpleLinuxDocOnePar(ofs, par, depth);
2695 // write closing SGML tags
2696 switch (style.latextype) {
2699 case LATEX_ENVIRONMENT:
2700 case LATEX_ITEM_ENVIRONMENT:
2701 if (style.latexparam() == "CDATA")
2705 sgmlCloseTag(ofs, depth, style.latexname());
2711 for (int i=depth; i >= 0; --i)
2712 sgmlCloseTag(ofs, depth, environment_stack[i]);
2716 sgmlCloseTag(ofs, 0, top_element);
2720 // How to check for successful close
2724 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2725 Paragraph::depth_type depth, int desc_on,
2728 Paragraph * tpar = par;
2730 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2732 tpar = tpar->next();
2735 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2736 "Caption").second) {
2737 sgmlOpenTag(os, depth + 1, inner_tag);
2739 simpleDocBookOnePar(os, extra_par, tpar,
2740 desc_on, depth + 2);
2741 sgmlCloseTag(os, depth+1, inner_tag);
2742 if (!extra_par.empty())
2748 // checks, if newcol chars should be put into this line
2749 // writes newline, if necessary.
2752 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2753 string::size_type newcol)
2756 if (colcount > lyxrc.ascii_linelen) {
2758 colcount = newcol; // assume write after this call
2773 string tag_name(PAR_TAG const & pt) {
2775 case NONE: return "!-- --";
2776 case TT: return "tt";
2777 case SF: return "sf";
2778 case BF: return "bf";
2779 case IT: return "it";
2780 case SL: return "sl";
2781 case EM: return "em";
2788 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2790 p1 = static_cast<PAR_TAG>(p1 | p2);
2795 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2797 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2805 // Handle internal paragraph parsing -- layout already processed.
2806 void Buffer::simpleLinuxDocOnePar(ostream & os,
2808 Paragraph::depth_type /*depth*/)
2810 LyXLayout const & style = textclasslist.Style(params.textclass,
2812 string::size_type char_line_count = 5; // Heuristic choice ;-)
2814 // gets paragraph main font
2817 if (style.labeltype == LABEL_MANUAL) {
2818 font_old = style.labelfont;
2821 font_old = style.font;
2825 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2826 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2827 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2830 stack < PAR_TAG > tag_state;
2831 // parsing main loop
2832 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2834 PAR_TAG tag_close = NONE;
2835 list < PAR_TAG > tag_open;
2837 LyXFont const font = par->getFont(params, i);
2839 if (font_old.family() != font.family()) {
2840 switch (family_type) {
2841 case LyXFont::SANS_FAMILY:
2844 case LyXFont::TYPEWRITER_FAMILY:
2851 family_type = font.family();
2853 switch (family_type) {
2854 case LyXFont::SANS_FAMILY:
2855 tag_open.push_back(SF);
2857 case LyXFont::TYPEWRITER_FAMILY:
2858 tag_open.push_back(TT);
2865 if (font_old.series() != font.series()) {
2866 switch (series_type) {
2867 case LyXFont::BOLD_SERIES:
2874 series_type = font.series();
2876 switch (series_type) {
2877 case LyXFont::BOLD_SERIES:
2878 tag_open.push_back(BF);
2886 if (font_old.shape() != font.shape()) {
2887 switch (shape_type) {
2888 case LyXFont::ITALIC_SHAPE:
2891 case LyXFont::SLANTED_SHAPE:
2898 shape_type = font.shape();
2900 switch (shape_type) {
2901 case LyXFont::ITALIC_SHAPE:
2902 tag_open.push_back(IT);
2904 case LyXFont::SLANTED_SHAPE:
2905 tag_open.push_back(SL);
2912 if (font_old.emph() != font.emph()) {
2913 if (font.emph() == LyXFont::ON) {
2914 tag_open.push_back(EM);
2923 list < PAR_TAG > temp;
2924 while(!tag_state.empty() && tag_close ) {
2925 PAR_TAG k = tag_state.top();
2927 os << "</" << tag_name(k) << ">";
2934 for(list< PAR_TAG >::const_iterator j = temp.begin();
2935 j != temp.end(); ++j) {
2937 os << "<" << tag_name(*j) << ">";
2940 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2941 j != tag_open.end(); ++j) {
2943 os << "<" << tag_name(*j) << ">";
2946 char c = par->getChar(i);
2948 if (c == Paragraph::META_INSET) {
2949 Inset * inset = par->getInset(i);
2950 inset->linuxdoc(this, os);
2957 font.latex() == LyXFont::ON ||
2959 style.latexparam() == "CDATA") {
2960 // "TeX"-Mode on == > SGML-Mode on.
2966 if (par->linuxDocConvertChar(c, sgml_string)
2967 && !style.free_spacing) {
2968 // in freespacing mode, spaces are
2969 // non-breaking characters
2970 if (desc_on) {// if char is ' ' then...
2973 linux_doc_line_break(os, char_line_count, 6);
2977 linux_doc_line_break(os, char_line_count, 1);
2982 char_line_count += sgml_string.length();
2988 while (!tag_state.empty()) {
2989 os << "</" << tag_name(tag_state.top()) << ">";
2993 // resets description flag correctly
2995 // <tag> not closed...
2996 linux_doc_line_break(os, char_line_count, 6);
3002 // Print an error message.
3003 void Buffer::linuxDocError(Paragraph * par, int pos,
3004 string const & message)
3006 // insert an error marker in text
3007 InsetError * new_inset = new InsetError(message);
3008 par->insertInset(pos, new_inset);
3012 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3014 ofstream ofs(fname.c_str());
3016 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3020 Paragraph * par = paragraph;
3022 niceFile = nice; // this will be used by Insetincludes.
3024 LyXTextClass const & tclass =
3025 textclasslist.TextClass(params.textclass);
3027 LaTeXFeatures features(params, tclass.numLayouts());
3032 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3035 string sgml_includedfiles = features.getIncludedFiles(fname);
3037 ofs << "<!doctype " << top_element
3038 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3040 if (params.preamble.empty() && sgml_includedfiles.empty())
3043 ofs << "\n [ " << params.preamble
3044 << sgml_includedfiles << " \n]>\n\n";
3047 string top = top_element;
3049 top += params.language->code();
3052 if (!params.options.empty()) {
3054 top += params.options;
3056 sgmlOpenTag(ofs, 0, top);
3058 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3059 << "\n See http://www.lyx.org/ for more information -->\n";
3061 vector<string> environment_stack(10);
3062 vector<string> environment_inner(10);
3063 vector<string> command_stack(10);
3065 bool command_flag = false;
3066 Paragraph::depth_type command_depth = 0;
3067 Paragraph::depth_type command_base = 0;
3068 Paragraph::depth_type cmd_depth = 0;
3069 Paragraph::depth_type depth = 0; // paragraph depth
3072 string command_name;
3078 int desc_on = 0; // description mode
3080 LyXLayout const & style =
3081 textclasslist.Style(params.textclass,
3084 // environment tag closing
3085 for (; depth > par->params().depth(); --depth) {
3086 if (environment_inner[depth] != "!-- --") {
3087 item_name = "listitem";
3088 sgmlCloseTag(ofs, command_depth + depth,
3090 if (environment_inner[depth] == "varlistentry")
3091 sgmlCloseTag(ofs, depth+command_depth,
3092 environment_inner[depth]);
3094 sgmlCloseTag(ofs, depth + command_depth,
3095 environment_stack[depth]);
3096 environment_stack[depth].erase();
3097 environment_inner[depth].erase();
3100 if (depth == par->params().depth()
3101 && environment_stack[depth] != style.latexname()
3102 && !environment_stack[depth].empty()) {
3103 if (environment_inner[depth] != "!-- --") {
3104 item_name= "listitem";
3105 sgmlCloseTag(ofs, command_depth+depth,
3107 if (environment_inner[depth] == "varlistentry")
3109 depth + command_depth,
3110 environment_inner[depth]);
3113 sgmlCloseTag(ofs, depth + command_depth,
3114 environment_stack[depth]);
3116 environment_stack[depth].erase();
3117 environment_inner[depth].erase();
3120 // Write opening SGML tags.
3121 switch (style.latextype) {
3122 case LATEX_PARAGRAPH:
3123 sgmlOpenTag(ofs, depth + command_depth,
3129 linuxDocError(par, 0,
3130 _("Error : Wrong depth for "
3131 "LatexType Command.\n"));
3133 command_name = style.latexname();
3135 sgmlparam = style.latexparam();
3136 c_params = split(sgmlparam, c_depth,'|');
3138 cmd_depth = lyx::atoi(c_depth);
3141 if (cmd_depth < command_base) {
3142 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3143 sgmlCloseTag(ofs, j, command_stack[j]);
3144 command_depth = command_base = cmd_depth;
3145 } else if (cmd_depth <= command_depth) {
3146 for (int j = command_depth; j >= int(cmd_depth); --j)
3147 sgmlCloseTag(ofs, j, command_stack[j]);
3148 command_depth = cmd_depth;
3150 command_depth = cmd_depth;
3152 command_depth = command_base = cmd_depth;
3153 command_flag = true;
3155 if (command_stack.size() == command_depth + 1)
3156 command_stack.push_back(string());
3157 command_stack[command_depth] = command_name;
3159 // treat label as a special case for
3160 // more WYSIWYM handling.
3161 if (par->getChar(0) == Paragraph::META_INSET) {
3162 Inset * inset = par->getInset(0);
3163 Inset::Code lyx_code = inset->lyxCode();
3164 if (lyx_code == Inset::LABEL_CODE){
3165 command_name += " id=\"";
3166 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3167 command_name += "\"";
3172 sgmlOpenTag(ofs, depth + command_depth, command_name);
3173 if (c_params.empty())
3174 item_name = "title";
3176 item_name = c_params;
3177 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3180 case LATEX_ENVIRONMENT:
3181 case LATEX_ITEM_ENVIRONMENT:
3182 if (depth < par->params().depth()) {
3183 depth = par->params().depth();
3184 environment_stack[depth].erase();
3187 if (environment_stack[depth] != style.latexname()) {
3188 if(environment_stack.size() == depth + 1) {
3189 environment_stack.push_back("!-- --");
3190 environment_inner.push_back("!-- --");
3192 environment_stack[depth] = style.latexname();
3193 environment_inner[depth] = "!-- --";
3194 sgmlOpenTag(ofs, depth + command_depth,
3195 environment_stack[depth]);
3197 if (environment_inner[depth] != "!-- --") {
3198 item_name= "listitem";
3200 command_depth + depth,
3202 if (environment_inner[depth] == "varlistentry")
3204 depth + command_depth,
3205 environment_inner[depth]);
3209 if (style.latextype == LATEX_ENVIRONMENT) {
3210 if (!style.latexparam().empty()) {
3211 if(style.latexparam() == "CDATA")
3214 sgmlOpenTag(ofs, depth + command_depth,
3215 style.latexparam());
3220 desc_on = (style.labeltype == LABEL_MANUAL);
3223 environment_inner[depth]= "varlistentry";
3225 environment_inner[depth]= "listitem";
3227 sgmlOpenTag(ofs, depth + 1 + command_depth,
3228 environment_inner[depth]);
3232 sgmlOpenTag(ofs, depth + 1 + command_depth,
3236 sgmlOpenTag(ofs, depth + 1 + command_depth,
3241 sgmlOpenTag(ofs, depth + command_depth,
3247 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3248 depth + 1 + command_depth);
3252 // write closing SGML tags
3253 switch (style.latextype) {
3255 if (c_params.empty())
3259 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3261 case LATEX_ENVIRONMENT:
3262 if (!style.latexparam().empty()) {
3263 if(style.latexparam() == "CDATA")
3266 sgmlCloseTag(ofs, depth + command_depth,
3267 style.latexparam());
3270 case LATEX_ITEM_ENVIRONMENT:
3271 if (desc_on == 1) break;
3273 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3275 case LATEX_PARAGRAPH:
3276 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3279 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3285 for (int d = depth; d >= 0; --d) {
3286 if (!environment_stack[depth].empty()) {
3287 if (environment_inner[depth] != "!-- --") {
3288 item_name = "listitem";
3289 sgmlCloseTag(ofs, command_depth + depth,
3291 if (environment_inner[depth] == "varlistentry")
3292 sgmlCloseTag(ofs, depth + command_depth,
3293 environment_inner[depth]);
3296 sgmlCloseTag(ofs, depth + command_depth,
3297 environment_stack[depth]);
3301 for (int j = command_depth; j >= 0 ; --j)
3302 if (!command_stack[j].empty())
3303 sgmlCloseTag(ofs, j, command_stack[j]);
3306 sgmlCloseTag(ofs, 0, top_element);
3309 // How to check for successful close
3313 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3314 Paragraph * par, int & desc_on,
3315 Paragraph::depth_type depth) const
3317 bool emph_flag = false;
3319 LyXLayout const & style = textclasslist.Style(params.textclass,
3322 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3324 int char_line_count = depth;
3325 //if (!style.free_spacing)
3326 // os << string(depth,' ');
3328 // parsing main loop
3329 for (Paragraph::size_type i = 0;
3330 i < par->size(); ++i) {
3331 LyXFont font = par->getFont(params, i);
3333 // handle <emphasis> tag
3334 if (font_old.emph() != font.emph()) {
3335 if (font.emph() == LyXFont::ON) {
3339 os << "</emphasis>";
3344 char c = par->getChar(i);
3346 if (c == Paragraph::META_INSET) {
3347 Inset * inset = par->getInset(i);
3349 inset->docBook(this, ost);
3350 string tmp_out = ost.str().c_str();
3353 // This code needs some explanation:
3354 // Two insets are treated specially
3355 // label if it is the first element in a command paragraph
3357 // graphics inside tables or figure floats can't go on
3358 // title (the equivalente in latex for this case is caption
3359 // and title should come first
3362 if (desc_on!= 3 || i!= 0) {
3363 if (!tmp_out.empty() && tmp_out[0] == '@') {
3365 extra += frontStrip(tmp_out, '@');
3367 os << frontStrip(tmp_out, '@');
3373 } else if (font.latex() == LyXFont::ON) {
3374 // "TeX"-Mode on ==> SGML-Mode on.
3381 if (par->linuxDocConvertChar(c, sgml_string)
3382 && !style.free_spacing) { // in freespacing
3384 // non-breaking characters
3388 os << "\n</term><listitem><para>";
3401 os << "</emphasis>";
3404 // resets description flag correctly
3406 // <term> not closed...
3409 if(style.free_spacing) os << '\n';
3413 // This should be enabled when the Chktex class is implemented. (Asger)
3414 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3415 // Other flags: -wall -v0 -x
3416 int Buffer::runChktex()
3418 if (!users->text) return 0;
3420 users->owner()->prohibitInput();
3422 // get LaTeX-Filename
3423 string const name = getLatexName();
3424 string path = OnlyPath(filename);
3426 string const org_path = path;
3427 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3431 Path p(path); // path to LaTeX file
3432 users->owner()->message(_("Running chktex..."));
3434 // Remove all error insets
3435 bool const removedErrorInsets = users->removeAutoInsets();
3437 // Generate the LaTeX file if neccessary
3438 makeLaTeXFile(name, org_path, false);
3441 Chktex chktex(lyxrc.chktex_command, name, filepath);
3442 int res = chktex.run(terr); // run chktex
3445 WriteAlert(_("chktex did not work!"),
3446 _("Could not run with file:"), name);
3447 } else if (res > 0) {
3448 // Insert all errors as errors boxes
3449 users->insertErrors(terr);
3452 // if we removed error insets before we ran chktex or if we inserted
3453 // error insets after we ran chktex, this must be run:
3454 if (removedErrorInsets || res){
3456 users->fitCursor(users->text);
3458 users->owner()->allowInput();
3464 void Buffer::validate(LaTeXFeatures & features) const
3466 Paragraph * par = paragraph;
3467 LyXTextClass const & tclass =
3468 textclasslist.TextClass(params.textclass);
3470 // AMS Style is at document level
3471 features.amsstyle = (params.use_amsmath ||
3472 tclass.provides(LyXTextClass::amsmath));
3475 // We don't use "lyxerr.debug" because of speed. (Asger)
3476 if (lyxerr.debugging(Debug::LATEX))
3477 lyxerr << "Paragraph: " << par << endl;
3479 // Now just follow the list of paragraphs and run
3480 // validate on each of them.
3481 par->validate(features);
3483 // and then the next paragraph
3487 // the bullet shapes are buffer level not paragraph level
3488 // so they are tested here
3489 for (int i = 0; i < 4; ++i) {
3490 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3491 int const font = params.user_defined_bullets[i].getFont();
3493 int const c = params
3494 .user_defined_bullets[i]
3501 features.latexsym = true;
3503 } else if (font == 1) {
3504 features.amssymb = true;
3505 } else if ((font >= 2 && font <= 5)) {
3506 features.pifont = true;
3511 if (lyxerr.debugging(Debug::LATEX)) {
3512 features.showStruct();
3517 void Buffer::setPaperStuff()
3519 params.papersize = BufferParams::PAPER_DEFAULT;
3520 char const c1 = params.paperpackage;
3521 if (c1 == BufferParams::PACKAGE_NONE) {
3522 char const c2 = params.papersize2;
3523 if (c2 == BufferParams::VM_PAPER_USLETTER)
3524 params.papersize = BufferParams::PAPER_USLETTER;
3525 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3526 params.papersize = BufferParams::PAPER_LEGALPAPER;
3527 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3528 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3529 else if (c2 == BufferParams::VM_PAPER_A3)
3530 params.papersize = BufferParams::PAPER_A3PAPER;
3531 else if (c2 == BufferParams::VM_PAPER_A4)
3532 params.papersize = BufferParams::PAPER_A4PAPER;
3533 else if (c2 == BufferParams::VM_PAPER_A5)
3534 params.papersize = BufferParams::PAPER_A5PAPER;
3535 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3536 (c2 == BufferParams::VM_PAPER_B5))
3537 params.papersize = BufferParams::PAPER_B5PAPER;
3538 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3539 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3540 params.papersize = BufferParams::PAPER_A4PAPER;
3544 // This function should be in Buffer because it's a buffer's property (ale)
3545 string const Buffer::getIncludeonlyList(char delim)
3548 for (inset_iterator it = inset_iterator_begin();
3549 it != inset_iterator_end(); ++it) {
3550 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3551 InsetInclude * insetinc =
3552 static_cast<InsetInclude *>(*it);
3553 if (insetinc->isIncludeOnly()) {
3556 lst += insetinc->getRelFileBaseName();
3560 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3565 vector<string> const Buffer::getLabelList()
3567 /// if this is a child document and the parent is already loaded
3568 /// Use the parent's list instead [ale990407]
3569 if (!params.parentname.empty()
3570 && bufferlist.exists(params.parentname)) {
3571 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3573 return tmp->getLabelList();
3576 vector<string> label_list;
3577 for (inset_iterator it = inset_iterator_begin();
3578 it != inset_iterator_end(); ++it) {
3579 vector<string> const l = (*it)->getLabelList();
3580 label_list.insert(label_list.end(), l.begin(), l.end());
3586 Buffer::Lists const Buffer::getLists() const
3589 Paragraph * par = paragraph;
3591 LyXTextClassList::size_type cap;
3592 boost::tie(found, cap) = textclasslist
3593 .NumberOfLayout(params.textclass, "Caption");
3596 char const labeltype =
3597 textclasslist.Style(params.textclass,
3598 par->getLayout()).labeltype;
3600 if (labeltype >= LABEL_COUNTER_CHAPTER
3601 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3602 // insert this into the table of contents
3603 SingleList & item = l["TOC"];
3606 textclasslist.TextClass(params.textclass).maxcounter());
3607 item.push_back(TocItem(par, depth, par->asString(this, true)));
3609 // For each paragrph, traverse its insets and look for
3613 Paragraph::inset_iterator it =
3614 par->inset_iterator_begin();
3615 Paragraph::inset_iterator end =
3616 par->inset_iterator_end();
3618 for (; it != end; ++it) {
3619 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3621 static_cast<InsetFloat*>(*it);
3623 string const type = il->type();
3625 // Now find the caption in the float...
3626 // We now tranverse the paragraphs of
3628 Paragraph * tmp = il->inset.paragraph();
3630 if (tmp->layout == cap) {
3631 SingleList & item = l[type];
3633 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3634 item.push_back(TocItem(tmp, 0 , str));
3641 lyxerr << "caption not found" << endl;
3650 // This is also a buffer property (ale)
3651 vector<pair<string, string> > const Buffer::getBibkeyList()
3653 /// if this is a child document and the parent is already loaded
3654 /// Use the parent's list instead [ale990412]
3655 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3656 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3658 return tmp->getBibkeyList();
3661 vector<pair<string, string> > keys;
3662 Paragraph * par = paragraph;
3665 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3666 par->asString(this, false)));
3670 // Might be either using bibtex or a child has bibliography
3672 for (inset_iterator it = inset_iterator_begin();
3673 it != inset_iterator_end(); ++it) {
3674 // Search for Bibtex or Include inset
3675 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3676 vector<pair<string,string> > tmp =
3677 static_cast<InsetBibtex*>(*it)->getKeys(this);
3678 keys.insert(keys.end(), tmp.begin(), tmp.end());
3679 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3680 vector<pair<string,string> > const tmp =
3681 static_cast<InsetInclude*>(*it)->getKeys();
3682 keys.insert(keys.end(), tmp.begin(), tmp.end());
3691 bool Buffer::isDepClean(string const & name) const
3693 DEPCLEAN * item = dep_clean;
3694 while (item && item->master != name)
3696 if (!item) return true;
3701 void Buffer::markDepClean(string const & name)
3704 dep_clean = new DEPCLEAN;
3705 dep_clean->clean = true;
3706 dep_clean->master = name;
3707 dep_clean->next = 0;
3709 DEPCLEAN * item = dep_clean;
3710 while (item && item->master != name)
3715 item = new DEPCLEAN;
3717 item->master = name;
3724 bool Buffer::dispatch(string const & command)
3726 // Split command string into command and argument
3728 string line = frontStrip(command);
3729 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3731 return dispatch(lyxaction.LookupFunc(cmd), arg);
3735 bool Buffer::dispatch(int action, string const & argument)
3737 bool dispatched = true;
3740 Exporter::Export(this, argument, false);
3750 void Buffer::resizeInsets(BufferView * bv)
3752 /// then remove all LyXText in text-insets
3753 Paragraph * par = paragraph;
3754 for (; par; par = par->next()) {
3755 par->resizeInsetsLyXText(bv);
3760 void Buffer::redraw()
3763 users->fitCursor(users->text);
3767 void Buffer::changeLanguage(Language const * from, Language const * to)
3770 Paragraph * par = paragraph;
3772 par->changeLanguage(params, from, to);
3778 bool Buffer::isMultiLingual()
3780 Paragraph * par = paragraph;
3782 if (par->isMultiLingual(params))
3790 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3791 Paragraph::size_type pos)
3794 it = par->InsetIterator(pos);
3795 if (it == par->inset_iterator_end()) {
3802 void Buffer::inset_iterator::setParagraph()
3805 it = par->inset_iterator_begin();
3806 if (it != par->inset_iterator_end())
3811 // We maintain an invariant that whenever par = 0 then it = 0
3815 Inset * Buffer::getInsetFromID(int id_arg) const
3817 for (inset_iterator it = inset_const_iterator_begin();
3818 it != inset_const_iterator_end(); ++it)
3820 if ((*it)->id() == id_arg)
3822 Inset * in = (*it)->getInsetFromID(id_arg);
3830 Paragraph * Buffer::getParFromID(int id) const
3832 if (id < 0) return 0;
3833 Paragraph * par = paragraph;
3835 if (par->id() == id) {
3838 Paragraph * tmp = par->getParFromID(id);