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") { // Backward compatibility
1457 inset = new InsetFig(100, 100, *this);
1458 //inset = new InsetGraphics;
1459 } else if (tmptok == "Graphics") {
1460 inset = new InsetGraphics;
1461 } else if (tmptok == "Info") {// backwards compatibility
1462 inset = new InsetNote(this,
1463 lex.getLongString("\\end_inset"),
1466 } else if (tmptok == "Note") {
1467 inset = new InsetNote;
1468 } else if (tmptok == "Include") {
1469 InsetCommandParams p( "Include" );
1470 inset = new InsetInclude(p, *this);
1471 } else if (tmptok == "ERT") {
1472 inset = new InsetERT;
1473 } else if (tmptok == "Tabular") {
1474 inset = new InsetTabular(*this);
1475 } else if (tmptok == "Text") {
1476 inset = new InsetText;
1477 } else if (tmptok == "Foot") {
1478 inset = new InsetFoot;
1479 } else if (tmptok == "Marginal") {
1480 inset = new InsetMarginal;
1481 } else if (tmptok == "Minipage") {
1482 inset = new InsetMinipage;
1483 } else if (tmptok == "Float") {
1485 string tmptok = lex.GetString();
1486 inset = new InsetFloat(tmptok);
1488 } else if (tmptok == "List") {
1489 inset = new InsetList;
1490 } else if (tmptok == "Theorem") {
1491 inset = new InsetList;
1493 } else if (tmptok == "Caption") {
1494 inset = new InsetCaption;
1495 } else if (tmptok == "FloatList") {
1496 inset = new InsetFloatList;
1499 if (inset && !alreadyread) inset->read(this, lex);
1503 par->insertInset(pos, inset, font);
1509 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1513 string const token(lex.GetString());
1514 if (token == "\\lyxformat") { // the first token _must_ be...
1516 string tmp_format = lex.GetString();
1517 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1518 // if present remove ".," from string.
1519 string::size_type dot = tmp_format.find_first_of(".,");
1520 //lyxerr << " dot found at " << dot << endl;
1521 if (dot != string::npos)
1522 tmp_format.erase(dot, 1);
1523 file_format = strToInt(tmp_format);
1524 if (file_format == LYX_FORMAT) {
1526 } else if (file_format > LYX_FORMAT) {
1528 WriteAlert(_("Warning!"),
1529 _("LyX file format is newer that what"),
1530 _("is supported in this LyX version. Expect some problems."));
1532 } else if (file_format < LYX_FORMAT) {
1534 if (file_format < 200) {
1535 WriteAlert(_("ERROR!"),
1536 _("Old LyX file format found. "
1537 "Use LyX 0.10.x to read this!"));
1541 bool the_end = readLyXformat2(lex, par);
1543 // the_end was added in 213
1544 if (file_format < 213)
1548 WriteAlert(_("Warning!"),
1549 _("Reading of document is not complete"),
1550 _("Maybe the document is truncated"));
1552 } else { // "\\lyxformat" not found
1553 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1556 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1561 // Should probably be moved to somewhere else: BufferView? LyXView?
1562 bool Buffer::save() const
1564 // We don't need autosaves in the immediate future. (Asger)
1565 resetAutosaveTimers();
1569 if (lyxrc.make_backup) {
1570 s = fileName() + '~';
1571 if (!lyxrc.backupdir_path.empty())
1572 s = AddName(lyxrc.backupdir_path,
1573 subst(os::slashify_path(s),'/','!'));
1575 // Rename is the wrong way of making a backup,
1576 // this is the correct way.
1577 /* truss cp fil fil2:
1578 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1579 stat("LyXVC.lyx", 0xEFFFF688) = 0
1580 open("LyXVC.lyx", O_RDONLY) = 3
1581 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1582 fstat(4, 0xEFFFF508) = 0
1583 fstat(3, 0xEFFFF508) = 0
1584 read(3, " # T h i s f i l e w".., 8192) = 5579
1585 write(4, " # T h i s f i l e w".., 5579) = 5579
1586 read(3, 0xEFFFD4A0, 8192) = 0
1589 chmod("LyXVC3.lyx", 0100644) = 0
1590 lseek(0, 0, SEEK_CUR) = 46440
1594 // Should probably have some more error checking here.
1595 // Should be cleaned up in 0.13, at least a bit.
1596 // Doing it this way, also makes the inodes stay the same.
1597 // This is still not a very good solution, in particular we
1598 // might loose the owner of the backup.
1599 FileInfo finfo(fileName());
1600 if (finfo.exist()) {
1601 mode_t fmode = finfo.getMode();
1602 struct utimbuf times = {
1603 finfo.getAccessTime(),
1604 finfo.getModificationTime() };
1606 ifstream ifs(fileName().c_str());
1607 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1612 ::chmod(s.c_str(), fmode);
1614 if (::utime(s.c_str(), ×)) {
1615 lyxerr << "utime error." << endl;
1618 lyxerr << "LyX was not able to make "
1619 "backup copy. Beware." << endl;
1624 if (writeFile(fileName(), false)) {
1626 removeAutosaveFile(fileName());
1628 // Saving failed, so backup is not backup
1629 if (lyxrc.make_backup) {
1630 lyx::rename(s, fileName());
1638 // Returns false if unsuccesful
1639 bool Buffer::writeFile(string const & fname, bool flag) const
1641 // if flag is false writeFile will not create any GUI
1642 // warnings, only cerr.
1643 // Needed for autosave in background or panic save (Matthias 120496)
1645 if (read_only && (fname == filename)) {
1646 // Here we should come with a question if we should
1647 // perform the write anyway.
1649 lyxerr << _("Error! Document is read-only: ")
1652 WriteAlert(_("Error! Document is read-only: "),
1657 FileInfo finfo(fname);
1658 if (finfo.exist() && !finfo.writable()) {
1659 // Here we should come with a question if we should
1660 // try to do the save anyway. (i.e. do a chmod first)
1662 lyxerr << _("Error! Cannot write file: ")
1665 WriteFSAlert(_("Error! Cannot write file: "),
1670 ofstream ofs(fname.c_str());
1673 lyxerr << _("Error! Cannot open file: ")
1676 WriteFSAlert(_("Error! Cannot open file: "),
1682 // Use the standard "C" locale for file output.
1683 ofs.imbue(std::locale::classic());
1686 // The top of the file should not be written by params.
1688 // write out a comment in the top of the file
1689 ofs << '#' << LYX_DOCVERSION
1690 << " created this file. For more info see http://www.lyx.org/\n"
1691 << "\\lyxformat " << LYX_FORMAT << "\n";
1693 // now write out the buffer paramters.
1694 params.writeFile(ofs);
1696 Paragraph::depth_type depth = 0;
1698 // this will write out all the paragraphs
1699 // using recursive descent.
1700 paragraph->writeFile(this, ofs, params, depth);
1702 // Write marker that shows file is complete
1703 ofs << "\n\\the_end" << endl;
1707 // how to check if close went ok?
1708 // Following is an attempt... (BE 20001011)
1710 // good() returns false if any error occured, including some
1711 // formatting error.
1712 // bad() returns true if something bad happened in the buffer,
1713 // which should include file system full errors.
1720 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1722 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1732 string const Buffer::asciiParagraph(Paragraph const * par,
1733 unsigned int linelen) const
1735 ostringstream buffer;
1736 Paragraph::depth_type depth = 0;
1738 Paragraph::depth_type ltype_depth = 0;
1739 unsigned int currlinelen = 0;
1740 bool ref_printed = false;
1744 if (!par->previous()) {
1745 // begins or ends a deeper area ?
1746 if (depth != par->params().depth()) {
1747 if (par->params().depth() > depth) {
1748 while (par->params().depth() > depth) {
1752 while (par->params().depth() < depth) {
1758 // First write the layout
1759 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1760 if (tmp == "Itemize") {
1762 ltype_depth = depth + 1;
1763 } else if (tmp == "Enumerate") {
1765 ltype_depth = depth + 1;
1766 } else if (contains(tmp, "ection")) {
1768 ltype_depth = depth + 1;
1769 } else if (contains(tmp, "aragraph")) {
1771 ltype_depth = depth + 1;
1772 } else if (tmp == "Description") {
1774 ltype_depth = depth + 1;
1775 } else if (tmp == "Abstract") {
1778 } else if (tmp == "Bibliography") {
1786 /* maybe some vertical spaces */
1788 /* the labelwidthstring used in lists */
1792 /* some pagebreaks? */
1796 /* what about the alignment */
1798 lyxerr << "Should this ever happen?" << endl;
1802 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1804 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1805 if (!i && !noparbreak) {
1808 for (Paragraph::depth_type j = 0; j < depth; ++j)
1810 currlinelen = depth * 2;
1813 case 4: // (Sub)Paragraph
1814 case 5: // Description
1818 buffer << "Abstract\n\n";
1820 buffer << "Abstract: ";
1822 case 7: // Bibliography
1825 buffer << "References\n\n";
1827 buffer << "References: ";
1832 buffer << par->params().labelString() << " ";
1835 if (ltype_depth > depth) {
1836 for (Paragraph::depth_type j = ltype_depth - 1;
1839 currlinelen += (ltype_depth-depth)*2;
1843 LyXFont const font2 = par->getFontSettings(params, i);
1844 if (font1.latex() != font2.latex()) {
1845 if (font2.latex() == LyXFont::OFF)
1854 char c = par->getUChar(params, i);
1858 case Paragraph::META_INSET:
1860 Inset const * inset = par->getInset(i);
1862 if (!inset->ascii(this, buffer)) {
1865 rsplit(buffer.str().c_str(),
1867 currlinelen += s.length();
1869 // to be sure it breaks paragraph
1870 currlinelen += linelen;
1876 case Paragraph::META_NEWLINE:
1879 for (Paragraph::depth_type j = 0;
1883 currlinelen = depth * 2;
1884 if (ltype_depth > depth) {
1885 for (Paragraph::depth_type j = ltype_depth;
1888 currlinelen += (ltype_depth - depth) * 2;
1892 case Paragraph::META_HFILL:
1901 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1902 (c == ' ') && ((i + 2) < par->size()))
1905 for (Paragraph::depth_type j = 0;
1908 currlinelen = depth * 2;
1909 if (ltype_depth > depth) {
1910 for (Paragraph::depth_type j = ltype_depth;
1913 currlinelen += (ltype_depth-depth)*2;
1915 } else if (c != '\0')
1918 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1923 return buffer.str().c_str();
1927 void Buffer::writeFileAscii(string const & fname, int linelen)
1929 ofstream ofs(fname.c_str());
1931 WriteFSAlert(_("Error: Cannot write file:"), fname);
1934 writeFileAscii(ofs, linelen);
1938 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1940 Paragraph * par = paragraph;
1942 ofs << asciiParagraph(par, linelen);
1950 void Buffer::makeLaTeXFile(string const & fname,
1951 string const & original_path,
1952 bool nice, bool only_body)
1954 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1956 niceFile = nice; // this will be used by Insetincludes.
1958 tex_code_break_column = lyxrc.ascii_linelen;
1960 LyXTextClass const & tclass =
1961 textclasslist.TextClass(params.textclass);
1963 ofstream ofs(fname.c_str());
1965 WriteFSAlert(_("Error: Cannot open file: "), fname);
1969 // validate the buffer.
1970 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1971 LaTeXFeatures features(params, tclass.numLayouts());
1973 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1976 // The starting paragraph of the coming rows is the
1977 // first paragraph of the document. (Asger)
1978 texrow.start(paragraph, 0);
1980 if (!only_body && nice) {
1981 ofs << "%% " LYX_DOCVERSION " created this file. "
1982 "For more info, see http://www.lyx.org/.\n"
1983 "%% Do not edit unless you really know what "
1988 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1989 // There are a few differences between nice LaTeX and usual files:
1990 // usual is \batchmode and has a
1991 // special input@path to allow the including of figures
1992 // with either \input or \includegraphics (what figinsets do).
1993 // batchmode is not set if there is a tex_code_break_column.
1994 // In this case somebody is interested in the generated LaTeX,
1995 // so this is OK. input@path is set when the actual parameter
1996 // original_path is set. This is done for usual tex-file, but not
1997 // for nice-latex-file. (Matthias 250696)
2000 // code for usual, NOT nice-latex-file
2001 ofs << "\\batchmode\n"; // changed
2002 // from \nonstopmode
2005 if (!original_path.empty()) {
2006 ofs << "\\makeatletter\n"
2007 << "\\def\\input@path{{"
2008 << os::external_path(original_path) << "/}}\n"
2009 << "\\makeatother\n";
2015 ofs << "\\documentclass";
2017 ostringstream options; // the document class options.
2019 if (tokenPos(tclass.opt_fontsize(),
2020 '|', params.fontsize) >= 0) {
2021 // only write if existing in list (and not default)
2022 options << params.fontsize << "pt,";
2026 if (!params.use_geometry &&
2027 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2028 switch (params.papersize) {
2029 case BufferParams::PAPER_A4PAPER:
2030 options << "a4paper,";
2032 case BufferParams::PAPER_USLETTER:
2033 options << "letterpaper,";
2035 case BufferParams::PAPER_A5PAPER:
2036 options << "a5paper,";
2038 case BufferParams::PAPER_B5PAPER:
2039 options << "b5paper,";
2041 case BufferParams::PAPER_EXECUTIVEPAPER:
2042 options << "executivepaper,";
2044 case BufferParams::PAPER_LEGALPAPER:
2045 options << "legalpaper,";
2051 if (params.sides != tclass.sides()) {
2052 switch (params.sides) {
2053 case LyXTextClass::OneSide:
2054 options << "oneside,";
2056 case LyXTextClass::TwoSides:
2057 options << "twoside,";
2063 if (params.columns != tclass.columns()) {
2064 if (params.columns == 2)
2065 options << "twocolumn,";
2067 options << "onecolumn,";
2070 if (!params.use_geometry
2071 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2072 options << "landscape,";
2074 // language should be a parameter to \documentclass
2076 ostringstream language_options;
2077 if (params.language->babel() == "hebrew"
2078 && default_language->babel() != "hebrew")
2079 // This seems necessary
2080 features.UsedLanguages.insert(default_language);
2082 if (lyxrc.language_use_babel ||
2083 params.language->lang() != lyxrc.default_language ||
2084 !features.UsedLanguages.empty()) {
2086 for (LaTeXFeatures::LanguageList::const_iterator cit =
2087 features.UsedLanguages.begin();
2088 cit != features.UsedLanguages.end(); ++cit)
2089 language_options << (*cit)->babel() << ',';
2090 language_options << params.language->babel();
2091 if (lyxrc.language_global_options)
2092 options << language_options.str() << ',';
2095 // the user-defined options
2096 if (!params.options.empty()) {
2097 options << params.options << ',';
2100 string strOptions(options.str().c_str());
2101 if (!strOptions.empty()){
2102 strOptions = strip(strOptions, ',');
2103 ofs << '[' << strOptions << ']';
2107 << textclasslist.LatexnameOfClass(params.textclass)
2110 // end of \documentclass defs
2112 // font selection must be done before loading fontenc.sty
2113 // The ae package is not needed when using OT1 font encoding.
2114 if (params.fonts != "default" &&
2115 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2116 ofs << "\\usepackage{" << params.fonts << "}\n";
2118 if (params.fonts == "ae") {
2119 ofs << "\\usepackage{aecompl}\n";
2123 // this one is not per buffer
2124 if (lyxrc.fontenc != "default") {
2125 ofs << "\\usepackage[" << lyxrc.fontenc
2130 if (params.inputenc == "auto") {
2131 string const doc_encoding =
2132 params.language->encoding()->LatexName();
2134 // Create a list with all the input encodings used
2136 set<string> encodings;
2137 for (LaTeXFeatures::LanguageList::const_iterator it =
2138 features.UsedLanguages.begin();
2139 it != features.UsedLanguages.end(); ++it)
2140 if ((*it)->encoding()->LatexName() != doc_encoding)
2141 encodings.insert((*it)->encoding()->LatexName());
2143 ofs << "\\usepackage[";
2144 std::copy(encodings.begin(), encodings.end(),
2145 std::ostream_iterator<string>(ofs, ","));
2146 ofs << doc_encoding << "]{inputenc}\n";
2148 } else if (params.inputenc != "default") {
2149 ofs << "\\usepackage[" << params.inputenc
2154 // At the very beginning the text parameters.
2155 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2156 switch (params.paperpackage) {
2157 case BufferParams::PACKAGE_A4:
2158 ofs << "\\usepackage{a4}\n";
2161 case BufferParams::PACKAGE_A4WIDE:
2162 ofs << "\\usepackage{a4wide}\n";
2165 case BufferParams::PACKAGE_WIDEMARGINSA4:
2166 ofs << "\\usepackage[widemargins]{a4}\n";
2171 if (params.use_geometry) {
2172 ofs << "\\usepackage{geometry}\n";
2174 ofs << "\\geometry{verbose";
2175 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2176 ofs << ",landscape";
2177 switch (params.papersize2) {
2178 case BufferParams::VM_PAPER_CUSTOM:
2179 if (!params.paperwidth.empty())
2180 ofs << ",paperwidth="
2181 << params.paperwidth;
2182 if (!params.paperheight.empty())
2183 ofs << ",paperheight="
2184 << params.paperheight;
2186 case BufferParams::VM_PAPER_USLETTER:
2187 ofs << ",letterpaper";
2189 case BufferParams::VM_PAPER_USLEGAL:
2190 ofs << ",legalpaper";
2192 case BufferParams::VM_PAPER_USEXECUTIVE:
2193 ofs << ",executivepaper";
2195 case BufferParams::VM_PAPER_A3:
2198 case BufferParams::VM_PAPER_A4:
2201 case BufferParams::VM_PAPER_A5:
2204 case BufferParams::VM_PAPER_B3:
2207 case BufferParams::VM_PAPER_B4:
2210 case BufferParams::VM_PAPER_B5:
2214 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2215 switch (lyxrc.default_papersize) {
2216 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2217 case BufferParams::PAPER_USLETTER:
2218 ofs << ",letterpaper";
2220 case BufferParams::PAPER_LEGALPAPER:
2221 ofs << ",legalpaper";
2223 case BufferParams::PAPER_EXECUTIVEPAPER:
2224 ofs << ",executivepaper";
2226 case BufferParams::PAPER_A3PAPER:
2229 case BufferParams::PAPER_A4PAPER:
2232 case BufferParams::PAPER_A5PAPER:
2235 case BufferParams::PAPER_B5PAPER:
2240 if (!params.topmargin.empty())
2241 ofs << ",tmargin=" << params.topmargin;
2242 if (!params.bottommargin.empty())
2243 ofs << ",bmargin=" << params.bottommargin;
2244 if (!params.leftmargin.empty())
2245 ofs << ",lmargin=" << params.leftmargin;
2246 if (!params.rightmargin.empty())
2247 ofs << ",rmargin=" << params.rightmargin;
2248 if (!params.headheight.empty())
2249 ofs << ",headheight=" << params.headheight;
2250 if (!params.headsep.empty())
2251 ofs << ",headsep=" << params.headsep;
2252 if (!params.footskip.empty())
2253 ofs << ",footskip=" << params.footskip;
2257 if (features.amsstyle
2258 && !tclass.provides(LyXTextClass::amsmath)) {
2259 ofs << "\\usepackage{amsmath}\n";
2263 if (tokenPos(tclass.opt_pagestyle(),
2264 '|', params.pagestyle) >= 0) {
2265 if (params.pagestyle == "fancy") {
2266 ofs << "\\usepackage{fancyhdr}\n";
2269 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2273 // We try to load babel late, in case it interferes
2274 // with other packages.
2276 string tmp = lyxrc.language_package;
2277 if (!lyxrc.language_global_options
2278 && tmp == "\\usepackage{babel}")
2279 tmp = string("\\usepackage[") +
2280 language_options.str().c_str() +
2286 if (params.secnumdepth != tclass.secnumdepth()) {
2287 ofs << "\\setcounter{secnumdepth}{"
2288 << params.secnumdepth
2292 if (params.tocdepth != tclass.tocdepth()) {
2293 ofs << "\\setcounter{tocdepth}{"
2299 if (params.paragraph_separation) {
2300 switch (params.defskip.kind()) {
2301 case VSpace::SMALLSKIP:
2302 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2304 case VSpace::MEDSKIP:
2305 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2307 case VSpace::BIGSKIP:
2308 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2310 case VSpace::LENGTH:
2311 ofs << "\\setlength\\parskip{"
2312 << params.defskip.length().asLatexString()
2315 default: // should never happen // Then delete it.
2316 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2321 ofs << "\\setlength\\parindent{0pt}\n";
2325 // Now insert the LyX specific LaTeX commands...
2327 // The optional packages;
2328 string preamble(features.getPackages());
2330 // this might be useful...
2331 preamble += "\n\\makeatletter\n";
2333 // Some macros LyX will need
2334 string tmppreamble(features.getMacros());
2336 if (!tmppreamble.empty()) {
2337 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2338 "LyX specific LaTeX commands.\n"
2339 + tmppreamble + '\n';
2342 // the text class specific preamble
2343 tmppreamble = features.getTClassPreamble();
2344 if (!tmppreamble.empty()) {
2345 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2346 "Textclass specific LaTeX commands.\n"
2347 + tmppreamble + '\n';
2350 /* the user-defined preamble */
2351 if (!params.preamble.empty()) {
2352 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2353 "User specified LaTeX commands.\n"
2354 + params.preamble + '\n';
2357 preamble += "\\makeatother\n";
2359 // Itemize bullet settings need to be last in case the user
2360 // defines their own bullets that use a package included
2361 // in the user-defined preamble -- ARRae
2362 // Actually it has to be done much later than that
2363 // since some packages like frenchb make modifications
2364 // at \begin{document} time -- JMarc
2366 for (int i = 0; i < 4; ++i) {
2367 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2368 if (bullets_def.empty())
2369 bullets_def="\\AtBeginDocument{\n";
2370 bullets_def += " \\renewcommand{\\labelitemi";
2372 // `i' is one less than the item to modify
2379 bullets_def += "ii";
2385 bullets_def += "}{" +
2386 params.user_defined_bullets[i].getText()
2391 if (!bullets_def.empty())
2392 preamble += bullets_def + "}\n\n";
2394 for (int j = countChar(preamble, '\n'); j-- ;) {
2401 ofs << "\\begin{document}\n";
2404 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2406 if (!lyxrc.language_auto_begin) {
2407 ofs << subst(lyxrc.language_command_begin, "$$lang",
2408 params.language->babel())
2413 latexParagraphs(ofs, paragraph, 0, texrow);
2415 // add this just in case after all the paragraphs
2419 if (!lyxrc.language_auto_end) {
2420 ofs << subst(lyxrc.language_command_end, "$$lang",
2421 params.language->babel())
2427 ofs << "\\end{document}\n";
2430 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2432 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2436 // Just to be sure. (Asger)
2439 // tex_code_break_column's value is used to decide
2440 // if we are in batchmode or not (within mathed_write()
2441 // in math_write.C) so we must set it to a non-zero
2442 // value when we leave otherwise we save incorrect .lyx files.
2443 tex_code_break_column = lyxrc.ascii_linelen;
2447 lyxerr << "File was not closed properly." << endl;
2450 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2455 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2457 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2458 Paragraph * endpar, TexRow & texrow) const
2460 bool was_title = false;
2461 bool already_title = false;
2464 while (par != endpar) {
2465 LyXLayout const & layout =
2466 textclasslist.Style(params.textclass,
2469 if (layout.intitle) {
2470 if (already_title) {
2471 lyxerr <<"Error in latexParagraphs: You"
2472 " should not mix title layouts"
2473 " with normal ones." << endl;
2476 } else if (was_title && !already_title) {
2477 ofs << "\\maketitle\n";
2479 already_title = true;
2483 if (layout.isEnvironment()) {
2484 par = par->TeXEnvironment(this, params, ofs, texrow);
2486 par = par->TeXOnePar(this, params, ofs, texrow, false);
2489 // It might be that we only have a title in this document
2490 if (was_title && !already_title) {
2491 ofs << "\\maketitle\n";
2497 bool Buffer::isLatex() const
2499 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2503 bool Buffer::isLinuxDoc() const
2505 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2509 bool Buffer::isLiterate() const
2511 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2515 bool Buffer::isDocBook() const
2517 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2521 bool Buffer::isSGML() const
2523 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2524 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2528 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2529 string const & latexname) const
2531 if (!latexname.empty() && latexname != "!-- --")
2532 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2533 //os << string(depth, ' ') << "<" << latexname << ">\n";
2537 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2538 string const & latexname) const
2540 if (!latexname.empty() && latexname != "!-- --")
2541 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2542 //os << string(depth, ' ') << "</" << latexname << ">\n";
2546 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2548 ofstream ofs(fname.c_str());
2551 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2555 niceFile = nice; // this will be used by included files.
2557 LyXTextClass const & tclass =
2558 textclasslist.TextClass(params.textclass);
2560 LaTeXFeatures features(params, tclass.numLayouts());
2565 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2568 string sgml_includedfiles=features.getIncludedFiles(fname);
2570 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2571 ofs << "<!doctype linuxdoc system>\n\n";
2573 ofs << "<!doctype linuxdoc system [ "
2574 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2577 if (params.options.empty())
2578 sgmlOpenTag(ofs, 0, top_element);
2580 string top = top_element;
2582 top += params.options;
2583 sgmlOpenTag(ofs, 0, top);
2587 ofs << "<!-- " << LYX_DOCVERSION
2588 << " created this file. For more info see http://www.lyx.org/"
2591 Paragraph::depth_type depth = 0; // paragraph depth
2592 Paragraph * par = paragraph;
2594 vector<string> environment_stack(5);
2597 LyXLayout const & style =
2598 textclasslist.Style(params.textclass,
2601 // treat <toc> as a special case for compatibility with old code
2602 if (par->getChar(0) == Paragraph::META_INSET) {
2603 Inset * inset = par->getInset(0);
2604 Inset::Code lyx_code = inset->lyxCode();
2605 if (lyx_code == Inset::TOC_CODE){
2606 string const temp = "toc";
2607 sgmlOpenTag(ofs, depth, temp);
2614 // environment tag closing
2615 for (; depth > par->params().depth(); --depth) {
2616 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2617 environment_stack[depth].erase();
2620 // write opening SGML tags
2621 switch (style.latextype) {
2622 case LATEX_PARAGRAPH:
2623 if (depth == par->params().depth()
2624 && !environment_stack[depth].empty()) {
2625 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2626 environment_stack[depth].erase();
2632 sgmlOpenTag(ofs, depth, style.latexname());
2637 linuxDocError(par, 0,
2638 _("Error : Wrong depth for"
2639 " LatexType Command.\n"));
2641 if (!environment_stack[depth].empty()){
2642 sgmlCloseTag(ofs, depth,
2643 environment_stack[depth]);
2647 environment_stack[depth].erase();
2648 sgmlOpenTag(ofs, depth, style.latexname());
2651 case LATEX_ENVIRONMENT:
2652 case LATEX_ITEM_ENVIRONMENT:
2653 if (depth == par->params().depth()
2654 && environment_stack[depth] != style.latexname()) {
2655 sgmlCloseTag(ofs, depth,
2656 environment_stack[depth]);
2657 environment_stack[depth].erase();
2659 if (depth < par->params().depth()) {
2660 depth = par->params().depth();
2661 environment_stack[depth].erase();
2663 if (environment_stack[depth] != style.latexname()) {
2665 sgmlOpenTag(ofs, depth, "p");
2667 sgmlOpenTag(ofs, depth, style.latexname());
2669 if (environment_stack.size() == depth + 1)
2670 environment_stack.push_back("!-- --");
2671 environment_stack[depth] = style.latexname();
2674 if (style.latexparam() == "CDATA")
2677 if (style.latextype == LATEX_ENVIRONMENT) break;
2679 if (style.labeltype == LABEL_MANUAL)
2684 sgmlOpenTag(ofs, depth + 1, item_name);
2687 sgmlOpenTag(ofs, depth, style.latexname());
2691 simpleLinuxDocOnePar(ofs, par, depth);
2696 // write closing SGML tags
2697 switch (style.latextype) {
2700 case LATEX_ENVIRONMENT:
2701 case LATEX_ITEM_ENVIRONMENT:
2702 if (style.latexparam() == "CDATA")
2706 sgmlCloseTag(ofs, depth, style.latexname());
2712 for (int i=depth; i >= 0; --i)
2713 sgmlCloseTag(ofs, depth, environment_stack[i]);
2717 sgmlCloseTag(ofs, 0, top_element);
2721 // How to check for successful close
2725 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2726 Paragraph::depth_type depth, int desc_on,
2729 Paragraph * tpar = par;
2731 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2733 tpar = tpar->next();
2736 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2737 "Caption").second) {
2738 sgmlOpenTag(os, depth + 1, inner_tag);
2740 simpleDocBookOnePar(os, extra_par, tpar,
2741 desc_on, depth + 2);
2742 sgmlCloseTag(os, depth+1, inner_tag);
2743 if (!extra_par.empty())
2749 // checks, if newcol chars should be put into this line
2750 // writes newline, if necessary.
2753 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2754 string::size_type newcol)
2757 if (colcount > lyxrc.ascii_linelen) {
2759 colcount = newcol; // assume write after this call
2774 string tag_name(PAR_TAG const & pt) {
2776 case NONE: return "!-- --";
2777 case TT: return "tt";
2778 case SF: return "sf";
2779 case BF: return "bf";
2780 case IT: return "it";
2781 case SL: return "sl";
2782 case EM: return "em";
2789 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2791 p1 = static_cast<PAR_TAG>(p1 | p2);
2796 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2798 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2806 // Handle internal paragraph parsing -- layout already processed.
2807 void Buffer::simpleLinuxDocOnePar(ostream & os,
2809 Paragraph::depth_type /*depth*/)
2811 LyXLayout const & style = textclasslist.Style(params.textclass,
2813 string::size_type char_line_count = 5; // Heuristic choice ;-)
2815 // gets paragraph main font
2818 if (style.labeltype == LABEL_MANUAL) {
2819 font_old = style.labelfont;
2822 font_old = style.font;
2826 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2827 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2828 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2831 stack < PAR_TAG > tag_state;
2832 // parsing main loop
2833 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2835 PAR_TAG tag_close = NONE;
2836 list < PAR_TAG > tag_open;
2838 LyXFont const font = par->getFont(params, i);
2840 if (font_old.family() != font.family()) {
2841 switch (family_type) {
2842 case LyXFont::SANS_FAMILY:
2845 case LyXFont::TYPEWRITER_FAMILY:
2852 family_type = font.family();
2854 switch (family_type) {
2855 case LyXFont::SANS_FAMILY:
2856 tag_open.push_back(SF);
2858 case LyXFont::TYPEWRITER_FAMILY:
2859 tag_open.push_back(TT);
2866 if (font_old.series() != font.series()) {
2867 switch (series_type) {
2868 case LyXFont::BOLD_SERIES:
2875 series_type = font.series();
2877 switch (series_type) {
2878 case LyXFont::BOLD_SERIES:
2879 tag_open.push_back(BF);
2887 if (font_old.shape() != font.shape()) {
2888 switch (shape_type) {
2889 case LyXFont::ITALIC_SHAPE:
2892 case LyXFont::SLANTED_SHAPE:
2899 shape_type = font.shape();
2901 switch (shape_type) {
2902 case LyXFont::ITALIC_SHAPE:
2903 tag_open.push_back(IT);
2905 case LyXFont::SLANTED_SHAPE:
2906 tag_open.push_back(SL);
2913 if (font_old.emph() != font.emph()) {
2914 if (font.emph() == LyXFont::ON) {
2915 tag_open.push_back(EM);
2924 list < PAR_TAG > temp;
2925 while(!tag_state.empty() && tag_close ) {
2926 PAR_TAG k = tag_state.top();
2928 os << "</" << tag_name(k) << ">";
2935 for(list< PAR_TAG >::const_iterator j = temp.begin();
2936 j != temp.end(); ++j) {
2938 os << "<" << tag_name(*j) << ">";
2941 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2942 j != tag_open.end(); ++j) {
2944 os << "<" << tag_name(*j) << ">";
2947 char c = par->getChar(i);
2949 if (c == Paragraph::META_INSET) {
2950 Inset * inset = par->getInset(i);
2951 inset->linuxdoc(this, os);
2958 font.latex() == LyXFont::ON ||
2960 style.latexparam() == "CDATA") {
2961 // "TeX"-Mode on == > SGML-Mode on.
2967 if (par->linuxDocConvertChar(c, sgml_string)
2968 && !style.free_spacing) {
2969 // in freespacing mode, spaces are
2970 // non-breaking characters
2971 if (desc_on) {// if char is ' ' then...
2974 linux_doc_line_break(os, char_line_count, 6);
2978 linux_doc_line_break(os, char_line_count, 1);
2983 char_line_count += sgml_string.length();
2989 while (!tag_state.empty()) {
2990 os << "</" << tag_name(tag_state.top()) << ">";
2994 // resets description flag correctly
2996 // <tag> not closed...
2997 linux_doc_line_break(os, char_line_count, 6);
3003 // Print an error message.
3004 void Buffer::linuxDocError(Paragraph * par, int pos,
3005 string const & message)
3007 // insert an error marker in text
3008 InsetError * new_inset = new InsetError(message);
3009 par->insertInset(pos, new_inset);
3013 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3015 ofstream ofs(fname.c_str());
3017 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3021 Paragraph * par = paragraph;
3023 niceFile = nice; // this will be used by Insetincludes.
3025 LyXTextClass const & tclass =
3026 textclasslist.TextClass(params.textclass);
3028 LaTeXFeatures features(params, tclass.numLayouts());
3033 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3036 string sgml_includedfiles = features.getIncludedFiles(fname);
3038 ofs << "<!doctype " << top_element
3039 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3041 if (params.preamble.empty() && sgml_includedfiles.empty())
3044 ofs << "\n [ " << params.preamble
3045 << sgml_includedfiles << " \n]>\n\n";
3048 string top = top_element;
3050 top += params.language->code();
3053 if (!params.options.empty()) {
3055 top += params.options;
3057 sgmlOpenTag(ofs, 0, top);
3059 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3060 << "\n See http://www.lyx.org/ for more information -->\n";
3062 vector<string> environment_stack(10);
3063 vector<string> environment_inner(10);
3064 vector<string> command_stack(10);
3066 bool command_flag = false;
3067 Paragraph::depth_type command_depth = 0;
3068 Paragraph::depth_type command_base = 0;
3069 Paragraph::depth_type cmd_depth = 0;
3070 Paragraph::depth_type depth = 0; // paragraph depth
3073 string command_name;
3079 int desc_on = 0; // description mode
3081 LyXLayout const & style =
3082 textclasslist.Style(params.textclass,
3085 // environment tag closing
3086 for (; depth > par->params().depth(); --depth) {
3087 if (environment_inner[depth] != "!-- --") {
3088 item_name = "listitem";
3089 sgmlCloseTag(ofs, command_depth + depth,
3091 if (environment_inner[depth] == "varlistentry")
3092 sgmlCloseTag(ofs, depth+command_depth,
3093 environment_inner[depth]);
3095 sgmlCloseTag(ofs, depth + command_depth,
3096 environment_stack[depth]);
3097 environment_stack[depth].erase();
3098 environment_inner[depth].erase();
3101 if (depth == par->params().depth()
3102 && environment_stack[depth] != style.latexname()
3103 && !environment_stack[depth].empty()) {
3104 if (environment_inner[depth] != "!-- --") {
3105 item_name= "listitem";
3106 sgmlCloseTag(ofs, command_depth+depth,
3108 if (environment_inner[depth] == "varlistentry")
3110 depth + command_depth,
3111 environment_inner[depth]);
3114 sgmlCloseTag(ofs, depth + command_depth,
3115 environment_stack[depth]);
3117 environment_stack[depth].erase();
3118 environment_inner[depth].erase();
3121 // Write opening SGML tags.
3122 switch (style.latextype) {
3123 case LATEX_PARAGRAPH:
3124 sgmlOpenTag(ofs, depth + command_depth,
3130 linuxDocError(par, 0,
3131 _("Error : Wrong depth for "
3132 "LatexType Command.\n"));
3134 command_name = style.latexname();
3136 sgmlparam = style.latexparam();
3137 c_params = split(sgmlparam, c_depth,'|');
3139 cmd_depth = lyx::atoi(c_depth);
3142 if (cmd_depth < command_base) {
3143 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3144 sgmlCloseTag(ofs, j, command_stack[j]);
3145 command_depth = command_base = cmd_depth;
3146 } else if (cmd_depth <= command_depth) {
3147 for (int j = command_depth; j >= int(cmd_depth); --j)
3148 sgmlCloseTag(ofs, j, command_stack[j]);
3149 command_depth = cmd_depth;
3151 command_depth = cmd_depth;
3153 command_depth = command_base = cmd_depth;
3154 command_flag = true;
3156 if (command_stack.size() == command_depth + 1)
3157 command_stack.push_back(string());
3158 command_stack[command_depth] = command_name;
3160 // treat label as a special case for
3161 // more WYSIWYM handling.
3162 if (par->getChar(0) == Paragraph::META_INSET) {
3163 Inset * inset = par->getInset(0);
3164 Inset::Code lyx_code = inset->lyxCode();
3165 if (lyx_code == Inset::LABEL_CODE){
3166 command_name += " id=\"";
3167 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3168 command_name += "\"";
3173 sgmlOpenTag(ofs, depth + command_depth, command_name);
3174 if (c_params.empty())
3175 item_name = "title";
3177 item_name = c_params;
3178 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3181 case LATEX_ENVIRONMENT:
3182 case LATEX_ITEM_ENVIRONMENT:
3183 if (depth < par->params().depth()) {
3184 depth = par->params().depth();
3185 environment_stack[depth].erase();
3188 if (environment_stack[depth] != style.latexname()) {
3189 if(environment_stack.size() == depth + 1) {
3190 environment_stack.push_back("!-- --");
3191 environment_inner.push_back("!-- --");
3193 environment_stack[depth] = style.latexname();
3194 environment_inner[depth] = "!-- --";
3195 sgmlOpenTag(ofs, depth + command_depth,
3196 environment_stack[depth]);
3198 if (environment_inner[depth] != "!-- --") {
3199 item_name= "listitem";
3201 command_depth + depth,
3203 if (environment_inner[depth] == "varlistentry")
3205 depth + command_depth,
3206 environment_inner[depth]);
3210 if (style.latextype == LATEX_ENVIRONMENT) {
3211 if (!style.latexparam().empty()) {
3212 if(style.latexparam() == "CDATA")
3215 sgmlOpenTag(ofs, depth + command_depth,
3216 style.latexparam());
3221 desc_on = (style.labeltype == LABEL_MANUAL);
3224 environment_inner[depth]= "varlistentry";
3226 environment_inner[depth]= "listitem";
3228 sgmlOpenTag(ofs, depth + 1 + command_depth,
3229 environment_inner[depth]);
3233 sgmlOpenTag(ofs, depth + 1 + command_depth,
3237 sgmlOpenTag(ofs, depth + 1 + command_depth,
3242 sgmlOpenTag(ofs, depth + command_depth,
3248 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3249 depth + 1 + command_depth);
3253 // write closing SGML tags
3254 switch (style.latextype) {
3256 if (c_params.empty())
3260 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3262 case LATEX_ENVIRONMENT:
3263 if (!style.latexparam().empty()) {
3264 if(style.latexparam() == "CDATA")
3267 sgmlCloseTag(ofs, depth + command_depth,
3268 style.latexparam());
3271 case LATEX_ITEM_ENVIRONMENT:
3272 if (desc_on == 1) break;
3274 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3276 case LATEX_PARAGRAPH:
3277 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3280 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3286 for (int d = depth; d >= 0; --d) {
3287 if (!environment_stack[depth].empty()) {
3288 if (environment_inner[depth] != "!-- --") {
3289 item_name = "listitem";
3290 sgmlCloseTag(ofs, command_depth + depth,
3292 if (environment_inner[depth] == "varlistentry")
3293 sgmlCloseTag(ofs, depth + command_depth,
3294 environment_inner[depth]);
3297 sgmlCloseTag(ofs, depth + command_depth,
3298 environment_stack[depth]);
3302 for (int j = command_depth; j >= 0 ; --j)
3303 if (!command_stack[j].empty())
3304 sgmlCloseTag(ofs, j, command_stack[j]);
3307 sgmlCloseTag(ofs, 0, top_element);
3310 // How to check for successful close
3314 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3315 Paragraph * par, int & desc_on,
3316 Paragraph::depth_type depth) const
3318 bool emph_flag = false;
3320 LyXLayout const & style = textclasslist.Style(params.textclass,
3323 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3325 int char_line_count = depth;
3326 //if (!style.free_spacing)
3327 // os << string(depth,' ');
3329 // parsing main loop
3330 for (Paragraph::size_type i = 0;
3331 i < par->size(); ++i) {
3332 LyXFont font = par->getFont(params, i);
3334 // handle <emphasis> tag
3335 if (font_old.emph() != font.emph()) {
3336 if (font.emph() == LyXFont::ON) {
3340 os << "</emphasis>";
3345 char c = par->getChar(i);
3347 if (c == Paragraph::META_INSET) {
3348 Inset * inset = par->getInset(i);
3350 inset->docBook(this, ost);
3351 string tmp_out = ost.str().c_str();
3354 // This code needs some explanation:
3355 // Two insets are treated specially
3356 // label if it is the first element in a command paragraph
3358 // graphics inside tables or figure floats can't go on
3359 // title (the equivalente in latex for this case is caption
3360 // and title should come first
3363 if (desc_on!= 3 || i!= 0) {
3364 if (!tmp_out.empty() && tmp_out[0] == '@') {
3366 extra += frontStrip(tmp_out, '@');
3368 os << frontStrip(tmp_out, '@');
3374 } else if (font.latex() == LyXFont::ON) {
3375 // "TeX"-Mode on ==> SGML-Mode on.
3382 if (par->linuxDocConvertChar(c, sgml_string)
3383 && !style.free_spacing) { // in freespacing
3385 // non-breaking characters
3389 os << "\n</term><listitem><para>";
3402 os << "</emphasis>";
3405 // resets description flag correctly
3407 // <term> not closed...
3410 if(style.free_spacing) os << '\n';
3414 // This should be enabled when the Chktex class is implemented. (Asger)
3415 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3416 // Other flags: -wall -v0 -x
3417 int Buffer::runChktex()
3419 if (!users->text) return 0;
3421 users->owner()->prohibitInput();
3423 // get LaTeX-Filename
3424 string const name = getLatexName();
3425 string path = OnlyPath(filename);
3427 string const org_path = path;
3428 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3432 Path p(path); // path to LaTeX file
3433 users->owner()->message(_("Running chktex..."));
3435 // Remove all error insets
3436 bool const removedErrorInsets = users->removeAutoInsets();
3438 // Generate the LaTeX file if neccessary
3439 makeLaTeXFile(name, org_path, false);
3442 Chktex chktex(lyxrc.chktex_command, name, filepath);
3443 int res = chktex.run(terr); // run chktex
3446 WriteAlert(_("chktex did not work!"),
3447 _("Could not run with file:"), name);
3448 } else if (res > 0) {
3449 // Insert all errors as errors boxes
3450 users->insertErrors(terr);
3453 // if we removed error insets before we ran chktex or if we inserted
3454 // error insets after we ran chktex, this must be run:
3455 if (removedErrorInsets || res){
3457 users->fitCursor(users->text);
3459 users->owner()->allowInput();
3465 void Buffer::validate(LaTeXFeatures & features) const
3467 Paragraph * par = paragraph;
3468 LyXTextClass const & tclass =
3469 textclasslist.TextClass(params.textclass);
3471 // AMS Style is at document level
3472 features.amsstyle = (params.use_amsmath ||
3473 tclass.provides(LyXTextClass::amsmath));
3476 // We don't use "lyxerr.debug" because of speed. (Asger)
3477 if (lyxerr.debugging(Debug::LATEX))
3478 lyxerr << "Paragraph: " << par << endl;
3480 // Now just follow the list of paragraphs and run
3481 // validate on each of them.
3482 par->validate(features);
3484 // and then the next paragraph
3488 // the bullet shapes are buffer level not paragraph level
3489 // so they are tested here
3490 for (int i = 0; i < 4; ++i) {
3491 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3492 int const font = params.user_defined_bullets[i].getFont();
3494 int const c = params
3495 .user_defined_bullets[i]
3502 features.latexsym = true;
3504 } else if (font == 1) {
3505 features.amssymb = true;
3506 } else if ((font >= 2 && font <= 5)) {
3507 features.pifont = true;
3512 if (lyxerr.debugging(Debug::LATEX)) {
3513 features.showStruct();
3518 void Buffer::setPaperStuff()
3520 params.papersize = BufferParams::PAPER_DEFAULT;
3521 char const c1 = params.paperpackage;
3522 if (c1 == BufferParams::PACKAGE_NONE) {
3523 char const c2 = params.papersize2;
3524 if (c2 == BufferParams::VM_PAPER_USLETTER)
3525 params.papersize = BufferParams::PAPER_USLETTER;
3526 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3527 params.papersize = BufferParams::PAPER_LEGALPAPER;
3528 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3529 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3530 else if (c2 == BufferParams::VM_PAPER_A3)
3531 params.papersize = BufferParams::PAPER_A3PAPER;
3532 else if (c2 == BufferParams::VM_PAPER_A4)
3533 params.papersize = BufferParams::PAPER_A4PAPER;
3534 else if (c2 == BufferParams::VM_PAPER_A5)
3535 params.papersize = BufferParams::PAPER_A5PAPER;
3536 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3537 (c2 == BufferParams::VM_PAPER_B5))
3538 params.papersize = BufferParams::PAPER_B5PAPER;
3539 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3540 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3541 params.papersize = BufferParams::PAPER_A4PAPER;
3545 // This function should be in Buffer because it's a buffer's property (ale)
3546 string const Buffer::getIncludeonlyList(char delim)
3549 for (inset_iterator it = inset_iterator_begin();
3550 it != inset_iterator_end(); ++it) {
3551 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3552 InsetInclude * insetinc =
3553 static_cast<InsetInclude *>(*it);
3554 if (insetinc->isIncludeOnly()) {
3557 lst += insetinc->getRelFileBaseName();
3561 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3566 vector<string> const Buffer::getLabelList()
3568 /// if this is a child document and the parent is already loaded
3569 /// Use the parent's list instead [ale990407]
3570 if (!params.parentname.empty()
3571 && bufferlist.exists(params.parentname)) {
3572 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3574 return tmp->getLabelList();
3577 vector<string> label_list;
3578 for (inset_iterator it = inset_iterator_begin();
3579 it != inset_iterator_end(); ++it) {
3580 vector<string> const l = (*it)->getLabelList();
3581 label_list.insert(label_list.end(), l.begin(), l.end());
3587 Buffer::Lists const Buffer::getLists() const
3590 Paragraph * par = paragraph;
3592 LyXTextClassList::size_type cap;
3593 boost::tie(found, cap) = textclasslist
3594 .NumberOfLayout(params.textclass, "Caption");
3597 char const labeltype =
3598 textclasslist.Style(params.textclass,
3599 par->getLayout()).labeltype;
3601 if (labeltype >= LABEL_COUNTER_CHAPTER
3602 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3603 // insert this into the table of contents
3604 SingleList & item = l["TOC"];
3607 textclasslist.TextClass(params.textclass).maxcounter());
3608 item.push_back(TocItem(par, depth, par->asString(this, true)));
3610 // For each paragrph, traverse its insets and look for
3614 Paragraph::inset_iterator it =
3615 par->inset_iterator_begin();
3616 Paragraph::inset_iterator end =
3617 par->inset_iterator_end();
3619 for (; it != end; ++it) {
3620 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3622 static_cast<InsetFloat*>(*it);
3624 string const type = il->type();
3626 // Now find the caption in the float...
3627 // We now tranverse the paragraphs of
3629 Paragraph * tmp = il->inset.paragraph();
3631 if (tmp->layout == cap) {
3632 SingleList & item = l[type];
3634 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3635 item.push_back(TocItem(tmp, 0 , str));
3642 lyxerr << "caption not found" << endl;
3651 // This is also a buffer property (ale)
3652 vector<pair<string, string> > const Buffer::getBibkeyList()
3654 /// if this is a child document and the parent is already loaded
3655 /// Use the parent's list instead [ale990412]
3656 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3657 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3659 return tmp->getBibkeyList();
3662 vector<pair<string, string> > keys;
3663 Paragraph * par = paragraph;
3666 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3667 par->asString(this, false)));
3671 // Might be either using bibtex or a child has bibliography
3673 for (inset_iterator it = inset_iterator_begin();
3674 it != inset_iterator_end(); ++it) {
3675 // Search for Bibtex or Include inset
3676 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3677 vector<pair<string,string> > tmp =
3678 static_cast<InsetBibtex*>(*it)->getKeys(this);
3679 keys.insert(keys.end(), tmp.begin(), tmp.end());
3680 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3681 vector<pair<string,string> > const tmp =
3682 static_cast<InsetInclude*>(*it)->getKeys();
3683 keys.insert(keys.end(), tmp.begin(), tmp.end());
3692 bool Buffer::isDepClean(string const & name) const
3694 DEPCLEAN * item = dep_clean;
3695 while (item && item->master != name)
3697 if (!item) return true;
3702 void Buffer::markDepClean(string const & name)
3705 dep_clean = new DEPCLEAN;
3706 dep_clean->clean = true;
3707 dep_clean->master = name;
3708 dep_clean->next = 0;
3710 DEPCLEAN * item = dep_clean;
3711 while (item && item->master != name)
3716 item = new DEPCLEAN;
3718 item->master = name;
3725 bool Buffer::dispatch(string const & command)
3727 // Split command string into command and argument
3729 string line = frontStrip(command);
3730 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3732 return dispatch(lyxaction.LookupFunc(cmd), arg);
3736 bool Buffer::dispatch(int action, string const & argument)
3738 bool dispatched = true;
3741 Exporter::Export(this, argument, false);
3751 void Buffer::resizeInsets(BufferView * bv)
3753 /// then remove all LyXText in text-insets
3754 Paragraph * par = paragraph;
3755 for (; par; par = par->next()) {
3756 par->resizeInsetsLyXText(bv);
3761 void Buffer::redraw()
3764 users->fitCursor(users->text);
3768 void Buffer::changeLanguage(Language const * from, Language const * to)
3771 Paragraph * par = paragraph;
3773 par->changeLanguage(params, from, to);
3779 bool Buffer::isMultiLingual()
3781 Paragraph * par = paragraph;
3783 if (par->isMultiLingual(params))
3791 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3792 Paragraph::size_type pos)
3795 it = par->InsetIterator(pos);
3796 if (it == par->inset_iterator_end()) {
3803 void Buffer::inset_iterator::setParagraph()
3806 it = par->inset_iterator_begin();
3807 if (it != par->inset_iterator_end())
3812 // We maintain an invariant that whenever par = 0 then it = 0
3816 Inset * Buffer::getInsetFromID(int id_arg) const
3818 for (inset_iterator it = inset_const_iterator_begin();
3819 it != inset_const_iterator_end(); ++it)
3821 if ((*it)->id() == id_arg)
3823 Inset * in = (*it)->getInsetFromID(id_arg);
3831 Paragraph * Buffer::getParFromID(int id) const
3833 if (id < 0) return 0;
3834 Paragraph * par = paragraph;
3836 if (par->id() == id) {
3839 Paragraph * tmp = par->getParFromID(id);