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 #pragma implementation
22 #include "bufferlist.h"
23 #include "LyXAction.h"
26 #include "tex-strings.h"
28 #include "bufferview_funcs.h"
34 #include "LaTeXFeatures.h"
41 #include "converter.h"
42 #include "BufferView.h"
43 #include "ParagraphParameters.h"
44 #include "iterators.h"
45 #include "lyxtextclasslist.h"
47 #include "paragraph_funcs.h"
49 #include "frontends/LyXView.h"
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
54 #include "insets/inset.h"
55 #include "insets/inseterror.h"
56 #include "insets/insetlabel.h"
57 #include "insets/insetref.h"
58 #include "insets/inseturl.h"
59 #include "insets/insetnote.h"
60 #include "insets/insetquotes.h"
61 #include "insets/insetlatexaccent.h"
62 #include "insets/insetbib.h"
63 #include "insets/insetcite.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetindex.h"
66 #include "insets/insetinclude.h"
67 #include "insets/insettoc.h"
68 #include "insets/insetparent.h"
69 #include "insets/insetspecialchar.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/insetoptarg.h"
76 #include "insets/insetminipage.h"
77 #include "insets/insetfloat.h"
78 #include "insets/insetwrap.h"
79 #include "insets/insettabular.h"
81 #include "insets/insettheorem.h"
82 #include "insets/insetlist.h"
84 #include "insets/insetcaption.h"
85 #include "insets/insetfloatlist.h"
87 #include "frontends/Dialogs.h"
88 #include "frontends/Alert.h"
90 #include "graphics/Previews.h"
92 #include "support/textutils.h"
93 #include "support/filetools.h"
94 #include "support/path.h"
95 #include "support/os.h"
96 #include "support/lyxlib.h"
97 #include "support/FileInfo.h"
98 #include "support/lyxmanip.h"
99 #include "support/lyxalgo.h" // for lyx::count
101 #include <boost/bind.hpp>
102 #include <boost/tuple/tuple.hpp>
103 #include "BoostFormat.h"
115 #include <sys/types.h>
122 #ifndef CXX_GLOBAL_CSTD
134 using std::make_pair;
144 using lyx::textclass_type;
146 // all these externs should eventually be removed.
147 extern BufferList bufferlist;
151 const int LYX_FORMAT = 221;
155 Buffer::Buffer(string const & file, bool ronly)
156 : niceFile(true), lyx_clean(true), bak_clean(true),
157 unnamed(false), dep_clean(0), read_only(ronly),
158 filename_(file), users(0)
160 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
161 filepath_ = OnlyPath(file);
163 if (read_only || lyxrc.use_tempdir) {
164 tmppath = CreateBufferTmpDir();
173 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
174 // here the buffer should take care that it is
175 // saved properly, before it goes into the void.
177 // make sure that views using this buffer
182 if (!tmppath.empty()) {
183 DestroyBufferTmpDir(tmppath);
188 // Remove any previewed LaTeX snippets assocoated with this buffer.
189 grfx::Previews::get().removeLoader(this);
193 string const Buffer::getLatexName(bool no_path) const
195 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
197 return OnlyFilename(name);
203 pair<Buffer::LogType, string> const Buffer::getLogName() const
205 string const filename = getLatexName(false);
207 if (filename.empty())
208 return make_pair(Buffer::latexlog, string());
210 string path = OnlyPath(filename);
212 if (lyxrc.use_tempdir || !IsDirWriteable(path))
215 string const fname = AddName(path,
216 OnlyFilename(ChangeExtension(filename,
219 AddName(path, OnlyFilename(
220 ChangeExtension(filename,
221 formats.extension("literate") + ".out")));
223 // If no Latex log or Build log is newer, show Build log
225 FileInfo const f_fi(fname);
226 FileInfo const b_fi(bname);
229 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
230 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
231 return make_pair(Buffer::buildlog, bname);
233 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
234 return make_pair(Buffer::latexlog, fname);
238 void Buffer::setReadonly(bool flag)
240 if (read_only != flag) {
243 users->owner()->getDialogs().updateBufferDependent(false);
248 /// Update window titles of all users
249 // Should work on a list
250 void Buffer::updateTitles() const
253 users->owner()->updateWindowTitle();
257 /// Reset autosave timer of all users
258 // Should work on a list
259 void Buffer::resetAutosaveTimers() const
262 users->owner()->resetAutosaveTimer();
266 void Buffer::setFileName(string const & newfile)
268 filename_ = MakeAbsPath(newfile);
269 filepath_ = OnlyPath(filename_);
270 setReadonly(IsFileWriteable(filename_) == 0);
275 // We'll remove this later. (Lgb)
278 string last_inset_read;
281 #warning And _why_ is this here? (Lgb)
289 // candidate for move to BufferView
290 // (at least some parts in the beginning of the func)
293 // changed to be public and have one parameter
294 // if par = 0 normal behavior
295 // else insert behavior
296 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
297 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
303 Paragraph::depth_type depth = 0;
304 bool the_end_read = false;
306 Paragraph * first_par = 0;
307 LyXFont font(LyXFont::ALL_INHERIT, params.language);
310 if (file_format < 216 && params.language->lang() == "hebrew")
311 font.setLanguage(default_language);
316 par->layout(params.getLyXTextClass().defaultLayout());
318 // We are inserting into an existing document
319 users->text->breakParagraph(users);
320 first_par = users->text->ownerParagraph();
323 // We don't want to adopt the parameters from the
324 // document we insert, so we skip until the text begins:
327 string const pretoken = lex.getString();
328 if (pretoken == "\\layout") {
329 lex.pushToken(pretoken);
337 string const token = lex.getString();
339 if (token.empty()) continue;
341 lyxerr[Debug::PARSER] << "Handling token: `"
342 << token << '\'' << endl;
345 parseSingleLyXformat2Token(lex, par, first_par,
353 paragraphs.set(first_par);
355 if (unknown_layouts > 0) {
356 string s = _("Couldn't set the layout for ");
357 if (unknown_layouts == 1) {
358 s += _("one paragraph");
360 s += tostr(unknown_layouts);
361 s += _(" paragraphs");
364 Alert::alert(_("Textclass Loading Error!"), s,
365 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
367 Alert::alert(_("Textclass Loading Error!"), s,
368 _("When reading ") + fileName());
372 if (unknown_tokens > 0) {
373 string s = _("Encountered ");
374 if (unknown_tokens == 1) {
375 s += _("one unknown token");
377 s += tostr(unknown_tokens);
378 s += _(" unknown tokens");
381 Alert::alert(_("Textclass Loading Error!"), s,
382 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
384 Alert::alert(_("Textclass Loading Error!"), s,
385 _("When reading ") + fileName());
394 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
395 Paragraph *& first_par,
396 string const & token, int & pos,
397 Paragraph::depth_type & depth,
401 bool the_end_read = false;
403 // The order of the tags tested may seem unnatural, but this
404 // has been done in order to reduce the number of string
405 // comparisons needed to recognize a given token. This leads
406 // on large documents like UserGuide to a reduction of a
408 if (token[0] != '\\') {
409 for (string::const_iterator cit = token.begin();
410 cit != token.end(); ++cit) {
411 par->insertChar(pos, (*cit), font);
414 } else if (token == "\\layout") {
415 // reset the font as we start a new layout and if the font is
416 // not ALL_INHERIT,document_language then it will be set to the
417 // right values after this tag (Jug 20020420)
418 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
421 if (file_format < 216 && params.language->lang() == "hebrew")
422 font.setLanguage(default_language);
426 string layoutname = lex.getString();
428 LyXTextClass const & tclass = params.getLyXTextClass();
430 if (layoutname.empty()) {
431 layoutname = tclass.defaultLayoutName();
433 bool hasLayout = tclass.hasLayout(layoutname);
435 lyxerr << "Layout '" << layoutname << "' does not"
436 << " exist in textclass '" << tclass.name()
438 lyxerr << "Trying to use default layout instead."
440 layoutname = tclass.defaultLayoutName();
444 // The is the compability reading of layout caption.
445 // It can be removed in LyX version 1.3.0. (Lgb)
446 if (compare_ascii_no_case(layoutname, "caption") == 0) {
447 // We expect that the par we are now working on is
448 // really inside a InsetText inside a InsetFloat.
449 // We also know that captions can only be
450 // one paragraph. (Lgb)
452 // We should now read until the next "\layout"
454 // This is probably not good enough, what if the
455 // caption is the last par in the document (Lgb)
456 istream & ist = lex.getStream();
462 if (prefixIs(line, "\\layout")) {
466 if (prefixIs(line, "\\begin_inset"))
468 if (prefixIs(line, "\\end_inset")) {
479 // Now we should have the whole layout in ss
480 // we should now be able to give this to the
482 ss << "\\end_inset\n";
484 // This seems like a bug in stringstream.
485 // We really should be able to use ss
487 istringstream is(ss.str());
489 tmplex.setStream(is);
490 Inset * inset = new InsetCaption;
491 inset->Read(this, tmplex);
492 par->InsertInset(pos, inset, font);
499 par = new Paragraph(par);
500 par->layout(params.getLyXTextClass().defaultLayout());
503 par->layout(params.getLyXTextClass()[layoutname]);
504 // Test whether the layout is obsolete.
505 LyXLayout_ptr const & layout = par->layout();
506 if (!layout->obsoleted_by().empty())
507 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
508 par->params().depth(depth);
513 } else if (token == "\\end_inset") {
514 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
515 << "Last inset read was: " << last_inset_read
517 // Simply ignore this. The insets do not have
519 // But insets should read it, it is a part of
520 // the inset isn't it? Lgb.
521 } else if (token == "\\begin_inset") {
522 readInset(lex, par, pos, font);
523 } else if (token == "\\family") {
525 font.setLyXFamily(lex.getString());
526 } else if (token == "\\series") {
528 font.setLyXSeries(lex.getString());
529 } else if (token == "\\shape") {
531 font.setLyXShape(lex.getString());
532 } else if (token == "\\size") {
534 font.setLyXSize(lex.getString());
535 } else if (token == "\\lang") {
537 string const tok = lex.getString();
538 Language const * lang = languages.getLanguage(tok);
540 font.setLanguage(lang);
542 font.setLanguage(params.language);
543 lex.printError("Unknown language `$$Token'");
545 } else if (token == "\\numeric") {
547 font.setNumber(font.setLyXMisc(lex.getString()));
548 } else if (token == "\\emph") {
550 font.setEmph(font.setLyXMisc(lex.getString()));
551 } else if (token == "\\bar") {
553 string const tok = lex.getString();
554 // This is dirty, but gone with LyX3. (Asger)
556 font.setUnderbar(LyXFont::ON);
557 else if (tok == "no")
558 font.setUnderbar(LyXFont::OFF);
559 else if (tok == "default")
560 font.setUnderbar(LyXFont::INHERIT);
562 lex.printError("Unknown bar font flag "
564 } else if (token == "\\noun") {
566 font.setNoun(font.setLyXMisc(lex.getString()));
567 } else if (token == "\\color") {
569 font.setLyXColor(lex.getString());
570 } else if (token == "\\SpecialChar") {
571 LyXLayout_ptr const & layout = par->layout();
573 // Insets don't make sense in a free-spacing context! ---Kayvan
574 if (layout->free_spacing || par->isFreeSpacing()) {
577 string const next_token = lex.getString();
578 if (next_token == "\\-") {
579 par->insertChar(pos, '-', font);
580 } else if (next_token == "~") {
581 par->insertChar(pos, ' ', font);
583 lex.printError("Token `$$Token' "
585 "paragraph layout!");
590 Inset * inset = new InsetSpecialChar;
591 inset->read(this, lex);
592 par->insertInset(pos, inset, font);
595 } else if (token == "\\i") {
596 Inset * inset = new InsetLatexAccent;
597 inset->read(this, lex);
598 par->insertInset(pos, inset, font);
600 } else if (token == "\\backslash") {
601 par->insertChar(pos, '\\', font);
603 } else if (token == "\\begin_deeper") {
605 } else if (token == "\\end_deeper") {
607 lex.printError("\\end_deeper: "
608 "depth is already null");
612 } else if (token == "\\begin_preamble") {
613 params.readPreamble(lex);
614 } else if (token == "\\textclass") {
616 pair<bool, textclass_type> pp =
617 textclasslist.NumberOfClass(lex.getString());
619 params.textclass = pp.second;
622 Alert::alert(_("Textclass error"),
623 boost::io::str(boost::format(_("The document uses an unknown textclass \"%1$s\".")) % lex.getString()),
624 _("LyX will not be able to produce output correctly."));
627 _("Textclass error"),
628 _("The document uses an unknown textclass ")
630 _("LyX will not be able to produce output correctly."));
632 params.textclass = 0;
634 if (!params.getLyXTextClass().load()) {
635 // if the textclass wasn't loaded properly
636 // we need to either substitute another
637 // or stop loading the file.
638 // I can substitute but I don't see how I can
639 // stop loading... ideas?? ARRae980418
641 Alert::alert(_("Textclass Loading Error!"),
642 boost::io::str(boost::format(_("Can't load textclass %1$s")) %
643 params.getLyXTextClass().name()),
644 _("-- substituting default"));
646 Alert::alert(_("Textclass Loading Error!"),
647 _("Can't load textclass ")
648 + params.getLyXTextClass().name(),
649 _("-- substituting default"));
651 params.textclass = 0;
653 } else if (token == "\\options") {
655 params.options = lex.getString();
656 } else if (token == "\\language") {
657 params.readLanguage(lex);
658 } else if (token == "\\fontencoding") {
660 } else if (token == "\\inputencoding") {
662 params.inputenc = lex.getString();
663 } else if (token == "\\graphics") {
664 params.readGraphicsDriver(lex);
665 } else if (token == "\\fontscheme") {
667 params.fonts = lex.getString();
668 } else if (token == "\\noindent") {
669 par->params().noindent(true);
670 } else if (token == "\\leftindent") {
672 LyXLength value(lex.getString());
673 par->params().leftIndent(value);
674 } else if (token == "\\fill_top") {
675 par->params().spaceTop(VSpace(VSpace::VFILL));
676 } else if (token == "\\fill_bottom") {
677 par->params().spaceBottom(VSpace(VSpace::VFILL));
678 } else if (token == "\\line_top") {
679 par->params().lineTop(true);
680 } else if (token == "\\line_bottom") {
681 par->params().lineBottom(true);
682 } else if (token == "\\pagebreak_top") {
683 par->params().pagebreakTop(true);
684 } else if (token == "\\pagebreak_bottom") {
685 par->params().pagebreakBottom(true);
686 } else if (token == "\\start_of_appendix") {
687 par->params().startOfAppendix(true);
688 } else if (token == "\\paragraph_separation") {
689 int tmpret = lex.findToken(string_paragraph_separation);
692 params.paragraph_separation =
693 static_cast<BufferParams::PARSEP>(tmpret);
694 } else if (token == "\\defskip") {
696 params.defskip = VSpace(lex.getString());
697 } else if (token == "\\quotes_language") {
698 int tmpret = lex.findToken(string_quotes_language);
701 InsetQuotes::quote_language tmpl =
702 InsetQuotes::EnglishQ;
705 tmpl = InsetQuotes::EnglishQ;
708 tmpl = InsetQuotes::SwedishQ;
711 tmpl = InsetQuotes::GermanQ;
714 tmpl = InsetQuotes::PolishQ;
717 tmpl = InsetQuotes::FrenchQ;
720 tmpl = InsetQuotes::DanishQ;
723 params.quotes_language = tmpl;
724 } else if (token == "\\quotes_times") {
726 switch (lex.getInteger()) {
728 params.quotes_times = InsetQuotes::SingleQ;
731 params.quotes_times = InsetQuotes::DoubleQ;
734 } else if (token == "\\papersize") {
735 int tmpret = lex.findToken(string_papersize);
739 params.papersize2 = tmpret;
740 } else if (token == "\\paperpackage") {
741 int tmpret = lex.findToken(string_paperpackages);
744 params.paperpackage = BufferParams::PACKAGE_NONE;
746 params.paperpackage = tmpret;
747 } else if (token == "\\use_geometry") {
749 params.use_geometry = lex.getInteger();
750 } else if (token == "\\use_amsmath") {
752 params.use_amsmath = lex.getInteger();
753 } else if (token == "\\use_natbib") {
755 params.use_natbib = lex.getInteger();
756 } else if (token == "\\use_numerical_citations") {
758 params.use_numerical_citations = lex.getInteger();
759 } else if (token == "\\paperorientation") {
760 int tmpret = lex.findToken(string_orientation);
764 static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
765 } else if (token == "\\paperwidth") {
767 params.paperwidth = lex.getString();
768 } else if (token == "\\paperheight") {
770 params.paperheight = lex.getString();
771 } else if (token == "\\leftmargin") {
773 params.leftmargin = lex.getString();
774 } else if (token == "\\topmargin") {
776 params.topmargin = lex.getString();
777 } else if (token == "\\rightmargin") {
779 params.rightmargin = lex.getString();
780 } else if (token == "\\bottommargin") {
782 params.bottommargin = lex.getString();
783 } else if (token == "\\headheight") {
785 params.headheight = lex.getString();
786 } else if (token == "\\headsep") {
788 params.headsep = lex.getString();
789 } else if (token == "\\footskip") {
791 params.footskip = lex.getString();
792 } else if (token == "\\paperfontsize") {
794 params.fontsize = rtrim(lex.getString());
795 } else if (token == "\\papercolumns") {
797 params.columns = lex.getInteger();
798 } else if (token == "\\papersides") {
800 switch (lex.getInteger()) {
802 case 1: params.sides = LyXTextClass::OneSide; break;
803 case 2: params.sides = LyXTextClass::TwoSides; break;
805 } else if (token == "\\paperpagestyle") {
807 params.pagestyle = rtrim(lex.getString());
808 } else if (token == "\\bullet") {
810 int const index = lex.getInteger();
812 int temp_int = lex.getInteger();
813 params.user_defined_bullets[index].setFont(temp_int);
814 params.temp_bullets[index].setFont(temp_int);
816 temp_int = lex.getInteger();
817 params.user_defined_bullets[index].setCharacter(temp_int);
818 params.temp_bullets[index].setCharacter(temp_int);
820 temp_int = lex.getInteger();
821 params.user_defined_bullets[index].setSize(temp_int);
822 params.temp_bullets[index].setSize(temp_int);
824 string const temp_str = lex.getString();
825 if (temp_str != "\\end_bullet") {
826 // this element isn't really necessary for
827 // parsing but is easier for humans
828 // to understand bullets. Put it back and
829 // set a debug message?
830 lex.printError("\\end_bullet expected, got" + temp_str);
831 //how can I put it back?
833 } else if (token == "\\bulletLaTeX") {
834 // The bullet class should be able to read this.
836 int const index = lex.getInteger();
838 string temp_str = lex.getString();
840 while (temp_str != "\\end_bullet") {
841 // this loop structure is needed when user
842 // enters an empty string since the first
843 // thing returned will be the \\end_bullet
845 // if the LaTeX entry has spaces. Each element
846 // therefore needs to be read in turn
849 temp_str = lex.getString();
852 params.user_defined_bullets[index].setText(sum_str);
853 params.temp_bullets[index].setText(sum_str);
854 } else if (token == "\\secnumdepth") {
856 params.secnumdepth = lex.getInteger();
857 } else if (token == "\\tocdepth") {
859 params.tocdepth = lex.getInteger();
860 } else if (token == "\\spacing") {
862 string const tmp = rtrim(lex.getString());
863 Spacing::Space tmp_space = Spacing::Default;
865 if (tmp == "single") {
866 tmp_space = Spacing::Single;
867 } else if (tmp == "onehalf") {
868 tmp_space = Spacing::Onehalf;
869 } else if (tmp == "double") {
870 tmp_space = Spacing::Double;
871 } else if (tmp == "other") {
873 tmp_space = Spacing::Other;
874 tmp_val = lex.getFloat();
876 lex.printError("Unknown spacing token: '$$Token'");
878 // Small hack so that files written with klyx will be
881 par->params().spacing(Spacing(tmp_space, tmp_val));
883 params.spacing.set(tmp_space, tmp_val);
885 } else if (token == "\\paragraph_spacing") {
887 string const tmp = rtrim(lex.getString());
888 if (tmp == "single") {
889 par->params().spacing(Spacing(Spacing::Single));
890 } else if (tmp == "onehalf") {
891 par->params().spacing(Spacing(Spacing::Onehalf));
892 } else if (tmp == "double") {
893 par->params().spacing(Spacing(Spacing::Double));
894 } else if (tmp == "other") {
896 par->params().spacing(Spacing(Spacing::Other,
899 lex.printError("Unknown spacing token: '$$Token'");
901 } else if (token == "\\float_placement") {
903 params.float_placement = lex.getString();
904 } else if (token == "\\align") {
905 int tmpret = lex.findToken(string_align);
906 if (tmpret == -1) ++tmpret;
907 int const tmpret2 = int(pow(2.0, tmpret));
908 par->params().align(LyXAlignment(tmpret2));
909 } else if (token == "\\added_space_top") {
911 VSpace value = VSpace(lex.getString());
912 // only add the length when value > 0 or
914 if ((value.length().len().value() != 0) ||
916 (value.kind() != VSpace::LENGTH))
917 par->params().spaceTop(value);
918 } else if (token == "\\added_space_bottom") {
920 VSpace value = VSpace(lex.getString());
921 // only add the length when value > 0 or
923 if ((value.length().len().value() != 0) ||
925 (value.kind() != VSpace::LENGTH))
926 par->params().spaceBottom(value);
927 } else if (token == "\\labelwidthstring") {
929 par->params().labelWidthString(lex.getString());
930 // do not delete this token, it is still needed!
931 } else if (token == "\\newline") {
932 par->insertChar(pos, Paragraph::META_NEWLINE, font);
934 } else if (token == "\\LyXTable") {
935 Inset * inset = new InsetTabular(*this);
936 inset->read(this, lex);
937 par->insertInset(pos, inset, font);
939 } else if (token == "\\hfill") {
940 par->insertChar(pos, Paragraph::META_HFILL, font);
942 } else if (token == "\\bibitem") { // ale970302
944 InsetCommandParams p("bibitem", "dummy");
945 par->bibkey = new InsetBibKey(p);
947 par->bibkey->read(this, lex);
948 } else if (token == "\\the_end") {
951 // This should be insurance for the future: (Asger)
955 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
956 fmt % token % lex.text();
957 string const s = fmt.str();
959 string const s = _("Unknown token: ") + token
960 + ' ' + lex.text() + '\n';
962 // we can do this here this way because we're actually reading
963 // the buffer and don't care about LyXText right now.
964 InsetError * new_inset = new InsetError(s);
965 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
974 // needed to insert the selection
975 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
976 LyXFont const & fn,string const & str) const
978 LyXLayout_ptr const & layout = par->layout();
982 par->checkInsertChar(font);
983 // insert the string, don't insert doublespace
984 bool space_inserted = true;
985 bool autobreakrows = !par->inInset() ||
986 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
987 for(string::const_iterator cit = str.begin();
988 cit != str.end(); ++cit) {
990 if (autobreakrows && (!par->empty() || layout->keepempty)) {
991 breakParagraph(params, par, pos,
992 layout->isEnvironment());
995 space_inserted = true;
999 // do not insert consecutive spaces if !free_spacing
1000 } else if ((*cit == ' ' || *cit == '\t') &&
1001 space_inserted && !layout->free_spacing &&
1002 !par->isFreeSpacing())
1005 } else if (*cit == '\t') {
1006 if (!layout->free_spacing && !par->isFreeSpacing()) {
1007 // tabs are like spaces here
1008 par->insertChar(pos, ' ', font);
1010 space_inserted = true;
1012 const pos_type nb = 8 - pos % 8;
1013 for (pos_type a = 0; a < nb ; ++a) {
1014 par->insertChar(pos, ' ', font);
1017 space_inserted = true;
1019 } else if (!IsPrintable(*cit)) {
1020 // Ignore unprintables
1023 // just insert the character
1024 par->insertChar(pos, *cit, font);
1026 space_inserted = (*cit == ' ');
1033 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1034 int & pos, LyXFont & font)
1036 // consistency check
1037 if (lex.getString() != "\\begin_inset") {
1038 lyxerr << "Buffer::readInset: Consistency check failed."
1045 string const tmptok = lex.getString();
1046 last_inset_read = tmptok;
1048 // test the different insets
1049 if (tmptok == "LatexCommand") {
1050 InsetCommandParams inscmd;
1053 string const cmdName = inscmd.getCmdName();
1055 // This strange command allows LyX to recognize "natbib" style
1056 // citations: citet, citep, Citet etc.
1057 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1058 inset = new InsetCitation(inscmd);
1059 } else if (cmdName == "bibitem") {
1060 lex.printError("Wrong place for bibitem");
1061 inset = new InsetBibKey(inscmd);
1062 } else if (cmdName == "BibTeX") {
1063 inset = new InsetBibtex(inscmd);
1064 } else if (cmdName == "index") {
1065 inset = new InsetIndex(inscmd);
1066 } else if (cmdName == "include") {
1067 inset = new InsetInclude(inscmd, *this);
1068 } else if (cmdName == "label") {
1069 inset = new InsetLabel(inscmd);
1070 } else if (cmdName == "url"
1071 || cmdName == "htmlurl") {
1072 inset = new InsetUrl(inscmd);
1073 } else if (cmdName == "ref"
1074 || cmdName == "pageref"
1075 || cmdName == "vref"
1076 || cmdName == "vpageref"
1077 || cmdName == "prettyref") {
1078 if (!inscmd.getOptions().empty()
1079 || !inscmd.getContents().empty()) {
1080 inset = new InsetRef(inscmd, *this);
1082 } else if (cmdName == "tableofcontents") {
1083 inset = new InsetTOC(inscmd);
1084 } else if (cmdName == "listofalgorithms") {
1085 inset = new InsetFloatList("algorithm");
1086 } else if (cmdName == "listoffigures") {
1087 inset = new InsetFloatList("figure");
1088 } else if (cmdName == "listoftables") {
1089 inset = new InsetFloatList("table");
1090 } else if (cmdName == "printindex") {
1091 inset = new InsetPrintIndex(inscmd);
1092 } else if (cmdName == "lyxparent") {
1093 inset = new InsetParent(inscmd, *this);
1096 bool alreadyread = false;
1097 if (tmptok == "Quotes") {
1098 inset = new InsetQuotes;
1099 } else if (tmptok == "External") {
1100 inset = new InsetExternal;
1101 } else if (tmptok == "FormulaMacro") {
1102 inset = new InsetFormulaMacro;
1103 } else if (tmptok == "Formula") {
1104 inset = new InsetFormula;
1105 } else if (tmptok == "Figure") { // Backward compatibility
1106 // inset = new InsetFig(100, 100, *this);
1107 inset = new InsetGraphics;
1108 } else if (tmptok == "Graphics") {
1109 inset = new InsetGraphics;
1110 } else if (tmptok == "Info") {// backwards compatibility
1111 inset = new InsetNote(this,
1112 lex.getLongString("\\end_inset"),
1115 } else if (tmptok == "Note") {
1116 inset = new InsetNote(params);
1117 } else if (tmptok == "Include") {
1118 InsetCommandParams p("Include");
1119 inset = new InsetInclude(p, *this);
1120 } else if (tmptok == "ERT") {
1121 inset = new InsetERT(params);
1122 } else if (tmptok == "Tabular") {
1123 inset = new InsetTabular(*this);
1124 } else if (tmptok == "Text") {
1125 inset = new InsetText(params);
1126 } else if (tmptok == "Foot") {
1127 inset = new InsetFoot(params);
1128 } else if (tmptok == "Marginal") {
1129 inset = new InsetMarginal(params);
1130 } else if (tmptok == "OptArg") {
1131 inset = new InsetOptArg(params);
1132 } else if (tmptok == "Minipage") {
1133 inset = new InsetMinipage(params);
1134 } else if (tmptok == "Float") {
1136 string tmptok = lex.getString();
1137 inset = new InsetFloat(params, tmptok);
1138 } else if (tmptok == "Wrap") {
1140 string tmptok = lex.getString();
1141 inset = new InsetWrap(params, tmptok);
1143 } else if (tmptok == "List") {
1144 inset = new InsetList;
1145 } else if (tmptok == "Theorem") {
1146 inset = new InsetList;
1148 } else if (tmptok == "Caption") {
1149 inset = new InsetCaption(params);
1150 } else if (tmptok == "FloatList") {
1151 inset = new InsetFloatList;
1154 if (inset && !alreadyread) inset->read(this, lex);
1158 par->insertInset(pos, inset, font);
1164 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
1168 string const token(lex.getString());
1169 if (token == "\\lyxformat") { // the first token _must_ be...
1171 string tmp_format = lex.getString();
1172 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
1173 // if present remove ".," from string.
1174 string::size_type dot = tmp_format.find_first_of(".,");
1175 //lyxerr << " dot found at " << dot << endl;
1176 if (dot != string::npos)
1177 tmp_format.erase(dot, 1);
1178 file_format = strToInt(tmp_format);
1179 //lyxerr << "format: " << file_format << endl;
1180 if (file_format == LYX_FORMAT) {
1182 } else if (file_format > LYX_FORMAT) {
1184 Alert::alert(_("Warning!"),
1185 _("The file was created with a newer version of"
1186 "LyX. This is likely to cause problems."));
1188 } else if (file_format < LYX_FORMAT) {
1190 if (file_format < 200) {
1191 Alert::alert(_("ERROR!"),
1192 _("Old LyX file format found. "
1193 "Use LyX 0.10.x to read this!"));
1195 } else if (!filename.empty()) {
1197 LibFileSearch("lyx2lyx", "lyx2lyx");
1198 if (command.empty()) {
1199 Alert::alert(_("ERROR!"),
1200 _("Can't find conversion script."));
1204 +tostr(LYX_FORMAT) + ' '
1205 + QuoteName(filename);
1206 lyxerr[Debug::INFO] << "Running '"
1209 cmd_ret const ret = RunCommand(command);
1211 Alert::alert(_("ERROR!"),
1212 _("An error occured while "
1213 "running the conversion script."));
1216 istringstream is(STRCONV(ret.second));
1217 LyXLex tmplex(0, 0);
1218 tmplex.setStream(is);
1219 return readFile(tmplex, string());
1221 // This code is reached if lyx2lyx failed (for
1222 // some reason) to change the file format of
1228 bool the_end = readLyXformat2(lex, par);
1229 params.setPaperStuff();
1232 // the_end was added in 213
1233 if (file_format < 213)
1238 Alert::alert(_("Warning!"),
1239 _("Reading of document is not complete"),
1240 _("Maybe the document is truncated"));
1243 } else { // "\\lyxformat" not found
1244 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1247 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1252 // Should probably be moved to somewhere else: BufferView? LyXView?
1253 bool Buffer::save() const
1255 // We don't need autosaves in the immediate future. (Asger)
1256 resetAutosaveTimers();
1260 if (lyxrc.make_backup) {
1261 s = fileName() + '~';
1262 if (!lyxrc.backupdir_path.empty())
1263 s = AddName(lyxrc.backupdir_path,
1264 subst(os::slashify_path(s),'/','!'));
1266 // Rename is the wrong way of making a backup,
1267 // this is the correct way.
1268 /* truss cp fil fil2:
1269 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1270 stat("LyXVC.lyx", 0xEFFFF688) = 0
1271 open("LyXVC.lyx", O_RDONLY) = 3
1272 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1273 fstat(4, 0xEFFFF508) = 0
1274 fstat(3, 0xEFFFF508) = 0
1275 read(3, " # T h i s f i l e w".., 8192) = 5579
1276 write(4, " # T h i s f i l e w".., 5579) = 5579
1277 read(3, 0xEFFFD4A0, 8192) = 0
1280 chmod("LyXVC3.lyx", 0100644) = 0
1281 lseek(0, 0, SEEK_CUR) = 46440
1285 // Should probably have some more error checking here.
1286 // Doing it this way, also makes the inodes stay the same.
1287 // This is still not a very good solution, in particular we
1288 // might loose the owner of the backup.
1289 FileInfo finfo(fileName());
1290 if (finfo.exist()) {
1291 mode_t fmode = finfo.getMode();
1292 struct utimbuf times = {
1293 finfo.getAccessTime(),
1294 finfo.getModificationTime() };
1296 ifstream ifs(fileName().c_str());
1297 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1302 ::chmod(s.c_str(), fmode);
1304 if (::utime(s.c_str(), ×)) {
1305 lyxerr << "utime error." << endl;
1308 lyxerr << "LyX was not able to make "
1309 "backup copy. Beware." << endl;
1314 if (writeFile(fileName())) {
1316 removeAutosaveFile(fileName());
1318 // Saving failed, so backup is not backup
1319 if (lyxrc.make_backup) {
1320 lyx::rename(s, fileName());
1328 bool Buffer::writeFile(string const & fname) const
1330 if (read_only && (fname == fileName())) {
1334 FileInfo finfo(fname);
1335 if (finfo.exist() && !finfo.writable()) {
1339 ofstream ofs(fname.c_str());
1345 // Use the standard "C" locale for file output.
1346 ofs.imbue(std::locale::classic());
1349 // The top of the file should not be written by params.
1351 // write out a comment in the top of the file
1352 ofs << '#' << lyx_docversion
1353 << " created this file. For more info see http://www.lyx.org/\n"
1354 << "\\lyxformat " << LYX_FORMAT << "\n";
1356 // now write out the buffer paramters.
1357 params.writeFile(ofs);
1359 Paragraph::depth_type depth = 0;
1361 // this will write out all the paragraphs
1362 // using recursive descent.
1363 ParagraphList::iterator pit = paragraphs.begin();
1364 ParagraphList::iterator pend = paragraphs.end();
1365 for (; pit != pend; ++pit)
1366 pit->write(this, ofs, params, depth);
1368 // Write marker that shows file is complete
1369 ofs << "\n\\the_end" << endl;
1373 // how to check if close went ok?
1374 // Following is an attempt... (BE 20001011)
1376 // good() returns false if any error occured, including some
1377 // formatting error.
1378 // bad() returns true if something bad happened in the buffer,
1379 // which should include file system full errors.
1386 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1388 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1400 pair<int, string> const addDepth(int depth, int ldepth)
1404 d += (ldepth - depth) * 2;
1405 return make_pair(d, string(d, ' '));
1411 string const Buffer::asciiParagraph(Paragraph const & par,
1412 unsigned int linelen,
1413 bool noparbreak) const
1415 ostringstream buffer;
1416 Paragraph::depth_type depth = 0;
1418 Paragraph::depth_type ltype_depth = 0;
1419 bool ref_printed = false;
1420 // if (!par->previous()) {
1422 // begins or ends a deeper area ?
1423 if (depth != par->params().depth()) {
1424 if (par->params().depth() > depth) {
1425 while (par->params().depth() > depth) {
1429 while (par->params().depth() < depth) {
1435 depth = par.params().depth();
1438 // First write the layout
1439 string const & tmp = par.layout()->name();
1440 if (compare_no_case(tmp, "itemize") == 0) {
1442 ltype_depth = depth + 1;
1443 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1445 ltype_depth = depth + 1;
1446 } else if (contains(ascii_lowercase(tmp), "ection")) {
1448 ltype_depth = depth + 1;
1449 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1451 ltype_depth = depth + 1;
1452 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1454 ltype_depth = depth + 1;
1455 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1458 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1466 /* maybe some vertical spaces */
1468 /* the labelwidthstring used in lists */
1472 /* some pagebreaks? */
1476 /* what about the alignment */
1478 // lyxerr << "Should this ever happen?" << endl;
1481 // linelen <= 0 is special and means we don't have paragraph breaks
1483 string::size_type currlinelen = 0;
1489 buffer << string(depth * 2, ' ');
1490 currlinelen += depth * 2;
1493 // we should probably change to the paragraph language in the
1494 // gettext here (if possible) so that strings are outputted in
1495 // the correct language! (20012712 Jug)
1499 case 4: // (Sub)Paragraph
1500 case 5: // Description
1504 buffer << _("Abstract") << "\n\n";
1507 string const abst = _("Abstract: ");
1509 currlinelen += abst.length();
1512 case 7: // Bibliography
1515 buffer << _("References") << "\n\n";
1518 string const refs = _("References: ");
1520 currlinelen += refs.length();
1528 string const parlab = par.params().labelString();
1529 buffer << parlab << ' ';
1530 currlinelen += parlab.length() + 1;
1538 pair<int, string> p = addDepth(depth, ltype_depth);
1540 currlinelen += p.first;
1543 // this is to change the linebreak to do it by word a bit more
1544 // intelligent hopefully! (only in the case where we have a
1545 // max linelenght!) (Jug)
1549 for (pos_type i = 0; i < par.size(); ++i) {
1550 char c = par.getUChar(params, i);
1552 case Paragraph::META_INSET:
1554 Inset const * inset = par.getInset(i);
1558 currlinelen += word.length();
1561 if (inset->ascii(this, buffer, linelen)) {
1562 // to be sure it breaks paragraph
1563 currlinelen += linelen;
1569 case Paragraph::META_NEWLINE:
1571 buffer << word << "\n";
1574 pair<int, string> p = addDepth(depth,
1577 currlinelen = p.first;
1581 case Paragraph::META_HFILL:
1582 buffer << word << "\t";
1583 currlinelen += word.length() + 1;
1590 currlinelen + word.length() > linelen - 10) {
1592 pair<int, string> p =
1593 addDepth(depth, ltype_depth);
1595 currlinelen = p.first;
1598 buffer << word << ' ';
1599 currlinelen += word.length() + 1;
1606 lyxerr[Debug::INFO] <<
1607 "writeAsciiFile: NULL char in structure." << endl;
1609 if ((linelen > 0) &&
1610 (currlinelen + word.length()) > linelen)
1614 pair<int, string> p =
1615 addDepth(depth, ltype_depth);
1617 currlinelen = p.first;
1624 return STRCONV(buffer.str());
1628 void Buffer::writeFileAscii(string const & fname, int linelen)
1630 ofstream ofs(fname.c_str());
1632 Alert::err_alert(_("Error: Cannot write file:"), fname);
1635 writeFileAscii(ofs, linelen);
1639 void Buffer::writeFileAscii(ostream & os, int linelen)
1641 ParagraphList::iterator beg = paragraphs.begin();
1642 ParagraphList::iterator end = paragraphs.end();
1643 ParagraphList::iterator it = beg;
1644 for (; it != end; ++it) {
1645 os << asciiParagraph(*it, linelen, it == beg);
1654 void Buffer::makeLaTeXFile(string const & fname,
1655 string const & original_path,
1656 bool nice, bool only_body, bool only_preamble)
1658 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1660 ofstream ofs(fname.c_str());
1662 Alert::err_alert(_("Error: Cannot open file: "), fname);
1666 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1670 lyxerr << "File was not closed properly." << endl;
1675 void Buffer::makeLaTeXFile(ostream & os,
1676 string const & original_path,
1677 bool nice, bool only_body, bool only_preamble)
1679 niceFile = nice; // this will be used by Insetincludes.
1681 // validate the buffer.
1682 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1683 LaTeXFeatures features(params);
1685 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1688 // The starting paragraph of the coming rows is the
1689 // first paragraph of the document. (Asger)
1690 texrow.start(&*(paragraphs.begin()), 0);
1692 if (!only_body && nice) {
1693 os << "%% " << lyx_docversion << " created this file. "
1694 "For more info, see http://www.lyx.org/.\n"
1695 "%% Do not edit unless you really know what "
1700 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1701 // There are a few differences between nice LaTeX and usual files:
1702 // usual is \batchmode and has a
1703 // special input@path to allow the including of figures
1704 // with either \input or \includegraphics (what figinsets do).
1705 // input@path is set when the actual parameter
1706 // original_path is set. This is done for usual tex-file, but not
1707 // for nice-latex-file. (Matthias 250696)
1710 // code for usual, NOT nice-latex-file
1711 os << "\\batchmode\n"; // changed
1712 // from \nonstopmode
1715 if (!original_path.empty()) {
1716 string inputpath = os::external_path(original_path);
1717 subst(inputpath, "~", "\\string~");
1718 os << "\\makeatletter\n"
1719 << "\\def\\input@path{{"
1720 << inputpath << "/}}\n"
1721 << "\\makeatother\n";
1727 os << "\\documentclass";
1729 LyXTextClass const & tclass = params.getLyXTextClass();
1731 ostringstream options; // the document class options.
1733 if (tokenPos(tclass.opt_fontsize(),
1734 '|', params.fontsize) >= 0) {
1735 // only write if existing in list (and not default)
1736 options << params.fontsize << "pt,";
1740 if (!params.use_geometry &&
1741 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1742 switch (params.papersize) {
1743 case BufferParams::PAPER_A4PAPER:
1744 options << "a4paper,";
1746 case BufferParams::PAPER_USLETTER:
1747 options << "letterpaper,";
1749 case BufferParams::PAPER_A5PAPER:
1750 options << "a5paper,";
1752 case BufferParams::PAPER_B5PAPER:
1753 options << "b5paper,";
1755 case BufferParams::PAPER_EXECUTIVEPAPER:
1756 options << "executivepaper,";
1758 case BufferParams::PAPER_LEGALPAPER:
1759 options << "legalpaper,";
1765 if (params.sides != tclass.sides()) {
1766 switch (params.sides) {
1767 case LyXTextClass::OneSide:
1768 options << "oneside,";
1770 case LyXTextClass::TwoSides:
1771 options << "twoside,";
1777 if (params.columns != tclass.columns()) {
1778 if (params.columns == 2)
1779 options << "twocolumn,";
1781 options << "onecolumn,";
1784 if (!params.use_geometry
1785 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1786 options << "landscape,";
1788 // language should be a parameter to \documentclass
1790 ostringstream language_options;
1791 if (params.language->babel() == "hebrew"
1792 && default_language->babel() != "hebrew")
1793 // This seems necessary
1794 features.useLanguage(default_language);
1796 if (lyxrc.language_use_babel ||
1797 params.language->lang() != lyxrc.default_language ||
1798 features.hasLanguages()) {
1800 language_options << features.getLanguages();
1801 language_options << params.language->babel();
1802 if (lyxrc.language_global_options)
1803 options << language_options.str() << ',';
1806 // the user-defined options
1807 if (!params.options.empty()) {
1808 options << params.options << ',';
1811 string strOptions(STRCONV(options.str()));
1812 if (!strOptions.empty()) {
1813 strOptions = rtrim(strOptions, ",");
1814 os << '[' << strOptions << ']';
1817 os << '{' << tclass.latexname() << "}\n";
1819 // end of \documentclass defs
1821 // font selection must be done before loading fontenc.sty
1822 // The ae package is not needed when using OT1 font encoding.
1823 if (params.fonts != "default" &&
1824 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1825 os << "\\usepackage{" << params.fonts << "}\n";
1827 if (params.fonts == "ae") {
1828 os << "\\usepackage{aecompl}\n";
1832 // this one is not per buffer
1833 if (lyxrc.fontenc != "default") {
1834 os << "\\usepackage[" << lyxrc.fontenc
1839 if (params.inputenc == "auto") {
1840 string const doc_encoding =
1841 params.language->encoding()->LatexName();
1843 // Create a list with all the input encodings used
1845 set<string> encodings = features.getEncodingSet(doc_encoding);
1847 os << "\\usepackage[";
1848 std::copy(encodings.begin(), encodings.end(),
1849 std::ostream_iterator<string>(os, ","));
1850 os << doc_encoding << "]{inputenc}\n";
1852 } else if (params.inputenc != "default") {
1853 os << "\\usepackage[" << params.inputenc
1858 // At the very beginning the text parameters.
1859 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1860 switch (params.paperpackage) {
1861 case BufferParams::PACKAGE_A4:
1862 os << "\\usepackage{a4}\n";
1865 case BufferParams::PACKAGE_A4WIDE:
1866 os << "\\usepackage{a4wide}\n";
1869 case BufferParams::PACKAGE_WIDEMARGINSA4:
1870 os << "\\usepackage[widemargins]{a4}\n";
1875 if (params.use_geometry) {
1876 os << "\\usepackage{geometry}\n";
1878 os << "\\geometry{verbose";
1879 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1881 switch (params.papersize2) {
1882 case BufferParams::VM_PAPER_CUSTOM:
1883 if (!params.paperwidth.empty())
1884 os << ",paperwidth="
1885 << params.paperwidth;
1886 if (!params.paperheight.empty())
1887 os << ",paperheight="
1888 << params.paperheight;
1890 case BufferParams::VM_PAPER_USLETTER:
1891 os << ",letterpaper";
1893 case BufferParams::VM_PAPER_USLEGAL:
1894 os << ",legalpaper";
1896 case BufferParams::VM_PAPER_USEXECUTIVE:
1897 os << ",executivepaper";
1899 case BufferParams::VM_PAPER_A3:
1902 case BufferParams::VM_PAPER_A4:
1905 case BufferParams::VM_PAPER_A5:
1908 case BufferParams::VM_PAPER_B3:
1911 case BufferParams::VM_PAPER_B4:
1914 case BufferParams::VM_PAPER_B5:
1918 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1919 switch (lyxrc.default_papersize) {
1920 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1921 case BufferParams::PAPER_USLETTER:
1922 os << ",letterpaper";
1924 case BufferParams::PAPER_LEGALPAPER:
1925 os << ",legalpaper";
1927 case BufferParams::PAPER_EXECUTIVEPAPER:
1928 os << ",executivepaper";
1930 case BufferParams::PAPER_A3PAPER:
1933 case BufferParams::PAPER_A4PAPER:
1936 case BufferParams::PAPER_A5PAPER:
1939 case BufferParams::PAPER_B5PAPER:
1944 if (!params.topmargin.empty())
1945 os << ",tmargin=" << params.topmargin;
1946 if (!params.bottommargin.empty())
1947 os << ",bmargin=" << params.bottommargin;
1948 if (!params.leftmargin.empty())
1949 os << ",lmargin=" << params.leftmargin;
1950 if (!params.rightmargin.empty())
1951 os << ",rmargin=" << params.rightmargin;
1952 if (!params.headheight.empty())
1953 os << ",headheight=" << params.headheight;
1954 if (!params.headsep.empty())
1955 os << ",headsep=" << params.headsep;
1956 if (!params.footskip.empty())
1957 os << ",footskip=" << params.footskip;
1962 if (tokenPos(tclass.opt_pagestyle(),
1963 '|', params.pagestyle) >= 0) {
1964 if (params.pagestyle == "fancy") {
1965 os << "\\usepackage{fancyhdr}\n";
1968 os << "\\pagestyle{" << params.pagestyle << "}\n";
1972 if (params.secnumdepth != tclass.secnumdepth()) {
1973 os << "\\setcounter{secnumdepth}{"
1974 << params.secnumdepth
1978 if (params.tocdepth != tclass.tocdepth()) {
1979 os << "\\setcounter{tocdepth}{"
1985 if (params.paragraph_separation) {
1986 switch (params.defskip.kind()) {
1987 case VSpace::SMALLSKIP:
1988 os << "\\setlength\\parskip{\\smallskipamount}\n";
1990 case VSpace::MEDSKIP:
1991 os << "\\setlength\\parskip{\\medskipamount}\n";
1993 case VSpace::BIGSKIP:
1994 os << "\\setlength\\parskip{\\bigskipamount}\n";
1996 case VSpace::LENGTH:
1997 os << "\\setlength\\parskip{"
1998 << params.defskip.length().asLatexString()
2001 default: // should never happen // Then delete it.
2002 os << "\\setlength\\parskip{\\medskipamount}\n";
2007 os << "\\setlength\\parindent{0pt}\n";
2011 // Now insert the LyX specific LaTeX commands...
2013 // The optional packages;
2014 string preamble(features.getPackages());
2016 // this might be useful...
2017 preamble += "\n\\makeatletter\n";
2019 // Some macros LyX will need
2020 string tmppreamble(features.getMacros());
2022 if (!tmppreamble.empty()) {
2023 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2024 "LyX specific LaTeX commands.\n"
2025 + tmppreamble + '\n';
2028 // the text class specific preamble
2029 tmppreamble = features.getTClassPreamble();
2030 if (!tmppreamble.empty()) {
2031 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2032 "Textclass specific LaTeX commands.\n"
2033 + tmppreamble + '\n';
2036 /* the user-defined preamble */
2037 if (!params.preamble.empty()) {
2038 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2039 "User specified LaTeX commands.\n"
2040 + params.preamble + '\n';
2043 // Itemize bullet settings need to be last in case the user
2044 // defines their own bullets that use a package included
2045 // in the user-defined preamble -- ARRae
2046 // Actually it has to be done much later than that
2047 // since some packages like frenchb make modifications
2048 // at \begin{document} time -- JMarc
2050 for (int i = 0; i < 4; ++i) {
2051 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2052 if (bullets_def.empty())
2053 bullets_def="\\AtBeginDocument{\n";
2054 bullets_def += " \\renewcommand{\\labelitemi";
2056 // `i' is one less than the item to modify
2063 bullets_def += "ii";
2069 bullets_def += "}{" +
2070 params.user_defined_bullets[i].getText()
2075 if (!bullets_def.empty())
2076 preamble += bullets_def + "}\n\n";
2079 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2080 for (int j = 0; j != nlines; ++j) {
2084 // We try to load babel late, in case it interferes
2085 // with other packages.
2087 string tmp = lyxrc.language_package;
2088 if (!lyxrc.language_global_options
2089 && tmp == "\\usepackage{babel}")
2090 tmp = string("\\usepackage[") +
2091 STRCONV(language_options.str()) +
2093 preamble += tmp + "\n";
2094 preamble += features.getBabelOptions();
2097 preamble += "\\makeatother\n";
2105 os << "\\begin{document}\n";
2108 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2110 if (!lyxrc.language_auto_begin) {
2111 os << subst(lyxrc.language_command_begin, "$$lang",
2112 params.language->babel())
2117 latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2119 // add this just in case after all the paragraphs
2123 if (!lyxrc.language_auto_end) {
2124 os << subst(lyxrc.language_command_end, "$$lang",
2125 params.language->babel())
2131 os << "\\end{document}\n";
2134 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2136 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2140 // Just to be sure. (Asger)
2143 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
2144 lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
2147 // we want this to be true outside previews (for insetexternal)
2153 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2155 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2156 Paragraph * endpar, TexRow & texrow,
2157 bool moving_arg) const
2159 bool was_title = false;
2160 bool already_title = false;
2163 while (par != endpar) {
2164 Inset * in = par->inInset();
2165 // well we have to check if we are in an inset with unlimited
2166 // length (all in one row) if that is true then we don't allow
2167 // any special options in the paragraph and also we don't allow
2168 // any environment other then "Standard" to be valid!
2169 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2170 LyXLayout_ptr const & layout = par->layout();
2172 if (layout->intitle) {
2173 if (already_title) {
2174 lyxerr <<"Error in latexParagraphs: You"
2175 " should not mix title layouts"
2176 " with normal ones." << endl;
2179 } else if (was_title && !already_title) {
2180 ofs << "\\maketitle\n";
2182 already_title = true;
2186 if (layout->isEnvironment() ||
2187 !par->params().leftIndent().zero())
2189 par = par->TeXEnvironment(this, params, ofs, texrow);
2191 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2194 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2197 // It might be that we only have a title in this document
2198 if (was_title && !already_title) {
2199 ofs << "\\maketitle\n";
2205 bool Buffer::isLatex() const
2207 return params.getLyXTextClass().outputType() == LATEX;
2211 bool Buffer::isLinuxDoc() const
2213 return params.getLyXTextClass().outputType() == LINUXDOC;
2217 bool Buffer::isLiterate() const
2219 return params.getLyXTextClass().outputType() == LITERATE;
2223 bool Buffer::isDocBook() const
2225 return params.getLyXTextClass().outputType() == DOCBOOK;
2229 bool Buffer::isSGML() const
2231 LyXTextClass const & tclass = params.getLyXTextClass();
2233 return tclass.outputType() == LINUXDOC ||
2234 tclass.outputType() == DOCBOOK;
2238 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2240 ofstream ofs(fname.c_str());
2243 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2247 niceFile = nice; // this will be used by included files.
2249 LaTeXFeatures features(params);
2255 LyXTextClass const & tclass = params.getLyXTextClass();
2257 string top_element = tclass.latexname();
2260 ofs << "<!doctype linuxdoc system";
2262 string preamble = params.preamble;
2263 const string name = nice ? ChangeExtension(filename_, ".sgml")
2265 preamble += features.getIncludedFiles(name);
2266 preamble += features.getLyXSGMLEntities();
2268 if (!preamble.empty()) {
2269 ofs << " [ " << preamble << " ]";
2273 if (params.options.empty())
2274 sgml::openTag(ofs, 0, false, top_element);
2276 string top = top_element;
2278 top += params.options;
2279 sgml::openTag(ofs, 0, false, top);
2283 ofs << "<!-- " << lyx_docversion
2284 << " created this file. For more info see http://www.lyx.org/"
2287 Paragraph::depth_type depth = 0; // paragraph depth
2288 Paragraph * par = &*(paragraphs.begin());
2290 vector<string> environment_stack(5);
2293 LyXLayout_ptr const & style = par->layout();
2294 // treat <toc> as a special case for compatibility with old code
2295 if (par->isInset(0)) {
2296 Inset * inset = par->getInset(0);
2297 Inset::Code lyx_code = inset->lyxCode();
2298 if (lyx_code == Inset::TOC_CODE) {
2299 string const temp = "toc";
2300 sgml::openTag(ofs, depth, false, temp);
2307 // environment tag closing
2308 for (; depth > par->params().depth(); --depth) {
2309 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2310 environment_stack[depth].erase();
2313 // write opening SGML tags
2314 switch (style->latextype) {
2315 case LATEX_PARAGRAPH:
2316 if (depth == par->params().depth()
2317 && !environment_stack[depth].empty()) {
2318 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2319 environment_stack[depth].erase();
2325 sgml::openTag(ofs, depth, false, style->latexname());
2331 _("Error: Wrong depth for LatexType Command.\n"));
2333 if (!environment_stack[depth].empty()) {
2334 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2338 environment_stack[depth].erase();
2339 sgml::openTag(ofs, depth, false, style->latexname());
2342 case LATEX_ENVIRONMENT:
2343 case LATEX_ITEM_ENVIRONMENT:
2345 string const & latexname = style->latexname();
2347 if (depth == par->params().depth()
2348 && environment_stack[depth] != latexname) {
2349 sgml::closeTag(ofs, depth, false,
2350 environment_stack[depth]);
2351 environment_stack[depth].erase();
2353 if (depth < par->params().depth()) {
2354 depth = par->params().depth();
2355 environment_stack[depth].erase();
2357 if (environment_stack[depth] != latexname) {
2359 sgml::openTag(ofs, depth, false, "p");
2361 sgml::openTag(ofs, depth, false, latexname);
2363 if (environment_stack.size() == depth + 1)
2364 environment_stack.push_back("!-- --");
2365 environment_stack[depth] = latexname;
2368 if (style->latexparam() == "CDATA")
2371 if (style->latextype == LATEX_ENVIRONMENT) break;
2373 if (style->labeltype == LABEL_MANUAL)
2378 sgml::openTag(ofs, depth + 1, false, item_name);
2383 sgml::openTag(ofs, depth, false, style->latexname());
2387 simpleLinuxDocOnePar(ofs, par, depth);
2392 // write closing SGML tags
2393 switch (style->latextype) {
2396 case LATEX_ENVIRONMENT:
2397 case LATEX_ITEM_ENVIRONMENT:
2398 if (style->latexparam() == "CDATA")
2402 sgml::closeTag(ofs, depth, false, style->latexname());
2408 for (int i = depth; i >= 0; --i)
2409 sgml::closeTag(ofs, depth, false, environment_stack[i]);
2413 sgml::closeTag(ofs, 0, false, top_element);
2417 // How to check for successful close
2419 // we want this to be true outside previews (for insetexternal)
2424 // checks, if newcol chars should be put into this line
2425 // writes newline, if necessary.
2428 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2429 string::size_type newcol)
2432 if (colcount > lyxrc.ascii_linelen) {
2434 colcount = newcol; // assume write after this call
2449 string tag_name(PAR_TAG const & pt) {
2451 case NONE: return "!-- --";
2452 case TT: return "tt";
2453 case SF: return "sf";
2454 case BF: return "bf";
2455 case IT: return "it";
2456 case SL: return "sl";
2457 case EM: return "em";
2464 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2466 p1 = static_cast<PAR_TAG>(p1 | p2);
2471 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2473 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2479 // Handle internal paragraph parsing -- layout already processed.
2480 void Buffer::simpleLinuxDocOnePar(ostream & os,
2482 Paragraph::depth_type /*depth*/)
2484 LyXLayout_ptr const & style = par->layout();
2486 string::size_type char_line_count = 5; // Heuristic choice ;-)
2488 // gets paragraph main font
2491 if (style->labeltype == LABEL_MANUAL) {
2492 font_old = style->labelfont;
2495 font_old = style->font;
2499 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2500 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2501 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2504 stack<PAR_TAG> tag_state;
2505 // parsing main loop
2506 for (pos_type i = 0; i < par->size(); ++i) {
2508 PAR_TAG tag_close = NONE;
2509 list < PAR_TAG > tag_open;
2511 LyXFont const font = par->getFont(params, i);
2513 if (font_old.family() != font.family()) {
2514 switch (family_type) {
2515 case LyXFont::SANS_FAMILY:
2518 case LyXFont::TYPEWRITER_FAMILY:
2525 family_type = font.family();
2527 switch (family_type) {
2528 case LyXFont::SANS_FAMILY:
2529 tag_open.push_back(SF);
2531 case LyXFont::TYPEWRITER_FAMILY:
2532 tag_open.push_back(TT);
2539 if (font_old.series() != font.series()) {
2540 switch (series_type) {
2541 case LyXFont::BOLD_SERIES:
2548 series_type = font.series();
2550 switch (series_type) {
2551 case LyXFont::BOLD_SERIES:
2552 tag_open.push_back(BF);
2560 if (font_old.shape() != font.shape()) {
2561 switch (shape_type) {
2562 case LyXFont::ITALIC_SHAPE:
2565 case LyXFont::SLANTED_SHAPE:
2572 shape_type = font.shape();
2574 switch (shape_type) {
2575 case LyXFont::ITALIC_SHAPE:
2576 tag_open.push_back(IT);
2578 case LyXFont::SLANTED_SHAPE:
2579 tag_open.push_back(SL);
2586 if (font_old.emph() != font.emph()) {
2587 if (font.emph() == LyXFont::ON) {
2588 tag_open.push_back(EM);
2597 list < PAR_TAG > temp;
2598 while (!tag_state.empty() && tag_close) {
2599 PAR_TAG k = tag_state.top();
2601 os << "</" << tag_name(k) << '>';
2608 for(list< PAR_TAG >::const_iterator j = temp.begin();
2609 j != temp.end(); ++j) {
2611 os << '<' << tag_name(*j) << '>';
2614 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2615 j != tag_open.end(); ++j) {
2617 os << '<' << tag_name(*j) << '>';
2620 char c = par->getChar(i);
2622 if (c == Paragraph::META_INSET) {
2623 Inset * inset = par->getInset(i);
2624 inset->linuxdoc(this, os);
2629 if (style->latexparam() == "CDATA") {
2630 // "TeX"-Mode on == > SGML-Mode on.
2637 boost::tie(ws, str) = sgml::escapeChar(c);
2638 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2639 // in freespacing mode, spaces are
2640 // non-breaking characters
2641 if (desc_on) {// if char is ' ' then...
2644 sgmlLineBreak(os, char_line_count, 6);
2648 sgmlLineBreak(os, char_line_count, 1);
2653 char_line_count += str.length();
2659 while (!tag_state.empty()) {
2660 os << "</" << tag_name(tag_state.top()) << '>';
2664 // resets description flag correctly
2666 // <tag> not closed...
2667 sgmlLineBreak(os, char_line_count, 6);
2673 // Print an error message.
2674 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2675 string const & /*message*/) const
2677 #ifdef WITH_WARNINGS
2678 #warning This is wrong we cannot insert an inset like this!!!
2679 // I guess this was Jose' so I explain you more or less why this
2680 // is wrong. This way you insert something in the paragraph and
2681 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2682 // I deactivate this code, have a look at BufferView::insertErrors
2683 // how you should do this correctly! (Jug 20020315)
2686 // insert an error marker in text
2687 InsetError * new_inset = new InsetError(message);
2688 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2694 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2696 ofstream ofs(fname.c_str());
2698 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2702 Paragraph * par = &*(paragraphs.begin());
2704 niceFile = nice; // this will be used by Insetincludes.
2706 LaTeXFeatures features(params);
2711 LyXTextClass const & tclass = params.getLyXTextClass();
2712 string top_element = tclass.latexname();
2715 ofs << "<!DOCTYPE " << top_element
2716 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2718 string preamble = params.preamble;
2719 const string name = nice ? ChangeExtension(filename_, ".sgml")
2721 preamble += features.getIncludedFiles(name);
2722 preamble += features.getLyXSGMLEntities();
2724 if (!preamble.empty()) {
2725 ofs << "\n [ " << preamble << " ]";
2730 string top = top_element;
2732 top += params.language->code();
2735 if (!params.options.empty()) {
2737 top += params.options;
2739 sgml::openTag(ofs, 0, false, top);
2741 ofs << "<!-- DocBook file was created by " << lyx_docversion
2742 << "\n See http://www.lyx.org/ for more information -->\n";
2744 vector<string> environment_stack(10);
2745 vector<string> environment_inner(10);
2746 vector<string> command_stack(10);
2748 bool command_flag = false;
2749 Paragraph::depth_type command_depth = 0;
2750 Paragraph::depth_type command_base = 0;
2751 Paragraph::depth_type cmd_depth = 0;
2752 Paragraph::depth_type depth = 0; // paragraph depth
2755 string command_name;
2761 int desc_on = 0; // description mode
2763 LyXLayout_ptr const & style = par->layout();
2765 // environment tag closing
2766 for (; depth > par->params().depth(); --depth) {
2767 if (environment_inner[depth] != "!-- --") {
2768 item_name = "listitem";
2769 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2770 if (environment_inner[depth] == "varlistentry")
2771 sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2773 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2774 environment_stack[depth].erase();
2775 environment_inner[depth].erase();
2778 if (depth == par->params().depth()
2779 && environment_stack[depth] != style->latexname()
2780 && !environment_stack[depth].empty()) {
2781 if (environment_inner[depth] != "!-- --") {
2782 item_name= "listitem";
2783 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2784 if (environment_inner[depth] == "varlistentry")
2785 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2788 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2790 environment_stack[depth].erase();
2791 environment_inner[depth].erase();
2794 // Write opening SGML tags.
2795 switch (style->latextype) {
2796 case LATEX_PARAGRAPH:
2797 sgml::openTag(ofs, depth + command_depth,
2798 false, style->latexname());
2804 _("Error: Wrong depth for LatexType Command.\n"));
2806 command_name = style->latexname();
2808 sgmlparam = style->latexparam();
2809 c_params = split(sgmlparam, c_depth,'|');
2811 cmd_depth = lyx::atoi(c_depth);
2814 if (cmd_depth < command_base) {
2815 for (Paragraph::depth_type j = command_depth;
2816 j >= command_base; --j) {
2817 sgml::closeTag(ofs, j, false, command_stack[j]);
2820 command_depth = command_base = cmd_depth;
2821 } else if (cmd_depth <= command_depth) {
2822 for (int j = command_depth;
2823 j >= int(cmd_depth); --j) {
2824 sgml::closeTag(ofs, j, false, command_stack[j]);
2827 command_depth = cmd_depth;
2829 command_depth = cmd_depth;
2831 command_depth = command_base = cmd_depth;
2832 command_flag = true;
2834 if (command_stack.size() == command_depth + 1)
2835 command_stack.push_back(string());
2836 command_stack[command_depth] = command_name;
2838 // treat label as a special case for
2839 // more WYSIWYM handling.
2840 // This is a hack while paragraphs can't have
2841 // attributes, like id in this case.
2842 if (par->isInset(0)) {
2843 Inset * inset = par->getInset(0);
2844 Inset::Code lyx_code = inset->lyxCode();
2845 if (lyx_code == Inset::LABEL_CODE) {
2846 command_name += " id=\"";
2847 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2848 command_name += '"';
2853 sgml::openTag(ofs, depth + command_depth, false, command_name);
2855 item_name = c_params.empty() ? "title" : c_params;
2856 sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2859 case LATEX_ENVIRONMENT:
2860 case LATEX_ITEM_ENVIRONMENT:
2861 if (depth < par->params().depth()) {
2862 depth = par->params().depth();
2863 environment_stack[depth].erase();
2866 if (environment_stack[depth] != style->latexname()) {
2867 if (environment_stack.size() == depth + 1) {
2868 environment_stack.push_back("!-- --");
2869 environment_inner.push_back("!-- --");
2871 environment_stack[depth] = style->latexname();
2872 environment_inner[depth] = "!-- --";
2873 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2875 if (environment_inner[depth] != "!-- --") {
2876 item_name= "listitem";
2877 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2878 if (environment_inner[depth] == "varlistentry")
2879 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2883 if (style->latextype == LATEX_ENVIRONMENT) {
2884 if (!style->latexparam().empty()) {
2885 if (style->latexparam() == "CDATA")
2888 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2893 desc_on = (style->labeltype == LABEL_MANUAL);
2895 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2896 sgml::openTag(ofs, depth + 1 + command_depth,
2897 false, environment_inner[depth]);
2899 item_name = desc_on ? "term" : "para";
2900 sgml::openTag(ofs, depth + 1 + command_depth,
2904 sgml::openTag(ofs, depth + command_depth,
2905 false, style->latexname());
2909 simpleDocBookOnePar(ofs, par, desc_on,
2910 depth + 1 + command_depth);
2914 // write closing SGML tags
2915 switch (style->latextype) {
2917 end_tag = c_params.empty() ? "title" : c_params;
2918 sgml::closeTag(ofs, depth + command_depth,
2921 case LATEX_ENVIRONMENT:
2922 if (!style->latexparam().empty()) {
2923 if (style->latexparam() == "CDATA")
2926 sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2929 case LATEX_ITEM_ENVIRONMENT:
2930 if (desc_on == 1) break;
2932 sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2934 case LATEX_PARAGRAPH:
2935 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2938 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2944 for (int d = depth; d >= 0; --d) {
2945 if (!environment_stack[depth].empty()) {
2946 if (environment_inner[depth] != "!-- --") {
2947 item_name = "listitem";
2948 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2949 if (environment_inner[depth] == "varlistentry")
2950 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2953 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2957 for (int j = command_depth; j >= 0 ; --j)
2958 if (!command_stack[j].empty()) {
2959 sgml::closeTag(ofs, j, false, command_stack[j]);
2964 sgml::closeTag(ofs, 0, false, top_element);
2967 // How to check for successful close
2969 // we want this to be true outside previews (for insetexternal)
2974 void Buffer::simpleDocBookOnePar(ostream & os,
2975 Paragraph * par, int & desc_on,
2976 Paragraph::depth_type depth) const
2978 bool emph_flag = false;
2980 LyXLayout_ptr const & style = par->layout();
2982 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2984 int char_line_count = depth;
2985 //if (!style.free_spacing)
2986 // os << string(depth,' ');
2988 // parsing main loop
2989 for (pos_type i = 0; i < par->size(); ++i) {
2990 LyXFont font = par->getFont(params, i);
2992 // handle <emphasis> tag
2993 if (font_old.emph() != font.emph()) {
2994 if (font.emph() == LyXFont::ON) {
2995 if (style->latexparam() == "CDATA")
2998 if (style->latexparam() == "CDATA")
3002 if (style->latexparam() == "CDATA")
3004 os << "</emphasis>";
3005 if (style->latexparam() == "CDATA")
3012 if (par->isInset(i)) {
3013 Inset * inset = par->getInset(i);
3014 // don't print the inset in position 0 if desc_on == 3 (label)
3015 if (i || desc_on != 3) {
3016 if (style->latexparam() == "CDATA")
3018 inset->docbook(this, os, false);
3019 if (style->latexparam() == "CDATA")
3023 char c = par->getChar(i);
3026 boost::tie(ws, str) = sgml::escapeChar(c);
3028 if (style->pass_thru) {
3030 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3032 } else if (desc_on ==1) {
3034 os << "\n</term><listitem><para>";
3044 if (style->latexparam() == "CDATA")
3046 os << "</emphasis>";
3047 if (style->latexparam() == "CDATA")
3051 // resets description flag correctly
3053 // <term> not closed...
3054 os << "</term>\n<listitem><para> </para>";
3056 if (style->free_spacing)
3061 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3062 // Other flags: -wall -v0 -x
3063 int Buffer::runChktex()
3065 if (!users->text) return 0;
3067 users->owner()->prohibitInput();
3069 // get LaTeX-Filename
3070 string const name = getLatexName();
3071 string path = filePath();
3073 string const org_path = path;
3074 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3078 Path p(path); // path to LaTeX file
3079 users->owner()->message(_("Running chktex..."));
3081 // Remove all error insets
3082 bool const removedErrorInsets = users->removeAutoInsets();
3084 // Generate the LaTeX file if neccessary
3085 makeLaTeXFile(name, org_path, false);
3088 Chktex chktex(lyxrc.chktex_command, name, filePath());
3089 int res = chktex.run(terr); // run chktex
3092 Alert::alert(_("chktex did not work!"),
3093 _("Could not run with file:"), name);
3094 } else if (res > 0) {
3095 // Insert all errors as errors boxes
3096 users->insertErrors(terr);
3099 // if we removed error insets before we ran chktex or if we inserted
3100 // error insets after we ran chktex, this must be run:
3101 if (removedErrorInsets || res) {
3102 #warning repaint needed here, or do you mean update() ?
3106 users->owner()->allowInput();
3112 void Buffer::validate(LaTeXFeatures & features) const
3114 LyXTextClass const & tclass = params.getLyXTextClass();
3116 // AMS Style is at document level
3117 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3118 features.require("amsmath");
3120 for_each(paragraphs.begin(), paragraphs.end(),
3121 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3123 // the bullet shapes are buffer level not paragraph level
3124 // so they are tested here
3125 for (int i = 0; i < 4; ++i) {
3126 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3127 int const font = params.user_defined_bullets[i].getFont();
3129 int const c = params
3130 .user_defined_bullets[i]
3137 features.require("latexsym");
3139 } else if (font == 1) {
3140 features.require("amssymb");
3141 } else if ((font >= 2 && font <= 5)) {
3142 features.require("pifont");
3147 if (lyxerr.debugging(Debug::LATEX)) {
3148 features.showStruct();
3153 vector<string> const Buffer::getLabelList() const
3155 /// if this is a child document and the parent is already loaded
3156 /// Use the parent's list instead [ale990407]
3157 if (!params.parentname.empty()
3158 && bufferlist.exists(params.parentname)) {
3159 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3161 return tmp->getLabelList();
3164 vector<string> label_list;
3165 for (inset_iterator it = inset_const_iterator_begin();
3166 it != inset_const_iterator_end(); ++it) {
3167 vector<string> const l = it->getLabelList();
3168 label_list.insert(label_list.end(), l.begin(), l.end());
3174 // This is also a buffer property (ale)
3175 vector<pair<string, string> > const Buffer::getBibkeyList() const
3177 typedef pair<string, string> StringPair;
3178 /// if this is a child document and the parent is already loaded
3179 /// Use the parent's list instead [ale990412]
3180 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3181 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3183 return tmp->getBibkeyList();
3186 vector<StringPair> keys;
3187 ParagraphList::iterator pit = paragraphs.begin();
3188 ParagraphList::iterator pend = paragraphs.end();
3189 for (; pit != pend; ++pit) {
3191 string const key = pit->bibkey->getContents();
3192 string const opt = pit->bibkey->getOptions();
3193 string const ref = pit->asString(this, false);
3194 string const info = opt + "TheBibliographyRef" + ref;
3196 keys.push_back(StringPair(key, info));
3203 // Might be either using bibtex or a child has bibliography
3204 for (inset_iterator it = inset_const_iterator_begin();
3205 it != inset_const_iterator_end(); ++it) {
3206 // Search for Bibtex or Include inset
3207 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3208 vector<StringPair> tmp =
3209 static_cast<InsetBibtex &>(*it).getKeys(this);
3210 keys.insert(keys.end(), tmp.begin(), tmp.end());
3211 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3212 vector<StringPair> const tmp =
3213 static_cast<InsetInclude &>(*it).getKeys();
3214 keys.insert(keys.end(), tmp.begin(), tmp.end());
3222 bool Buffer::isDepClean(string const & name) const
3224 DEPCLEAN * item = dep_clean;
3225 while (item && item->master != name)
3227 if (!item) return true;
3232 void Buffer::markDepClean(string const & name)
3235 dep_clean = new DEPCLEAN;
3236 dep_clean->clean = true;
3237 dep_clean->master = name;
3238 dep_clean->next = 0;
3240 DEPCLEAN * item = dep_clean;
3241 while (item && item->master != name)
3246 item = new DEPCLEAN;
3248 item->master = name;
3255 bool Buffer::dispatch(string const & command, bool * result)
3257 // Split command string into command and argument
3259 string line = ltrim(command);
3260 string const arg = trim(split(line, cmd, ' '));
3262 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3266 bool Buffer::dispatch(int action, string const & argument, bool * result)
3268 bool dispatched = true;
3272 bool const tmp = Exporter::Export(this, argument, false);
3285 void Buffer::resizeInsets(BufferView * bv)
3287 /// then remove all LyXText in text-insets
3288 for_each(paragraphs.begin(), paragraphs.end(),
3289 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3293 void Buffer::redraw()
3295 #warning repaint needed here, or do you mean update() ?
3301 void Buffer::changeLanguage(Language const * from, Language const * to)
3304 ParIterator end = par_iterator_end();
3305 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3306 (*it)->changeLanguage(params, from, to);
3310 bool Buffer::isMultiLingual()
3312 ParIterator end = par_iterator_end();
3313 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3314 if ((*it)->isMultiLingual(params))
3321 void Buffer::inset_iterator::setParagraph()
3323 while (pit != pend) {
3324 it = pit->insetlist.begin();
3325 if (it != pit->insetlist.end())
3332 Inset * Buffer::getInsetFromID(int id_arg) const
3334 for (inset_iterator it = inset_const_iterator_begin();
3335 it != inset_const_iterator_end(); ++it)
3337 if (it->id() == id_arg)
3339 Inset * in = it->getInsetFromID(id_arg);
3347 Paragraph * Buffer::getParFromID(int id) const
3352 ParagraphList::iterator it = paragraphs.begin();
3353 ParagraphList::iterator end = paragraphs.end();
3354 for (; it != end; ++it) {
3355 if (it->id() == id) {
3358 Paragraph * tmp = it->getParFromID(id);
3367 ParIterator Buffer::par_iterator_begin()
3369 return ParIterator(&*(paragraphs.begin()));
3373 ParIterator Buffer::par_iterator_end()
3375 return ParIterator();
3378 ParConstIterator Buffer::par_iterator_begin() const
3380 return ParConstIterator(&*(paragraphs.begin()));
3384 ParConstIterator Buffer::par_iterator_end() const
3386 return ParConstIterator();
3391 void Buffer::addUser(BufferView * u)
3397 void Buffer::delUser(BufferView *)
3403 Language const * Buffer::getLanguage() const
3405 return params.language;
3409 bool Buffer::isClean() const
3415 bool Buffer::isBakClean() const
3421 void Buffer::markClean() const
3427 // if the .lyx file has been saved, we don't need an
3433 void Buffer::markBakClean()
3439 void Buffer::setUnnamed(bool flag)
3445 bool Buffer::isUnnamed()
3451 void Buffer::markDirty()
3458 DEPCLEAN * tmp = dep_clean;
3466 string const & Buffer::fileName() const
3472 string const & Buffer::filePath() const
3478 bool Buffer::isReadonly() const
3484 BufferView * Buffer::getUser() const
3490 void Buffer::setParentName(string const & name)
3492 params.parentname = name;
3496 Buffer::inset_iterator::inset_iterator()
3501 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3508 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3512 if (it == pit->insetlist.end()) {
3521 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3523 inset_iterator tmp = *this;
3529 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3531 return *it.getInset();
3535 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3537 return it.getInset();
3541 Paragraph * Buffer::inset_iterator::getPar()
3547 lyx::pos_type Buffer::inset_iterator::getPos() const
3553 bool operator==(Buffer::inset_iterator const & iter1,
3554 Buffer::inset_iterator const & iter2)
3556 return iter1.pit == iter2.pit
3557 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3561 bool operator!=(Buffer::inset_iterator const & iter1,
3562 Buffer::inset_iterator const & iter2)
3564 return !(iter1 == iter2);