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/insetlist.h"
78 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
82 #include "support/textutils.h"
83 #include "support/filetools.h"
84 #include "support/path.h"
85 #include "support/os.h"
90 #include "LaTeXFeatures.h"
91 #include "support/syscall.h"
92 #include "support/lyxlib.h"
93 #include "support/FileInfo.h"
94 #include "support/lyxmanip.h"
98 #include "lyx_gui_misc.h" // WarnReadonly()
99 #include "frontends/Dialogs.h"
100 #include "encoding.h"
101 #include "exporter.h"
102 #include "Lsstream.h"
103 #include "converter.h"
104 #include "BufferView.h"
105 #include "ParagraphParameters.h"
115 using std::make_pair;
123 // all these externs should eventually be removed.
124 extern BufferList bufferlist;
126 extern LyXAction lyxaction;
130 const int LYX_FORMAT = 220;
134 extern int tex_code_break_column;
137 Buffer::Buffer(string const & file, bool ronly)
139 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
141 filepath = OnlyPath(file);
150 if (read_only || (lyxrc.use_tempdir)) {
151 tmppath = CreateBufferTmpDir();
152 } else tmppath.erase();
158 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
159 // here the buffer should take care that it is
160 // saved properly, before it goes into the void.
162 // make sure that views using this buffer
167 if (!tmppath.empty()) {
168 DestroyBufferTmpDir(tmppath);
171 Paragraph * par = paragraph;
174 tmppar = par->next();
182 string const Buffer::getLatexName(bool no_path) const
184 string name = ChangeExtension(MakeLatexName(filename), ".tex");
186 return OnlyFilename(name);
192 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
194 string const filename = getLatexName(false);
196 if (filename.empty())
197 return make_pair(Buffer::latexlog, string());
199 string path = OnlyPath(filename);
201 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
204 string const fname = AddName(path,
205 OnlyFilename(ChangeExtension(filename,
208 AddName(path, OnlyFilename(
209 ChangeExtension(filename,
210 formats.Extension("literate") + ".out")));
212 // If no Latex log or Build log is newer, show Build log
214 FileInfo const f_fi(fname);
215 FileInfo const b_fi(bname);
218 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
219 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
220 return make_pair(Buffer::buildlog, bname);
222 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
223 return make_pair(Buffer::latexlog, fname);
227 void Buffer::setReadonly(bool flag)
229 if (read_only != flag) {
232 users->owner()->getDialogs()->updateBufferDependent(false);
235 WarnReadonly(filename);
240 bool Buffer::saveParamsAsDefaults() // const
242 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
244 Buffer defaults = Buffer(fname);
246 // Use the current buffer's parameters as default
247 defaults.params = params;
249 // add an empty paragraph. Is this enough?
250 defaults.paragraph = new Paragraph;
252 return defaults.writeFile(defaults.filename, false);
256 /// Update window titles of all users
257 // Should work on a list
258 void Buffer::updateTitles() const
260 if (users) users->owner()->updateWindowTitle();
264 /// Reset autosave timer of all users
265 // Should work on a list
266 void Buffer::resetAutosaveTimers() const
268 if (users) users->owner()->resetAutosaveTimer();
272 void Buffer::setFileName(string const & newfile)
274 filename = MakeAbsPath(newfile);
275 filepath = OnlyPath(filename);
276 setReadonly(IsFileWriteable(filename) == 0);
281 // We'll remove this later. (Lgb)
284 string last_inset_read;
288 ErtComp() : active(false), in_tabular(false) {
295 std::stack<ErtComp> ert_stack;
304 // candidate for move to BufferView
305 // (at least some parts in the beginning of the func)
308 // changed to be public and have one parameter
309 // if par = 0 normal behavior
310 // else insert behavior
311 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
312 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
316 ert_comp.contents.erase();
317 ert_comp.active = false;
318 ert_comp.in_tabular = false;
322 Paragraph::depth_type depth = 0;
323 bool the_end_read = false;
325 Paragraph * first_par = 0;
326 LyXFont font(LyXFont::ALL_INHERIT, params.language);
327 if (file_format < 216 && params.language->lang() == "hebrew")
328 font.setLanguage(default_language);
333 // We are inserting into an existing document
334 users->text->breakParagraph(users);
335 first_par = users->text->firstParagraph();
338 // We don't want to adopt the parameters from the
339 // document we insert, so we skip until the text begins:
342 string const pretoken = lex.GetString();
343 if (pretoken == "\\layout") {
344 lex.pushToken(pretoken);
352 string const token = lex.GetString();
354 if (token.empty()) continue;
356 lyxerr[Debug::PARSER] << "Handling token: `"
357 << token << "'" << endl;
360 parseSingleLyXformat2Token(lex, par, first_par,
368 paragraph = first_par;
370 if (unknown_layouts > 0) {
371 string s = _("Couldn't set the layout for ");
372 if (unknown_layouts == 1) {
373 s += _("one paragraph");
375 s += tostr(unknown_layouts);
376 s += _(" paragraphs");
378 WriteAlert(_("Textclass Loading Error!"), s,
379 _("When reading " + fileName()));
386 void Buffer::insertErtContents(Paragraph * par, int & pos,
387 LyXFont const & font, bool set_inactive)
389 if (!ert_comp.contents.empty()) {
390 lyxerr[Debug::INSETS] << "ERT contents:\n"
391 << ert_comp.contents << endl;
392 Inset * inset = new InsetERT(ert_comp.contents, true);
393 par->insertInset(pos++, inset, font);
394 ert_comp.contents.erase();
397 ert_comp.active = false;
403 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
404 Paragraph *& first_par,
405 string const & token, int & pos,
406 Paragraph::depth_type & depth,
410 bool the_end_read = false;
411 #ifndef NO_PEXTRA_REALLY
412 // This is super temporary but is needed to get the compability
413 // mode for minipages work correctly together with new tabulars.
414 static int call_depth;
416 bool checkminipage = false;
417 static Paragraph * minipar;
418 static Paragraph * parBeforeMinipage;
421 if (token[0] != '\\') {
423 if (ert_comp.active) {
424 ert_comp.contents += token;
427 for (string::const_iterator cit = token.begin();
428 cit != token.end(); ++cit) {
429 par->insertChar(pos, (*cit), font);
432 checkminipage = true;
436 } else if (token == "\\i") {
437 Inset * inset = new InsetLatexAccent;
438 inset->read(this, lex);
439 par->insertInset(pos, inset, font);
441 } else if (token == "\\layout") {
443 ert_comp.in_tabular = false;
445 insertErtContents(par, pos, font);
448 string const layoutname = lex.GetString();
449 pair<bool, LyXTextClass::LayoutList::size_type> pp
450 = textclasslist.NumberOfLayout(params.textclass,
454 if (compare_no_case(layoutname, "latex") == 0) {
455 ert_comp.active = true;
459 // The is the compability reading of layout caption.
460 // It can be removed in LyX version 1.3.0. (Lgb)
461 if (compare_no_case(layoutname, "caption") == 0) {
462 // We expect that the par we are now working on is
463 // really inside a InsetText inside a InsetFloat.
464 // We also know that captions can only be
465 // one paragraph. (Lgb)
467 // We should now read until the next "\layout"
469 // This is probably not good enough, what if the
470 // caption is the last par in the document (Lgb)
471 istream & ist = lex.getStream();
477 if (prefixIs(line, "\\layout")) {
481 if (prefixIs(line, "\\begin_inset"))
483 if (prefixIs(line, "\\end_inset")) {
494 // Now we should have the whole layout in ss
495 // we should now be able to give this to the
497 ss << "\\end_inset\n";
499 // This seems like a bug in stringstream.
500 // We really should be able to use ss
502 istringstream is(ss.str());
504 tmplex.setStream(is);
505 Inset * inset = new InsetCaption;
506 inset->Read(this, tmplex);
507 par->InsertInset(pos, inset, font);
514 par = new Paragraph(par);
518 par->layout = pp.second;
521 // use default layout "Standard" (0)
524 string const s = _("Layout had to be changed from\n")
525 + layoutname + _(" to ")
526 + textclasslist.NameOfLayout(params.textclass, par->layout);
527 InsetError * new_inset = new InsetError(s);
528 par->insertInset(0, new_inset);
530 // Test whether the layout is obsolete.
531 LyXLayout const & layout =
532 textclasslist.Style(params.textclass,
534 if (!layout.obsoleted_by().empty())
535 par->layout = textclasslist
536 .NumberOfLayout(params.textclass,
537 layout.obsoleted_by())
539 par->params().depth(depth);
540 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
541 if (file_format < 216
542 && params.language->lang() == "hebrew")
543 font.setLanguage(default_language);
548 } else if (token == "\\begin_float") {
549 // This is the compability reader. It can be removed in
550 // LyX version 1.3.0. (Lgb)
552 string const tmptok = lex.GetString();
553 //lyxerr << "old float: " << tmptok << endl;
556 stringstream old_float;
558 if (tmptok == "footnote") {
559 inset = new InsetFoot;
560 } else if (tmptok == "margin") {
561 inset = new InsetMarginal;
562 } else if (tmptok == "fig") {
563 inset = new InsetFloat("figure");
564 old_float << "placement htbp\n"
566 } else if (tmptok == "tab") {
567 inset = new InsetFloat("table");
568 old_float << "placement htbp\n"
570 } else if (tmptok == "alg") {
571 inset = new InsetFloat("algorithm");
572 old_float << "placement htbp\n"
574 } else if (tmptok == "wide-fig") {
575 inset = new InsetFloat("figure");
576 //InsetFloat * tmp = new InsetFloat("figure");
579 old_float << "placement htbp\n"
581 } else if (tmptok == "wide-tab") {
582 inset = new InsetFloat("table");
583 //InsetFloat * tmp = new InsetFloat("table");
586 old_float << "placement htbp\n"
592 return false; // no end read yet
595 old_float << "collapsed true\n";
597 // Here we need to check for \end_deeper and handle that
598 // before we do the footnote parsing.
599 // This _is_ a hack! (Lgb)
602 string const tmp = lex.GetString();
603 if (tmp == "\\end_deeper") {
604 //lyxerr << "\\end_deeper caught!" << endl;
606 lex.printError("\\end_deeper: "
607 "depth is already null");
612 old_float << tmp << ' ';
617 old_float << lex.getLongString("\\end_float")
618 << "\n\\end_inset\n";
619 //lyxerr << "Float Body:\n" << old_float.str() << endl;
620 // That this does not work seems like a bug
621 // in stringstream. (Lgb)
622 istringstream istr(old_float.str());
624 nylex.setStream(istr);
625 inset->read(this, nylex);
626 par->insertInset(pos, inset, font);
628 } else if (token == "\\begin_deeper") {
630 } else if (token == "\\end_deeper") {
632 lex.printError("\\end_deeper: "
633 "depth is already null");
637 } else if (token == "\\begin_preamble") {
638 params.readPreamble(lex);
639 } else if (token == "\\textclass") {
641 pair<bool, LyXTextClassList::size_type> pp =
642 textclasslist.NumberOfClass(lex.GetString());
644 params.textclass = pp.second;
646 WriteAlert(string(_("Textclass error")),
647 string(_("The document uses an unknown textclass \"")) +
648 lex.GetString() + string("\"."),
649 string(_("LyX will not be able to produce output correctly.")));
650 params.textclass = 0;
652 if (!textclasslist.Load(params.textclass)) {
653 // if the textclass wasn't loaded properly
654 // we need to either substitute another
655 // or stop loading the file.
656 // I can substitute but I don't see how I can
657 // stop loading... ideas?? ARRae980418
658 WriteAlert(_("Textclass Loading Error!"),
659 string(_("Can't load textclass ")) +
660 textclasslist.NameOfClass(params.textclass),
661 _("-- substituting default"));
662 params.textclass = 0;
664 } else if (token == "\\options") {
666 params.options = lex.GetString();
667 } else if (token == "\\language") {
668 params.readLanguage(lex);
669 } else if (token == "\\fontencoding") {
671 } else if (token == "\\inputencoding") {
673 params.inputenc = lex.GetString();
674 } else if (token == "\\graphics") {
675 params.readGraphicsDriver(lex);
676 } else if (token == "\\fontscheme") {
678 params.fonts = lex.GetString();
679 } else if (token == "\\noindent") {
680 par->params().noindent(true);
681 } else if (token == "\\fill_top") {
682 par->params().spaceTop(VSpace(VSpace::VFILL));
683 } else if (token == "\\fill_bottom") {
684 par->params().spaceBottom(VSpace(VSpace::VFILL));
685 } else if (token == "\\line_top") {
686 par->params().lineTop(true);
687 } else if (token == "\\line_bottom") {
688 par->params().lineBottom(true);
689 } else if (token == "\\pagebreak_top") {
690 par->params().pagebreakTop(true);
691 } else if (token == "\\pagebreak_bottom") {
692 par->params().pagebreakBottom(true);
693 } else if (token == "\\start_of_appendix") {
694 par->params().startOfAppendix(true);
695 } else if (token == "\\paragraph_separation") {
696 int tmpret = lex.FindToken(string_paragraph_separation);
697 if (tmpret == -1) ++tmpret;
698 if (tmpret != LYX_LAYOUT_DEFAULT)
699 params.paragraph_separation =
700 static_cast<BufferParams::PARSEP>(tmpret);
701 } else if (token == "\\defskip") {
703 params.defskip = VSpace(lex.GetString());
704 } else if (token == "\\epsfig") { // obsolete
705 // Indeed it is obsolete, but we HAVE to be backwards
706 // compatible until 0.14, because otherwise all figures
707 // in existing documents are irretrivably lost. (Asger)
708 params.readGraphicsDriver(lex);
709 } else if (token == "\\quotes_language") {
710 int tmpret = lex.FindToken(string_quotes_language);
711 if (tmpret == -1) ++tmpret;
712 if (tmpret != LYX_LAYOUT_DEFAULT) {
713 InsetQuotes::quote_language tmpl =
714 InsetQuotes::EnglishQ;
717 tmpl = InsetQuotes::EnglishQ;
720 tmpl = InsetQuotes::SwedishQ;
723 tmpl = InsetQuotes::GermanQ;
726 tmpl = InsetQuotes::PolishQ;
729 tmpl = InsetQuotes::FrenchQ;
732 tmpl = InsetQuotes::DanishQ;
735 params.quotes_language = tmpl;
737 } else if (token == "\\quotes_times") {
739 switch (lex.GetInteger()) {
741 params.quotes_times = InsetQuotes::SingleQ;
744 params.quotes_times = InsetQuotes::DoubleQ;
747 } else if (token == "\\papersize") {
748 int tmpret = lex.FindToken(string_papersize);
752 params.papersize2 = tmpret;
753 } else if (token == "\\paperpackage") {
754 int tmpret = lex.FindToken(string_paperpackages);
757 params.paperpackage = BufferParams::PACKAGE_NONE;
759 params.paperpackage = tmpret;
760 } else if (token == "\\use_geometry") {
762 params.use_geometry = lex.GetInteger();
763 } else if (token == "\\use_amsmath") {
765 params.use_amsmath = lex.GetInteger();
766 } else if (token == "\\use_natbib") {
768 params.use_natbib = lex.GetInteger();
769 } else if (token == "\\use_numerical_citations") {
771 params.use_numerical_citations = lex.GetInteger();
772 } else if (token == "\\paperorientation") {
773 int tmpret = lex.FindToken(string_orientation);
774 if (tmpret == -1) ++tmpret;
775 if (tmpret != LYX_LAYOUT_DEFAULT)
776 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
777 } else if (token == "\\paperwidth") {
779 params.paperwidth = lex.GetString();
780 } else if (token == "\\paperheight") {
782 params.paperheight = lex.GetString();
783 } else if (token == "\\leftmargin") {
785 params.leftmargin = lex.GetString();
786 } else if (token == "\\topmargin") {
788 params.topmargin = lex.GetString();
789 } else if (token == "\\rightmargin") {
791 params.rightmargin = lex.GetString();
792 } else if (token == "\\bottommargin") {
794 params.bottommargin = lex.GetString();
795 } else if (token == "\\headheight") {
797 params.headheight = lex.GetString();
798 } else if (token == "\\headsep") {
800 params.headsep = lex.GetString();
801 } else if (token == "\\footskip") {
803 params.footskip = lex.GetString();
804 } else if (token == "\\paperfontsize") {
806 params.fontsize = strip(lex.GetString());
807 } else if (token == "\\papercolumns") {
809 params.columns = lex.GetInteger();
810 } else if (token == "\\papersides") {
812 switch (lex.GetInteger()) {
814 case 1: params.sides = LyXTextClass::OneSide; break;
815 case 2: params.sides = LyXTextClass::TwoSides; break;
817 } else if (token == "\\paperpagestyle") {
819 params.pagestyle = strip(lex.GetString());
820 } else if (token == "\\bullet") {
822 int const index = lex.GetInteger();
824 int temp_int = lex.GetInteger();
825 params.user_defined_bullets[index].setFont(temp_int);
826 params.temp_bullets[index].setFont(temp_int);
828 temp_int = lex.GetInteger();
829 params.user_defined_bullets[index].setCharacter(temp_int);
830 params.temp_bullets[index].setCharacter(temp_int);
832 temp_int = lex.GetInteger();
833 params.user_defined_bullets[index].setSize(temp_int);
834 params.temp_bullets[index].setSize(temp_int);
836 string const temp_str = lex.GetString();
837 if (temp_str != "\\end_bullet") {
838 // this element isn't really necessary for
839 // parsing but is easier for humans
840 // to understand bullets. Put it back and
841 // set a debug message?
842 lex.printError("\\end_bullet expected, got" + temp_str);
843 //how can I put it back?
845 } else if (token == "\\bulletLaTeX") {
847 int const index = lex.GetInteger();
849 string temp_str = lex.GetString();
851 while (temp_str != "\\end_bullet") {
852 // this loop structure is needed when user
853 // enters an empty string since the first
854 // thing returned will be the \\end_bullet
856 // if the LaTeX entry has spaces. Each element
857 // therefore needs to be read in turn
860 temp_str = lex.GetString();
862 params.user_defined_bullets[index].setText(sum_str);
863 params.temp_bullets[index].setText(sum_str);
864 } else if (token == "\\secnumdepth") {
866 params.secnumdepth = lex.GetInteger();
867 } else if (token == "\\tocdepth") {
869 params.tocdepth = lex.GetInteger();
870 } else if (token == "\\spacing") {
872 string const tmp = strip(lex.GetString());
873 Spacing::Space tmp_space = Spacing::Default;
875 if (tmp == "single") {
876 tmp_space = Spacing::Single;
877 } else if (tmp == "onehalf") {
878 tmp_space = Spacing::Onehalf;
879 } else if (tmp == "double") {
880 tmp_space = Spacing::Double;
881 } else if (tmp == "other") {
883 tmp_space = Spacing::Other;
884 tmp_val = lex.GetFloat();
886 lex.printError("Unknown spacing token: '$$Token'");
888 // Small hack so that files written with klyx will be
891 par->params().spacing(Spacing(tmp_space, tmp_val));
893 params.spacing.set(tmp_space, tmp_val);
895 } else if (token == "\\paragraph_spacing") {
897 string const tmp = strip(lex.GetString());
898 if (tmp == "single") {
899 par->params().spacing(Spacing(Spacing::Single));
900 } else if (tmp == "onehalf") {
901 par->params().spacing(Spacing(Spacing::Onehalf));
902 } else if (tmp == "double") {
903 par->params().spacing(Spacing(Spacing::Double));
904 } else if (tmp == "other") {
906 par->params().spacing(Spacing(Spacing::Other,
909 lex.printError("Unknown spacing token: '$$Token'");
911 } else if (token == "\\float_placement") {
913 params.float_placement = lex.GetString();
914 } else if (token == "\\family") {
916 font.setLyXFamily(lex.GetString());
917 } else if (token == "\\series") {
919 font.setLyXSeries(lex.GetString());
920 } else if (token == "\\shape") {
922 font.setLyXShape(lex.GetString());
923 } else if (token == "\\size") {
925 font.setLyXSize(lex.GetString());
928 #warning compatability hack needed
930 } else if (token == "\\latex") {
932 string const tok = lex.GetString();
933 // This is dirty, but gone with LyX3. (Asger)
934 if (tok == "no_latex")
935 font.setLatex(LyXFont::OFF);
936 else if (tok == "latex")
937 font.setLatex(LyXFont::ON);
938 else if (tok == "default")
939 font.setLatex(LyXFont::INHERIT);
941 lex.printError("Unknown LaTeX font flag "
944 } else if (token == "\\latex") {
946 string const tok = lex.GetString();
947 if (tok == "no_latex") {
949 insertErtContents(par, pos, font);
950 } else if (tok == "latex") {
951 ert_comp.active = true;
952 } else if (tok == "default") {
954 insertErtContents(par, pos, font);
956 lex.printError("Unknown LaTeX font flag "
960 } else if (token == "\\lang") {
962 string const tok = lex.GetString();
963 Language const * lang = languages.getLanguage(tok);
965 font.setLanguage(lang);
967 font.setLanguage(params.language);
968 lex.printError("Unknown language `$$Token'");
970 } else if (token == "\\numeric") {
972 font.setNumber(font.setLyXMisc(lex.GetString()));
973 } else if (token == "\\emph") {
975 font.setEmph(font.setLyXMisc(lex.GetString()));
976 } else if (token == "\\bar") {
978 string const tok = lex.GetString();
979 // This is dirty, but gone with LyX3. (Asger)
981 font.setUnderbar(LyXFont::ON);
982 else if (tok == "no")
983 font.setUnderbar(LyXFont::OFF);
984 else if (tok == "default")
985 font.setUnderbar(LyXFont::INHERIT);
987 lex.printError("Unknown bar font flag "
989 } else if (token == "\\noun") {
991 font.setNoun(font.setLyXMisc(lex.GetString()));
992 } else if (token == "\\color") {
994 font.setLyXColor(lex.GetString());
995 } else if (token == "\\align") {
996 int tmpret = lex.FindToken(string_align);
997 if (tmpret == -1) ++tmpret;
998 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
999 int const tmpret2 = int(pow(2.0, tmpret));
1000 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1001 par->params().align(LyXAlignment(tmpret2));
1003 } else if (token == "\\added_space_top") {
1005 par->params().spaceTop(VSpace(lex.GetString()));
1006 } else if (token == "\\added_space_bottom") {
1008 par->params().spaceBottom(VSpace(lex.GetString()));
1009 #ifndef NO_PEXTRA_REALLY
1010 } else if (token == "\\pextra_type") {
1012 par->params().pextraType(lex.GetInteger());
1013 } else if (token == "\\pextra_width") {
1015 par->params().pextraWidth(lex.GetString());
1016 } else if (token == "\\pextra_widthp") {
1018 par->params().pextraWidthp(lex.GetString());
1019 } else if (token == "\\pextra_alignment") {
1021 par->params().pextraAlignment(lex.GetInteger());
1022 } else if (token == "\\pextra_hfill") {
1024 par->params().pextraHfill(lex.GetInteger());
1025 } else if (token == "\\pextra_start_minipage") {
1027 par->params().pextraStartMinipage(lex.GetInteger());
1029 } else if (token == "\\labelwidthstring") {
1031 par->params().labelWidthString(lex.GetString());
1032 // do not delete this token, it is still needed!
1033 } else if (token == "\\end_inset") {
1034 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1035 << "Last inset read was: " << last_inset_read
1037 // Simply ignore this. The insets do not have
1039 // But insets should read it, it is a part of
1040 // the inset isn't it? Lgb.
1041 } else if (token == "\\begin_inset") {
1043 insertErtContents(par, pos, font, false);
1044 ert_stack.push(ert_comp);
1045 ert_comp = ErtComp();
1047 readInset(lex, par, pos, font);
1049 ert_comp = ert_stack.top();
1052 } else if (token == "\\SpecialChar") {
1053 LyXLayout const & layout =
1054 textclasslist.Style(params.textclass,
1057 // Insets don't make sense in a free-spacing context! ---Kayvan
1058 if (layout.free_spacing) {
1061 string next_token = lex.GetString();
1062 if (next_token == "\\-") {
1063 par->insertChar(pos, '-', font);
1064 } else if (next_token == "\\protected_separator"
1065 || next_token == "~") {
1066 par->insertChar(pos, ' ', font);
1068 lex.printError("Token `$$Token' "
1070 "paragraph layout!");
1075 Inset * inset = new InsetSpecialChar;
1076 inset->read(this, lex);
1077 par->insertInset(pos, inset, font);
1080 } else if (token == "\\newline") {
1083 if (!ert_comp.in_tabular && ert_comp.active) {
1084 ert_comp.contents += char(Paragraph::META_NEWLINE);
1086 // Since we cannot know it this is only a regular
1087 // newline or a tabular cell delimter we have to
1088 // handle the ERT here.
1089 insertErtContents(par, pos, font, false);
1091 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1095 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1098 } else if (token == "\\LyXTable") {
1100 ert_comp.in_tabular = true;
1102 Inset * inset = new InsetTabular(*this);
1103 inset->read(this, lex);
1104 par->insertInset(pos, inset, font);
1106 // because of OLD_TABULAR_READ where tabulars have been
1108 checkminipage = true;
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 minipar = parBeforeMinipage = 0;
1154 if (ert_comp.active) {
1155 ert_comp.contents += token;
1158 // This should be insurance for the future: (Asger)
1159 lex.printError("Unknown token `$$Token'. "
1160 "Inserting as text.");
1161 string::const_iterator cit = token.begin();
1162 string::const_iterator end = token.end();
1163 for (; cit != end; ++cit) {
1164 par->insertChar(pos, (*cit), font);
1171 #ifndef NO_PEXTRA_REALLY
1172 // now check if we have a minipage paragraph as at this
1173 // point we already read all the necessary data!
1174 // this cannot be done in layout because there we did
1175 // not read yet the paragraph PEXTRA-params (Jug)
1177 // BEGIN pextra_minipage compability
1178 // This should be removed in 1.3.x (Lgb)
1180 // This compability code is not perfect. In a couple
1181 // of rand cases it fails. When the minipage par is
1182 // the first par in the document, and when there are
1183 // none or only one regular paragraphs after the
1184 // minipage. Currently I am not investing any effort
1185 // in fixing those cases.
1187 //lyxerr << "Call depth: " << call_depth << endl;
1188 if (checkminipage && (call_depth == 1)) {
1189 checkminipage = false;
1190 if (minipar && (minipar != par) &&
1191 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1193 lyxerr << "minipages in a row" << endl;
1194 if (par->params().pextraStartMinipage()) {
1195 lyxerr << "start new minipage" << endl;
1196 // minipages in a row
1197 par->previous()->next(0);
1200 Paragraph * tmp = minipar;
1202 tmp->params().pextraType(0);
1203 tmp->params().pextraWidth(string());
1204 tmp->params().pextraWidthp(string());
1205 tmp->params().pextraAlignment(0);
1206 tmp->params().pextraHfill(false);
1207 tmp->params().pextraStartMinipage(false);
1210 // create a new paragraph to insert the
1211 // minipages in the following case
1212 if (par->params().pextraStartMinipage() &&
1213 !par->params().pextraHfill())
1215 Paragraph * p = new Paragraph;
1217 p->previous(parBeforeMinipage);
1218 parBeforeMinipage->next(p);
1220 p->params().depth(parBeforeMinipage->params().depth());
1221 parBeforeMinipage = p;
1223 InsetMinipage * mini = new InsetMinipage;
1224 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1225 mini->width(par->params().pextraWidth());
1226 if (!par->params().pextraWidthp().empty()) {
1227 lyxerr << "WP:" << mini->width() << endl;
1228 mini->width(tostr(par->params().pextraWidthp())+"%");
1230 mini->inset.paragraph(par);
1231 // Insert the minipage last in the
1232 // previous paragraph.
1233 if (par->params().pextraHfill()) {
1234 parBeforeMinipage->insertChar
1235 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1237 parBeforeMinipage->insertInset
1238 (parBeforeMinipage->size(), mini);
1242 lyxerr << "new minipage par" << endl;
1243 //nothing to do just continue reading
1246 } else if (minipar && (minipar != par)) {
1247 lyxerr << "last minipage par read" << endl;
1248 // The last paragraph read was not part of a
1249 // minipage but the par linked list is...
1250 // So we need to remove the last par from the
1252 if (par->previous())
1253 par->previous()->next(0);
1254 par->previous(parBeforeMinipage);
1255 parBeforeMinipage->next(par);
1256 Paragraph * tmp = minipar;
1258 tmp->params().pextraType(0);
1259 tmp->params().pextraWidth(string());
1260 tmp->params().pextraWidthp(string());
1261 tmp->params().pextraAlignment(0);
1262 tmp->params().pextraHfill(false);
1263 tmp->params().pextraStartMinipage(false);
1266 depth = parBeforeMinipage->params().depth();
1267 minipar = parBeforeMinipage = 0;
1268 } else if (!minipar &&
1269 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1271 // par is the first paragraph in a minipage
1272 lyxerr << "begin minipage" << endl;
1273 // To minimize problems for
1274 // the users we will insert
1275 // the first minipage in
1276 // a sequence of minipages
1277 // in its own paragraph.
1278 Paragraph * p = new Paragraph;
1280 p->previous(par->previous());
1282 p->params().depth(depth);
1283 par->params().depth(0);
1285 if (par->previous())
1286 par->previous()->next(p);
1288 parBeforeMinipage = p;
1290 if (!first_par || (first_par == par))
1293 InsetMinipage * mini = new InsetMinipage;
1294 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1295 mini->width(minipar->params().pextraWidth());
1296 if (!par->params().pextraWidthp().empty()) {
1297 lyxerr << "WP:" << mini->width() << endl;
1298 mini->width(tostr(par->params().pextraWidthp())+"%");
1300 mini->inset.paragraph(minipar);
1302 // Insert the minipage last in the
1303 // previous paragraph.
1304 if (minipar->params().pextraHfill()) {
1305 parBeforeMinipage->insertChar
1306 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1308 parBeforeMinipage->insertInset
1309 (parBeforeMinipage->size(), mini);
1312 // End of pextra_minipage compability
1315 return the_end_read;
1318 // needed to insert the selection
1319 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1320 LyXFont const & font,
1321 string const & str) const
1323 LyXLayout const & layout = textclasslist.Style(params.textclass,
1325 // insert the string, don't insert doublespace
1326 bool space_inserted = true;
1327 for(string::const_iterator cit = str.begin();
1328 cit != str.end(); ++cit) {
1330 if (par->size() || layout.keepempty) {
1331 par->breakParagraph(params, pos,
1332 layout.isEnvironment());
1335 space_inserted = true;
1339 // do not insert consecutive spaces if !free_spacing
1340 } else if ((*cit == ' ' || *cit == '\t')
1341 && space_inserted && !layout.free_spacing) {
1343 } else if (*cit == '\t') {
1344 if (!layout.free_spacing) {
1345 // tabs are like spaces here
1346 par->insertChar(pos, ' ', font);
1348 space_inserted = true;
1350 const Paragraph::value_type nb = 8 - pos % 8;
1351 for (Paragraph::size_type a = 0;
1353 par->insertChar(pos, ' ', font);
1356 space_inserted = true;
1358 } else if (!IsPrintable(*cit)) {
1359 // Ignore unprintables
1362 // just insert the character
1363 par->insertChar(pos, *cit, font);
1365 space_inserted = (*cit == ' ');
1372 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1373 int & pos, LyXFont & font)
1375 // consistency check
1376 if (lex.GetString() != "\\begin_inset") {
1377 lyxerr << "Buffer::readInset: Consistency check failed."
1384 string const tmptok = lex.GetString();
1385 last_inset_read = tmptok;
1387 // test the different insets
1388 if (tmptok == "LatexCommand") {
1389 InsetCommandParams inscmd;
1392 string const cmdName = inscmd.getCmdName();
1394 // This strange command allows LyX to recognize "natbib" style
1395 // citations: citet, citep, Citet etc.
1396 if (compare_no_case(cmdName, "cite", 4) == 0) {
1397 inset = new InsetCitation(inscmd);
1398 } else if (cmdName == "bibitem") {
1399 lex.printError("Wrong place for bibitem");
1400 inset = new InsetBibKey(inscmd);
1401 } else if (cmdName == "BibTeX") {
1402 inset = new InsetBibtex(inscmd);
1403 } else if (cmdName == "index") {
1404 inset = new InsetIndex(inscmd);
1405 } else if (cmdName == "include") {
1406 inset = new InsetInclude(inscmd, *this);
1407 } else if (cmdName == "label") {
1408 inset = new InsetLabel(inscmd);
1409 } else if (cmdName == "url"
1410 || cmdName == "htmlurl") {
1411 inset = new InsetUrl(inscmd);
1412 } else if (cmdName == "ref"
1413 || cmdName == "pageref"
1414 || cmdName == "vref"
1415 || cmdName == "vpageref"
1416 || cmdName == "prettyref") {
1417 if (!inscmd.getOptions().empty()
1418 || !inscmd.getContents().empty()) {
1419 inset = new InsetRef(inscmd, *this);
1421 } else if (cmdName == "tableofcontents") {
1422 inset = new InsetTOC(inscmd);
1423 } else if (cmdName == "listofalgorithms") {
1424 inset = new InsetFloatList("algorithm");
1425 } else if (cmdName == "listoffigures") {
1426 inset = new InsetFloatList("figure");
1427 } else if (cmdName == "listoftables") {
1428 inset = new InsetFloatList("table");
1429 } else if (cmdName == "printindex") {
1430 inset = new InsetPrintIndex(inscmd);
1431 } else if (cmdName == "lyxparent") {
1432 inset = new InsetParent(inscmd, *this);
1435 bool alreadyread = false;
1436 if (tmptok == "Quotes") {
1437 inset = new InsetQuotes;
1438 } else if (tmptok == "External") {
1439 inset = new InsetExternal;
1440 } else if (tmptok == "FormulaMacro") {
1441 inset = new InsetFormulaMacro;
1442 } else if (tmptok == "Formula") {
1443 inset = new InsetFormula;
1444 } else if (tmptok == "Figure") {
1445 inset = new InsetFig(100, 100, *this);
1446 } else if (tmptok == "Info") {// backwards compatibility
1447 inset = new InsetNote(this,
1448 lex.getLongString("\\end_inset"),
1451 } else if (tmptok == "Note") {
1452 inset = new InsetNote;
1453 } else if (tmptok == "Include") {
1454 InsetCommandParams p( "Include" );
1455 inset = new InsetInclude(p, *this);
1456 } else if (tmptok == "ERT") {
1457 inset = new InsetERT;
1458 } else if (tmptok == "Tabular") {
1459 inset = new InsetTabular(*this);
1460 } else if (tmptok == "Text") {
1461 inset = new InsetText;
1462 } else if (tmptok == "Foot") {
1463 inset = new InsetFoot;
1464 } else if (tmptok == "Marginal") {
1465 inset = new InsetMarginal;
1466 } else if (tmptok == "Minipage") {
1467 inset = new InsetMinipage;
1468 } else if (tmptok == "Float") {
1470 string tmptok = lex.GetString();
1471 inset = new InsetFloat(tmptok);
1472 } else if (tmptok == "List") {
1473 inset = new InsetList;
1474 } else if (tmptok == "Theorem") {
1475 inset = new InsetList;
1476 } else if (tmptok == "Caption") {
1477 inset = new InsetCaption;
1478 } else if (tmptok == "GRAPHICS") {
1479 inset = new InsetGraphics;
1480 } else if (tmptok == "FloatList") {
1481 inset = new InsetFloatList;
1484 if (inset && !alreadyread) inset->read(this, lex);
1488 par->insertInset(pos, inset, font);
1494 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1498 string const token(lex.GetString());
1499 if (token == "\\lyxformat") { // the first token _must_ be...
1501 string tmp_format = lex.GetString();
1502 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1503 // if present remove ".," from string.
1504 string::size_type dot = tmp_format.find_first_of(".,");
1505 //lyxerr << " dot found at " << dot << endl;
1506 if (dot != string::npos)
1507 tmp_format.erase(dot, 1);
1508 file_format = strToInt(tmp_format);
1509 if (file_format == LYX_FORMAT) {
1511 } else if (file_format > LYX_FORMAT) {
1513 WriteAlert(_("Warning!"),
1514 _("LyX file format is newer that what"),
1515 _("is supported in this LyX version. Expect some problems."));
1517 } else if (file_format < LYX_FORMAT) {
1519 if (file_format < 200) {
1520 WriteAlert(_("ERROR!"),
1521 _("Old LyX file format found. "
1522 "Use LyX 0.10.x to read this!"));
1526 bool the_end = readLyXformat2(lex, par);
1528 // the_end was added in 213
1529 if (file_format < 213)
1533 WriteAlert(_("Warning!"),
1534 _("Reading of document is not complete"),
1535 _("Maybe the document is truncated"));
1537 } else { // "\\lyxformat" not found
1538 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1541 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1546 // Should probably be moved to somewhere else: BufferView? LyXView?
1547 bool Buffer::save() const
1549 // We don't need autosaves in the immediate future. (Asger)
1550 resetAutosaveTimers();
1554 if (lyxrc.make_backup) {
1555 s = fileName() + '~';
1556 if (!lyxrc.backupdir_path.empty())
1557 s = AddName(lyxrc.backupdir_path,
1558 subst(os::slashify_path(s),'/','!'));
1560 // Rename is the wrong way of making a backup,
1561 // this is the correct way.
1562 /* truss cp fil fil2:
1563 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1564 stat("LyXVC.lyx", 0xEFFFF688) = 0
1565 open("LyXVC.lyx", O_RDONLY) = 3
1566 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1567 fstat(4, 0xEFFFF508) = 0
1568 fstat(3, 0xEFFFF508) = 0
1569 read(3, " # T h i s f i l e w".., 8192) = 5579
1570 write(4, " # T h i s f i l e w".., 5579) = 5579
1571 read(3, 0xEFFFD4A0, 8192) = 0
1574 chmod("LyXVC3.lyx", 0100644) = 0
1575 lseek(0, 0, SEEK_CUR) = 46440
1579 // Should probably have some more error checking here.
1580 // Should be cleaned up in 0.13, at least a bit.
1581 // Doing it this way, also makes the inodes stay the same.
1582 // This is still not a very good solution, in particular we
1583 // might loose the owner of the backup.
1584 FileInfo finfo(fileName());
1585 if (finfo.exist()) {
1586 mode_t fmode = finfo.getMode();
1587 struct utimbuf times = {
1588 finfo.getAccessTime(),
1589 finfo.getModificationTime() };
1591 ifstream ifs(fileName().c_str());
1592 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1597 ::chmod(s.c_str(), fmode);
1599 if (::utime(s.c_str(), ×)) {
1600 lyxerr << "utime error." << endl;
1603 lyxerr << "LyX was not able to make "
1604 "backup copy. Beware." << endl;
1609 if (writeFile(fileName(), false)) {
1611 removeAutosaveFile(fileName());
1613 // Saving failed, so backup is not backup
1614 if (lyxrc.make_backup) {
1615 lyx::rename(s, fileName());
1623 // Returns false if unsuccesful
1624 bool Buffer::writeFile(string const & fname, bool flag) const
1626 // if flag is false writeFile will not create any GUI
1627 // warnings, only cerr.
1628 // Needed for autosave in background or panic save (Matthias 120496)
1630 if (read_only && (fname == filename)) {
1631 // Here we should come with a question if we should
1632 // perform the write anyway.
1634 lyxerr << _("Error! Document is read-only: ")
1637 WriteAlert(_("Error! Document is read-only: "),
1642 FileInfo finfo(fname);
1643 if (finfo.exist() && !finfo.writable()) {
1644 // Here we should come with a question if we should
1645 // try to do the save anyway. (i.e. do a chmod first)
1647 lyxerr << _("Error! Cannot write file: ")
1650 WriteFSAlert(_("Error! Cannot write file: "),
1655 ofstream ofs(fname.c_str());
1658 lyxerr << _("Error! Cannot open file: ")
1661 WriteFSAlert(_("Error! Cannot open file: "),
1667 // Use the standard "C" locale for file output.
1668 ofs.imbue(std::locale::classic());
1671 // The top of the file should not be written by params.
1673 // write out a comment in the top of the file
1674 ofs << '#' << LYX_DOCVERSION
1675 << " created this file. For more info see http://www.lyx.org/\n"
1676 << "\\lyxformat " << LYX_FORMAT << "\n";
1678 // now write out the buffer paramters.
1679 params.writeFile(ofs);
1681 Paragraph::depth_type depth = 0;
1683 // this will write out all the paragraphs
1684 // using recursive descent.
1685 paragraph->writeFile(this, ofs, params, depth);
1687 // Write marker that shows file is complete
1688 ofs << "\n\\the_end" << endl;
1692 // how to check if close went ok?
1693 // Following is an attempt... (BE 20001011)
1695 // good() returns false if any error occured, including some
1696 // formatting error.
1697 // bad() returns true if something bad happened in the buffer,
1698 // which should include file system full errors.
1705 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1707 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1717 string const Buffer::asciiParagraph(Paragraph const * par,
1718 unsigned int linelen) const
1720 ostringstream buffer;
1721 Paragraph::depth_type depth = 0;
1723 Paragraph::depth_type ltype_depth = 0;
1724 unsigned int currlinelen = 0;
1725 bool ref_printed = false;
1729 if (!par->previous()) {
1730 // begins or ends a deeper area ?
1731 if (depth != par->params().depth()) {
1732 if (par->params().depth() > depth) {
1733 while (par->params().depth() > depth) {
1737 while (par->params().depth() < depth) {
1743 // First write the layout
1744 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1745 if (tmp == "Itemize") {
1747 ltype_depth = depth + 1;
1748 } else if (tmp == "Enumerate") {
1750 ltype_depth = depth + 1;
1751 } else if (contains(tmp, "ection")) {
1753 ltype_depth = depth + 1;
1754 } else if (contains(tmp, "aragraph")) {
1756 ltype_depth = depth + 1;
1757 } else if (tmp == "Description") {
1759 ltype_depth = depth + 1;
1760 } else if (tmp == "Abstract") {
1763 } else if (tmp == "Bibliography") {
1771 /* maybe some vertical spaces */
1773 /* the labelwidthstring used in lists */
1777 /* some pagebreaks? */
1781 /* what about the alignment */
1783 lyxerr << "Should this ever happen?" << endl;
1787 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1789 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1790 if (!i && !noparbreak) {
1793 for (Paragraph::depth_type j = 0; j < depth; ++j)
1795 currlinelen = depth * 2;
1798 case 4: // (Sub)Paragraph
1799 case 5: // Description
1803 buffer << "Abstract\n\n";
1805 buffer << "Abstract: ";
1807 case 7: // Bibliography
1810 buffer << "References\n\n";
1812 buffer << "References: ";
1817 buffer << par->params().labelString() << " ";
1820 if (ltype_depth > depth) {
1821 for (Paragraph::depth_type j = ltype_depth - 1;
1824 currlinelen += (ltype_depth-depth)*2;
1828 LyXFont const font2 = par->getFontSettings(params, i);
1829 if (font1.latex() != font2.latex()) {
1830 if (font2.latex() == LyXFont::OFF)
1839 char c = par->getUChar(params, i);
1843 case Paragraph::META_INSET:
1845 Inset const * inset = par->getInset(i);
1847 if (!inset->ascii(this, buffer)) {
1850 rsplit(buffer.str().c_str(),
1852 currlinelen += s.length();
1854 // to be sure it breaks paragraph
1855 currlinelen += linelen;
1861 case Paragraph::META_NEWLINE:
1864 for (Paragraph::depth_type j = 0;
1868 currlinelen = depth * 2;
1869 if (ltype_depth > depth) {
1870 for (Paragraph::depth_type j = ltype_depth;
1873 currlinelen += (ltype_depth - depth) * 2;
1877 case Paragraph::META_HFILL:
1886 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1887 (c == ' ') && ((i + 2) < par->size()))
1890 for (Paragraph::depth_type j = 0;
1893 currlinelen = depth * 2;
1894 if (ltype_depth > depth) {
1895 for (Paragraph::depth_type j = ltype_depth;
1898 currlinelen += (ltype_depth-depth)*2;
1900 } else if (c != '\0')
1903 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1908 return buffer.str().c_str();
1912 void Buffer::writeFileAscii(string const & fname, int linelen)
1914 ofstream ofs(fname.c_str());
1916 WriteFSAlert(_("Error: Cannot write file:"), fname);
1919 writeFileAscii(ofs, linelen);
1923 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1925 Paragraph * par = paragraph;
1927 ofs << asciiParagraph(par, linelen);
1935 void Buffer::makeLaTeXFile(string const & fname,
1936 string const & original_path,
1937 bool nice, bool only_body)
1939 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1941 niceFile = nice; // this will be used by Insetincludes.
1943 tex_code_break_column = lyxrc.ascii_linelen;
1945 LyXTextClass const & tclass =
1946 textclasslist.TextClass(params.textclass);
1948 ofstream ofs(fname.c_str());
1950 WriteFSAlert(_("Error: Cannot open file: "), fname);
1954 // validate the buffer.
1955 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1956 LaTeXFeatures features(params, tclass.numLayouts());
1958 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1961 // The starting paragraph of the coming rows is the
1962 // first paragraph of the document. (Asger)
1963 texrow.start(paragraph, 0);
1965 if (!only_body && nice) {
1966 ofs << "%% " LYX_DOCVERSION " created this file. "
1967 "For more info, see http://www.lyx.org/.\n"
1968 "%% Do not edit unless you really know what "
1973 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1974 // There are a few differences between nice LaTeX and usual files:
1975 // usual is \batchmode and has a
1976 // special input@path to allow the including of figures
1977 // with either \input or \includegraphics (what figinsets do).
1978 // batchmode is not set if there is a tex_code_break_column.
1979 // In this case somebody is interested in the generated LaTeX,
1980 // so this is OK. input@path is set when the actual parameter
1981 // original_path is set. This is done for usual tex-file, but not
1982 // for nice-latex-file. (Matthias 250696)
1985 // code for usual, NOT nice-latex-file
1986 ofs << "\\batchmode\n"; // changed
1987 // from \nonstopmode
1990 if (!original_path.empty()) {
1991 ofs << "\\makeatletter\n"
1992 << "\\def\\input@path{{"
1993 << os::external_path(original_path) << "/}}\n"
1994 << "\\makeatother\n";
2000 ofs << "\\documentclass";
2002 ostringstream options; // the document class options.
2004 if (tokenPos(tclass.opt_fontsize(),
2005 '|', params.fontsize) >= 0) {
2006 // only write if existing in list (and not default)
2007 options << params.fontsize << "pt,";
2011 if (!params.use_geometry &&
2012 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2013 switch (params.papersize) {
2014 case BufferParams::PAPER_A4PAPER:
2015 options << "a4paper,";
2017 case BufferParams::PAPER_USLETTER:
2018 options << "letterpaper,";
2020 case BufferParams::PAPER_A5PAPER:
2021 options << "a5paper,";
2023 case BufferParams::PAPER_B5PAPER:
2024 options << "b5paper,";
2026 case BufferParams::PAPER_EXECUTIVEPAPER:
2027 options << "executivepaper,";
2029 case BufferParams::PAPER_LEGALPAPER:
2030 options << "legalpaper,";
2036 if (params.sides != tclass.sides()) {
2037 switch (params.sides) {
2038 case LyXTextClass::OneSide:
2039 options << "oneside,";
2041 case LyXTextClass::TwoSides:
2042 options << "twoside,";
2048 if (params.columns != tclass.columns()) {
2049 if (params.columns == 2)
2050 options << "twocolumn,";
2052 options << "onecolumn,";
2055 if (!params.use_geometry
2056 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2057 options << "landscape,";
2059 // language should be a parameter to \documentclass
2061 ostringstream language_options;
2062 if (params.language->babel() == "hebrew"
2063 && default_language->babel() != "hebrew")
2064 // This seems necessary
2065 features.UsedLanguages.insert(default_language);
2067 if (lyxrc.language_use_babel ||
2068 params.language->lang() != lyxrc.default_language ||
2069 !features.UsedLanguages.empty()) {
2071 for (LaTeXFeatures::LanguageList::const_iterator cit =
2072 features.UsedLanguages.begin();
2073 cit != features.UsedLanguages.end(); ++cit)
2074 language_options << (*cit)->babel() << ',';
2075 language_options << params.language->babel();
2076 if (lyxrc.language_global_options)
2077 options << language_options.str() << ',';
2080 // the user-defined options
2081 if (!params.options.empty()) {
2082 options << params.options << ',';
2085 string strOptions(options.str().c_str());
2086 if (!strOptions.empty()){
2087 strOptions = strip(strOptions, ',');
2088 ofs << '[' << strOptions << ']';
2092 << textclasslist.LatexnameOfClass(params.textclass)
2095 // end of \documentclass defs
2097 // font selection must be done before loading fontenc.sty
2098 // The ae package is not needed when using OT1 font encoding.
2099 if (params.fonts != "default" &&
2100 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2101 ofs << "\\usepackage{" << params.fonts << "}\n";
2103 if (params.fonts == "ae") {
2104 ofs << "\\usepackage{aecompl}\n";
2108 // this one is not per buffer
2109 if (lyxrc.fontenc != "default") {
2110 ofs << "\\usepackage[" << lyxrc.fontenc
2115 if (params.inputenc == "auto") {
2116 string const doc_encoding =
2117 params.language->encoding()->LatexName();
2119 // Create a list with all the input encodings used
2121 set<string> encodings;
2122 for (LaTeXFeatures::LanguageList::const_iterator it =
2123 features.UsedLanguages.begin();
2124 it != features.UsedLanguages.end(); ++it)
2125 if ((*it)->encoding()->LatexName() != doc_encoding)
2126 encodings.insert((*it)->encoding()->LatexName());
2128 ofs << "\\usepackage[";
2129 std::copy(encodings.begin(), encodings.end(),
2130 std::ostream_iterator<string>(ofs, ","));
2131 ofs << doc_encoding << "]{inputenc}\n";
2133 } else if (params.inputenc != "default") {
2134 ofs << "\\usepackage[" << params.inputenc
2139 // At the very beginning the text parameters.
2140 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2141 switch (params.paperpackage) {
2142 case BufferParams::PACKAGE_A4:
2143 ofs << "\\usepackage{a4}\n";
2146 case BufferParams::PACKAGE_A4WIDE:
2147 ofs << "\\usepackage{a4wide}\n";
2150 case BufferParams::PACKAGE_WIDEMARGINSA4:
2151 ofs << "\\usepackage[widemargins]{a4}\n";
2156 if (params.use_geometry) {
2157 ofs << "\\usepackage{geometry}\n";
2159 ofs << "\\geometry{verbose";
2160 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2161 ofs << ",landscape";
2162 switch (params.papersize2) {
2163 case BufferParams::VM_PAPER_CUSTOM:
2164 if (!params.paperwidth.empty())
2165 ofs << ",paperwidth="
2166 << params.paperwidth;
2167 if (!params.paperheight.empty())
2168 ofs << ",paperheight="
2169 << params.paperheight;
2171 case BufferParams::VM_PAPER_USLETTER:
2172 ofs << ",letterpaper";
2174 case BufferParams::VM_PAPER_USLEGAL:
2175 ofs << ",legalpaper";
2177 case BufferParams::VM_PAPER_USEXECUTIVE:
2178 ofs << ",executivepaper";
2180 case BufferParams::VM_PAPER_A3:
2183 case BufferParams::VM_PAPER_A4:
2186 case BufferParams::VM_PAPER_A5:
2189 case BufferParams::VM_PAPER_B3:
2192 case BufferParams::VM_PAPER_B4:
2195 case BufferParams::VM_PAPER_B5:
2199 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2200 switch (lyxrc.default_papersize) {
2201 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2202 case BufferParams::PAPER_USLETTER:
2203 ofs << ",letterpaper";
2205 case BufferParams::PAPER_LEGALPAPER:
2206 ofs << ",legalpaper";
2208 case BufferParams::PAPER_EXECUTIVEPAPER:
2209 ofs << ",executivepaper";
2211 case BufferParams::PAPER_A3PAPER:
2214 case BufferParams::PAPER_A4PAPER:
2217 case BufferParams::PAPER_A5PAPER:
2220 case BufferParams::PAPER_B5PAPER:
2225 if (!params.topmargin.empty())
2226 ofs << ",tmargin=" << params.topmargin;
2227 if (!params.bottommargin.empty())
2228 ofs << ",bmargin=" << params.bottommargin;
2229 if (!params.leftmargin.empty())
2230 ofs << ",lmargin=" << params.leftmargin;
2231 if (!params.rightmargin.empty())
2232 ofs << ",rmargin=" << params.rightmargin;
2233 if (!params.headheight.empty())
2234 ofs << ",headheight=" << params.headheight;
2235 if (!params.headsep.empty())
2236 ofs << ",headsep=" << params.headsep;
2237 if (!params.footskip.empty())
2238 ofs << ",footskip=" << params.footskip;
2242 if (features.amsstyle
2243 && !tclass.provides(LyXTextClass::amsmath)) {
2244 ofs << "\\usepackage{amsmath}\n";
2248 if (tokenPos(tclass.opt_pagestyle(),
2249 '|', params.pagestyle) >= 0) {
2250 if (params.pagestyle == "fancy") {
2251 ofs << "\\usepackage{fancyhdr}\n";
2254 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2258 // We try to load babel late, in case it interferes
2259 // with other packages.
2261 string tmp = lyxrc.language_package;
2262 if (!lyxrc.language_global_options
2263 && tmp == "\\usepackage{babel}")
2264 tmp = string("\\usepackage[") +
2265 language_options.str().c_str() +
2271 if (params.secnumdepth != tclass.secnumdepth()) {
2272 ofs << "\\setcounter{secnumdepth}{"
2273 << params.secnumdepth
2277 if (params.tocdepth != tclass.tocdepth()) {
2278 ofs << "\\setcounter{tocdepth}{"
2284 if (params.paragraph_separation) {
2285 switch (params.defskip.kind()) {
2286 case VSpace::SMALLSKIP:
2287 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2289 case VSpace::MEDSKIP:
2290 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2292 case VSpace::BIGSKIP:
2293 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2295 case VSpace::LENGTH:
2296 ofs << "\\setlength\\parskip{"
2297 << params.defskip.length().asLatexString()
2300 default: // should never happen // Then delete it.
2301 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2306 ofs << "\\setlength\\parindent{0pt}\n";
2310 // Now insert the LyX specific LaTeX commands...
2312 // The optional packages;
2313 string preamble(features.getPackages());
2315 // this might be useful...
2316 preamble += "\n\\makeatletter\n";
2318 // Some macros LyX will need
2319 string tmppreamble(features.getMacros());
2321 if (!tmppreamble.empty()) {
2322 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2323 "LyX specific LaTeX commands.\n"
2324 + tmppreamble + '\n';
2327 // the text class specific preamble
2328 tmppreamble = features.getTClassPreamble();
2329 if (!tmppreamble.empty()) {
2330 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2331 "Textclass specific LaTeX commands.\n"
2332 + tmppreamble + '\n';
2335 /* the user-defined preamble */
2336 if (!params.preamble.empty()) {
2337 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2338 "User specified LaTeX commands.\n"
2339 + params.preamble + '\n';
2342 preamble += "\\makeatother\n";
2344 // Itemize bullet settings need to be last in case the user
2345 // defines their own bullets that use a package included
2346 // in the user-defined preamble -- ARRae
2347 // Actually it has to be done much later than that
2348 // since some packages like frenchb make modifications
2349 // at \begin{document} time -- JMarc
2351 for (int i = 0; i < 4; ++i) {
2352 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2353 if (bullets_def.empty())
2354 bullets_def="\\AtBeginDocument{\n";
2355 bullets_def += " \\renewcommand{\\labelitemi";
2357 // `i' is one less than the item to modify
2364 bullets_def += "ii";
2370 bullets_def += "}{" +
2371 params.user_defined_bullets[i].getText()
2376 if (!bullets_def.empty())
2377 preamble += bullets_def + "}\n\n";
2379 for (int j = countChar(preamble, '\n'); j-- ;) {
2386 ofs << "\\begin{document}\n";
2389 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2391 if (!lyxrc.language_auto_begin) {
2392 ofs << subst(lyxrc.language_command_begin, "$$lang",
2393 params.language->babel())
2398 latexParagraphs(ofs, paragraph, 0, texrow);
2400 // add this just in case after all the paragraphs
2404 if (!lyxrc.language_auto_end) {
2405 ofs << subst(lyxrc.language_command_end, "$$lang",
2406 params.language->babel())
2412 ofs << "\\end{document}\n";
2415 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2417 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2421 // Just to be sure. (Asger)
2424 // tex_code_break_column's value is used to decide
2425 // if we are in batchmode or not (within mathed_write()
2426 // in math_write.C) so we must set it to a non-zero
2427 // value when we leave otherwise we save incorrect .lyx files.
2428 tex_code_break_column = lyxrc.ascii_linelen;
2432 lyxerr << "File was not closed properly." << endl;
2435 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2440 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2442 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2443 Paragraph * endpar, TexRow & texrow) const
2445 bool was_title = false;
2446 bool already_title = false;
2449 while (par != endpar) {
2450 LyXLayout const & layout =
2451 textclasslist.Style(params.textclass,
2454 if (layout.intitle) {
2455 if (already_title) {
2456 lyxerr <<"Error in latexParagraphs: You"
2457 " should not mix title layouts"
2458 " with normal ones." << endl;
2461 } else if (was_title && !already_title) {
2462 ofs << "\\maketitle\n";
2464 already_title = true;
2468 if (layout.isEnvironment()) {
2469 par = par->TeXEnvironment(this, params, ofs, texrow);
2471 par = par->TeXOnePar(this, params, ofs, texrow, false);
2474 // It might be that we only have a title in this document
2475 if (was_title && !already_title) {
2476 ofs << "\\maketitle\n";
2482 bool Buffer::isLatex() const
2484 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2488 bool Buffer::isLinuxDoc() const
2490 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2494 bool Buffer::isLiterate() const
2496 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2500 bool Buffer::isDocBook() const
2502 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2506 bool Buffer::isSGML() const
2508 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2509 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2513 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2514 string const & latexname) const
2516 if (!latexname.empty() && latexname != "!-- --")
2517 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2518 //os << string(depth, ' ') << "<" << latexname << ">\n";
2522 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2523 string const & latexname) const
2525 if (!latexname.empty() && latexname != "!-- --")
2526 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2527 //os << string(depth, ' ') << "</" << latexname << ">\n";
2531 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2533 ofstream ofs(fname.c_str());
2536 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2540 niceFile = nice; // this will be used by included files.
2542 LyXTextClass const & tclass =
2543 textclasslist.TextClass(params.textclass);
2545 LaTeXFeatures features(params, tclass.numLayouts());
2550 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2553 string sgml_includedfiles=features.getIncludedFiles(fname);
2555 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2556 ofs << "<!doctype linuxdoc system>\n\n";
2558 ofs << "<!doctype linuxdoc system [ "
2559 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2562 if (params.options.empty())
2563 sgmlOpenTag(ofs, 0, top_element);
2565 string top = top_element;
2567 top += params.options;
2568 sgmlOpenTag(ofs, 0, top);
2572 ofs << "<!-- " << LYX_DOCVERSION
2573 << " created this file. For more info see http://www.lyx.org/"
2576 Paragraph::depth_type depth = 0; // paragraph depth
2577 Paragraph * par = paragraph;
2579 vector<string> environment_stack(5);
2582 LyXLayout const & style =
2583 textclasslist.Style(params.textclass,
2586 // treat <toc> as a special case for compatibility with old code
2587 if (par->getChar(0) == Paragraph::META_INSET) {
2588 Inset * inset = par->getInset(0);
2589 Inset::Code lyx_code = inset->lyxCode();
2590 if (lyx_code == Inset::TOC_CODE){
2591 string const temp = "toc";
2592 sgmlOpenTag(ofs, depth, temp);
2599 // environment tag closing
2600 for (; depth > par->params().depth(); --depth) {
2601 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2602 environment_stack[depth].erase();
2605 // write opening SGML tags
2606 switch (style.latextype) {
2607 case LATEX_PARAGRAPH:
2608 if (depth == par->params().depth()
2609 && !environment_stack[depth].empty()) {
2610 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2611 environment_stack[depth].erase();
2617 sgmlOpenTag(ofs, depth, style.latexname());
2622 linuxDocError(par, 0,
2623 _("Error : Wrong depth for"
2624 " LatexType Command.\n"));
2626 if (!environment_stack[depth].empty()){
2627 sgmlCloseTag(ofs, depth,
2628 environment_stack[depth]);
2632 environment_stack[depth].erase();
2633 sgmlOpenTag(ofs, depth, style.latexname());
2636 case LATEX_ENVIRONMENT:
2637 case LATEX_ITEM_ENVIRONMENT:
2638 if (depth == par->params().depth()
2639 && environment_stack[depth] != style.latexname()) {
2640 sgmlCloseTag(ofs, depth,
2641 environment_stack[depth]);
2642 environment_stack[depth].erase();
2644 if (depth < par->params().depth()) {
2645 depth = par->params().depth();
2646 environment_stack[depth].erase();
2648 if (environment_stack[depth] != style.latexname()) {
2650 sgmlOpenTag(ofs, depth, "p");
2652 sgmlOpenTag(ofs, depth, style.latexname());
2654 if (environment_stack.size() == depth + 1)
2655 environment_stack.push_back("!-- --");
2656 environment_stack[depth] = style.latexname();
2659 if (style.latexparam() == "CDATA")
2662 if (style.latextype == LATEX_ENVIRONMENT) break;
2664 if (style.labeltype == LABEL_MANUAL)
2669 sgmlOpenTag(ofs, depth + 1, item_name);
2672 sgmlOpenTag(ofs, depth, style.latexname());
2676 simpleLinuxDocOnePar(ofs, par, depth);
2681 // write closing SGML tags
2682 switch (style.latextype) {
2685 case LATEX_ENVIRONMENT:
2686 case LATEX_ITEM_ENVIRONMENT:
2687 if (style.latexparam() == "CDATA")
2691 sgmlCloseTag(ofs, depth, style.latexname());
2697 for (int i=depth; i >= 0; --i)
2698 sgmlCloseTag(ofs, depth, environment_stack[i]);
2702 sgmlCloseTag(ofs, 0, top_element);
2706 // How to check for successful close
2710 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2711 Paragraph::depth_type depth, int desc_on,
2714 Paragraph * tpar = par;
2716 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2718 tpar = tpar->next();
2721 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2722 "Caption").second) {
2723 sgmlOpenTag(os, depth + 1, inner_tag);
2725 simpleDocBookOnePar(os, extra_par, tpar,
2726 desc_on, depth + 2);
2727 sgmlCloseTag(os, depth+1, inner_tag);
2728 if (!extra_par.empty())
2734 // checks, if newcol chars should be put into this line
2735 // writes newline, if necessary.
2738 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2739 string::size_type newcol)
2742 if (colcount > lyxrc.ascii_linelen) {
2744 colcount = newcol; // assume write after this call
2759 string tag_name(PAR_TAG const & pt) {
2761 case NONE: return "!-- --";
2762 case TT: return "tt";
2763 case SF: return "sf";
2764 case BF: return "bf";
2765 case IT: return "it";
2766 case SL: return "sl";
2767 case EM: return "em";
2774 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2776 p1 = static_cast<PAR_TAG>(p1 | p2);
2781 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2783 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2791 // Handle internal paragraph parsing -- layout already processed.
2792 void Buffer::simpleLinuxDocOnePar(ostream & os,
2794 Paragraph::depth_type /*depth*/)
2796 LyXLayout const & style = textclasslist.Style(params.textclass,
2798 string::size_type char_line_count = 5; // Heuristic choice ;-)
2800 // gets paragraph main font
2803 if (style.labeltype == LABEL_MANUAL) {
2804 font_old = style.labelfont;
2807 font_old = style.font;
2811 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2812 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2813 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2816 stack < PAR_TAG > tag_state;
2817 // parsing main loop
2818 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2820 PAR_TAG tag_close = NONE;
2821 list < PAR_TAG > tag_open;
2823 LyXFont const font = par->getFont(params, i);
2825 if (font_old.family() != font.family()) {
2826 switch (family_type) {
2827 case LyXFont::SANS_FAMILY:
2830 case LyXFont::TYPEWRITER_FAMILY:
2837 family_type = font.family();
2839 switch (family_type) {
2840 case LyXFont::SANS_FAMILY:
2841 tag_open.push_back(SF);
2843 case LyXFont::TYPEWRITER_FAMILY:
2844 tag_open.push_back(TT);
2851 if (font_old.series() != font.series()) {
2852 switch (series_type) {
2853 case LyXFont::BOLD_SERIES:
2860 series_type = font.series();
2862 switch (series_type) {
2863 case LyXFont::BOLD_SERIES:
2864 tag_open.push_back(BF);
2872 if (font_old.shape() != font.shape()) {
2873 switch (shape_type) {
2874 case LyXFont::ITALIC_SHAPE:
2877 case LyXFont::SLANTED_SHAPE:
2884 shape_type = font.shape();
2886 switch (shape_type) {
2887 case LyXFont::ITALIC_SHAPE:
2888 tag_open.push_back(IT);
2890 case LyXFont::SLANTED_SHAPE:
2891 tag_open.push_back(SL);
2898 if (font_old.emph() != font.emph()) {
2899 if (font.emph() == LyXFont::ON) {
2900 tag_open.push_back(EM);
2909 list < PAR_TAG > temp;
2910 while(!tag_state.empty() && tag_close ) {
2911 PAR_TAG k = tag_state.top();
2913 os << "</" << tag_name(k) << ">";
2920 for(list< PAR_TAG >::const_iterator j = temp.begin();
2921 j != temp.end(); ++j) {
2923 os << "<" << tag_name(*j) << ">";
2926 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2927 j != tag_open.end(); ++j) {
2929 os << "<" << tag_name(*j) << ">";
2932 char c = par->getChar(i);
2934 if (c == Paragraph::META_INSET) {
2935 Inset * inset = par->getInset(i);
2936 inset->linuxdoc(this, os);
2943 font.latex() == LyXFont::ON ||
2945 style.latexparam() == "CDATA") {
2946 // "TeX"-Mode on == > SGML-Mode on.
2952 if (par->linuxDocConvertChar(c, sgml_string)
2953 && !style.free_spacing) {
2954 // in freespacing mode, spaces are
2955 // non-breaking characters
2956 if (desc_on) {// if char is ' ' then...
2959 linux_doc_line_break(os, char_line_count, 6);
2963 linux_doc_line_break(os, char_line_count, 1);
2968 char_line_count += sgml_string.length();
2974 while (!tag_state.empty()) {
2975 os << "</" << tag_name(tag_state.top()) << ">";
2979 // resets description flag correctly
2981 // <tag> not closed...
2982 linux_doc_line_break(os, char_line_count, 6);
2988 // Print an error message.
2989 void Buffer::linuxDocError(Paragraph * par, int pos,
2990 string const & message)
2992 // insert an error marker in text
2993 InsetError * new_inset = new InsetError(message);
2994 par->insertInset(pos, new_inset);
2998 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3000 ofstream ofs(fname.c_str());
3002 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3006 Paragraph * par = paragraph;
3008 niceFile = nice; // this will be used by Insetincludes.
3010 LyXTextClass const & tclass =
3011 textclasslist.TextClass(params.textclass);
3013 LaTeXFeatures features(params, tclass.numLayouts());
3018 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3021 string sgml_includedfiles = features.getIncludedFiles(fname);
3023 ofs << "<!doctype " << top_element
3024 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3026 if (params.preamble.empty() && sgml_includedfiles.empty())
3029 ofs << "\n [ " << params.preamble
3030 << sgml_includedfiles << " \n]>\n\n";
3033 string top = top_element;
3035 top += params.language->code();
3038 if (!params.options.empty()) {
3040 top += params.options;
3042 sgmlOpenTag(ofs, 0, top);
3044 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3045 << "\n See http://www.lyx.org/ for more information -->\n";
3047 vector<string> environment_stack(10);
3048 vector<string> environment_inner(10);
3049 vector<string> command_stack(10);
3051 bool command_flag = false;
3052 Paragraph::depth_type command_depth = 0;
3053 Paragraph::depth_type command_base = 0;
3054 Paragraph::depth_type cmd_depth = 0;
3055 Paragraph::depth_type depth = 0; // paragraph depth
3058 string command_name;
3064 int desc_on = 0; // description mode
3066 LyXLayout const & style =
3067 textclasslist.Style(params.textclass,
3070 // environment tag closing
3071 for (; depth > par->params().depth(); --depth) {
3072 if (environment_inner[depth] != "!-- --") {
3073 item_name = "listitem";
3074 sgmlCloseTag(ofs, command_depth + depth,
3076 if (environment_inner[depth] == "varlistentry")
3077 sgmlCloseTag(ofs, depth+command_depth,
3078 environment_inner[depth]);
3080 sgmlCloseTag(ofs, depth + command_depth,
3081 environment_stack[depth]);
3082 environment_stack[depth].erase();
3083 environment_inner[depth].erase();
3086 if (depth == par->params().depth()
3087 && environment_stack[depth] != style.latexname()
3088 && !environment_stack[depth].empty()) {
3089 if (environment_inner[depth] != "!-- --") {
3090 item_name= "listitem";
3091 sgmlCloseTag(ofs, command_depth+depth,
3093 if (environment_inner[depth] == "varlistentry")
3095 depth + command_depth,
3096 environment_inner[depth]);
3099 sgmlCloseTag(ofs, depth + command_depth,
3100 environment_stack[depth]);
3102 environment_stack[depth].erase();
3103 environment_inner[depth].erase();
3106 // Write opening SGML tags.
3107 switch (style.latextype) {
3108 case LATEX_PARAGRAPH:
3109 sgmlOpenTag(ofs, depth + command_depth,
3115 linuxDocError(par, 0,
3116 _("Error : Wrong depth for "
3117 "LatexType Command.\n"));
3119 command_name = style.latexname();
3121 sgmlparam = style.latexparam();
3122 c_params = split(sgmlparam, c_depth,'|');
3124 cmd_depth = lyx::atoi(c_depth);
3127 if (cmd_depth < command_base) {
3128 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3129 sgmlCloseTag(ofs, j, command_stack[j]);
3130 command_depth = command_base = cmd_depth;
3131 } else if (cmd_depth <= command_depth) {
3132 for (int j = command_depth; j >= int(cmd_depth); --j)
3133 sgmlCloseTag(ofs, j, command_stack[j]);
3134 command_depth = cmd_depth;
3136 command_depth = cmd_depth;
3138 command_depth = command_base = cmd_depth;
3139 command_flag = true;
3141 if (command_stack.size() == command_depth + 1)
3142 command_stack.push_back(string());
3143 command_stack[command_depth] = command_name;
3145 // treat label as a special case for
3146 // more WYSIWYM handling.
3147 if (par->getChar(0) == Paragraph::META_INSET) {
3148 Inset * inset = par->getInset(0);
3149 Inset::Code lyx_code = inset->lyxCode();
3150 if (lyx_code == Inset::LABEL_CODE){
3151 command_name += " id=\"";
3152 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3153 command_name += "\"";
3158 sgmlOpenTag(ofs, depth + command_depth, command_name);
3159 if (c_params.empty())
3160 item_name = "title";
3162 item_name = c_params;
3163 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3166 case LATEX_ENVIRONMENT:
3167 case LATEX_ITEM_ENVIRONMENT:
3168 if (depth < par->params().depth()) {
3169 depth = par->params().depth();
3170 environment_stack[depth].erase();
3173 if (environment_stack[depth] != style.latexname()) {
3174 if(environment_stack.size() == depth + 1) {
3175 environment_stack.push_back("!-- --");
3176 environment_inner.push_back("!-- --");
3178 environment_stack[depth] = style.latexname();
3179 environment_inner[depth] = "!-- --";
3180 sgmlOpenTag(ofs, depth + command_depth,
3181 environment_stack[depth]);
3183 if (environment_inner[depth] != "!-- --") {
3184 item_name= "listitem";
3186 command_depth + depth,
3188 if (environment_inner[depth] == "varlistentry")
3190 depth + command_depth,
3191 environment_inner[depth]);
3195 if (style.latextype == LATEX_ENVIRONMENT) {
3196 if (!style.latexparam().empty()) {
3197 if(style.latexparam() == "CDATA")
3200 sgmlOpenTag(ofs, depth + command_depth,
3201 style.latexparam());
3206 desc_on = (style.labeltype == LABEL_MANUAL);
3209 environment_inner[depth]= "varlistentry";
3211 environment_inner[depth]= "listitem";
3213 sgmlOpenTag(ofs, depth + 1 + command_depth,
3214 environment_inner[depth]);
3218 sgmlOpenTag(ofs, depth + 1 + command_depth,
3222 sgmlOpenTag(ofs, depth + 1 + command_depth,
3227 sgmlOpenTag(ofs, depth + command_depth,
3233 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3234 depth + 1 + command_depth);
3238 // write closing SGML tags
3239 switch (style.latextype) {
3241 if (c_params.empty())
3245 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3247 case LATEX_ENVIRONMENT:
3248 if (!style.latexparam().empty()) {
3249 if(style.latexparam() == "CDATA")
3252 sgmlCloseTag(ofs, depth + command_depth,
3253 style.latexparam());
3256 case LATEX_ITEM_ENVIRONMENT:
3257 if (desc_on == 1) break;
3259 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3261 case LATEX_PARAGRAPH:
3262 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3265 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3271 for (int d = depth; d >= 0; --d) {
3272 if (!environment_stack[depth].empty()) {
3273 if (environment_inner[depth] != "!-- --") {
3274 item_name = "listitem";
3275 sgmlCloseTag(ofs, command_depth + depth,
3277 if (environment_inner[depth] == "varlistentry")
3278 sgmlCloseTag(ofs, depth + command_depth,
3279 environment_inner[depth]);
3282 sgmlCloseTag(ofs, depth + command_depth,
3283 environment_stack[depth]);
3287 for (int j = command_depth; j >= 0 ; --j)
3288 if (!command_stack[j].empty())
3289 sgmlCloseTag(ofs, j, command_stack[j]);
3292 sgmlCloseTag(ofs, 0, top_element);
3295 // How to check for successful close
3299 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3300 Paragraph * par, int & desc_on,
3301 Paragraph::depth_type depth) const
3303 bool emph_flag = false;
3305 LyXLayout const & style = textclasslist.Style(params.textclass,
3308 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3310 int char_line_count = depth;
3311 //if (!style.free_spacing)
3312 // os << string(depth,' ');
3314 // parsing main loop
3315 for (Paragraph::size_type i = 0;
3316 i < par->size(); ++i) {
3317 LyXFont font = par->getFont(params, i);
3319 // handle <emphasis> tag
3320 if (font_old.emph() != font.emph()) {
3321 if (font.emph() == LyXFont::ON) {
3325 os << "</emphasis>";
3330 char c = par->getChar(i);
3332 if (c == Paragraph::META_INSET) {
3333 Inset * inset = par->getInset(i);
3335 inset->docBook(this, ost);
3336 string tmp_out = ost.str().c_str();
3339 // This code needs some explanation:
3340 // Two insets are treated specially
3341 // label if it is the first element in a command paragraph
3343 // graphics inside tables or figure floats can't go on
3344 // title (the equivalente in latex for this case is caption
3345 // and title should come first
3348 if (desc_on!= 3 || i!= 0) {
3349 if (!tmp_out.empty() && tmp_out[0] == '@') {
3351 extra += frontStrip(tmp_out, '@');
3353 os << frontStrip(tmp_out, '@');
3359 } else if (font.latex() == LyXFont::ON) {
3360 // "TeX"-Mode on ==> SGML-Mode on.
3367 if (par->linuxDocConvertChar(c, sgml_string)
3368 && !style.free_spacing) { // in freespacing
3370 // non-breaking characters
3374 os << "\n</term><listitem><para>";
3387 os << "</emphasis>";
3390 // resets description flag correctly
3392 // <term> not closed...
3395 if(style.free_spacing) os << '\n';
3399 // This should be enabled when the Chktex class is implemented. (Asger)
3400 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3401 // Other flags: -wall -v0 -x
3402 int Buffer::runChktex()
3404 if (!users->text) return 0;
3406 users->owner()->prohibitInput();
3408 // get LaTeX-Filename
3409 string const name = getLatexName();
3410 string path = OnlyPath(filename);
3412 string const org_path = path;
3413 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3417 Path p(path); // path to LaTeX file
3418 users->owner()->message(_("Running chktex..."));
3420 // Remove all error insets
3421 bool const removedErrorInsets = users->removeAutoInsets();
3423 // Generate the LaTeX file if neccessary
3424 makeLaTeXFile(name, org_path, false);
3427 Chktex chktex(lyxrc.chktex_command, name, filepath);
3428 int res = chktex.run(terr); // run chktex
3431 WriteAlert(_("chktex did not work!"),
3432 _("Could not run with file:"), name);
3433 } else if (res > 0) {
3434 // Insert all errors as errors boxes
3435 users->insertErrors(terr);
3438 // if we removed error insets before we ran chktex or if we inserted
3439 // error insets after we ran chktex, this must be run:
3440 if (removedErrorInsets || res){
3442 users->fitCursor(users->text);
3444 users->owner()->allowInput();
3450 void Buffer::validate(LaTeXFeatures & features) const
3452 Paragraph * par = paragraph;
3453 LyXTextClass const & tclass =
3454 textclasslist.TextClass(params.textclass);
3456 // AMS Style is at document level
3457 features.amsstyle = (params.use_amsmath ||
3458 tclass.provides(LyXTextClass::amsmath));
3461 // We don't use "lyxerr.debug" because of speed. (Asger)
3462 if (lyxerr.debugging(Debug::LATEX))
3463 lyxerr << "Paragraph: " << par << endl;
3465 // Now just follow the list of paragraphs and run
3466 // validate on each of them.
3467 par->validate(features);
3469 // and then the next paragraph
3473 // the bullet shapes are buffer level not paragraph level
3474 // so they are tested here
3475 for (int i = 0; i < 4; ++i) {
3476 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3477 int const font = params.user_defined_bullets[i].getFont();
3479 int const c = params
3480 .user_defined_bullets[i]
3487 features.latexsym = true;
3489 } else if (font == 1) {
3490 features.amssymb = true;
3491 } else if ((font >= 2 && font <= 5)) {
3492 features.pifont = true;
3497 if (lyxerr.debugging(Debug::LATEX)) {
3498 features.showStruct();
3503 void Buffer::setPaperStuff()
3505 params.papersize = BufferParams::PAPER_DEFAULT;
3506 char const c1 = params.paperpackage;
3507 if (c1 == BufferParams::PACKAGE_NONE) {
3508 char const c2 = params.papersize2;
3509 if (c2 == BufferParams::VM_PAPER_USLETTER)
3510 params.papersize = BufferParams::PAPER_USLETTER;
3511 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3512 params.papersize = BufferParams::PAPER_LEGALPAPER;
3513 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3514 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3515 else if (c2 == BufferParams::VM_PAPER_A3)
3516 params.papersize = BufferParams::PAPER_A3PAPER;
3517 else if (c2 == BufferParams::VM_PAPER_A4)
3518 params.papersize = BufferParams::PAPER_A4PAPER;
3519 else if (c2 == BufferParams::VM_PAPER_A5)
3520 params.papersize = BufferParams::PAPER_A5PAPER;
3521 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3522 (c2 == BufferParams::VM_PAPER_B5))
3523 params.papersize = BufferParams::PAPER_B5PAPER;
3524 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3525 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3526 params.papersize = BufferParams::PAPER_A4PAPER;
3530 // This function should be in Buffer because it's a buffer's property (ale)
3531 string const Buffer::getIncludeonlyList(char delim)
3534 for (inset_iterator it = inset_iterator_begin();
3535 it != inset_iterator_end(); ++it) {
3536 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3537 InsetInclude * insetinc =
3538 static_cast<InsetInclude *>(*it);
3539 if (insetinc->isIncludeOnly()) {
3542 lst += insetinc->getRelFileBaseName();
3546 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3551 vector<string> const Buffer::getLabelList()
3553 /// if this is a child document and the parent is already loaded
3554 /// Use the parent's list instead [ale990407]
3555 if (!params.parentname.empty()
3556 && bufferlist.exists(params.parentname)) {
3557 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3559 return tmp->getLabelList();
3562 vector<string> label_list;
3563 for (inset_iterator it = inset_iterator_begin();
3564 it != inset_iterator_end(); ++it) {
3565 vector<string> const l = (*it)->getLabelList();
3566 label_list.insert(label_list.end(), l.begin(), l.end());
3572 Buffer::Lists const Buffer::getLists() const
3575 Paragraph * par = paragraph;
3577 LyXTextClassList::size_type cap;
3578 boost::tie(found, cap) = textclasslist
3579 .NumberOfLayout(params.textclass, "Caption");
3582 char const labeltype =
3583 textclasslist.Style(params.textclass,
3584 par->getLayout()).labeltype;
3586 if (labeltype >= LABEL_COUNTER_CHAPTER
3587 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3588 // insert this into the table of contents
3589 SingleList & item = l["TOC"];
3592 textclasslist.TextClass(params.textclass).maxcounter());
3593 item.push_back(TocItem(par, depth, par->asString(this, true)));
3595 // For each paragrph, traverse its insets and look for
3599 Paragraph::inset_iterator it =
3600 par->inset_iterator_begin();
3601 Paragraph::inset_iterator end =
3602 par->inset_iterator_end();
3604 for (; it != end; ++it) {
3605 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3607 static_cast<InsetFloat*>(*it);
3609 string const type = il->type();
3611 // Now find the caption in the float...
3612 // We now tranverse the paragraphs of
3614 Paragraph * tmp = il->inset.paragraph();
3616 if (tmp->layout == cap) {
3617 SingleList & item = l[type];
3619 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3620 item.push_back(TocItem(tmp, 0 , str));
3627 lyxerr << "caption not found" << endl;
3636 // This is also a buffer property (ale)
3637 vector<pair<string, string> > const Buffer::getBibkeyList()
3639 /// if this is a child document and the parent is already loaded
3640 /// Use the parent's list instead [ale990412]
3641 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3642 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3644 return tmp->getBibkeyList();
3647 vector<pair<string, string> > keys;
3648 Paragraph * par = paragraph;
3651 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3652 par->asString(this, false)));
3656 // Might be either using bibtex or a child has bibliography
3658 for (inset_iterator it = inset_iterator_begin();
3659 it != inset_iterator_end(); ++it) {
3660 // Search for Bibtex or Include inset
3661 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3662 vector<pair<string,string> > tmp =
3663 static_cast<InsetBibtex*>(*it)->getKeys(this);
3664 keys.insert(keys.end(), tmp.begin(), tmp.end());
3665 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3666 vector<pair<string,string> > const tmp =
3667 static_cast<InsetInclude*>(*it)->getKeys();
3668 keys.insert(keys.end(), tmp.begin(), tmp.end());
3677 bool Buffer::isDepClean(string const & name) const
3679 DEPCLEAN * item = dep_clean;
3680 while (item && item->master != name)
3682 if (!item) return true;
3687 void Buffer::markDepClean(string const & name)
3690 dep_clean = new DEPCLEAN;
3691 dep_clean->clean = true;
3692 dep_clean->master = name;
3693 dep_clean->next = 0;
3695 DEPCLEAN * item = dep_clean;
3696 while (item && item->master != name)
3701 item = new DEPCLEAN;
3703 item->master = name;
3710 bool Buffer::dispatch(string const & command)
3712 // Split command string into command and argument
3714 string line = frontStrip(command);
3715 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3717 return dispatch(lyxaction.LookupFunc(cmd), arg);
3721 bool Buffer::dispatch(int action, string const & argument)
3723 bool dispatched = true;
3726 Exporter::Export(this, argument, false);
3736 void Buffer::resizeInsets(BufferView * bv)
3738 /// then remove all LyXText in text-insets
3739 Paragraph * par = paragraph;
3740 for (; par; par = par->next()) {
3741 par->resizeInsetsLyXText(bv);
3746 void Buffer::redraw()
3749 users->fitCursor(users->text);
3753 void Buffer::changeLanguage(Language const * from, Language const * to)
3756 Paragraph * par = paragraph;
3758 par->changeLanguage(params, from, to);
3764 bool Buffer::isMultiLingual()
3766 Paragraph * par = paragraph;
3768 if (par->isMultiLingual(params))
3776 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3777 Paragraph::size_type pos)
3780 it = par->InsetIterator(pos);
3781 if (it == par->inset_iterator_end()) {
3788 void Buffer::inset_iterator::setParagraph()
3791 it = par->inset_iterator_begin();
3792 if (it != par->inset_iterator_end())
3797 // We maintain an invariant that whenever par = 0 then it = 0
3801 Inset * Buffer::getInsetFromID(int id_arg) const
3803 for (inset_iterator it = inset_const_iterator_begin();
3804 it != inset_const_iterator_end(); ++it)
3806 if ((*it)->id() == id_arg)
3808 Inset * in = (*it)->getInsetFromID(id_arg);
3816 Paragraph * Buffer::getParFromID(int id) const
3818 if (id < 0) return 0;
3819 Paragraph * par = paragraph;
3821 if (par->id() == id) {
3824 Paragraph * tmp = par->getParFromID(id);