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 * ======================================================
18 #include "bufferlist.h"
19 #include "LyXAction.h"
22 #include "tex-strings.h"
24 #include "bufferview_funcs.h"
30 #include "LaTeXFeatures.h"
37 #include "converter.h"
38 #include "BufferView.h"
39 #include "ParagraphParameters.h"
40 #include "iterators.h"
41 #include "lyxtextclasslist.h"
43 #include "paragraph_funcs.h"
46 #include "frontends/LyXView.h"
48 #include "mathed/formulamacro.h"
49 #include "mathed/formula.h"
51 #include "insets/inset.h"
52 #include "insets/inseterror.h"
53 #include "insets/insetlabel.h"
54 #include "insets/insetref.h"
55 #include "insets/inseturl.h"
56 #include "insets/insetnote.h"
57 #include "insets/insetquotes.h"
58 #include "insets/insetlatexaccent.h"
59 #include "insets/insetbib.h"
60 #include "insets/insetcite.h"
61 #include "insets/insetexternal.h"
62 #include "insets/insetindex.h"
63 #include "insets/insetinclude.h"
64 #include "insets/insettoc.h"
65 #include "insets/insetparent.h"
66 #include "insets/insetspecialchar.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetoptarg.h"
73 #include "insets/insetminipage.h"
74 #include "insets/insetfloat.h"
75 #include "insets/insetwrap.h"
76 #include "insets/insettabular.h"
78 #include "insets/insettheorem.h"
79 #include "insets/insetlist.h"
81 #include "insets/insetcaption.h"
82 #include "insets/insetfloatlist.h"
84 #include "frontends/Dialogs.h"
85 #include "frontends/Alert.h"
87 #include "graphics/Previews.h"
89 #include "support/textutils.h"
90 #include "support/filetools.h"
91 #include "support/path.h"
92 #include "support/os.h"
93 #include "support/lyxlib.h"
94 #include "support/FileInfo.h"
95 #include "support/lyxmanip.h"
96 #include "support/lyxalgo.h" // for lyx::count
97 #include "support/lyxtime.h"
99 #include <boost/bind.hpp>
100 #include <boost/tuple/tuple.hpp>
101 #include "BoostFormat.h"
113 #include <sys/types.h>
120 #ifndef CXX_GLOBAL_CSTD
132 using std::make_pair;
142 using lyx::textclass_type;
144 // all these externs should eventually be removed.
145 extern BufferList bufferlist;
149 const int LYX_FORMAT = 222;
153 Buffer::Buffer(string const & file, bool ronly)
154 : niceFile(true), lyx_clean(true), bak_clean(true),
155 unnamed(false), read_only(ronly),
156 filename_(file), users(0)
158 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
159 filepath_ = OnlyPath(file);
161 if (read_only || lyxrc.use_tempdir) {
162 tmppath = CreateBufferTmpDir();
167 // set initial author
168 authorlist.record(Author(lyxrc.user_name, lyxrc.user_email));
174 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
175 // here the buffer should take care that it is
176 // saved properly, before it goes into the void.
178 // make sure that views using this buffer
183 if (!tmppath.empty()) {
184 DestroyBufferTmpDir(tmppath);
189 // Remove any previewed LaTeX snippets assocoated with this buffer.
190 grfx::Previews::get().removeLoader(this);
194 string const Buffer::getLatexName(bool no_path) const
196 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
198 return OnlyFilename(name);
204 pair<Buffer::LogType, string> const Buffer::getLogName() const
206 string const filename = getLatexName(false);
208 if (filename.empty())
209 return make_pair(Buffer::latexlog, string());
211 string path = OnlyPath(filename);
213 if (lyxrc.use_tempdir || !IsDirWriteable(path))
216 string const fname = AddName(path,
217 OnlyFilename(ChangeExtension(filename,
220 AddName(path, OnlyFilename(
221 ChangeExtension(filename,
222 formats.extension("literate") + ".out")));
224 // If no Latex log or Build log is newer, show Build log
226 FileInfo const f_fi(fname);
227 FileInfo const b_fi(bname);
230 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
231 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
232 return make_pair(Buffer::buildlog, bname);
234 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
235 return make_pair(Buffer::latexlog, fname);
239 void Buffer::setReadonly(bool flag)
241 if (read_only != flag) {
244 users->owner()->getDialogs().updateBufferDependent(false);
249 AuthorList & Buffer::authors()
255 /// Update window titles of all users
256 // Should work on a list
257 void Buffer::updateTitles() const
260 users->owner()->updateWindowTitle();
264 /// Reset autosave timer of all users
265 // Should work on a list
266 void Buffer::resetAutosaveTimers() const
269 users->owner()->resetAutosaveTimer();
273 void Buffer::setFileName(string const & newfile)
275 filename_ = MakeAbsPath(newfile);
276 filepath_ = OnlyPath(filename_);
277 setReadonly(IsFileWriteable(filename_) == 0);
282 // We'll remove this later. (Lgb)
285 string last_inset_read;
288 #warning And _why_ is this here? (Lgb)
292 vector<int> author_ids;
297 // candidate for move to BufferView
298 // (at least some parts in the beginning of the func)
301 // changed to be public and have one parameter
302 // if par = 0 normal behavior
303 // else insert behavior
304 // Returns false if "\the_end" is not read (Asger)
305 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
312 Paragraph::depth_type depth = 0;
313 bool the_end_read = false;
315 Paragraph * first_par = 0;
316 LyXFont font(LyXFont::ALL_INHERIT, params.language);
320 par->layout(params.getLyXTextClass().defaultLayout());
322 // We are inserting into an existing document
323 users->text->breakParagraph(users);
324 first_par = users->text->ownerParagraph();
327 // We don't want to adopt the parameters from the
328 // document we insert, so we skip until the text begins:
331 string const pretoken = lex.getString();
332 if (pretoken == "\\layout") {
333 lex.pushToken(pretoken);
341 string const token = lex.getString();
343 if (token.empty()) continue;
345 lyxerr[Debug::PARSER] << "Handling token: `"
346 << token << '\'' << endl;
349 parseSingleLyXformat2Token(lex, par, first_par,
357 paragraphs.set(first_par);
359 if (unknown_layouts > 0) {
360 string s = _("Couldn't set the layout for ");
361 if (unknown_layouts == 1) {
362 s += _("one paragraph");
364 s += tostr(unknown_layouts);
365 s += _(" paragraphs");
368 Alert::alert(_("Textclass Loading Error!"), s,
369 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
371 Alert::alert(_("Textclass Loading Error!"), s,
372 _("When reading ") + fileName());
376 if (unknown_tokens > 0) {
377 string s = _("Encountered ");
378 if (unknown_tokens == 1) {
379 s += _("one unknown token");
381 s += tostr(unknown_tokens);
382 s += _(" unknown tokens");
385 Alert::alert(_("Textclass Loading Error!"), s,
386 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
388 Alert::alert(_("Textclass Loading Error!"), s,
389 _("When reading ") + fileName());
398 // This stuff is, in the traditional LyX terminology, Super UGLY
399 // but this code is too b0rken to admit of a better solution yet
400 Change current_change;
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;
414 // The order of the tags tested may seem unnatural, but this
415 // has been done in order to reduce the number of string
416 // comparisons needed to recognize a given token. This leads
417 // on large documents like UserGuide to a reduction of a
419 if (token[0] != '\\') {
420 for (string::const_iterator cit = token.begin();
421 cit != token.end(); ++cit) {
422 par->insertChar(pos, (*cit), font, current_change);
425 } else if (token == "\\layout") {
426 // reset the font as we start a new layout and if the font is
427 // not ALL_INHERIT,document_language then it will be set to the
428 // right values after this tag (Jug 20020420)
429 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
432 string layoutname = lex.getString();
434 LyXTextClass const & tclass = params.getLyXTextClass();
436 if (layoutname.empty()) {
437 layoutname = tclass.defaultLayoutName();
439 bool hasLayout = tclass.hasLayout(layoutname);
441 lyxerr << "Layout '" << layoutname << "' does not"
442 << " exist in textclass '" << tclass.name()
444 lyxerr << "Trying to use default layout instead."
446 layoutname = tclass.defaultLayoutName();
450 // The is the compability reading of layout caption.
451 // It can be removed in LyX version 1.3.0. (Lgb)
452 if (compare_ascii_no_case(layoutname, "caption") == 0) {
453 // We expect that the par we are now working on is
454 // really inside a InsetText inside a InsetFloat.
455 // We also know that captions can only be
456 // one paragraph. (Lgb)
458 // We should now read until the next "\layout"
460 // This is probably not good enough, what if the
461 // caption is the last par in the document (Lgb)
462 istream & ist = lex.getStream();
468 if (prefixIs(line, "\\layout")) {
472 if (prefixIs(line, "\\begin_inset"))
474 if (prefixIs(line, "\\end_inset")) {
485 // Now we should have the whole layout in ss
486 // we should now be able to give this to the
488 ss << "\\end_inset\n";
490 // This seems like a bug in stringstream.
491 // We really should be able to use ss
493 istringstream is(ss.str());
495 tmplex.setStream(is);
496 Inset * inset = new InsetCaption;
497 inset->Read(this, tmplex);
498 par->InsertInset(pos, inset, font);
505 par = new Paragraph(par);
506 par->layout(params.getLyXTextClass().defaultLayout());
507 if (params.tracking_changes)
511 par->layout(params.getLyXTextClass()[layoutname]);
512 // Test whether the layout is obsolete.
513 LyXLayout_ptr const & layout = par->layout();
514 if (!layout->obsoleted_by().empty())
515 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
516 par->params().depth(depth);
521 } else if (token == "\\end_inset") {
522 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
523 << "Last inset read was: " << last_inset_read
525 // Simply ignore this. The insets do not have
527 // But insets should read it, it is a part of
528 // the inset isn't it? Lgb.
529 } else if (token == "\\begin_inset") {
530 readInset(lex, par, pos, font);
531 } else if (token == "\\family") {
533 font.setLyXFamily(lex.getString());
534 } else if (token == "\\series") {
536 font.setLyXSeries(lex.getString());
537 } else if (token == "\\shape") {
539 font.setLyXShape(lex.getString());
540 } else if (token == "\\size") {
542 font.setLyXSize(lex.getString());
543 } else if (token == "\\lang") {
545 string const tok = lex.getString();
546 Language const * lang = languages.getLanguage(tok);
548 font.setLanguage(lang);
550 font.setLanguage(params.language);
551 lex.printError("Unknown language `$$Token'");
553 } else if (token == "\\numeric") {
555 font.setNumber(font.setLyXMisc(lex.getString()));
556 } else if (token == "\\emph") {
558 font.setEmph(font.setLyXMisc(lex.getString()));
559 } else if (token == "\\bar") {
561 string const tok = lex.getString();
562 // This is dirty, but gone with LyX3. (Asger)
564 font.setUnderbar(LyXFont::ON);
565 else if (tok == "no")
566 font.setUnderbar(LyXFont::OFF);
567 else if (tok == "default")
568 font.setUnderbar(LyXFont::INHERIT);
570 lex.printError("Unknown bar font flag "
572 } else if (token == "\\noun") {
574 font.setNoun(font.setLyXMisc(lex.getString()));
575 } else if (token == "\\color") {
577 font.setLyXColor(lex.getString());
578 } else if (token == "\\SpecialChar") {
579 LyXLayout_ptr const & layout = par->layout();
581 // Insets don't make sense in a free-spacing context! ---Kayvan
582 if (layout->free_spacing || par->isFreeSpacing()) {
585 string const next_token = lex.getString();
586 if (next_token == "\\-") {
587 par->insertChar(pos, '-', font, current_change);
588 } else if (next_token == "~") {
589 par->insertChar(pos, ' ', font, current_change);
591 lex.printError("Token `$$Token' "
593 "paragraph layout!");
598 Inset * inset = new InsetSpecialChar;
599 inset->read(this, lex);
600 par->insertInset(pos, inset, font, current_change);
603 } else if (token == "\\i") {
604 Inset * inset = new InsetLatexAccent;
605 inset->read(this, lex);
606 par->insertInset(pos, inset, font, current_change);
608 } else if (token == "\\backslash") {
609 par->insertChar(pos, '\\', font, current_change);
611 } else if (token == "\\begin_deeper") {
613 } else if (token == "\\end_deeper") {
615 lex.printError("\\end_deeper: "
616 "depth is already null");
620 } else if (token == "\\begin_preamble") {
621 params.readPreamble(lex);
622 } else if (token == "\\textclass") {
624 pair<bool, textclass_type> pp =
625 textclasslist.NumberOfClass(lex.getString());
627 params.textclass = pp.second;
630 Alert::alert(_("Textclass error"),
631 boost::io::str(boost::format(_("The document uses an unknown textclass \"%1$s\".")) % lex.getString()),
632 _("-- substituting default."));
635 _("Textclass error"),
636 _("The document uses an unknown textclass ")
638 _("-- substituting default."));
640 params.textclass = 0;
642 if (!params.getLyXTextClass().load()) {
643 // if the textclass wasn't loaded properly
644 // we need to either substitute another
645 // or stop loading the file.
646 // I can substitute but I don't see how I can
647 // stop loading... ideas?? ARRae980418
649 Alert::alert(_("Textclass Loading Error!"),
650 boost::io::str(boost::format(_("Can't load textclass %1$s")) %
651 params.getLyXTextClass().name()),
652 _("-- substituting default."));
654 Alert::alert(_("Textclass Loading Error!"),
655 _("Can't load textclass ")
656 + params.getLyXTextClass().name(),
657 _("-- substituting default."));
659 params.textclass = 0;
661 } else if (token == "\\options") {
663 params.options = lex.getString();
664 } else if (token == "\\language") {
665 params.readLanguage(lex);
666 } else if (token == "\\fontencoding") {
668 } else if (token == "\\inputencoding") {
670 params.inputenc = lex.getString();
671 } else if (token == "\\graphics") {
672 params.readGraphicsDriver(lex);
673 } else if (token == "\\fontscheme") {
675 params.fonts = lex.getString();
676 } else if (token == "\\noindent") {
677 par->params().noindent(true);
678 } else if (token == "\\leftindent") {
680 LyXLength value(lex.getString());
681 par->params().leftIndent(value);
682 } else if (token == "\\fill_top") {
683 par->params().spaceTop(VSpace(VSpace::VFILL));
684 } else if (token == "\\fill_bottom") {
685 par->params().spaceBottom(VSpace(VSpace::VFILL));
686 } else if (token == "\\line_top") {
687 par->params().lineTop(true);
688 } else if (token == "\\line_bottom") {
689 par->params().lineBottom(true);
690 } else if (token == "\\pagebreak_top") {
691 par->params().pagebreakTop(true);
692 } else if (token == "\\pagebreak_bottom") {
693 par->params().pagebreakBottom(true);
694 } else if (token == "\\start_of_appendix") {
695 par->params().startOfAppendix(true);
696 } else if (token == "\\paragraph_separation") {
697 int tmpret = lex.findToken(string_paragraph_separation);
700 params.paragraph_separation =
701 static_cast<BufferParams::PARSEP>(tmpret);
702 } else if (token == "\\defskip") {
704 params.defskip = VSpace(lex.getString());
705 } else if (token == "\\quotes_language") {
706 int tmpret = lex.findToken(string_quotes_language);
709 InsetQuotes::quote_language tmpl =
710 InsetQuotes::EnglishQ;
713 tmpl = InsetQuotes::EnglishQ;
716 tmpl = InsetQuotes::SwedishQ;
719 tmpl = InsetQuotes::GermanQ;
722 tmpl = InsetQuotes::PolishQ;
725 tmpl = InsetQuotes::FrenchQ;
728 tmpl = InsetQuotes::DanishQ;
731 params.quotes_language = tmpl;
732 } else if (token == "\\quotes_times") {
734 switch (lex.getInteger()) {
736 params.quotes_times = InsetQuotes::SingleQ;
739 params.quotes_times = InsetQuotes::DoubleQ;
742 } else if (token == "\\papersize") {
743 int tmpret = lex.findToken(string_papersize);
747 params.papersize2 = tmpret;
748 } else if (token == "\\paperpackage") {
749 int tmpret = lex.findToken(string_paperpackages);
752 params.paperpackage = BufferParams::PACKAGE_NONE;
754 params.paperpackage = tmpret;
755 } else if (token == "\\use_geometry") {
757 params.use_geometry = lex.getInteger();
758 } else if (token == "\\use_amsmath") {
760 params.use_amsmath = lex.getInteger();
761 } else if (token == "\\use_natbib") {
763 params.use_natbib = lex.getInteger();
764 } else if (token == "\\use_numerical_citations") {
766 params.use_numerical_citations = lex.getInteger();
767 } else if (token == "\\tracking_changes") {
769 params.tracking_changes = lex.getInteger();
770 // mark the first paragraph
771 if (params.tracking_changes)
773 } else if (token == "\\author") {
775 istringstream ss(lex.getString());
778 int aid(authorlist.record(a));
779 lyxerr << "aid is " << aid << endl;
780 lyxerr << "listed aid is " << author_ids.size() << endl;
781 author_ids.push_back(authorlist.record(a));
782 } else if (token == "\\paperorientation") {
783 int tmpret = lex.findToken(string_orientation);
787 static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
788 } else if (token == "\\paperwidth") {
790 params.paperwidth = lex.getString();
791 } else if (token == "\\paperheight") {
793 params.paperheight = lex.getString();
794 } else if (token == "\\leftmargin") {
796 params.leftmargin = lex.getString();
797 } else if (token == "\\topmargin") {
799 params.topmargin = lex.getString();
800 } else if (token == "\\rightmargin") {
802 params.rightmargin = lex.getString();
803 } else if (token == "\\bottommargin") {
805 params.bottommargin = lex.getString();
806 } else if (token == "\\headheight") {
808 params.headheight = lex.getString();
809 } else if (token == "\\headsep") {
811 params.headsep = lex.getString();
812 } else if (token == "\\footskip") {
814 params.footskip = lex.getString();
815 } else if (token == "\\paperfontsize") {
817 params.fontsize = rtrim(lex.getString());
818 } else if (token == "\\papercolumns") {
820 params.columns = lex.getInteger();
821 } else if (token == "\\papersides") {
823 switch (lex.getInteger()) {
825 case 1: params.sides = LyXTextClass::OneSide; break;
826 case 2: params.sides = LyXTextClass::TwoSides; break;
828 } else if (token == "\\paperpagestyle") {
830 params.pagestyle = rtrim(lex.getString());
831 } else if (token == "\\bullet") {
833 int const index = lex.getInteger();
835 int temp_int = lex.getInteger();
836 params.user_defined_bullets[index].setFont(temp_int);
837 params.temp_bullets[index].setFont(temp_int);
839 temp_int = lex.getInteger();
840 params.user_defined_bullets[index].setCharacter(temp_int);
841 params.temp_bullets[index].setCharacter(temp_int);
843 temp_int = lex.getInteger();
844 params.user_defined_bullets[index].setSize(temp_int);
845 params.temp_bullets[index].setSize(temp_int);
847 string const temp_str = lex.getString();
848 if (temp_str != "\\end_bullet") {
849 // this element isn't really necessary for
850 // parsing but is easier for humans
851 // to understand bullets. Put it back and
852 // set a debug message?
853 lex.printError("\\end_bullet expected, got" + temp_str);
854 //how can I put it back?
856 } else if (token == "\\bulletLaTeX") {
857 // The bullet class should be able to read this.
859 int const index = lex.getInteger();
861 string temp_str = lex.getString();
863 while (temp_str != "\\end_bullet") {
864 // this loop structure is needed when user
865 // enters an empty string since the first
866 // thing returned will be the \\end_bullet
868 // if the LaTeX entry has spaces. Each element
869 // therefore needs to be read in turn
872 temp_str = lex.getString();
875 params.user_defined_bullets[index].setText(sum_str);
876 params.temp_bullets[index].setText(sum_str);
877 } else if (token == "\\secnumdepth") {
879 params.secnumdepth = lex.getInteger();
880 } else if (token == "\\tocdepth") {
882 params.tocdepth = lex.getInteger();
883 } else if (token == "\\spacing") {
885 string const tmp = rtrim(lex.getString());
886 Spacing::Space tmp_space = Spacing::Default;
888 if (tmp == "single") {
889 tmp_space = Spacing::Single;
890 } else if (tmp == "onehalf") {
891 tmp_space = Spacing::Onehalf;
892 } else if (tmp == "double") {
893 tmp_space = Spacing::Double;
894 } else if (tmp == "other") {
896 tmp_space = Spacing::Other;
897 tmp_val = lex.getFloat();
899 lex.printError("Unknown spacing token: '$$Token'");
901 // Small hack so that files written with klyx will be
904 par->params().spacing(Spacing(tmp_space, tmp_val));
906 params.spacing.set(tmp_space, tmp_val);
908 } else if (token == "\\paragraph_spacing") {
910 string const tmp = rtrim(lex.getString());
911 if (tmp == "single") {
912 par->params().spacing(Spacing(Spacing::Single));
913 } else if (tmp == "onehalf") {
914 par->params().spacing(Spacing(Spacing::Onehalf));
915 } else if (tmp == "double") {
916 par->params().spacing(Spacing(Spacing::Double));
917 } else if (tmp == "other") {
919 par->params().spacing(Spacing(Spacing::Other,
922 lex.printError("Unknown spacing token: '$$Token'");
924 } else if (token == "\\float_placement") {
926 params.float_placement = lex.getString();
927 } else if (token == "\\align") {
928 int tmpret = lex.findToken(string_align);
929 if (tmpret == -1) ++tmpret;
930 int const tmpret2 = int(pow(2.0, tmpret));
931 par->params().align(LyXAlignment(tmpret2));
932 } else if (token == "\\added_space_top") {
934 VSpace value = VSpace(lex.getString());
935 // only add the length when value > 0 or
937 if ((value.length().len().value() != 0) ||
939 (value.kind() != VSpace::LENGTH))
940 par->params().spaceTop(value);
941 } else if (token == "\\added_space_bottom") {
943 VSpace value = VSpace(lex.getString());
944 // only add the length when value > 0 or
946 if ((value.length().len().value() != 0) ||
948 (value.kind() != VSpace::LENGTH))
949 par->params().spaceBottom(value);
950 } else if (token == "\\labelwidthstring") {
952 par->params().labelWidthString(lex.getString());
953 // do not delete this token, it is still needed!
954 } else if (token == "\\newline") {
955 par->insertChar(pos, Paragraph::META_NEWLINE, font, current_change);
957 } else if (token == "\\LyXTable") {
958 Inset * inset = new InsetTabular(*this);
959 inset->read(this, lex);
960 par->insertInset(pos, inset, font, current_change);
962 } else if (token == "\\hfill") {
963 par->insertChar(pos, Paragraph::META_HFILL, font, current_change);
965 } else if (token == "\\change_unchanged") {
966 // Hack ! Needed for empty paragraphs :/
969 current_change = Change(Change::UNCHANGED);
970 } else if (token == "\\change_inserted") {
972 istringstream istr(lex.getString());
977 current_change = Change(Change::INSERTED, author_ids[aid], ct);
978 } else if (token == "\\change_deleted") {
980 istringstream istr(lex.getString());
985 current_change = Change(Change::DELETED, author_ids[aid], ct);
986 } else if (token == "\\bibitem") { // ale970302
988 InsetCommandParams p("bibitem", "dummy");
989 par->bibkey = new InsetBibKey(p);
991 par->bibkey->read(this, lex);
992 } else if (token == "\\the_end") {
995 // This should be insurance for the future: (Asger)
999 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
1000 fmt % token % lex.text();
1001 string const s = fmt.str();
1003 string const s = _("Unknown token: ") + token
1004 + ' ' + lex.text() + '\n';
1006 // we can do this here this way because we're actually reading
1007 // the buffer and don't care about LyXText right now.
1008 InsetError * new_inset = new InsetError(s);
1009 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1014 return the_end_read;
1018 // needed to insert the selection
1019 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1020 LyXFont const & fn,string const & str) const
1022 LyXLayout_ptr const & layout = par->layout();
1026 par->checkInsertChar(font);
1027 // insert the string, don't insert doublespace
1028 bool space_inserted = true;
1029 bool autobreakrows = !par->inInset() ||
1030 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
1031 for(string::const_iterator cit = str.begin();
1032 cit != str.end(); ++cit) {
1034 if (autobreakrows && (!par->empty() || layout->keepempty)) {
1035 breakParagraph(params, par, pos,
1036 layout->isEnvironment());
1039 space_inserted = true;
1043 // do not insert consecutive spaces if !free_spacing
1044 } else if ((*cit == ' ' || *cit == '\t') &&
1045 space_inserted && !layout->free_spacing &&
1046 !par->isFreeSpacing())
1049 } else if (*cit == '\t') {
1050 if (!layout->free_spacing && !par->isFreeSpacing()) {
1051 // tabs are like spaces here
1052 par->insertChar(pos, ' ', font, current_change);
1054 space_inserted = true;
1056 const pos_type nb = 8 - pos % 8;
1057 for (pos_type a = 0; a < nb ; ++a) {
1058 par->insertChar(pos, ' ', font, current_change);
1061 space_inserted = true;
1063 } else if (!IsPrintable(*cit)) {
1064 // Ignore unprintables
1067 // just insert the character
1068 par->insertChar(pos, *cit, font);
1070 space_inserted = (*cit == ' ');
1077 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1078 int & pos, LyXFont & font)
1080 // consistency check
1081 if (lex.getString() != "\\begin_inset") {
1082 lyxerr << "Buffer::readInset: Consistency check failed."
1089 string const tmptok = lex.getString();
1090 last_inset_read = tmptok;
1092 // test the different insets
1093 if (tmptok == "LatexCommand") {
1094 InsetCommandParams inscmd;
1097 string const cmdName = inscmd.getCmdName();
1099 // This strange command allows LyX to recognize "natbib" style
1100 // citations: citet, citep, Citet etc.
1101 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1102 inset = new InsetCitation(inscmd);
1103 } else if (cmdName == "bibitem") {
1104 lex.printError("Wrong place for bibitem");
1105 inset = new InsetBibKey(inscmd);
1106 } else if (cmdName == "BibTeX") {
1107 inset = new InsetBibtex(inscmd);
1108 } else if (cmdName == "index") {
1109 inset = new InsetIndex(inscmd);
1110 } else if (cmdName == "include") {
1111 inset = new InsetInclude(inscmd, *this);
1112 } else if (cmdName == "label") {
1113 inset = new InsetLabel(inscmd);
1114 } else if (cmdName == "url"
1115 || cmdName == "htmlurl") {
1116 inset = new InsetUrl(inscmd);
1117 } else if (cmdName == "ref"
1118 || cmdName == "pageref"
1119 || cmdName == "vref"
1120 || cmdName == "vpageref"
1121 || cmdName == "prettyref") {
1122 if (!inscmd.getOptions().empty()
1123 || !inscmd.getContents().empty()) {
1124 inset = new InsetRef(inscmd, *this);
1126 } else if (cmdName == "tableofcontents") {
1127 inset = new InsetTOC(inscmd);
1128 } else if (cmdName == "listofalgorithms") {
1129 inset = new InsetFloatList("algorithm");
1130 } else if (cmdName == "listoffigures") {
1131 inset = new InsetFloatList("figure");
1132 } else if (cmdName == "listoftables") {
1133 inset = new InsetFloatList("table");
1134 } else if (cmdName == "printindex") {
1135 inset = new InsetPrintIndex(inscmd);
1136 } else if (cmdName == "lyxparent") {
1137 inset = new InsetParent(inscmd, *this);
1140 bool alreadyread = false;
1141 if (tmptok == "Quotes") {
1142 inset = new InsetQuotes;
1143 } else if (tmptok == "External") {
1144 inset = new InsetExternal;
1145 } else if (tmptok == "FormulaMacro") {
1146 inset = new InsetFormulaMacro;
1147 } else if (tmptok == "Formula") {
1148 inset = new InsetFormula;
1149 } else if (tmptok == "Figure") { // Backward compatibility
1150 // inset = new InsetFig(100, 100, *this);
1151 inset = new InsetGraphics;
1152 } else if (tmptok == "Graphics") {
1153 inset = new InsetGraphics;
1154 } else if (tmptok == "Info") {// backwards compatibility
1155 inset = new InsetNote(this,
1156 lex.getLongString("\\end_inset"),
1159 } else if (tmptok == "Note") {
1160 inset = new InsetNote(params);
1161 } else if (tmptok == "Include") {
1162 InsetCommandParams p("Include");
1163 inset = new InsetInclude(p, *this);
1164 } else if (tmptok == "ERT") {
1165 inset = new InsetERT(params);
1166 } else if (tmptok == "Tabular") {
1167 inset = new InsetTabular(*this);
1168 } else if (tmptok == "Text") {
1169 inset = new InsetText(params);
1170 } else if (tmptok == "Foot") {
1171 inset = new InsetFoot(params);
1172 } else if (tmptok == "Marginal") {
1173 inset = new InsetMarginal(params);
1174 } else if (tmptok == "OptArg") {
1175 inset = new InsetOptArg(params);
1176 } else if (tmptok == "Minipage") {
1177 inset = new InsetMinipage(params);
1178 } else if (tmptok == "Float") {
1180 string tmptok = lex.getString();
1181 inset = new InsetFloat(params, tmptok);
1182 } else if (tmptok == "Wrap") {
1184 string tmptok = lex.getString();
1185 inset = new InsetWrap(params, tmptok);
1187 } else if (tmptok == "List") {
1188 inset = new InsetList;
1189 } else if (tmptok == "Theorem") {
1190 inset = new InsetList;
1192 } else if (tmptok == "Caption") {
1193 inset = new InsetCaption(params);
1194 } else if (tmptok == "FloatList") {
1195 inset = new InsetFloatList;
1198 if (inset && !alreadyread) inset->read(this, lex);
1202 par->insertInset(pos, inset, font, current_change);
1208 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
1212 string const token(lex.getString());
1213 if (token == "\\lyxformat") { // the first token _must_ be...
1215 string tmp_format = lex.getString();
1216 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
1217 // if present remove ".," from string.
1218 string::size_type dot = tmp_format.find_first_of(".,");
1219 //lyxerr << " dot found at " << dot << endl;
1220 if (dot != string::npos)
1221 tmp_format.erase(dot, 1);
1222 file_format = strToInt(tmp_format);
1223 //lyxerr << "format: " << file_format << endl;
1224 if (file_format == LYX_FORMAT) {
1226 } else if (file_format > LYX_FORMAT) {
1228 Alert::alert(_("Warning!"),
1229 _("The file was created with a newer version of "
1230 "LyX. This is likely to cause problems."));
1232 } else if (file_format < LYX_FORMAT) {
1234 if (file_format < 200) {
1235 Alert::alert(_("ERROR!"),
1236 _("Old LyX file format found. "
1237 "Use LyX 0.10.x to read this!"));
1239 } else if (!filename.empty()) {
1241 LibFileSearch("lyx2lyx", "lyx2lyx");
1242 if (command.empty()) {
1243 Alert::alert(_("ERROR!"),
1244 _("Can't find conversion script."));
1248 +tostr(LYX_FORMAT) + ' '
1249 + QuoteName(filename);
1250 lyxerr[Debug::INFO] << "Running '"
1253 cmd_ret const ret = RunCommand(command);
1255 Alert::alert(_("ERROR!"),
1256 _("An error occured while "
1257 "running the conversion script."));
1260 istringstream is(STRCONV(ret.second));
1261 LyXLex tmplex(0, 0);
1262 tmplex.setStream(is);
1263 return readFile(tmplex, string(), par);
1265 // This code is reached if lyx2lyx failed (for
1266 // some reason) to change the file format of
1272 bool the_end = readLyXformat2(lex, par);
1273 params.setPaperStuff();
1276 Alert::alert(_("Warning!"),
1277 _("Reading of document is not complete"),
1278 _("Maybe the document is truncated"));
1281 } else { // "\\lyxformat" not found
1282 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1285 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1290 // Should probably be moved to somewhere else: BufferView? LyXView?
1291 bool Buffer::save() const
1293 // We don't need autosaves in the immediate future. (Asger)
1294 resetAutosaveTimers();
1298 if (lyxrc.make_backup) {
1299 s = fileName() + '~';
1300 if (!lyxrc.backupdir_path.empty())
1301 s = AddName(lyxrc.backupdir_path,
1302 subst(os::slashify_path(s),'/','!'));
1304 // Rename is the wrong way of making a backup,
1305 // this is the correct way.
1306 /* truss cp fil fil2:
1307 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1308 stat("LyXVC.lyx", 0xEFFFF688) = 0
1309 open("LyXVC.lyx", O_RDONLY) = 3
1310 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1311 fstat(4, 0xEFFFF508) = 0
1312 fstat(3, 0xEFFFF508) = 0
1313 read(3, " # T h i s f i l e w".., 8192) = 5579
1314 write(4, " # T h i s f i l e w".., 5579) = 5579
1315 read(3, 0xEFFFD4A0, 8192) = 0
1318 chmod("LyXVC3.lyx", 0100644) = 0
1319 lseek(0, 0, SEEK_CUR) = 46440
1323 // Should probably have some more error checking here.
1324 // Doing it this way, also makes the inodes stay the same.
1325 // This is still not a very good solution, in particular we
1326 // might loose the owner of the backup.
1327 FileInfo finfo(fileName());
1328 if (finfo.exist()) {
1329 mode_t fmode = finfo.getMode();
1330 struct utimbuf times = {
1331 finfo.getAccessTime(),
1332 finfo.getModificationTime() };
1334 ifstream ifs(fileName().c_str());
1335 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1340 ::chmod(s.c_str(), fmode);
1342 if (::utime(s.c_str(), ×)) {
1343 lyxerr << "utime error." << endl;
1346 lyxerr << "LyX was not able to make "
1347 "backup copy. Beware." << endl;
1352 if (writeFile(fileName())) {
1354 removeAutosaveFile(fileName());
1356 // Saving failed, so backup is not backup
1357 if (lyxrc.make_backup) {
1358 lyx::rename(s, fileName());
1366 bool Buffer::writeFile(string const & fname) const
1368 if (read_only && (fname == fileName())) {
1372 FileInfo finfo(fname);
1373 if (finfo.exist() && !finfo.writable()) {
1377 ofstream ofs(fname.c_str());
1383 // Use the standard "C" locale for file output.
1384 ofs.imbue(std::locale::classic());
1387 // The top of the file should not be written by params.
1389 // write out a comment in the top of the file
1390 ofs << '#' << lyx_docversion
1391 << " created this file. For more info see http://www.lyx.org/\n"
1392 << "\\lyxformat " << LYX_FORMAT << "\n";
1394 // now write out the buffer paramters.
1395 params.writeFile(ofs);
1397 // if we're tracking, list all possible authors
1398 if (params.tracking_changes) {
1399 AuthorList::Authors::const_iterator it = authorlist.begin();
1400 AuthorList::Authors::const_iterator end = authorlist.end();
1401 for (; it != end; ++it) {
1402 ofs << "\\author " << it->second << "\n";
1406 Paragraph::depth_type depth = 0;
1408 // this will write out all the paragraphs
1409 // using recursive descent.
1410 ParagraphList::iterator pit = paragraphs.begin();
1411 ParagraphList::iterator pend = paragraphs.end();
1412 for (; pit != pend; ++pit)
1413 pit->write(this, ofs, params, depth);
1415 // Write marker that shows file is complete
1416 ofs << "\n\\the_end" << endl;
1420 // how to check if close went ok?
1421 // Following is an attempt... (BE 20001011)
1423 // good() returns false if any error occured, including some
1424 // formatting error.
1425 // bad() returns true if something bad happened in the buffer,
1426 // which should include file system full errors.
1433 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1435 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1447 pair<int, string> const addDepth(int depth, int ldepth)
1451 d += (ldepth - depth) * 2;
1452 return make_pair(d, string(d, ' '));
1458 string const Buffer::asciiParagraph(Paragraph const & par,
1459 unsigned int linelen,
1460 bool noparbreak) const
1462 ostringstream buffer;
1463 Paragraph::depth_type depth = 0;
1465 Paragraph::depth_type ltype_depth = 0;
1466 bool ref_printed = false;
1467 // if (!par->previous()) {
1469 // begins or ends a deeper area ?
1470 if (depth != par->params().depth()) {
1471 if (par->params().depth() > depth) {
1472 while (par->params().depth() > depth) {
1476 while (par->params().depth() < depth) {
1482 depth = par.params().depth();
1485 // First write the layout
1486 string const & tmp = par.layout()->name();
1487 if (compare_no_case(tmp, "itemize") == 0) {
1489 ltype_depth = depth + 1;
1490 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1492 ltype_depth = depth + 1;
1493 } else if (contains(ascii_lowercase(tmp), "ection")) {
1495 ltype_depth = depth + 1;
1496 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1498 ltype_depth = depth + 1;
1499 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1501 ltype_depth = depth + 1;
1502 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1505 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1513 /* maybe some vertical spaces */
1515 /* the labelwidthstring used in lists */
1519 /* some pagebreaks? */
1523 /* what about the alignment */
1525 // lyxerr << "Should this ever happen?" << endl;
1528 // linelen <= 0 is special and means we don't have paragraph breaks
1530 string::size_type currlinelen = 0;
1536 buffer << string(depth * 2, ' ');
1537 currlinelen += depth * 2;
1540 // we should probably change to the paragraph language in the
1541 // gettext here (if possible) so that strings are outputted in
1542 // the correct language! (20012712 Jug)
1546 case 4: // (Sub)Paragraph
1547 case 5: // Description
1551 buffer << _("Abstract") << "\n\n";
1554 string const abst = _("Abstract: ");
1556 currlinelen += abst.length();
1559 case 7: // Bibliography
1562 buffer << _("References") << "\n\n";
1565 string const refs = _("References: ");
1567 currlinelen += refs.length();
1575 string const parlab = par.params().labelString();
1576 buffer << parlab << ' ';
1577 currlinelen += parlab.length() + 1;
1585 pair<int, string> p = addDepth(depth, ltype_depth);
1587 currlinelen += p.first;
1590 // this is to change the linebreak to do it by word a bit more
1591 // intelligent hopefully! (only in the case where we have a
1592 // max linelenght!) (Jug)
1596 for (pos_type i = 0; i < par.size(); ++i) {
1597 char c = par.getUChar(params, i);
1599 case Paragraph::META_INSET:
1601 Inset const * inset = par.getInset(i);
1605 currlinelen += word.length();
1608 if (inset->ascii(this, buffer, linelen)) {
1609 // to be sure it breaks paragraph
1610 currlinelen += linelen;
1616 case Paragraph::META_NEWLINE:
1618 buffer << word << "\n";
1621 pair<int, string> p = addDepth(depth,
1624 currlinelen = p.first;
1628 case Paragraph::META_HFILL:
1629 buffer << word << "\t";
1630 currlinelen += word.length() + 1;
1637 currlinelen + word.length() > linelen - 10) {
1639 pair<int, string> p =
1640 addDepth(depth, ltype_depth);
1642 currlinelen = p.first;
1645 buffer << word << ' ';
1646 currlinelen += word.length() + 1;
1653 lyxerr[Debug::INFO] <<
1654 "writeAsciiFile: NULL char in structure." << endl;
1656 if ((linelen > 0) &&
1657 (currlinelen + word.length()) > linelen)
1661 pair<int, string> p =
1662 addDepth(depth, ltype_depth);
1664 currlinelen = p.first;
1671 return STRCONV(buffer.str());
1675 void Buffer::writeFileAscii(string const & fname, int linelen)
1677 ofstream ofs(fname.c_str());
1679 Alert::err_alert(_("Error: Cannot write file:"), fname);
1682 writeFileAscii(ofs, linelen);
1686 void Buffer::writeFileAscii(ostream & os, int linelen)
1688 ParagraphList::iterator beg = paragraphs.begin();
1689 ParagraphList::iterator end = paragraphs.end();
1690 ParagraphList::iterator it = beg;
1691 for (; it != end; ++it) {
1692 os << asciiParagraph(*it, linelen, it == beg);
1701 void Buffer::makeLaTeXFile(string const & fname,
1702 string const & original_path,
1703 bool nice, bool only_body, bool only_preamble)
1705 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1707 ofstream ofs(fname.c_str());
1709 Alert::err_alert(_("Error: Cannot open file: "), fname);
1713 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1717 lyxerr << "File was not closed properly." << endl;
1722 void Buffer::makeLaTeXFile(ostream & os,
1723 string const & original_path,
1724 bool nice, bool only_body, bool only_preamble)
1726 niceFile = nice; // this will be used by Insetincludes.
1728 // validate the buffer.
1729 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1730 LaTeXFeatures features(params);
1732 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1735 // The starting paragraph of the coming rows is the
1736 // first paragraph of the document. (Asger)
1737 texrow.start(&*(paragraphs.begin()), 0);
1739 if (!only_body && nice) {
1740 os << "%% " << lyx_docversion << " created this file. "
1741 "For more info, see http://www.lyx.org/.\n"
1742 "%% Do not edit unless you really know what "
1747 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1748 // There are a few differences between nice LaTeX and usual files:
1749 // usual is \batchmode and has a
1750 // special input@path to allow the including of figures
1751 // with either \input or \includegraphics (what figinsets do).
1752 // input@path is set when the actual parameter
1753 // original_path is set. This is done for usual tex-file, but not
1754 // for nice-latex-file. (Matthias 250696)
1757 // code for usual, NOT nice-latex-file
1758 os << "\\batchmode\n"; // changed
1759 // from \nonstopmode
1762 if (!original_path.empty()) {
1763 string inputpath = os::external_path(original_path);
1764 subst(inputpath, "~", "\\string~");
1765 os << "\\makeatletter\n"
1766 << "\\def\\input@path{{"
1767 << inputpath << "/}}\n"
1768 << "\\makeatother\n";
1774 os << "\\documentclass";
1776 LyXTextClass const & tclass = params.getLyXTextClass();
1778 ostringstream options; // the document class options.
1780 if (tokenPos(tclass.opt_fontsize(),
1781 '|', params.fontsize) >= 0) {
1782 // only write if existing in list (and not default)
1783 options << params.fontsize << "pt,";
1787 if (!params.use_geometry &&
1788 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1789 switch (params.papersize) {
1790 case BufferParams::PAPER_A4PAPER:
1791 options << "a4paper,";
1793 case BufferParams::PAPER_USLETTER:
1794 options << "letterpaper,";
1796 case BufferParams::PAPER_A5PAPER:
1797 options << "a5paper,";
1799 case BufferParams::PAPER_B5PAPER:
1800 options << "b5paper,";
1802 case BufferParams::PAPER_EXECUTIVEPAPER:
1803 options << "executivepaper,";
1805 case BufferParams::PAPER_LEGALPAPER:
1806 options << "legalpaper,";
1812 if (params.sides != tclass.sides()) {
1813 switch (params.sides) {
1814 case LyXTextClass::OneSide:
1815 options << "oneside,";
1817 case LyXTextClass::TwoSides:
1818 options << "twoside,";
1824 if (params.columns != tclass.columns()) {
1825 if (params.columns == 2)
1826 options << "twocolumn,";
1828 options << "onecolumn,";
1831 if (!params.use_geometry
1832 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1833 options << "landscape,";
1835 // language should be a parameter to \documentclass
1837 ostringstream language_options;
1838 if (params.language->babel() == "hebrew"
1839 && default_language->babel() != "hebrew")
1840 // This seems necessary
1841 features.useLanguage(default_language);
1843 if (lyxrc.language_use_babel ||
1844 params.language->lang() != lyxrc.default_language ||
1845 features.hasLanguages()) {
1847 language_options << features.getLanguages();
1848 language_options << params.language->babel();
1849 if (lyxrc.language_global_options)
1850 options << language_options.str() << ',';
1853 // the user-defined options
1854 if (!params.options.empty()) {
1855 options << params.options << ',';
1858 string strOptions(STRCONV(options.str()));
1859 if (!strOptions.empty()) {
1860 strOptions = rtrim(strOptions, ",");
1861 os << '[' << strOptions << ']';
1864 os << '{' << tclass.latexname() << "}\n";
1866 // end of \documentclass defs
1868 // font selection must be done before loading fontenc.sty
1869 // The ae package is not needed when using OT1 font encoding.
1870 if (params.fonts != "default" &&
1871 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1872 os << "\\usepackage{" << params.fonts << "}\n";
1874 if (params.fonts == "ae") {
1875 os << "\\usepackage{aecompl}\n";
1879 // this one is not per buffer
1880 if (lyxrc.fontenc != "default") {
1881 os << "\\usepackage[" << lyxrc.fontenc
1886 if (params.inputenc == "auto") {
1887 string const doc_encoding =
1888 params.language->encoding()->LatexName();
1890 // Create a list with all the input encodings used
1892 set<string> encodings = features.getEncodingSet(doc_encoding);
1894 os << "\\usepackage[";
1895 std::copy(encodings.begin(), encodings.end(),
1896 std::ostream_iterator<string>(os, ","));
1897 os << doc_encoding << "]{inputenc}\n";
1899 } else if (params.inputenc != "default") {
1900 os << "\\usepackage[" << params.inputenc
1905 // At the very beginning the text parameters.
1906 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1907 switch (params.paperpackage) {
1908 case BufferParams::PACKAGE_A4:
1909 os << "\\usepackage{a4}\n";
1912 case BufferParams::PACKAGE_A4WIDE:
1913 os << "\\usepackage{a4wide}\n";
1916 case BufferParams::PACKAGE_WIDEMARGINSA4:
1917 os << "\\usepackage[widemargins]{a4}\n";
1922 if (params.use_geometry) {
1923 os << "\\usepackage{geometry}\n";
1925 os << "\\geometry{verbose";
1926 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1928 switch (params.papersize2) {
1929 case BufferParams::VM_PAPER_CUSTOM:
1930 if (!params.paperwidth.empty())
1931 os << ",paperwidth="
1932 << params.paperwidth;
1933 if (!params.paperheight.empty())
1934 os << ",paperheight="
1935 << params.paperheight;
1937 case BufferParams::VM_PAPER_USLETTER:
1938 os << ",letterpaper";
1940 case BufferParams::VM_PAPER_USLEGAL:
1941 os << ",legalpaper";
1943 case BufferParams::VM_PAPER_USEXECUTIVE:
1944 os << ",executivepaper";
1946 case BufferParams::VM_PAPER_A3:
1949 case BufferParams::VM_PAPER_A4:
1952 case BufferParams::VM_PAPER_A5:
1955 case BufferParams::VM_PAPER_B3:
1958 case BufferParams::VM_PAPER_B4:
1961 case BufferParams::VM_PAPER_B5:
1965 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1966 switch (lyxrc.default_papersize) {
1967 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1968 case BufferParams::PAPER_USLETTER:
1969 os << ",letterpaper";
1971 case BufferParams::PAPER_LEGALPAPER:
1972 os << ",legalpaper";
1974 case BufferParams::PAPER_EXECUTIVEPAPER:
1975 os << ",executivepaper";
1977 case BufferParams::PAPER_A3PAPER:
1980 case BufferParams::PAPER_A4PAPER:
1983 case BufferParams::PAPER_A5PAPER:
1986 case BufferParams::PAPER_B5PAPER:
1991 if (!params.topmargin.empty())
1992 os << ",tmargin=" << params.topmargin;
1993 if (!params.bottommargin.empty())
1994 os << ",bmargin=" << params.bottommargin;
1995 if (!params.leftmargin.empty())
1996 os << ",lmargin=" << params.leftmargin;
1997 if (!params.rightmargin.empty())
1998 os << ",rmargin=" << params.rightmargin;
1999 if (!params.headheight.empty())
2000 os << ",headheight=" << params.headheight;
2001 if (!params.headsep.empty())
2002 os << ",headsep=" << params.headsep;
2003 if (!params.footskip.empty())
2004 os << ",footskip=" << params.footskip;
2009 if (tokenPos(tclass.opt_pagestyle(),
2010 '|', params.pagestyle) >= 0) {
2011 if (params.pagestyle == "fancy") {
2012 os << "\\usepackage{fancyhdr}\n";
2015 os << "\\pagestyle{" << params.pagestyle << "}\n";
2019 if (params.secnumdepth != tclass.secnumdepth()) {
2020 os << "\\setcounter{secnumdepth}{"
2021 << params.secnumdepth
2025 if (params.tocdepth != tclass.tocdepth()) {
2026 os << "\\setcounter{tocdepth}{"
2032 if (params.paragraph_separation) {
2033 switch (params.defskip.kind()) {
2034 case VSpace::SMALLSKIP:
2035 os << "\\setlength\\parskip{\\smallskipamount}\n";
2037 case VSpace::MEDSKIP:
2038 os << "\\setlength\\parskip{\\medskipamount}\n";
2040 case VSpace::BIGSKIP:
2041 os << "\\setlength\\parskip{\\bigskipamount}\n";
2043 case VSpace::LENGTH:
2044 os << "\\setlength\\parskip{"
2045 << params.defskip.length().asLatexString()
2048 default: // should never happen // Then delete it.
2049 os << "\\setlength\\parskip{\\medskipamount}\n";
2054 os << "\\setlength\\parindent{0pt}\n";
2058 // Now insert the LyX specific LaTeX commands...
2060 // The optional packages;
2061 string preamble(features.getPackages());
2063 // this might be useful...
2064 preamble += "\n\\makeatletter\n";
2066 // Some macros LyX will need
2067 string tmppreamble(features.getMacros());
2069 if (!tmppreamble.empty()) {
2070 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2071 "LyX specific LaTeX commands.\n"
2072 + tmppreamble + '\n';
2075 // the text class specific preamble
2076 tmppreamble = features.getTClassPreamble();
2077 if (!tmppreamble.empty()) {
2078 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2079 "Textclass specific LaTeX commands.\n"
2080 + tmppreamble + '\n';
2083 /* the user-defined preamble */
2084 if (!params.preamble.empty()) {
2085 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2086 "User specified LaTeX commands.\n"
2087 + params.preamble + '\n';
2090 // Itemize bullet settings need to be last in case the user
2091 // defines their own bullets that use a package included
2092 // in the user-defined preamble -- ARRae
2093 // Actually it has to be done much later than that
2094 // since some packages like frenchb make modifications
2095 // at \begin{document} time -- JMarc
2097 for (int i = 0; i < 4; ++i) {
2098 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2099 if (bullets_def.empty())
2100 bullets_def="\\AtBeginDocument{\n";
2101 bullets_def += " \\renewcommand{\\labelitemi";
2103 // `i' is one less than the item to modify
2110 bullets_def += "ii";
2116 bullets_def += "}{" +
2117 params.user_defined_bullets[i].getText()
2122 if (!bullets_def.empty())
2123 preamble += bullets_def + "}\n\n";
2126 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2127 for (int j = 0; j != nlines; ++j) {
2131 // We try to load babel late, in case it interferes
2132 // with other packages.
2134 string tmp = lyxrc.language_package;
2135 if (!lyxrc.language_global_options
2136 && tmp == "\\usepackage{babel}")
2137 tmp = string("\\usepackage[") +
2138 STRCONV(language_options.str()) +
2140 preamble += tmp + "\n";
2141 preamble += features.getBabelOptions();
2144 preamble += "\\makeatother\n";
2146 // dvipost settings come after everything else
2147 if (params.tracking_changes) {
2148 preamble += "\\dvipostlayout\n";
2149 preamble += "\\dvipost{osstart color push Red}\n";
2150 preamble += "\\dvipost{osend color pop}\n";
2151 preamble += "\\dvipost{cbstart color push Blue}\n";
2152 preamble += "\\dvipost{cbend color pop} \n";
2161 os << "\\begin{document}\n";
2164 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2166 if (!lyxrc.language_auto_begin) {
2167 os << subst(lyxrc.language_command_begin, "$$lang",
2168 params.language->babel())
2173 latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2175 // add this just in case after all the paragraphs
2179 if (!lyxrc.language_auto_end) {
2180 os << subst(lyxrc.language_command_end, "$$lang",
2181 params.language->babel())
2187 os << "\\end{document}\n";
2190 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2192 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2196 // Just to be sure. (Asger)
2199 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
2200 lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
2203 // we want this to be true outside previews (for insetexternal)
2209 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2211 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2212 Paragraph * endpar, TexRow & texrow,
2213 bool moving_arg) const
2215 bool was_title = false;
2216 bool already_title = false;
2217 LyXTextClass const & tclass = params.getLyXTextClass();
2220 while (par != endpar) {
2221 Inset * in = par->inInset();
2222 // well we have to check if we are in an inset with unlimited
2223 // length (all in one row) if that is true then we don't allow
2224 // any special options in the paragraph and also we don't allow
2225 // any environment other then "Standard" to be valid!
2226 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2227 LyXLayout_ptr const & layout = par->layout();
2229 if (layout->intitle) {
2230 if (already_title) {
2231 lyxerr <<"Error in latexParagraphs: You"
2232 " should not mix title layouts"
2233 " with normal ones." << endl;
2234 } else if (!was_title) {
2236 if (tclass.titletype() == TITLE_ENVIRONMENT) {
2238 << tclass.titlename()
2243 } else if (was_title && !already_title) {
2244 if (tclass.titletype() == TITLE_ENVIRONMENT) {
2245 ofs << "\\end{" << tclass.titlename()
2249 ofs << "\\" << tclass.titlename()
2253 already_title = true;
2257 if (layout->isEnvironment() ||
2258 !par->params().leftIndent().zero())
2260 par = par->TeXEnvironment(this, params, ofs, texrow);
2262 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2265 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2268 // It might be that we only have a title in this document
2269 if (was_title && !already_title) {
2270 if (tclass.titletype() == TITLE_ENVIRONMENT) {
2271 ofs << "\\end{" << tclass.titlename()
2275 ofs << "\\" << tclass.titlename()
2283 bool Buffer::isLatex() const
2285 return params.getLyXTextClass().outputType() == LATEX;
2289 bool Buffer::isLinuxDoc() const
2291 return params.getLyXTextClass().outputType() == LINUXDOC;
2295 bool Buffer::isLiterate() const
2297 return params.getLyXTextClass().outputType() == LITERATE;
2301 bool Buffer::isDocBook() const
2303 return params.getLyXTextClass().outputType() == DOCBOOK;
2307 bool Buffer::isSGML() const
2309 LyXTextClass const & tclass = params.getLyXTextClass();
2311 return tclass.outputType() == LINUXDOC ||
2312 tclass.outputType() == DOCBOOK;
2316 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2318 ofstream ofs(fname.c_str());
2321 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2325 niceFile = nice; // this will be used by included files.
2327 LaTeXFeatures features(params);
2333 LyXTextClass const & tclass = params.getLyXTextClass();
2335 string top_element = tclass.latexname();
2338 ofs << "<!doctype linuxdoc system";
2340 string preamble = params.preamble;
2341 const string name = nice ? ChangeExtension(filename_, ".sgml")
2343 preamble += features.getIncludedFiles(name);
2344 preamble += features.getLyXSGMLEntities();
2346 if (!preamble.empty()) {
2347 ofs << " [ " << preamble << " ]";
2351 if (params.options.empty())
2352 sgml::openTag(ofs, 0, false, top_element);
2354 string top = top_element;
2356 top += params.options;
2357 sgml::openTag(ofs, 0, false, top);
2361 ofs << "<!-- " << lyx_docversion
2362 << " created this file. For more info see http://www.lyx.org/"
2365 Paragraph::depth_type depth = 0; // paragraph depth
2366 Paragraph * par = &*(paragraphs.begin());
2368 vector<string> environment_stack(5);
2371 LyXLayout_ptr const & style = par->layout();
2372 // treat <toc> as a special case for compatibility with old code
2373 if (par->isInset(0)) {
2374 Inset * inset = par->getInset(0);
2375 Inset::Code lyx_code = inset->lyxCode();
2376 if (lyx_code == Inset::TOC_CODE) {
2377 string const temp = "toc";
2378 sgml::openTag(ofs, depth, false, temp);
2385 // environment tag closing
2386 for (; depth > par->params().depth(); --depth) {
2387 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2388 environment_stack[depth].erase();
2391 // write opening SGML tags
2392 switch (style->latextype) {
2393 case LATEX_PARAGRAPH:
2394 if (depth == par->params().depth()
2395 && !environment_stack[depth].empty()) {
2396 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2397 environment_stack[depth].erase();
2403 sgml::openTag(ofs, depth, false, style->latexname());
2409 _("Error: Wrong depth for LatexType Command.\n"));
2411 if (!environment_stack[depth].empty()) {
2412 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2416 environment_stack[depth].erase();
2417 sgml::openTag(ofs, depth, false, style->latexname());
2420 case LATEX_ENVIRONMENT:
2421 case LATEX_ITEM_ENVIRONMENT:
2423 string const & latexname = style->latexname();
2425 if (depth == par->params().depth()
2426 && environment_stack[depth] != latexname) {
2427 sgml::closeTag(ofs, depth, false,
2428 environment_stack[depth]);
2429 environment_stack[depth].erase();
2431 if (depth < par->params().depth()) {
2432 depth = par->params().depth();
2433 environment_stack[depth].erase();
2435 if (environment_stack[depth] != latexname) {
2437 sgml::openTag(ofs, depth, false, "p");
2439 sgml::openTag(ofs, depth, false, latexname);
2441 if (environment_stack.size() == depth + 1)
2442 environment_stack.push_back("!-- --");
2443 environment_stack[depth] = latexname;
2446 if (style->latexparam() == "CDATA")
2449 if (style->latextype == LATEX_ENVIRONMENT) break;
2451 if (style->labeltype == LABEL_MANUAL)
2456 sgml::openTag(ofs, depth + 1, false, item_name);
2461 sgml::openTag(ofs, depth, false, style->latexname());
2465 simpleLinuxDocOnePar(ofs, par, depth);
2470 // write closing SGML tags
2471 switch (style->latextype) {
2474 case LATEX_ENVIRONMENT:
2475 case LATEX_ITEM_ENVIRONMENT:
2476 if (style->latexparam() == "CDATA")
2480 sgml::closeTag(ofs, depth, false, style->latexname());
2486 for (int i = depth; i >= 0; --i)
2487 sgml::closeTag(ofs, depth, false, environment_stack[i]);
2491 sgml::closeTag(ofs, 0, false, top_element);
2495 // How to check for successful close
2497 // we want this to be true outside previews (for insetexternal)
2502 // checks, if newcol chars should be put into this line
2503 // writes newline, if necessary.
2506 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2507 string::size_type newcol)
2510 if (colcount > lyxrc.ascii_linelen) {
2512 colcount = newcol; // assume write after this call
2527 string tag_name(PAR_TAG const & pt) {
2529 case NONE: return "!-- --";
2530 case TT: return "tt";
2531 case SF: return "sf";
2532 case BF: return "bf";
2533 case IT: return "it";
2534 case SL: return "sl";
2535 case EM: return "em";
2542 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2544 p1 = static_cast<PAR_TAG>(p1 | p2);
2549 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2551 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2557 // Handle internal paragraph parsing -- layout already processed.
2558 void Buffer::simpleLinuxDocOnePar(ostream & os,
2560 Paragraph::depth_type /*depth*/)
2562 LyXLayout_ptr const & style = par->layout();
2564 string::size_type char_line_count = 5; // Heuristic choice ;-)
2566 // gets paragraph main font
2569 if (style->labeltype == LABEL_MANUAL) {
2570 font_old = style->labelfont;
2573 font_old = style->font;
2577 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2578 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2579 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2582 stack<PAR_TAG> tag_state;
2583 // parsing main loop
2584 for (pos_type i = 0; i < par->size(); ++i) {
2586 PAR_TAG tag_close = NONE;
2587 list < PAR_TAG > tag_open;
2589 LyXFont const font = par->getFont(params, i);
2591 if (font_old.family() != font.family()) {
2592 switch (family_type) {
2593 case LyXFont::SANS_FAMILY:
2596 case LyXFont::TYPEWRITER_FAMILY:
2603 family_type = font.family();
2605 switch (family_type) {
2606 case LyXFont::SANS_FAMILY:
2607 tag_open.push_back(SF);
2609 case LyXFont::TYPEWRITER_FAMILY:
2610 tag_open.push_back(TT);
2617 if (font_old.series() != font.series()) {
2618 switch (series_type) {
2619 case LyXFont::BOLD_SERIES:
2626 series_type = font.series();
2628 switch (series_type) {
2629 case LyXFont::BOLD_SERIES:
2630 tag_open.push_back(BF);
2638 if (font_old.shape() != font.shape()) {
2639 switch (shape_type) {
2640 case LyXFont::ITALIC_SHAPE:
2643 case LyXFont::SLANTED_SHAPE:
2650 shape_type = font.shape();
2652 switch (shape_type) {
2653 case LyXFont::ITALIC_SHAPE:
2654 tag_open.push_back(IT);
2656 case LyXFont::SLANTED_SHAPE:
2657 tag_open.push_back(SL);
2664 if (font_old.emph() != font.emph()) {
2665 if (font.emph() == LyXFont::ON) {
2666 tag_open.push_back(EM);
2675 list < PAR_TAG > temp;
2676 while (!tag_state.empty() && tag_close) {
2677 PAR_TAG k = tag_state.top();
2679 os << "</" << tag_name(k) << '>';
2686 for(list< PAR_TAG >::const_iterator j = temp.begin();
2687 j != temp.end(); ++j) {
2689 os << '<' << tag_name(*j) << '>';
2692 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2693 j != tag_open.end(); ++j) {
2695 os << '<' << tag_name(*j) << '>';
2698 char c = par->getChar(i);
2700 if (c == Paragraph::META_INSET) {
2701 Inset * inset = par->getInset(i);
2702 inset->linuxdoc(this, os);
2707 if (style->latexparam() == "CDATA") {
2708 // "TeX"-Mode on == > SGML-Mode on.
2715 boost::tie(ws, str) = sgml::escapeChar(c);
2716 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2717 // in freespacing mode, spaces are
2718 // non-breaking characters
2719 if (desc_on) {// if char is ' ' then...
2722 sgmlLineBreak(os, char_line_count, 6);
2726 sgmlLineBreak(os, char_line_count, 1);
2731 char_line_count += str.length();
2737 while (!tag_state.empty()) {
2738 os << "</" << tag_name(tag_state.top()) << '>';
2742 // resets description flag correctly
2744 // <tag> not closed...
2745 sgmlLineBreak(os, char_line_count, 6);
2751 // Print an error message.
2752 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2753 string const & /*message*/) const
2755 #ifdef WITH_WARNINGS
2756 #warning This is wrong we cannot insert an inset like this!!!
2757 // I guess this was Jose' so I explain you more or less why this
2758 // is wrong. This way you insert something in the paragraph and
2759 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2760 // I deactivate this code, have a look at BufferView::insertErrors
2761 // how you should do this correctly! (Jug 20020315)
2764 // insert an error marker in text
2765 InsetError * new_inset = new InsetError(message);
2766 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2772 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2774 ofstream ofs(fname.c_str());
2776 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2780 Paragraph * par = &*(paragraphs.begin());
2782 niceFile = nice; // this will be used by Insetincludes.
2784 LaTeXFeatures features(params);
2789 LyXTextClass const & tclass = params.getLyXTextClass();
2790 string top_element = tclass.latexname();
2793 ofs << "<!DOCTYPE " << top_element
2794 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2796 string preamble = params.preamble;
2797 const string name = nice ? ChangeExtension(filename_, ".sgml")
2799 preamble += features.getIncludedFiles(name);
2800 preamble += features.getLyXSGMLEntities();
2802 if (!preamble.empty()) {
2803 ofs << "\n [ " << preamble << " ]";
2808 string top = top_element;
2810 top += params.language->code();
2813 if (!params.options.empty()) {
2815 top += params.options;
2817 sgml::openTag(ofs, 0, false, top);
2819 ofs << "<!-- DocBook file was created by " << lyx_docversion
2820 << "\n See http://www.lyx.org/ for more information -->\n";
2822 vector<string> environment_stack(10);
2823 vector<string> environment_inner(10);
2824 vector<string> command_stack(10);
2826 bool command_flag = false;
2827 Paragraph::depth_type command_depth = 0;
2828 Paragraph::depth_type command_base = 0;
2829 Paragraph::depth_type cmd_depth = 0;
2830 Paragraph::depth_type depth = 0; // paragraph depth
2833 string command_name;
2839 int desc_on = 0; // description mode
2841 LyXLayout_ptr const & style = par->layout();
2843 // environment tag closing
2844 for (; depth > par->params().depth(); --depth) {
2845 if (environment_inner[depth] != "!-- --") {
2846 item_name = "listitem";
2847 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2848 if (environment_inner[depth] == "varlistentry")
2849 sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2851 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2852 environment_stack[depth].erase();
2853 environment_inner[depth].erase();
2856 if (depth == par->params().depth()
2857 && environment_stack[depth] != style->latexname()
2858 && !environment_stack[depth].empty()) {
2859 if (environment_inner[depth] != "!-- --") {
2860 item_name= "listitem";
2861 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2862 if (environment_inner[depth] == "varlistentry")
2863 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2866 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2868 environment_stack[depth].erase();
2869 environment_inner[depth].erase();
2872 // Write opening SGML tags.
2873 switch (style->latextype) {
2874 case LATEX_PARAGRAPH:
2875 sgml::openTag(ofs, depth + command_depth,
2876 false, style->latexname());
2882 _("Error: Wrong depth for LatexType Command.\n"));
2884 command_name = style->latexname();
2886 sgmlparam = style->latexparam();
2887 c_params = split(sgmlparam, c_depth,'|');
2889 cmd_depth = lyx::atoi(c_depth);
2892 if (cmd_depth < command_base) {
2893 for (Paragraph::depth_type j = command_depth;
2894 j >= command_base; --j) {
2895 sgml::closeTag(ofs, j, false, command_stack[j]);
2898 command_depth = command_base = cmd_depth;
2899 } else if (cmd_depth <= command_depth) {
2900 for (int j = command_depth;
2901 j >= int(cmd_depth); --j) {
2902 sgml::closeTag(ofs, j, false, command_stack[j]);
2905 command_depth = cmd_depth;
2907 command_depth = cmd_depth;
2909 command_depth = command_base = cmd_depth;
2910 command_flag = true;
2912 if (command_stack.size() == command_depth + 1)
2913 command_stack.push_back(string());
2914 command_stack[command_depth] = command_name;
2916 // treat label as a special case for
2917 // more WYSIWYM handling.
2918 // This is a hack while paragraphs can't have
2919 // attributes, like id in this case.
2920 if (par->isInset(0)) {
2921 Inset * inset = par->getInset(0);
2922 Inset::Code lyx_code = inset->lyxCode();
2923 if (lyx_code == Inset::LABEL_CODE) {
2924 command_name += " id=\"";
2925 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2926 command_name += '"';
2931 sgml::openTag(ofs, depth + command_depth, false, command_name);
2933 item_name = c_params.empty() ? "title" : c_params;
2934 sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2937 case LATEX_ENVIRONMENT:
2938 case LATEX_ITEM_ENVIRONMENT:
2939 if (depth < par->params().depth()) {
2940 depth = par->params().depth();
2941 environment_stack[depth].erase();
2944 if (environment_stack[depth] != style->latexname()) {
2945 if (environment_stack.size() == depth + 1) {
2946 environment_stack.push_back("!-- --");
2947 environment_inner.push_back("!-- --");
2949 environment_stack[depth] = style->latexname();
2950 environment_inner[depth] = "!-- --";
2951 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2953 if (environment_inner[depth] != "!-- --") {
2954 item_name= "listitem";
2955 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2956 if (environment_inner[depth] == "varlistentry")
2957 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2961 if (style->latextype == LATEX_ENVIRONMENT) {
2962 if (!style->latexparam().empty()) {
2963 if (style->latexparam() == "CDATA")
2966 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2971 desc_on = (style->labeltype == LABEL_MANUAL);
2973 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2974 sgml::openTag(ofs, depth + 1 + command_depth,
2975 false, environment_inner[depth]);
2977 item_name = desc_on ? "term" : "para";
2978 sgml::openTag(ofs, depth + 1 + command_depth,
2982 sgml::openTag(ofs, depth + command_depth,
2983 false, style->latexname());
2987 simpleDocBookOnePar(ofs, par, desc_on,
2988 depth + 1 + command_depth);
2992 // write closing SGML tags
2993 switch (style->latextype) {
2995 end_tag = c_params.empty() ? "title" : c_params;
2996 sgml::closeTag(ofs, depth + command_depth,
2999 case LATEX_ENVIRONMENT:
3000 if (!style->latexparam().empty()) {
3001 if (style->latexparam() == "CDATA")
3004 sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
3007 case LATEX_ITEM_ENVIRONMENT:
3008 if (desc_on == 1) break;
3010 sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
3012 case LATEX_PARAGRAPH:
3013 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
3016 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
3022 for (int d = depth; d >= 0; --d) {
3023 if (!environment_stack[depth].empty()) {
3024 if (environment_inner[depth] != "!-- --") {
3025 item_name = "listitem";
3026 sgml::closeTag(ofs, command_depth + depth, false, item_name);
3027 if (environment_inner[depth] == "varlistentry")
3028 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
3031 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
3035 for (int j = command_depth; j >= 0 ; --j)
3036 if (!command_stack[j].empty()) {
3037 sgml::closeTag(ofs, j, false, command_stack[j]);
3042 sgml::closeTag(ofs, 0, false, top_element);
3045 // How to check for successful close
3047 // we want this to be true outside previews (for insetexternal)
3052 void Buffer::simpleDocBookOnePar(ostream & os,
3053 Paragraph * par, int & desc_on,
3054 Paragraph::depth_type depth) const
3056 bool emph_flag = false;
3058 LyXLayout_ptr const & style = par->layout();
3060 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
3062 int char_line_count = depth;
3063 //if (!style.free_spacing)
3064 // os << string(depth,' ');
3066 // parsing main loop
3067 for (pos_type i = 0; i < par->size(); ++i) {
3068 LyXFont font = par->getFont(params, i);
3070 // handle <emphasis> tag
3071 if (font_old.emph() != font.emph()) {
3072 if (font.emph() == LyXFont::ON) {
3073 if (style->latexparam() == "CDATA")
3076 if (style->latexparam() == "CDATA")
3080 if (style->latexparam() == "CDATA")
3082 os << "</emphasis>";
3083 if (style->latexparam() == "CDATA")
3090 if (par->isInset(i)) {
3091 Inset * inset = par->getInset(i);
3092 // don't print the inset in position 0 if desc_on == 3 (label)
3093 if (i || desc_on != 3) {
3094 if (style->latexparam() == "CDATA")
3096 inset->docbook(this, os, false);
3097 if (style->latexparam() == "CDATA")
3101 char c = par->getChar(i);
3104 boost::tie(ws, str) = sgml::escapeChar(c);
3106 if (style->pass_thru) {
3108 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3110 } else if (desc_on ==1) {
3112 os << "\n</term><listitem><para>";
3122 if (style->latexparam() == "CDATA")
3124 os << "</emphasis>";
3125 if (style->latexparam() == "CDATA")
3129 // resets description flag correctly
3131 // <term> not closed...
3132 os << "</term>\n<listitem><para> </para>";
3134 if (style->free_spacing)
3139 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3140 // Other flags: -wall -v0 -x
3141 int Buffer::runChktex()
3143 if (!users->text) return 0;
3145 users->owner()->busy(true);
3147 // get LaTeX-Filename
3148 string const name = getLatexName();
3149 string path = filePath();
3151 string const org_path = path;
3152 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3156 Path p(path); // path to LaTeX file
3157 users->owner()->message(_("Running chktex..."));
3159 // Remove all error insets
3160 bool const removedErrorInsets = users->removeAutoInsets();
3162 // Generate the LaTeX file if neccessary
3163 makeLaTeXFile(name, org_path, false);
3166 Chktex chktex(lyxrc.chktex_command, name, filePath());
3167 int res = chktex.run(terr); // run chktex
3170 Alert::alert(_("chktex did not work!"),
3171 _("Could not run with file:"), name);
3172 } else if (res > 0) {
3173 // Insert all errors as errors boxes
3174 users->insertErrors(terr);
3177 // if we removed error insets before we ran chktex or if we inserted
3178 // error insets after we ran chktex, this must be run:
3179 if (removedErrorInsets || res) {
3180 #warning repaint needed here, or do you mean update() ?
3184 users->owner()->busy(false);
3190 void Buffer::validate(LaTeXFeatures & features) const
3192 LyXTextClass const & tclass = params.getLyXTextClass();
3194 if (params.tracking_changes) {
3195 features.require("dvipost");
3196 features.require("color");
3199 // AMS Style is at document level
3200 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3201 features.require("amsmath");
3203 for_each(paragraphs.begin(), paragraphs.end(),
3204 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3206 // the bullet shapes are buffer level not paragraph level
3207 // so they are tested here
3208 for (int i = 0; i < 4; ++i) {
3209 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3210 int const font = params.user_defined_bullets[i].getFont();
3212 int const c = params
3213 .user_defined_bullets[i]
3220 features.require("latexsym");
3222 } else if (font == 1) {
3223 features.require("amssymb");
3224 } else if ((font >= 2 && font <= 5)) {
3225 features.require("pifont");
3230 if (lyxerr.debugging(Debug::LATEX)) {
3231 features.showStruct();
3236 vector<string> const Buffer::getLabelList() const
3238 /// if this is a child document and the parent is already loaded
3239 /// Use the parent's list instead [ale990407]
3240 if (!params.parentname.empty()
3241 && bufferlist.exists(params.parentname)) {
3242 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3244 return tmp->getLabelList();
3247 vector<string> label_list;
3248 for (inset_iterator it = inset_const_iterator_begin();
3249 it != inset_const_iterator_end(); ++it) {
3250 vector<string> const l = it->getLabelList();
3251 label_list.insert(label_list.end(), l.begin(), l.end());
3257 // This is also a buffer property (ale)
3258 vector<pair<string, string> > const Buffer::getBibkeyList() const
3260 typedef pair<string, string> StringPair;
3261 /// if this is a child document and the parent is already loaded
3262 /// Use the parent's list instead [ale990412]
3263 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3264 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3266 return tmp->getBibkeyList();
3269 vector<StringPair> keys;
3270 ParagraphList::iterator pit = paragraphs.begin();
3271 ParagraphList::iterator pend = paragraphs.end();
3272 for (; pit != pend; ++pit) {
3274 string const key = pit->bibkey->getContents();
3275 string const opt = pit->bibkey->getOptions();
3276 string const ref = pit->asString(this, false);
3277 string const info = opt + "TheBibliographyRef" + ref;
3279 keys.push_back(StringPair(key, info));
3286 // Might be either using bibtex or a child has bibliography
3287 for (inset_iterator it = inset_const_iterator_begin();
3288 it != inset_const_iterator_end(); ++it) {
3289 // Search for Bibtex or Include inset
3290 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3291 vector<StringPair> tmp =
3292 static_cast<InsetBibtex &>(*it).getKeys(this);
3293 keys.insert(keys.end(), tmp.begin(), tmp.end());
3294 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3295 vector<StringPair> const tmp =
3296 static_cast<InsetInclude &>(*it).getKeys();
3297 keys.insert(keys.end(), tmp.begin(), tmp.end());
3305 bool Buffer::isDepClean(string const & name) const
3307 DepClean::const_iterator it = dep_clean_.find(name);
3308 if (it == dep_clean_.end())
3314 void Buffer::markDepClean(string const & name)
3316 dep_clean_[name] = true;
3320 bool Buffer::dispatch(string const & command, bool * result)
3322 // Split command string into command and argument
3324 string line = ltrim(command);
3325 string const arg = trim(split(line, cmd, ' '));
3327 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3331 bool Buffer::dispatch(int action, string const & argument, bool * result)
3333 bool dispatched = true;
3337 bool const tmp = Exporter::Export(this, argument, false);
3350 void Buffer::resizeInsets(BufferView * bv)
3352 /// then remove all LyXText in text-insets
3353 for_each(paragraphs.begin(), paragraphs.end(),
3354 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3358 void Buffer::redraw()
3360 #warning repaint needed here, or do you mean update() ?
3366 void Buffer::changeLanguage(Language const * from, Language const * to)
3369 ParIterator end = par_iterator_end();
3370 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3371 (*it)->changeLanguage(params, from, to);
3375 bool Buffer::isMultiLingual()
3377 ParIterator end = par_iterator_end();
3378 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3379 if ((*it)->isMultiLingual(params))
3386 void Buffer::inset_iterator::setParagraph()
3388 while (pit != pend) {
3389 it = pit->insetlist.begin();
3390 if (it != pit->insetlist.end())
3397 Inset * Buffer::getInsetFromID(int id_arg) const
3399 for (inset_iterator it = inset_const_iterator_begin();
3400 it != inset_const_iterator_end(); ++it)
3402 if (it->id() == id_arg)
3404 Inset * in = it->getInsetFromID(id_arg);
3412 Paragraph * Buffer::getParFromID(int id) const
3417 // why should we allow < 0 ??
3418 //lyx::Assert(id >= 0);
3420 ParConstIterator it(par_iterator_begin());
3421 ParConstIterator end(par_iterator_end());
3423 for (; it != end; ++it) {
3424 // go on then, show me how to remove
3426 if ((*it)->id() == id) {
3427 return const_cast<Paragraph*>(*it);
3435 ParIterator Buffer::par_iterator_begin()
3437 return ParIterator(&*(paragraphs.begin()));
3441 ParIterator Buffer::par_iterator_end()
3443 return ParIterator();
3446 ParConstIterator Buffer::par_iterator_begin() const
3448 return ParConstIterator(&*(paragraphs.begin()));
3452 ParConstIterator Buffer::par_iterator_end() const
3454 return ParConstIterator();
3459 void Buffer::addUser(BufferView * u)
3465 void Buffer::delUser(BufferView *)
3471 Language const * Buffer::getLanguage() const
3473 return params.language;
3477 bool Buffer::isClean() const
3483 bool Buffer::isBakClean() const
3489 void Buffer::markClean() const
3495 // if the .lyx file has been saved, we don't need an
3501 void Buffer::markBakClean()
3507 void Buffer::setUnnamed(bool flag)
3513 bool Buffer::isUnnamed()
3519 void Buffer::markDirty()
3527 DepClean::iterator it = dep_clean_.begin();
3528 DepClean::const_iterator const end = dep_clean_.end();
3530 for (; it != end; ++it) {
3536 string const & Buffer::fileName() const
3542 string const & Buffer::filePath() const
3548 bool Buffer::isReadonly() const
3554 BufferView * Buffer::getUser() const
3560 void Buffer::setParentName(string const & name)
3562 params.parentname = name;
3566 Buffer::inset_iterator::inset_iterator()
3571 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3578 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3582 if (it == pit->insetlist.end()) {
3591 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3593 inset_iterator tmp = *this;
3599 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3601 return *it.getInset();
3605 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3607 return it.getInset();
3611 Paragraph * Buffer::inset_iterator::getPar()
3617 lyx::pos_type Buffer::inset_iterator::getPos() const
3623 bool operator==(Buffer::inset_iterator const & iter1,
3624 Buffer::inset_iterator const & iter2)
3626 return iter1.pit == iter2.pit
3627 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3631 bool operator!=(Buffer::inset_iterator const & iter1,
3632 Buffer::inset_iterator const & iter2)
3634 return !(iter1 == iter2);