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"
24 #include "LyXAction.h"
27 #include "tex-strings.h"
29 #include "bufferview_funcs.h"
35 #include "LaTeXFeatures.h"
42 #include "converter.h"
43 #include "BufferView.h"
44 #include "ParagraphParameters.h"
45 #include "iterators.h"
46 #include "lyxtextclasslist.h"
48 #include "paragraph_funcs.h"
50 #include "frontends/LyXView.h"
52 #include "mathed/formulamacro.h"
53 #include "mathed/formula.h"
55 #include "insets/inset.h"
56 #include "insets/inseterror.h"
57 #include "insets/insetlabel.h"
58 #include "insets/insetref.h"
59 #include "insets/inseturl.h"
60 #include "insets/insetnote.h"
61 #include "insets/insetquotes.h"
62 #include "insets/insetlatexaccent.h"
63 #include "insets/insetbib.h"
64 #include "insets/insetcite.h"
65 #include "insets/insetexternal.h"
66 #include "insets/insetindex.h"
67 #include "insets/insetinclude.h"
68 #include "insets/insettoc.h"
69 #include "insets/insetparent.h"
70 #include "insets/insetspecialchar.h"
71 #include "insets/insettext.h"
72 #include "insets/insetert.h"
73 #include "insets/insetgraphics.h"
74 #include "insets/insetfoot.h"
75 #include "insets/insetmarginal.h"
76 #include "insets/insetoptarg.h"
77 #include "insets/insetminipage.h"
78 #include "insets/insetfloat.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>
114 #include <sys/types.h>
121 #ifndef CXX_GLOBAL_CSTD
133 using std::make_pair;
143 using lyx::textclass_type;
145 // all these externs should eventually be removed.
146 extern BufferList bufferlist;
150 const int LYX_FORMAT = 221;
154 Buffer::Buffer(string const & file, bool ronly)
155 : niceFile(true), lyx_clean(true), bak_clean(true),
156 unnamed(false), dep_clean(0), read_only(ronly),
157 filename_(file), users(0), ctrs(new Counters)
159 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
160 filepath_ = OnlyPath(file);
162 if (read_only || lyxrc.use_tempdir) {
163 tmppath = CreateBufferTmpDir();
172 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
173 // here the buffer should take care that it is
174 // saved properly, before it goes into the void.
176 // make sure that views using this buffer
181 if (!tmppath.empty()) {
182 DestroyBufferTmpDir(tmppath);
187 // Remove any previewed LaTeX snippets assocoated with this buffer.
188 grfx::Previews::get().removeLoader(this);
192 string const Buffer::getLatexName(bool no_path) const
194 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
196 return OnlyFilename(name);
202 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
204 string const filename = getLatexName(false);
206 if (filename.empty())
207 return make_pair(Buffer::latexlog, string());
209 string path = OnlyPath(filename);
211 if (lyxrc.use_tempdir || !IsDirWriteable(path))
214 string const fname = AddName(path,
215 OnlyFilename(ChangeExtension(filename,
218 AddName(path, OnlyFilename(
219 ChangeExtension(filename,
220 formats.extension("literate") + ".out")));
222 // If no Latex log or Build log is newer, show Build log
224 FileInfo const f_fi(fname);
225 FileInfo const b_fi(bname);
228 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
229 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
230 return make_pair(Buffer::buildlog, bname);
232 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
233 return make_pair(Buffer::latexlog, fname);
237 void Buffer::setReadonly(bool flag)
239 if (read_only != flag) {
242 users->owner()->getDialogs().updateBufferDependent(false);
247 /// Update window titles of all users
248 // Should work on a list
249 void Buffer::updateTitles() const
252 users->owner()->updateWindowTitle();
256 /// Reset autosave timer of all users
257 // Should work on a list
258 void Buffer::resetAutosaveTimers() const
261 users->owner()->resetAutosaveTimer();
265 void Buffer::setFileName(string const & newfile)
267 filename_ = MakeAbsPath(newfile);
268 filepath_ = OnlyPath(filename_);
269 setReadonly(IsFileWriteable(filename_) == 0);
274 // We'll remove this later. (Lgb)
277 string last_inset_read;
280 #warning And _why_ is this here? (Lgb)
288 // candidate for move to BufferView
289 // (at least some parts in the beginning of the func)
292 // changed to be public and have one parameter
293 // if par = 0 normal behavior
294 // else insert behavior
295 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
296 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
302 Paragraph::depth_type depth = 0;
303 bool the_end_read = false;
305 Paragraph * first_par = 0;
306 LyXFont font(LyXFont::ALL_INHERIT, params.language);
309 if (file_format < 216 && params.language->lang() == "hebrew")
310 font.setLanguage(default_language);
315 par->layout(params.getLyXTextClass().defaultLayout());
317 // We are inserting into an existing document
318 users->text->breakParagraph(users);
319 first_par = users->text->ownerParagraph();
322 // We don't want to adopt the parameters from the
323 // document we insert, so we skip until the text begins:
326 string const pretoken = lex.getString();
327 if (pretoken == "\\layout") {
328 lex.pushToken(pretoken);
336 string const token = lex.getString();
338 if (token.empty()) continue;
340 lyxerr[Debug::PARSER] << "Handling token: `"
341 << token << "'" << endl;
344 parseSingleLyXformat2Token(lex, par, first_par,
352 paragraphs.set(first_par);
354 if (unknown_layouts > 0) {
355 string s = _("Couldn't set the layout for ");
356 if (unknown_layouts == 1) {
357 s += _("one paragraph");
359 s += tostr(unknown_layouts);
360 s += _(" paragraphs");
362 Alert::alert(_("Textclass Loading Error!"), s,
363 _("When reading " + fileName()));
366 if (unknown_tokens > 0) {
367 string s = _("Encountered ");
368 if (unknown_tokens == 1) {
369 s += _("one unknown token");
371 s += tostr(unknown_tokens);
372 s += _(" unknown tokens");
374 Alert::alert(_("Textclass Loading Error!"), s,
375 _("When reading " + fileName()));
383 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
384 Paragraph *& first_par,
385 string const & token, int & pos,
386 Paragraph::depth_type & depth,
390 bool the_end_read = false;
392 // The order of the tags tested may seem unnatural, but this
393 // has been done in order to reduce the number of string
394 // comparisons needed to recognize a given token. This leads
395 // on large documents like UserGuide to a reduction of a
397 if (token[0] != '\\') {
398 for (string::const_iterator cit = token.begin();
399 cit != token.end(); ++cit) {
400 par->insertChar(pos, (*cit), font);
403 } else if (token == "\\layout") {
404 // reset the font as we start a new layout and if the font is
405 // not ALL_INHERIT,document_language then it will be set to the
406 // right values after this tag (Jug 20020420)
407 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
410 if (file_format < 216 && params.language->lang() == "hebrew")
411 font.setLanguage(default_language);
415 string layoutname = lex.getString();
417 LyXTextClass const & tclass = params.getLyXTextClass();
419 if (layoutname.empty()) {
420 layoutname = tclass.defaultLayoutName();
422 bool hasLayout = tclass.hasLayout(layoutname);
424 lyxerr << "Layout '" << layoutname << "' does not"
425 << " exist in textclass '" << tclass.name()
427 lyxerr << "Trying to use default layout instead."
429 layoutname = tclass.defaultLayoutName();
433 // The is the compability reading of layout caption.
434 // It can be removed in LyX version 1.3.0. (Lgb)
435 if (compare_ascii_no_case(layoutname, "caption") == 0) {
436 // We expect that the par we are now working on is
437 // really inside a InsetText inside a InsetFloat.
438 // We also know that captions can only be
439 // one paragraph. (Lgb)
441 // We should now read until the next "\layout"
443 // This is probably not good enough, what if the
444 // caption is the last par in the document (Lgb)
445 istream & ist = lex.getStream();
451 if (prefixIs(line, "\\layout")) {
455 if (prefixIs(line, "\\begin_inset"))
457 if (prefixIs(line, "\\end_inset")) {
468 // Now we should have the whole layout in ss
469 // we should now be able to give this to the
471 ss << "\\end_inset\n";
473 // This seems like a bug in stringstream.
474 // We really should be able to use ss
476 istringstream is(ss.str());
478 tmplex.setStream(is);
479 Inset * inset = new InsetCaption;
480 inset->Read(this, tmplex);
481 par->InsertInset(pos, inset, font);
488 par = new Paragraph(par);
489 par->layout(params.getLyXTextClass().defaultLayout());
492 par->layout(params.getLyXTextClass()[layoutname]);
493 // Test whether the layout is obsolete.
494 LyXLayout_ptr const & layout = par->layout();
495 if (!layout->obsoleted_by().empty())
496 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
497 par->params().depth(depth);
502 } else if (token == "\\end_inset") {
503 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
504 << "Last inset read was: " << last_inset_read
506 // Simply ignore this. The insets do not have
508 // But insets should read it, it is a part of
509 // the inset isn't it? Lgb.
510 } else if (token == "\\begin_inset") {
511 readInset(lex, par, pos, font);
512 } else if (token == "\\family") {
514 font.setLyXFamily(lex.getString());
515 } else if (token == "\\series") {
517 font.setLyXSeries(lex.getString());
518 } else if (token == "\\shape") {
520 font.setLyXShape(lex.getString());
521 } else if (token == "\\size") {
523 font.setLyXSize(lex.getString());
524 } else if (token == "\\lang") {
526 string const tok = lex.getString();
527 Language const * lang = languages.getLanguage(tok);
529 font.setLanguage(lang);
531 font.setLanguage(params.language);
532 lex.printError("Unknown language `$$Token'");
534 } else if (token == "\\numeric") {
536 font.setNumber(font.setLyXMisc(lex.getString()));
537 } else if (token == "\\emph") {
539 font.setEmph(font.setLyXMisc(lex.getString()));
540 } else if (token == "\\bar") {
542 string const tok = lex.getString();
543 // This is dirty, but gone with LyX3. (Asger)
545 font.setUnderbar(LyXFont::ON);
546 else if (tok == "no")
547 font.setUnderbar(LyXFont::OFF);
548 else if (tok == "default")
549 font.setUnderbar(LyXFont::INHERIT);
551 lex.printError("Unknown bar font flag "
553 } else if (token == "\\noun") {
555 font.setNoun(font.setLyXMisc(lex.getString()));
556 } else if (token == "\\color") {
558 font.setLyXColor(lex.getString());
559 } else if (token == "\\SpecialChar") {
560 LyXLayout_ptr const & layout = par->layout();
562 // Insets don't make sense in a free-spacing context! ---Kayvan
563 if (layout->free_spacing || par->isFreeSpacing()) {
566 string next_token = lex.getString();
567 if (next_token == "\\-") {
568 par->insertChar(pos, '-', font);
569 } else if (next_token == "\\protected_separator"
570 || next_token == "~") {
571 par->insertChar(pos, ' ', font);
573 lex.printError("Token `$$Token' "
575 "paragraph layout!");
580 Inset * inset = new InsetSpecialChar;
581 inset->read(this, lex);
582 par->insertInset(pos, inset, font);
585 } else if (token == "\\i") {
586 Inset * inset = new InsetLatexAccent;
587 inset->read(this, lex);
588 par->insertInset(pos, inset, font);
590 } else if (token == "\\backslash") {
591 par->insertChar(pos, '\\', font);
593 } else if (token == "\\begin_deeper") {
595 } else if (token == "\\end_deeper") {
597 lex.printError("\\end_deeper: "
598 "depth is already null");
602 } else if (token == "\\begin_preamble") {
603 params.readPreamble(lex);
604 } else if (token == "\\textclass") {
606 pair<bool, textclass_type> pp =
607 textclasslist.NumberOfClass(lex.getString());
609 params.textclass = pp.second;
611 Alert::alert(string(_("Textclass error")),
612 string(_("The document uses an unknown textclass \"")) +
613 lex.getString() + string("\"."),
614 string(_("LyX will not be able to produce output correctly.")));
615 params.textclass = 0;
617 if (!params.getLyXTextClass().load()) {
618 // if the textclass wasn't loaded properly
619 // we need to either substitute another
620 // or stop loading the file.
621 // I can substitute but I don't see how I can
622 // stop loading... ideas?? ARRae980418
623 Alert::alert(_("Textclass Loading Error!"),
624 string(_("Can't load textclass ")) +
625 params.getLyXTextClass().name(),
626 _("-- substituting default"));
627 params.textclass = 0;
629 } else if (token == "\\options") {
631 params.options = lex.getString();
632 } else if (token == "\\language") {
633 params.readLanguage(lex);
634 } else if (token == "\\fontencoding") {
636 } else if (token == "\\inputencoding") {
638 params.inputenc = lex.getString();
639 } else if (token == "\\graphics") {
640 params.readGraphicsDriver(lex);
641 } else if (token == "\\fontscheme") {
643 params.fonts = lex.getString();
644 } else if (token == "\\noindent") {
645 par->params().noindent(true);
646 } else if (token == "\\leftindent") {
648 LyXLength value(lex.getString());
649 par->params().leftIndent(value);
650 } else if (token == "\\fill_top") {
651 par->params().spaceTop(VSpace(VSpace::VFILL));
652 } else if (token == "\\fill_bottom") {
653 par->params().spaceBottom(VSpace(VSpace::VFILL));
654 } else if (token == "\\line_top") {
655 par->params().lineTop(true);
656 } else if (token == "\\line_bottom") {
657 par->params().lineBottom(true);
658 } else if (token == "\\pagebreak_top") {
659 par->params().pagebreakTop(true);
660 } else if (token == "\\pagebreak_bottom") {
661 par->params().pagebreakBottom(true);
662 } else if (token == "\\start_of_appendix") {
663 par->params().startOfAppendix(true);
664 } else if (token == "\\paragraph_separation") {
665 int tmpret = lex.findToken(string_paragraph_separation);
668 params.paragraph_separation =
669 static_cast<BufferParams::PARSEP>(tmpret);
670 } else if (token == "\\defskip") {
672 params.defskip = VSpace(lex.getString());
673 } else if (token == "\\quotes_language") {
674 int tmpret = lex.findToken(string_quotes_language);
677 InsetQuotes::quote_language tmpl =
678 InsetQuotes::EnglishQ;
681 tmpl = InsetQuotes::EnglishQ;
684 tmpl = InsetQuotes::SwedishQ;
687 tmpl = InsetQuotes::GermanQ;
690 tmpl = InsetQuotes::PolishQ;
693 tmpl = InsetQuotes::FrenchQ;
696 tmpl = InsetQuotes::DanishQ;
699 params.quotes_language = tmpl;
700 } else if (token == "\\quotes_times") {
702 switch (lex.getInteger()) {
704 params.quotes_times = InsetQuotes::SingleQ;
707 params.quotes_times = InsetQuotes::DoubleQ;
710 } else if (token == "\\papersize") {
711 int tmpret = lex.findToken(string_papersize);
715 params.papersize2 = tmpret;
716 } else if (token == "\\paperpackage") {
717 int tmpret = lex.findToken(string_paperpackages);
720 params.paperpackage = BufferParams::PACKAGE_NONE;
722 params.paperpackage = tmpret;
723 } else if (token == "\\use_geometry") {
725 params.use_geometry = lex.getInteger();
726 } else if (token == "\\use_amsmath") {
728 params.use_amsmath = lex.getInteger();
729 } else if (token == "\\use_natbib") {
731 params.use_natbib = lex.getInteger();
732 } else if (token == "\\use_numerical_citations") {
734 params.use_numerical_citations = lex.getInteger();
735 } else if (token == "\\paperorientation") {
736 int tmpret = lex.findToken(string_orientation);
740 static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
741 } else if (token == "\\paperwidth") {
743 params.paperwidth = lex.getString();
744 } else if (token == "\\paperheight") {
746 params.paperheight = lex.getString();
747 } else if (token == "\\leftmargin") {
749 params.leftmargin = lex.getString();
750 } else if (token == "\\topmargin") {
752 params.topmargin = lex.getString();
753 } else if (token == "\\rightmargin") {
755 params.rightmargin = lex.getString();
756 } else if (token == "\\bottommargin") {
758 params.bottommargin = lex.getString();
759 } else if (token == "\\headheight") {
761 params.headheight = lex.getString();
762 } else if (token == "\\headsep") {
764 params.headsep = lex.getString();
765 } else if (token == "\\footskip") {
767 params.footskip = lex.getString();
768 } else if (token == "\\paperfontsize") {
770 params.fontsize = rtrim(lex.getString());
771 } else if (token == "\\papercolumns") {
773 params.columns = lex.getInteger();
774 } else if (token == "\\papersides") {
776 switch (lex.getInteger()) {
778 case 1: params.sides = LyXTextClass::OneSide; break;
779 case 2: params.sides = LyXTextClass::TwoSides; break;
781 } else if (token == "\\paperpagestyle") {
783 params.pagestyle = rtrim(lex.getString());
784 } else if (token == "\\bullet") {
786 int const index = lex.getInteger();
788 int temp_int = lex.getInteger();
789 params.user_defined_bullets[index].setFont(temp_int);
790 params.temp_bullets[index].setFont(temp_int);
792 temp_int = lex.getInteger();
793 params.user_defined_bullets[index].setCharacter(temp_int);
794 params.temp_bullets[index].setCharacter(temp_int);
796 temp_int = lex.getInteger();
797 params.user_defined_bullets[index].setSize(temp_int);
798 params.temp_bullets[index].setSize(temp_int);
800 string const temp_str = lex.getString();
801 if (temp_str != "\\end_bullet") {
802 // this element isn't really necessary for
803 // parsing but is easier for humans
804 // to understand bullets. Put it back and
805 // set a debug message?
806 lex.printError("\\end_bullet expected, got" + temp_str);
807 //how can I put it back?
809 } else if (token == "\\bulletLaTeX") {
810 // The bullet class should be able to read this.
812 int const index = lex.getInteger();
814 string temp_str = lex.getString();
816 while (temp_str != "\\end_bullet") {
817 // this loop structure is needed when user
818 // enters an empty string since the first
819 // thing returned will be the \\end_bullet
821 // if the LaTeX entry has spaces. Each element
822 // therefore needs to be read in turn
825 temp_str = lex.getString();
828 params.user_defined_bullets[index].setText(sum_str);
829 params.temp_bullets[index].setText(sum_str);
830 } else if (token == "\\secnumdepth") {
832 params.secnumdepth = lex.getInteger();
833 } else if (token == "\\tocdepth") {
835 params.tocdepth = lex.getInteger();
836 } else if (token == "\\spacing") {
838 string const tmp = rtrim(lex.getString());
839 Spacing::Space tmp_space = Spacing::Default;
841 if (tmp == "single") {
842 tmp_space = Spacing::Single;
843 } else if (tmp == "onehalf") {
844 tmp_space = Spacing::Onehalf;
845 } else if (tmp == "double") {
846 tmp_space = Spacing::Double;
847 } else if (tmp == "other") {
849 tmp_space = Spacing::Other;
850 tmp_val = lex.getFloat();
852 lex.printError("Unknown spacing token: '$$Token'");
854 // Small hack so that files written with klyx will be
857 par->params().spacing(Spacing(tmp_space, tmp_val));
859 params.spacing.set(tmp_space, tmp_val);
861 } else if (token == "\\paragraph_spacing") {
863 string const tmp = rtrim(lex.getString());
864 if (tmp == "single") {
865 par->params().spacing(Spacing(Spacing::Single));
866 } else if (tmp == "onehalf") {
867 par->params().spacing(Spacing(Spacing::Onehalf));
868 } else if (tmp == "double") {
869 par->params().spacing(Spacing(Spacing::Double));
870 } else if (tmp == "other") {
872 par->params().spacing(Spacing(Spacing::Other,
875 lex.printError("Unknown spacing token: '$$Token'");
877 } else if (token == "\\float_placement") {
879 params.float_placement = lex.getString();
880 } else if (token == "\\align") {
881 int tmpret = lex.findToken(string_align);
882 if (tmpret == -1) ++tmpret;
883 int const tmpret2 = int(pow(2.0, tmpret));
884 par->params().align(LyXAlignment(tmpret2));
885 } else if (token == "\\added_space_top") {
887 VSpace value = VSpace(lex.getString());
888 // only add the length when value > 0 or
890 if ((value.length().len().value() != 0) ||
892 (value.kind() != VSpace::LENGTH))
893 par->params().spaceTop(value);
894 } else if (token == "\\added_space_bottom") {
896 VSpace value = VSpace(lex.getString());
897 // only add the length when value > 0 or
899 if ((value.length().len().value() != 0) ||
901 (value.kind() != VSpace::LENGTH))
902 par->params().spaceBottom(value);
903 } else if (token == "\\labelwidthstring") {
905 par->params().labelWidthString(lex.getString());
906 // do not delete this token, it is still needed!
907 } else if (token == "\\newline") {
908 par->insertChar(pos, Paragraph::META_NEWLINE, font);
910 } else if (token == "\\LyXTable") {
911 Inset * inset = new InsetTabular(*this);
912 inset->read(this, lex);
913 par->insertInset(pos, inset, font);
915 } else if (token == "\\hfill") {
916 par->insertChar(pos, Paragraph::META_HFILL, font);
918 } else if (token == "\\protected_separator") { // obsolete
919 // This is a backward compability thingie. (Lgb)
920 // Remove it later some time...introduced with fileformat
922 LyXLayout_ptr const & layout = par->layout();
924 if (layout->free_spacing || par->isFreeSpacing()) {
925 par->insertChar(pos, ' ', font);
927 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
928 par->insertInset(pos, inset, font);
931 } else if (token == "\\bibitem") { // ale970302
933 InsetCommandParams p("bibitem", "dummy");
934 par->bibkey = new InsetBibKey(p);
936 par->bibkey->read(this, lex);
937 } else if (token == "\\the_end") {
940 // This should be insurance for the future: (Asger)
943 string const s = _("Unknown token: ") + token
944 + " " + lex.text() + "\n";
945 // we can do this here this way because we're actually reading
946 // the buffer and don't care about LyXText right now.
947 InsetError * new_inset = new InsetError(s);
948 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
956 // needed to insert the selection
957 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
958 LyXFont const & fn,string const & str) const
960 LyXLayout_ptr const & layout = par->layout();
964 par->checkInsertChar(font);
965 // insert the string, don't insert doublespace
966 bool space_inserted = true;
967 bool autobreakrows = !par->inInset() ||
968 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
969 for(string::const_iterator cit = str.begin();
970 cit != str.end(); ++cit) {
972 if (autobreakrows && (!par->empty() || layout->keepempty)) {
973 breakParagraph(params, par, pos,
974 layout->isEnvironment());
977 space_inserted = true;
981 // do not insert consecutive spaces if !free_spacing
982 } else if ((*cit == ' ' || *cit == '\t') &&
983 space_inserted && !layout->free_spacing &&
984 !par->isFreeSpacing())
987 } else if (*cit == '\t') {
988 if (!layout->free_spacing && !par->isFreeSpacing()) {
989 // tabs are like spaces here
990 par->insertChar(pos, ' ', font);
992 space_inserted = true;
994 const pos_type nb = 8 - pos % 8;
995 for (pos_type a = 0; a < nb ; ++a) {
996 par->insertChar(pos, ' ', font);
999 space_inserted = true;
1001 } else if (!IsPrintable(*cit)) {
1002 // Ignore unprintables
1005 // just insert the character
1006 par->insertChar(pos, *cit, font);
1008 space_inserted = (*cit == ' ');
1015 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1016 int & pos, LyXFont & font)
1018 // consistency check
1019 if (lex.getString() != "\\begin_inset") {
1020 lyxerr << "Buffer::readInset: Consistency check failed."
1027 string const tmptok = lex.getString();
1028 last_inset_read = tmptok;
1030 // test the different insets
1031 if (tmptok == "LatexCommand") {
1032 InsetCommandParams inscmd;
1035 string const cmdName = inscmd.getCmdName();
1037 // This strange command allows LyX to recognize "natbib" style
1038 // citations: citet, citep, Citet etc.
1039 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1040 inset = new InsetCitation(inscmd);
1041 } else if (cmdName == "bibitem") {
1042 lex.printError("Wrong place for bibitem");
1043 inset = new InsetBibKey(inscmd);
1044 } else if (cmdName == "BibTeX") {
1045 inset = new InsetBibtex(inscmd);
1046 } else if (cmdName == "index") {
1047 inset = new InsetIndex(inscmd);
1048 } else if (cmdName == "include") {
1049 inset = new InsetInclude(inscmd, *this);
1050 } else if (cmdName == "label") {
1051 inset = new InsetLabel(inscmd);
1052 } else if (cmdName == "url"
1053 || cmdName == "htmlurl") {
1054 inset = new InsetUrl(inscmd);
1055 } else if (cmdName == "ref"
1056 || cmdName == "pageref"
1057 || cmdName == "vref"
1058 || cmdName == "vpageref"
1059 || cmdName == "prettyref") {
1060 if (!inscmd.getOptions().empty()
1061 || !inscmd.getContents().empty()) {
1062 inset = new InsetRef(inscmd, *this);
1064 } else if (cmdName == "tableofcontents") {
1065 inset = new InsetTOC(inscmd);
1066 } else if (cmdName == "listofalgorithms") {
1067 inset = new InsetFloatList("algorithm");
1068 } else if (cmdName == "listoffigures") {
1069 inset = new InsetFloatList("figure");
1070 } else if (cmdName == "listoftables") {
1071 inset = new InsetFloatList("table");
1072 } else if (cmdName == "printindex") {
1073 inset = new InsetPrintIndex(inscmd);
1074 } else if (cmdName == "lyxparent") {
1075 inset = new InsetParent(inscmd, *this);
1078 bool alreadyread = false;
1079 if (tmptok == "Quotes") {
1080 inset = new InsetQuotes;
1081 } else if (tmptok == "External") {
1082 inset = new InsetExternal;
1083 } else if (tmptok == "FormulaMacro") {
1084 inset = new InsetFormulaMacro;
1085 } else if (tmptok == "Formula") {
1086 inset = new InsetFormula;
1087 } else if (tmptok == "Figure") { // Backward compatibility
1088 // inset = new InsetFig(100, 100, *this);
1089 inset = new InsetGraphics;
1090 } else if (tmptok == "Graphics") {
1091 inset = new InsetGraphics;
1092 } else if (tmptok == "Info") {// backwards compatibility
1093 inset = new InsetNote(this,
1094 lex.getLongString("\\end_inset"),
1097 } else if (tmptok == "Note") {
1098 inset = new InsetNote(params);
1099 } else if (tmptok == "Include") {
1100 InsetCommandParams p("Include");
1101 inset = new InsetInclude(p, *this);
1102 } else if (tmptok == "ERT") {
1103 inset = new InsetERT(params);
1104 } else if (tmptok == "Tabular") {
1105 inset = new InsetTabular(*this);
1106 } else if (tmptok == "Text") {
1107 inset = new InsetText(params);
1108 } else if (tmptok == "Foot") {
1109 inset = new InsetFoot(params);
1110 } else if (tmptok == "Marginal") {
1111 inset = new InsetMarginal(params);
1112 } else if (tmptok == "OptArg") {
1113 inset = new InsetOptArg(params);
1114 } else if (tmptok == "Minipage") {
1115 inset = new InsetMinipage(params);
1116 } else if (tmptok == "Float") {
1118 string tmptok = lex.getString();
1119 inset = new InsetFloat(params, tmptok);
1121 } else if (tmptok == "List") {
1122 inset = new InsetList;
1123 } else if (tmptok == "Theorem") {
1124 inset = new InsetList;
1126 } else if (tmptok == "Caption") {
1127 inset = new InsetCaption(params);
1128 } else if (tmptok == "FloatList") {
1129 inset = new InsetFloatList;
1132 if (inset && !alreadyread) inset->read(this, lex);
1136 par->insertInset(pos, inset, font);
1142 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1146 string const token(lex.getString());
1147 if (token == "\\lyxformat") { // the first token _must_ be...
1149 string tmp_format = lex.getString();
1150 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1151 // if present remove ".," from string.
1152 string::size_type dot = tmp_format.find_first_of(".,");
1153 //lyxerr << " dot found at " << dot << endl;
1154 if (dot != string::npos)
1155 tmp_format.erase(dot, 1);
1156 file_format = strToInt(tmp_format);
1157 //lyxerr << "format: " << file_format << endl;
1158 if (file_format == LYX_FORMAT) {
1160 } else if (file_format > LYX_FORMAT) {
1162 Alert::alert(_("Warning!"),
1163 _("LyX file format is newer that what"),
1164 _("is supported in this LyX version. Expect some problems."));
1166 } else if (file_format < LYX_FORMAT) {
1168 if (file_format < 200) {
1169 Alert::alert(_("ERROR!"),
1170 _("Old LyX file format found. "
1171 "Use LyX 0.10.x to read this!"));
1175 LibFileSearch("lyx2lyx", "lyx2lyx");
1176 if (command.empty()) {
1177 Alert::alert(_("ERROR!"),
1178 _("Can't find conversion script."));
1182 +tostr(LYX_FORMAT)+" "
1183 + QuoteName(filename_);
1184 cmd_ret const ret = RunCommand(command);
1186 Alert::alert(_("ERROR!"),
1187 _("An error occured while "
1188 "running the conversion script."));
1191 istringstream is(ret.second);
1192 LyXLex tmplex(0, 0);
1193 tmplex.setStream(is);
1194 return readFile(tmplex);
1197 bool the_end = readLyXformat2(lex, par);
1198 params.setPaperStuff();
1201 // the_end was added in 213
1202 if (file_format < 213)
1207 Alert::alert(_("Warning!"),
1208 _("Reading of document is not complete"),
1209 _("Maybe the document is truncated"));
1212 } else { // "\\lyxformat" not found
1213 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1216 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1221 // Should probably be moved to somewhere else: BufferView? LyXView?
1222 bool Buffer::save() const
1224 // We don't need autosaves in the immediate future. (Asger)
1225 resetAutosaveTimers();
1229 if (lyxrc.make_backup) {
1230 s = fileName() + '~';
1231 if (!lyxrc.backupdir_path.empty())
1232 s = AddName(lyxrc.backupdir_path,
1233 subst(os::slashify_path(s),'/','!'));
1235 // Rename is the wrong way of making a backup,
1236 // this is the correct way.
1237 /* truss cp fil fil2:
1238 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1239 stat("LyXVC.lyx", 0xEFFFF688) = 0
1240 open("LyXVC.lyx", O_RDONLY) = 3
1241 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1242 fstat(4, 0xEFFFF508) = 0
1243 fstat(3, 0xEFFFF508) = 0
1244 read(3, " # T h i s f i l e w".., 8192) = 5579
1245 write(4, " # T h i s f i l e w".., 5579) = 5579
1246 read(3, 0xEFFFD4A0, 8192) = 0
1249 chmod("LyXVC3.lyx", 0100644) = 0
1250 lseek(0, 0, SEEK_CUR) = 46440
1254 // Should probably have some more error checking here.
1255 // Doing it this way, also makes the inodes stay the same.
1256 // This is still not a very good solution, in particular we
1257 // might loose the owner of the backup.
1258 FileInfo finfo(fileName());
1259 if (finfo.exist()) {
1260 mode_t fmode = finfo.getMode();
1261 struct utimbuf times = {
1262 finfo.getAccessTime(),
1263 finfo.getModificationTime() };
1265 ifstream ifs(fileName().c_str());
1266 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1271 ::chmod(s.c_str(), fmode);
1273 if (::utime(s.c_str(), ×)) {
1274 lyxerr << "utime error." << endl;
1277 lyxerr << "LyX was not able to make "
1278 "backup copy. Beware." << endl;
1283 if (writeFile(fileName())) {
1285 removeAutosaveFile(fileName());
1287 // Saving failed, so backup is not backup
1288 if (lyxrc.make_backup) {
1289 lyx::rename(s, fileName());
1297 bool Buffer::writeFile(string const & fname) const
1299 if (read_only && (fname == fileName())) {
1303 FileInfo finfo(fname);
1304 if (finfo.exist() && !finfo.writable()) {
1308 ofstream ofs(fname.c_str());
1314 // Use the standard "C" locale for file output.
1315 ofs.imbue(std::locale::classic());
1318 // The top of the file should not be written by params.
1320 // write out a comment in the top of the file
1321 ofs << '#' << lyx_docversion
1322 << " created this file. For more info see http://www.lyx.org/\n"
1323 << "\\lyxformat " << LYX_FORMAT << "\n";
1325 // now write out the buffer paramters.
1326 params.writeFile(ofs);
1328 Paragraph::depth_type depth = 0;
1330 // this will write out all the paragraphs
1331 // using recursive descent.
1332 ParagraphList::iterator pit = paragraphs.begin();
1333 ParagraphList::iterator pend = paragraphs.end();
1334 for (; pit != pend; ++pit)
1335 pit->write(this, ofs, params, depth);
1337 // Write marker that shows file is complete
1338 ofs << "\n\\the_end" << endl;
1342 // how to check if close went ok?
1343 // Following is an attempt... (BE 20001011)
1345 // good() returns false if any error occured, including some
1346 // formatting error.
1347 // bad() returns true if something bad happened in the buffer,
1348 // which should include file system full errors.
1355 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1357 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1369 pair<int, string> const addDepth(int depth, int ldepth)
1373 d += (ldepth - depth) * 2;
1374 return make_pair(d, string(d, ' '));
1380 string const Buffer::asciiParagraph(Paragraph const & par,
1381 unsigned int linelen,
1382 bool noparbreak) const
1384 ostringstream buffer;
1385 Paragraph::depth_type depth = 0;
1387 Paragraph::depth_type ltype_depth = 0;
1388 bool ref_printed = false;
1389 // if (!par->previous()) {
1391 // begins or ends a deeper area ?
1392 if (depth != par->params().depth()) {
1393 if (par->params().depth() > depth) {
1394 while (par->params().depth() > depth) {
1398 while (par->params().depth() < depth) {
1404 depth = par.params().depth();
1407 // First write the layout
1408 string const & tmp = par.layout()->name();
1409 if (compare_no_case(tmp, "itemize") == 0) {
1411 ltype_depth = depth + 1;
1412 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1414 ltype_depth = depth + 1;
1415 } else if (contains(ascii_lowercase(tmp), "ection")) {
1417 ltype_depth = depth + 1;
1418 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1420 ltype_depth = depth + 1;
1421 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1423 ltype_depth = depth + 1;
1424 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1427 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1435 /* maybe some vertical spaces */
1437 /* the labelwidthstring used in lists */
1441 /* some pagebreaks? */
1445 /* what about the alignment */
1447 // lyxerr << "Should this ever happen?" << endl;
1450 // linelen <= 0 is special and means we don't have paragraph breaks
1452 string::size_type currlinelen = 0;
1458 buffer << string(depth * 2, ' ');
1459 currlinelen += depth * 2;
1462 // we should probably change to the paragraph language in the
1463 // gettext here (if possible) so that strings are outputted in
1464 // the correct language! (20012712 Jug)
1468 case 4: // (Sub)Paragraph
1469 case 5: // Description
1473 buffer << _("Abstract") << "\n\n";
1476 string const abst = _("Abstract: ");
1478 currlinelen += abst.length();
1481 case 7: // Bibliography
1484 buffer << _("References") << "\n\n";
1487 string const refs = _("References: ");
1489 currlinelen += refs.length();
1497 string const parlab = par.params().labelString();
1498 buffer << parlab << " ";
1499 currlinelen += parlab.length() + 1;
1507 pair<int, string> p = addDepth(depth, ltype_depth);
1509 currlinelen += p.first;
1512 // this is to change the linebreak to do it by word a bit more
1513 // intelligent hopefully! (only in the case where we have a
1514 // max linelenght!) (Jug)
1518 for (pos_type i = 0; i < par.size(); ++i) {
1519 char c = par.getUChar(params, i);
1521 case Paragraph::META_INSET:
1523 Inset const * inset = par.getInset(i);
1527 currlinelen += word.length();
1530 if (inset->ascii(this, buffer, linelen)) {
1531 // to be sure it breaks paragraph
1532 currlinelen += linelen;
1538 case Paragraph::META_NEWLINE:
1540 buffer << word << "\n";
1543 pair<int, string> p = addDepth(depth,
1546 currlinelen = p.first;
1550 case Paragraph::META_HFILL:
1551 buffer << word << "\t";
1552 currlinelen += word.length() + 1;
1559 currlinelen + word.length() > linelen - 10) {
1561 pair<int, string> p =
1562 addDepth(depth, ltype_depth);
1564 currlinelen = p.first;
1567 buffer << word << ' ';
1568 currlinelen += word.length() + 1;
1575 lyxerr[Debug::INFO] <<
1576 "writeAsciiFile: NULL char in structure." << endl;
1578 if ((linelen > 0) &&
1579 (currlinelen + word.length()) > linelen)
1583 pair<int, string> p =
1584 addDepth(depth, ltype_depth);
1586 currlinelen = p.first;
1593 return buffer.str().c_str();
1597 void Buffer::writeFileAscii(string const & fname, int linelen)
1599 ofstream ofs(fname.c_str());
1601 Alert::err_alert(_("Error: Cannot write file:"), fname);
1604 writeFileAscii(ofs, linelen);
1608 void Buffer::writeFileAscii(ostream & os, int linelen)
1610 ParagraphList::iterator beg = paragraphs.begin();
1611 ParagraphList::iterator end = paragraphs.end();
1612 ParagraphList::iterator it = beg;
1613 for (; it != end; ++it) {
1614 os << asciiParagraph(*it, linelen, it == beg);
1623 void Buffer::makeLaTeXFile(string const & fname,
1624 string const & original_path,
1625 bool nice, bool only_body, bool only_preamble)
1627 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1629 ofstream ofs(fname.c_str());
1631 Alert::err_alert(_("Error: Cannot open file: "), fname);
1635 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1639 lyxerr << "File was not closed properly." << endl;
1644 void Buffer::makeLaTeXFile(ostream & os,
1645 string const & original_path,
1646 bool nice, bool only_body, bool only_preamble)
1648 niceFile = nice; // this will be used by Insetincludes.
1650 // validate the buffer.
1651 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1652 LaTeXFeatures features(params);
1654 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1657 // The starting paragraph of the coming rows is the
1658 // first paragraph of the document. (Asger)
1659 texrow.start(&*(paragraphs.begin()), 0);
1661 if (!only_body && nice) {
1662 os << "%% " << lyx_docversion << " created this file. "
1663 "For more info, see http://www.lyx.org/.\n"
1664 "%% Do not edit unless you really know what "
1669 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1670 // There are a few differences between nice LaTeX and usual files:
1671 // usual is \batchmode and has a
1672 // special input@path to allow the including of figures
1673 // with either \input or \includegraphics (what figinsets do).
1674 // input@path is set when the actual parameter
1675 // original_path is set. This is done for usual tex-file, but not
1676 // for nice-latex-file. (Matthias 250696)
1679 // code for usual, NOT nice-latex-file
1680 os << "\\batchmode\n"; // changed
1681 // from \nonstopmode
1684 if (!original_path.empty()) {
1685 string inputpath = os::external_path(original_path);
1686 subst(inputpath, "~", "\\string~");
1687 os << "\\makeatletter\n"
1688 << "\\def\\input@path{{"
1689 << inputpath << "/}}\n"
1690 << "\\makeatother\n";
1696 os << "\\documentclass";
1698 LyXTextClass const & tclass = params.getLyXTextClass();
1700 ostringstream options; // the document class options.
1702 if (tokenPos(tclass.opt_fontsize(),
1703 '|', params.fontsize) >= 0) {
1704 // only write if existing in list (and not default)
1705 options << params.fontsize << "pt,";
1709 if (!params.use_geometry &&
1710 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1711 switch (params.papersize) {
1712 case BufferParams::PAPER_A4PAPER:
1713 options << "a4paper,";
1715 case BufferParams::PAPER_USLETTER:
1716 options << "letterpaper,";
1718 case BufferParams::PAPER_A5PAPER:
1719 options << "a5paper,";
1721 case BufferParams::PAPER_B5PAPER:
1722 options << "b5paper,";
1724 case BufferParams::PAPER_EXECUTIVEPAPER:
1725 options << "executivepaper,";
1727 case BufferParams::PAPER_LEGALPAPER:
1728 options << "legalpaper,";
1734 if (params.sides != tclass.sides()) {
1735 switch (params.sides) {
1736 case LyXTextClass::OneSide:
1737 options << "oneside,";
1739 case LyXTextClass::TwoSides:
1740 options << "twoside,";
1746 if (params.columns != tclass.columns()) {
1747 if (params.columns == 2)
1748 options << "twocolumn,";
1750 options << "onecolumn,";
1753 if (!params.use_geometry
1754 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1755 options << "landscape,";
1757 // language should be a parameter to \documentclass
1759 ostringstream language_options;
1760 if (params.language->babel() == "hebrew"
1761 && default_language->babel() != "hebrew")
1762 // This seems necessary
1763 features.useLanguage(default_language);
1765 if (lyxrc.language_use_babel ||
1766 params.language->lang() != lyxrc.default_language ||
1767 features.hasLanguages()) {
1769 language_options << features.getLanguages();
1770 language_options << params.language->babel();
1771 if (lyxrc.language_global_options)
1772 options << language_options.str() << ',';
1775 // the user-defined options
1776 if (!params.options.empty()) {
1777 options << params.options << ',';
1780 string strOptions(options.str().c_str());
1781 if (!strOptions.empty()) {
1782 strOptions = rtrim(strOptions, ",");
1783 os << '[' << strOptions << ']';
1786 os << '{' << tclass.latexname() << "}\n";
1788 // end of \documentclass defs
1790 // font selection must be done before loading fontenc.sty
1791 // The ae package is not needed when using OT1 font encoding.
1792 if (params.fonts != "default" &&
1793 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1794 os << "\\usepackage{" << params.fonts << "}\n";
1796 if (params.fonts == "ae") {
1797 os << "\\usepackage{aecompl}\n";
1801 // this one is not per buffer
1802 if (lyxrc.fontenc != "default") {
1803 os << "\\usepackage[" << lyxrc.fontenc
1808 if (params.inputenc == "auto") {
1809 string const doc_encoding =
1810 params.language->encoding()->LatexName();
1812 // Create a list with all the input encodings used
1814 set<string> encodings = features.getEncodingSet(doc_encoding);
1816 os << "\\usepackage[";
1817 std::copy(encodings.begin(), encodings.end(),
1818 std::ostream_iterator<string>(os, ","));
1819 os << doc_encoding << "]{inputenc}\n";
1821 } else if (params.inputenc != "default") {
1822 os << "\\usepackage[" << params.inputenc
1827 // At the very beginning the text parameters.
1828 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1829 switch (params.paperpackage) {
1830 case BufferParams::PACKAGE_A4:
1831 os << "\\usepackage{a4}\n";
1834 case BufferParams::PACKAGE_A4WIDE:
1835 os << "\\usepackage{a4wide}\n";
1838 case BufferParams::PACKAGE_WIDEMARGINSA4:
1839 os << "\\usepackage[widemargins]{a4}\n";
1844 if (params.use_geometry) {
1845 os << "\\usepackage{geometry}\n";
1847 os << "\\geometry{verbose";
1848 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1850 switch (params.papersize2) {
1851 case BufferParams::VM_PAPER_CUSTOM:
1852 if (!params.paperwidth.empty())
1853 os << ",paperwidth="
1854 << params.paperwidth;
1855 if (!params.paperheight.empty())
1856 os << ",paperheight="
1857 << params.paperheight;
1859 case BufferParams::VM_PAPER_USLETTER:
1860 os << ",letterpaper";
1862 case BufferParams::VM_PAPER_USLEGAL:
1863 os << ",legalpaper";
1865 case BufferParams::VM_PAPER_USEXECUTIVE:
1866 os << ",executivepaper";
1868 case BufferParams::VM_PAPER_A3:
1871 case BufferParams::VM_PAPER_A4:
1874 case BufferParams::VM_PAPER_A5:
1877 case BufferParams::VM_PAPER_B3:
1880 case BufferParams::VM_PAPER_B4:
1883 case BufferParams::VM_PAPER_B5:
1887 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1888 switch (lyxrc.default_papersize) {
1889 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1890 case BufferParams::PAPER_USLETTER:
1891 os << ",letterpaper";
1893 case BufferParams::PAPER_LEGALPAPER:
1894 os << ",legalpaper";
1896 case BufferParams::PAPER_EXECUTIVEPAPER:
1897 os << ",executivepaper";
1899 case BufferParams::PAPER_A3PAPER:
1902 case BufferParams::PAPER_A4PAPER:
1905 case BufferParams::PAPER_A5PAPER:
1908 case BufferParams::PAPER_B5PAPER:
1913 if (!params.topmargin.empty())
1914 os << ",tmargin=" << params.topmargin;
1915 if (!params.bottommargin.empty())
1916 os << ",bmargin=" << params.bottommargin;
1917 if (!params.leftmargin.empty())
1918 os << ",lmargin=" << params.leftmargin;
1919 if (!params.rightmargin.empty())
1920 os << ",rmargin=" << params.rightmargin;
1921 if (!params.headheight.empty())
1922 os << ",headheight=" << params.headheight;
1923 if (!params.headsep.empty())
1924 os << ",headsep=" << params.headsep;
1925 if (!params.footskip.empty())
1926 os << ",footskip=" << params.footskip;
1931 if (tokenPos(tclass.opt_pagestyle(),
1932 '|', params.pagestyle) >= 0) {
1933 if (params.pagestyle == "fancy") {
1934 os << "\\usepackage{fancyhdr}\n";
1937 os << "\\pagestyle{" << params.pagestyle << "}\n";
1941 if (params.secnumdepth != tclass.secnumdepth()) {
1942 os << "\\setcounter{secnumdepth}{"
1943 << params.secnumdepth
1947 if (params.tocdepth != tclass.tocdepth()) {
1948 os << "\\setcounter{tocdepth}{"
1954 if (params.paragraph_separation) {
1955 switch (params.defskip.kind()) {
1956 case VSpace::SMALLSKIP:
1957 os << "\\setlength\\parskip{\\smallskipamount}\n";
1959 case VSpace::MEDSKIP:
1960 os << "\\setlength\\parskip{\\medskipamount}\n";
1962 case VSpace::BIGSKIP:
1963 os << "\\setlength\\parskip{\\bigskipamount}\n";
1965 case VSpace::LENGTH:
1966 os << "\\setlength\\parskip{"
1967 << params.defskip.length().asLatexString()
1970 default: // should never happen // Then delete it.
1971 os << "\\setlength\\parskip{\\medskipamount}\n";
1976 os << "\\setlength\\parindent{0pt}\n";
1980 // Now insert the LyX specific LaTeX commands...
1982 // The optional packages;
1983 string preamble(features.getPackages());
1985 // this might be useful...
1986 preamble += "\n\\makeatletter\n";
1988 // Some macros LyX will need
1989 string tmppreamble(features.getMacros());
1991 if (!tmppreamble.empty()) {
1992 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1993 "LyX specific LaTeX commands.\n"
1994 + tmppreamble + '\n';
1997 // the text class specific preamble
1998 tmppreamble = features.getTClassPreamble();
1999 if (!tmppreamble.empty()) {
2000 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2001 "Textclass specific LaTeX commands.\n"
2002 + tmppreamble + '\n';
2005 /* the user-defined preamble */
2006 if (!params.preamble.empty()) {
2007 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2008 "User specified LaTeX commands.\n"
2009 + params.preamble + '\n';
2012 // Itemize bullet settings need to be last in case the user
2013 // defines their own bullets that use a package included
2014 // in the user-defined preamble -- ARRae
2015 // Actually it has to be done much later than that
2016 // since some packages like frenchb make modifications
2017 // at \begin{document} time -- JMarc
2019 for (int i = 0; i < 4; ++i) {
2020 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2021 if (bullets_def.empty())
2022 bullets_def="\\AtBeginDocument{\n";
2023 bullets_def += " \\renewcommand{\\labelitemi";
2025 // `i' is one less than the item to modify
2032 bullets_def += "ii";
2038 bullets_def += "}{" +
2039 params.user_defined_bullets[i].getText()
2044 if (!bullets_def.empty())
2045 preamble += bullets_def + "}\n\n";
2048 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2049 for (int j = 0; j != nlines; ++j) {
2053 // We try to load babel late, in case it interferes
2054 // with other packages.
2056 string tmp = lyxrc.language_package;
2057 if (!lyxrc.language_global_options
2058 && tmp == "\\usepackage{babel}")
2059 tmp = string("\\usepackage[") +
2060 language_options.str().c_str() +
2062 preamble += tmp + "\n";
2063 preamble += features.getBabelOptions();
2066 preamble += "\\makeatother\n";
2074 os << "\\begin{document}\n";
2077 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2079 if (!lyxrc.language_auto_begin) {
2080 os << subst(lyxrc.language_command_begin, "$$lang",
2081 params.language->babel())
2086 latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2088 // add this just in case after all the paragraphs
2092 if (!lyxrc.language_auto_end) {
2093 os << subst(lyxrc.language_command_end, "$$lang",
2094 params.language->babel())
2100 os << "\\end{document}\n";
2103 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2105 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2109 // Just to be sure. (Asger)
2112 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2113 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2115 // we want this to be true outside previews (for insetexternal)
2121 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2123 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2124 Paragraph * endpar, TexRow & texrow,
2125 bool moving_arg) const
2127 bool was_title = false;
2128 bool already_title = false;
2131 while (par != endpar) {
2132 Inset * in = par->inInset();
2133 // well we have to check if we are in an inset with unlimited
2134 // length (all in one row) if that is true then we don't allow
2135 // any special options in the paragraph and also we don't allow
2136 // any environment other then "Standard" to be valid!
2137 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2138 LyXLayout_ptr const & layout = par->layout();
2140 if (layout->intitle) {
2141 if (already_title) {
2142 lyxerr <<"Error in latexParagraphs: You"
2143 " should not mix title layouts"
2144 " with normal ones." << endl;
2147 } else if (was_title && !already_title) {
2148 ofs << "\\maketitle\n";
2150 already_title = true;
2154 if (layout->isEnvironment() ||
2155 !par->params().leftIndent().zero())
2157 par = par->TeXEnvironment(this, params, ofs, texrow);
2159 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2162 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2165 // It might be that we only have a title in this document
2166 if (was_title && !already_title) {
2167 ofs << "\\maketitle\n";
2173 bool Buffer::isLatex() const
2175 return params.getLyXTextClass().outputType() == LATEX;
2179 bool Buffer::isLinuxDoc() const
2181 return params.getLyXTextClass().outputType() == LINUXDOC;
2185 bool Buffer::isLiterate() const
2187 return params.getLyXTextClass().outputType() == LITERATE;
2191 bool Buffer::isDocBook() const
2193 return params.getLyXTextClass().outputType() == DOCBOOK;
2197 bool Buffer::isSGML() const
2199 LyXTextClass const & tclass = params.getLyXTextClass();
2201 return tclass.outputType() == LINUXDOC ||
2202 tclass.outputType() == DOCBOOK;
2206 int Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2207 string const & latexname) const
2209 if (!latexname.empty() && latexname != "!-- --") {
2211 os << string(" ",depth);
2212 os << "<" << latexname << ">";
2222 int Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2223 string const & latexname) const
2225 if (!latexname.empty() && latexname != "!-- --") {
2227 os << endl << string(" ",depth);
2228 os << "</" << latexname << ">";
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 sgmlOpenTag(ofs, 0, false, top_element);
2276 string top = top_element;
2278 top += params.options;
2279 sgmlOpenTag(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 sgmlOpenTag(ofs, depth, false, temp);
2307 // environment tag closing
2308 for (; depth > par->params().depth(); --depth) {
2309 sgmlCloseTag(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 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2319 environment_stack[depth].erase();
2325 sgmlOpenTag(ofs, depth, false, style->latexname());
2331 _("Error : Wrong depth for"
2332 " LatexType Command.\n"));
2334 if (!environment_stack[depth].empty()) {
2335 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2339 environment_stack[depth].erase();
2340 sgmlOpenTag(ofs, depth, false, style->latexname());
2343 case LATEX_ENVIRONMENT:
2344 case LATEX_ITEM_ENVIRONMENT:
2346 string const & latexname = style->latexname();
2348 if (depth == par->params().depth()
2349 && environment_stack[depth] != latexname) {
2350 sgmlCloseTag(ofs, depth, false,
2351 environment_stack[depth]);
2352 environment_stack[depth].erase();
2354 if (depth < par->params().depth()) {
2355 depth = par->params().depth();
2356 environment_stack[depth].erase();
2358 if (environment_stack[depth] != latexname) {
2360 sgmlOpenTag(ofs, depth, false, "p");
2362 sgmlOpenTag(ofs, depth, false, latexname);
2364 if (environment_stack.size() == depth + 1)
2365 environment_stack.push_back("!-- --");
2366 environment_stack[depth] = latexname;
2369 if (style->latexparam() == "CDATA")
2372 if (style->latextype == LATEX_ENVIRONMENT) break;
2374 if (style->labeltype == LABEL_MANUAL)
2379 sgmlOpenTag(ofs, depth + 1, false, item_name);
2384 sgmlOpenTag(ofs, depth, false, style->latexname());
2388 simpleLinuxDocOnePar(ofs, par, depth);
2393 // write closing SGML tags
2394 switch (style->latextype) {
2397 case LATEX_ENVIRONMENT:
2398 case LATEX_ITEM_ENVIRONMENT:
2399 if (style->latexparam() == "CDATA")
2403 sgmlCloseTag(ofs, depth, false, style->latexname());
2409 for (int i = depth; i >= 0; --i)
2410 sgmlCloseTag(ofs, depth, false, environment_stack[i]);
2414 sgmlCloseTag(ofs, 0, false, top_element);
2418 // How to check for successful close
2420 // we want this to be true outside previews (for insetexternal)
2425 // checks, if newcol chars should be put into this line
2426 // writes newline, if necessary.
2429 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2430 string::size_type newcol)
2433 if (colcount > lyxrc.ascii_linelen) {
2435 colcount = newcol; // assume write after this call
2450 string tag_name(PAR_TAG const & pt) {
2452 case NONE: return "!-- --";
2453 case TT: return "tt";
2454 case SF: return "sf";
2455 case BF: return "bf";
2456 case IT: return "it";
2457 case SL: return "sl";
2458 case EM: return "em";
2465 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2467 p1 = static_cast<PAR_TAG>(p1 | p2);
2472 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2474 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2480 // Handle internal paragraph parsing -- layout already processed.
2481 void Buffer::simpleLinuxDocOnePar(ostream & os,
2483 Paragraph::depth_type /*depth*/)
2485 LyXLayout_ptr const & style = par->layout();
2487 string::size_type char_line_count = 5; // Heuristic choice ;-)
2489 // gets paragraph main font
2492 if (style->labeltype == LABEL_MANUAL) {
2493 font_old = style->labelfont;
2496 font_old = style->font;
2500 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2501 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2502 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2505 stack<PAR_TAG> tag_state;
2506 // parsing main loop
2507 for (pos_type i = 0; i < par->size(); ++i) {
2509 PAR_TAG tag_close = NONE;
2510 list < PAR_TAG > tag_open;
2512 LyXFont const font = par->getFont(params, i);
2514 if (font_old.family() != font.family()) {
2515 switch (family_type) {
2516 case LyXFont::SANS_FAMILY:
2519 case LyXFont::TYPEWRITER_FAMILY:
2526 family_type = font.family();
2528 switch (family_type) {
2529 case LyXFont::SANS_FAMILY:
2530 tag_open.push_back(SF);
2532 case LyXFont::TYPEWRITER_FAMILY:
2533 tag_open.push_back(TT);
2540 if (font_old.series() != font.series()) {
2541 switch (series_type) {
2542 case LyXFont::BOLD_SERIES:
2549 series_type = font.series();
2551 switch (series_type) {
2552 case LyXFont::BOLD_SERIES:
2553 tag_open.push_back(BF);
2561 if (font_old.shape() != font.shape()) {
2562 switch (shape_type) {
2563 case LyXFont::ITALIC_SHAPE:
2566 case LyXFont::SLANTED_SHAPE:
2573 shape_type = font.shape();
2575 switch (shape_type) {
2576 case LyXFont::ITALIC_SHAPE:
2577 tag_open.push_back(IT);
2579 case LyXFont::SLANTED_SHAPE:
2580 tag_open.push_back(SL);
2587 if (font_old.emph() != font.emph()) {
2588 if (font.emph() == LyXFont::ON) {
2589 tag_open.push_back(EM);
2598 list < PAR_TAG > temp;
2599 while (!tag_state.empty() && tag_close) {
2600 PAR_TAG k = tag_state.top();
2602 os << "</" << tag_name(k) << ">";
2609 for(list< PAR_TAG >::const_iterator j = temp.begin();
2610 j != temp.end(); ++j) {
2612 os << "<" << tag_name(*j) << ">";
2615 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2616 j != tag_open.end(); ++j) {
2618 os << "<" << tag_name(*j) << ">";
2621 char c = par->getChar(i);
2623 if (c == Paragraph::META_INSET) {
2624 Inset * inset = par->getInset(i);
2625 inset->linuxdoc(this, os);
2630 if (style->latexparam() == "CDATA") {
2631 // "TeX"-Mode on == > SGML-Mode on.
2638 boost::tie(ws, str) = sgml::escapeChar(c);
2639 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2640 // in freespacing mode, spaces are
2641 // non-breaking characters
2642 if (desc_on) {// if char is ' ' then...
2645 sgmlLineBreak(os, char_line_count, 6);
2649 sgmlLineBreak(os, char_line_count, 1);
2654 char_line_count += str.length();
2660 while (!tag_state.empty()) {
2661 os << "</" << tag_name(tag_state.top()) << ">";
2665 // resets description flag correctly
2667 // <tag> not closed...
2668 sgmlLineBreak(os, char_line_count, 6);
2674 // Print an error message.
2675 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2676 string const & /*message*/) const
2678 #ifdef WITH_WARNINGS
2679 #warning This is wrong we cannot insert an inset like this!!!
2680 // I guess this was Jose' so I explain you more or less why this
2681 // is wrong. This way you insert something in the paragraph and
2682 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2683 // I deactivate this code, have a look at BufferView::insertErrors
2684 // how you should do this correctly! (Jug 20020315)
2687 // insert an error marker in text
2688 InsetError * new_inset = new InsetError(message);
2689 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2695 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2697 ofstream ofs(fname.c_str());
2699 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2703 Paragraph * par = &*(paragraphs.begin());
2705 niceFile = nice; // this will be used by Insetincludes.
2707 LaTeXFeatures features(params);
2712 LyXTextClass const & tclass = params.getLyXTextClass();
2713 string top_element = tclass.latexname();
2716 ofs << "<!DOCTYPE " << top_element
2717 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2719 string preamble = params.preamble;
2720 const string name = nice ? ChangeExtension(filename_, ".sgml")
2722 preamble += features.getIncludedFiles(name);
2723 preamble += features.getLyXSGMLEntities();
2725 if (!preamble.empty()) {
2726 ofs << "\n [ " << preamble << " ]";
2731 string top = top_element;
2733 top += params.language->code();
2736 if (!params.options.empty()) {
2738 top += params.options;
2740 sgmlOpenTag(ofs, 0, false, top);
2742 ofs << "<!-- DocBook file was created by " << lyx_docversion
2743 << "\n See http://www.lyx.org/ for more information -->\n";
2745 vector<string> environment_stack(10);
2746 vector<string> environment_inner(10);
2747 vector<string> command_stack(10);
2749 bool command_flag = false;
2750 Paragraph::depth_type command_depth = 0;
2751 Paragraph::depth_type command_base = 0;
2752 Paragraph::depth_type cmd_depth = 0;
2753 Paragraph::depth_type depth = 0; // paragraph depth
2756 string command_name;
2762 int desc_on = 0; // description mode
2764 LyXLayout_ptr const & style = par->layout();
2766 // environment tag closing
2767 for (; depth > par->params().depth(); --depth) {
2768 if (environment_inner[depth] != "!-- --") {
2769 item_name = "listitem";
2770 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2771 if (environment_inner[depth] == "varlistentry")
2772 sgmlCloseTag(ofs, depth+command_depth, false, environment_inner[depth]);
2774 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2775 environment_stack[depth].erase();
2776 environment_inner[depth].erase();
2779 if (depth == par->params().depth()
2780 && environment_stack[depth] != style->latexname()
2781 && !environment_stack[depth].empty()) {
2782 if (environment_inner[depth] != "!-- --") {
2783 item_name= "listitem";
2784 sgmlCloseTag(ofs, command_depth+depth, false, item_name);
2785 if (environment_inner[depth] == "varlistentry")
2786 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2789 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2791 environment_stack[depth].erase();
2792 environment_inner[depth].erase();
2795 // Write opening SGML tags.
2796 switch (style->latextype) {
2797 case LATEX_PARAGRAPH:
2798 sgmlOpenTag(ofs, depth + command_depth,
2799 false, style->latexname());
2805 _("Error : Wrong depth for "
2806 "LatexType Command.\n"));
2808 command_name = style->latexname();
2810 sgmlparam = style->latexparam();
2811 c_params = split(sgmlparam, c_depth,'|');
2813 cmd_depth = lyx::atoi(c_depth);
2816 if (cmd_depth < command_base) {
2817 for (Paragraph::depth_type j = command_depth;
2818 j >= command_base; --j) {
2819 sgmlCloseTag(ofs, j, false, command_stack[j]);
2822 command_depth = command_base = cmd_depth;
2823 } else if (cmd_depth <= command_depth) {
2824 for (int j = command_depth;
2825 j >= int(cmd_depth); --j) {
2826 sgmlCloseTag(ofs, j, false, command_stack[j]);
2829 command_depth = cmd_depth;
2831 command_depth = cmd_depth;
2833 command_depth = command_base = cmd_depth;
2834 command_flag = true;
2836 if (command_stack.size() == command_depth + 1)
2837 command_stack.push_back(string());
2838 command_stack[command_depth] = command_name;
2840 // treat label as a special case for
2841 // more WYSIWYM handling.
2842 // This is a hack while paragraphs can't have
2843 // attributes, like id in this case.
2844 if (par->isInset(0)) {
2845 Inset * inset = par->getInset(0);
2846 Inset::Code lyx_code = inset->lyxCode();
2847 if (lyx_code == Inset::LABEL_CODE) {
2848 command_name += " id=\"";
2849 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2850 command_name += "\"";
2855 sgmlOpenTag(ofs, depth + command_depth, false, command_name);
2857 item_name = c_params.empty()?"title":c_params;
2858 sgmlOpenTag(ofs, depth + 1 + command_depth, false, item_name);
2861 case LATEX_ENVIRONMENT:
2862 case LATEX_ITEM_ENVIRONMENT:
2863 if (depth < par->params().depth()) {
2864 depth = par->params().depth();
2865 environment_stack[depth].erase();
2868 if (environment_stack[depth] != style->latexname()) {
2869 if (environment_stack.size() == depth + 1) {
2870 environment_stack.push_back("!-- --");
2871 environment_inner.push_back("!-- --");
2873 environment_stack[depth] = style->latexname();
2874 environment_inner[depth] = "!-- --";
2875 sgmlOpenTag(ofs, depth + command_depth, false, environment_stack[depth]);
2877 if (environment_inner[depth] != "!-- --") {
2878 item_name= "listitem";
2879 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2880 if (environment_inner[depth] == "varlistentry")
2881 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2885 if (style->latextype == LATEX_ENVIRONMENT) {
2886 if (!style->latexparam().empty()) {
2887 if (style->latexparam() == "CDATA")
2890 sgmlOpenTag(ofs, depth + command_depth, false, style->latexparam());
2895 desc_on = (style->labeltype == LABEL_MANUAL);
2897 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2898 sgmlOpenTag(ofs, depth + 1 + command_depth,
2899 false, environment_inner[depth]);
2901 item_name = desc_on ? "term" : "para";
2902 sgmlOpenTag(ofs, depth + 1 + command_depth,
2906 sgmlOpenTag(ofs, depth + command_depth,
2907 false, style->latexname());
2911 simpleDocBookOnePar(ofs, par, desc_on,
2912 depth + 1 + command_depth);
2916 // write closing SGML tags
2917 switch (style->latextype) {
2919 end_tag = c_params.empty() ? "title" : c_params;
2920 sgmlCloseTag(ofs, depth + command_depth,
2923 case LATEX_ENVIRONMENT:
2924 if (!style->latexparam().empty()) {
2925 if (style->latexparam() == "CDATA")
2928 sgmlCloseTag(ofs, depth + command_depth, false, style->latexparam());
2931 case LATEX_ITEM_ENVIRONMENT:
2932 if (desc_on == 1) break;
2934 sgmlCloseTag(ofs, depth + 1 + command_depth, false, end_tag);
2936 case LATEX_PARAGRAPH:
2937 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2940 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2946 for (int d = depth; d >= 0; --d) {
2947 if (!environment_stack[depth].empty()) {
2948 if (environment_inner[depth] != "!-- --") {
2949 item_name = "listitem";
2950 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2951 if (environment_inner[depth] == "varlistentry")
2952 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2955 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2959 for (int j = command_depth; j >= 0 ; --j)
2960 if (!command_stack[j].empty()) {
2961 sgmlCloseTag(ofs, j, false, command_stack[j]);
2966 sgmlCloseTag(ofs, 0, false, top_element);
2969 // How to check for successful close
2971 // we want this to be true outside previews (for insetexternal)
2976 void Buffer::simpleDocBookOnePar(ostream & os,
2977 Paragraph * par, int & desc_on,
2978 Paragraph::depth_type depth) const
2980 bool emph_flag = false;
2982 LyXLayout_ptr const & style = par->layout();
2984 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2986 int char_line_count = depth;
2987 //if (!style.free_spacing)
2988 // os << string(depth,' ');
2990 // parsing main loop
2991 for (pos_type i = 0; i < par->size(); ++i) {
2992 LyXFont font = par->getFont(params, i);
2994 // handle <emphasis> tag
2995 if (font_old.emph() != font.emph()) {
2996 if (font.emph() == LyXFont::ON) {
2997 if (style->latexparam() == "CDATA")
3000 if (style->latexparam() == "CDATA")
3004 if (style->latexparam() == "CDATA")
3006 os << "</emphasis>";
3007 if (style->latexparam() == "CDATA")
3014 if (par->isInset(i)) {
3015 Inset * inset = par->getInset(i);
3016 // don't print the inset in position 0 if desc_on == 3 (label)
3017 if (i || desc_on != 3) {
3018 if (style->latexparam() == "CDATA")
3020 inset->docbook(this, os, false);
3021 if (style->latexparam() == "CDATA")
3025 char c = par->getChar(i);
3028 boost::tie(ws, str) = sgml::escapeChar(c);
3030 if (style->pass_thru) {
3032 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3034 } else if (desc_on ==1) {
3036 os << "\n</term><listitem><para>";
3046 if (style->latexparam() == "CDATA")
3048 os << "</emphasis>";
3049 if (style->latexparam() == "CDATA")
3053 // resets description flag correctly
3055 // <term> not closed...
3056 os << "</term>\n<listitem><para> </para>";
3058 if (style->free_spacing)
3063 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3064 // Other flags: -wall -v0 -x
3065 int Buffer::runChktex()
3067 if (!users->text) return 0;
3069 users->owner()->prohibitInput();
3071 // get LaTeX-Filename
3072 string const name = getLatexName();
3073 string path = filePath();
3075 string const org_path = path;
3076 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3080 Path p(path); // path to LaTeX file
3081 users->owner()->message(_("Running chktex..."));
3083 // Remove all error insets
3084 bool const removedErrorInsets = users->removeAutoInsets();
3086 // Generate the LaTeX file if neccessary
3087 makeLaTeXFile(name, org_path, false);
3090 Chktex chktex(lyxrc.chktex_command, name, filePath());
3091 int res = chktex.run(terr); // run chktex
3094 Alert::alert(_("chktex did not work!"),
3095 _("Could not run with file:"), name);
3096 } else if (res > 0) {
3097 // Insert all errors as errors boxes
3098 users->insertErrors(terr);
3101 // if we removed error insets before we ran chktex or if we inserted
3102 // error insets after we ran chktex, this must be run:
3103 if (removedErrorInsets || res) {
3104 #warning repaint needed here, or do you mean update() ?
3108 users->owner()->allowInput();
3114 void Buffer::validate(LaTeXFeatures & features) const
3116 LyXTextClass const & tclass = params.getLyXTextClass();
3118 // AMS Style is at document level
3119 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3120 features.require("amsmath");
3122 for_each(paragraphs.begin(), paragraphs.end(),
3123 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3125 // the bullet shapes are buffer level not paragraph level
3126 // so they are tested here
3127 for (int i = 0; i < 4; ++i) {
3128 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3129 int const font = params.user_defined_bullets[i].getFont();
3131 int const c = params
3132 .user_defined_bullets[i]
3139 features.require("latexsym");
3141 } else if (font == 1) {
3142 features.require("amssymb");
3143 } else if ((font >= 2 && font <= 5)) {
3144 features.require("pifont");
3149 if (lyxerr.debugging(Debug::LATEX)) {
3150 features.showStruct();
3155 // This function should be in Buffer because it's a buffer's property (ale)
3156 string const Buffer::getIncludeonlyList(char delim)
3159 for (inset_iterator it = inset_iterator_begin();
3160 it != inset_iterator_end(); ++it) {
3161 if (it->lyxCode() == Inset::INCLUDE_CODE) {
3162 InsetInclude & inc = static_cast<InsetInclude &>(*it);
3163 if (inc.isIncludeOnly()) {
3166 lst += inc.getRelFileBaseName();
3170 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3175 vector<string> const Buffer::getLabelList() const
3177 /// if this is a child document and the parent is already loaded
3178 /// Use the parent's list instead [ale990407]
3179 if (!params.parentname.empty()
3180 && bufferlist.exists(params.parentname)) {
3181 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3183 return tmp->getLabelList();
3186 vector<string> label_list;
3187 for (inset_iterator it = inset_const_iterator_begin();
3188 it != inset_const_iterator_end(); ++it) {
3189 vector<string> const l = it->getLabelList();
3190 label_list.insert(label_list.end(), l.begin(), l.end());
3196 // This is also a buffer property (ale)
3197 vector<pair<string, string> > const Buffer::getBibkeyList() const
3199 typedef pair<string, string> StringPair;
3200 /// if this is a child document and the parent is already loaded
3201 /// Use the parent's list instead [ale990412]
3202 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3203 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3205 return tmp->getBibkeyList();
3208 vector<StringPair> keys;
3209 ParagraphList::iterator pit = paragraphs.begin();
3210 ParagraphList::iterator pend = paragraphs.end();
3211 for (; pit != pend; ++pit) {
3213 string const key = pit->bibkey->getContents();
3214 string const opt = pit->bibkey->getOptions();
3215 string const ref = pit->asString(this, false);
3216 string const info = opt + "TheBibliographyRef" + ref;
3218 keys.push_back(StringPair(key, info));
3225 // Might be either using bibtex or a child has bibliography
3226 for (inset_iterator it = inset_const_iterator_begin();
3227 it != inset_const_iterator_end(); ++it) {
3228 // Search for Bibtex or Include inset
3229 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3230 vector<StringPair> tmp =
3231 static_cast<InsetBibtex &>(*it).getKeys(this);
3232 keys.insert(keys.end(), tmp.begin(), tmp.end());
3233 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3234 vector<StringPair> const tmp =
3235 static_cast<InsetInclude &>(*it).getKeys();
3236 keys.insert(keys.end(), tmp.begin(), tmp.end());
3244 bool Buffer::isDepClean(string const & name) const
3246 DEPCLEAN * item = dep_clean;
3247 while (item && item->master != name)
3249 if (!item) return true;
3254 void Buffer::markDepClean(string const & name)
3257 dep_clean = new DEPCLEAN;
3258 dep_clean->clean = true;
3259 dep_clean->master = name;
3260 dep_clean->next = 0;
3262 DEPCLEAN * item = dep_clean;
3263 while (item && item->master != name)
3268 item = new DEPCLEAN;
3270 item->master = name;
3277 bool Buffer::dispatch(string const & command, bool * result)
3279 // Split command string into command and argument
3281 string line = ltrim(command);
3282 string const arg = trim(split(line, cmd, ' '));
3284 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3288 bool Buffer::dispatch(int action, string const & argument, bool * result)
3290 bool dispatched = true;
3294 bool const tmp = Exporter::Export(this, argument, false);
3307 void Buffer::resizeInsets(BufferView * bv)
3309 /// then remove all LyXText in text-insets
3310 for_each(paragraphs.begin(), paragraphs.end(),
3311 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3315 void Buffer::redraw()
3317 #warning repaint needed here, or do you mean update() ?
3323 void Buffer::changeLanguage(Language const * from, Language const * to)
3326 ParIterator end = par_iterator_end();
3327 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3328 (*it)->changeLanguage(params, from, to);
3332 bool Buffer::isMultiLingual()
3334 ParIterator end = par_iterator_end();
3335 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3336 if ((*it)->isMultiLingual(params))
3343 Counters & Buffer::counters() const
3349 void Buffer::inset_iterator::setParagraph()
3351 while (pit != pend) {
3352 it = pit->insetlist.begin();
3353 if (it != pit->insetlist.end())
3360 Inset * Buffer::getInsetFromID(int id_arg) const
3362 for (inset_iterator it = inset_const_iterator_begin();
3363 it != inset_const_iterator_end(); ++it)
3365 if (it->id() == id_arg)
3367 Inset * in = it->getInsetFromID(id_arg);
3375 Paragraph * Buffer::getParFromID(int id) const
3380 ParagraphList::iterator it = paragraphs.begin();
3381 ParagraphList::iterator end = paragraphs.end();
3382 for (; it != end; ++it) {
3383 if (it->id() == id) {
3386 Paragraph * tmp = it->getParFromID(id);
3395 ParIterator Buffer::par_iterator_begin()
3397 return ParIterator(&*(paragraphs.begin()));
3401 ParIterator Buffer::par_iterator_end()
3403 return ParIterator();
3407 void Buffer::addUser(BufferView * u)
3413 void Buffer::delUser(BufferView *)
3419 Language const * Buffer::getLanguage() const
3421 return params.language;
3425 bool Buffer::isClean() const
3431 bool Buffer::isBakClean() const
3437 void Buffer::markClean() const
3443 // if the .lyx file has been saved, we don't need an
3449 void Buffer::markBakClean()
3455 void Buffer::setUnnamed(bool flag)
3461 bool Buffer::isUnnamed()
3467 void Buffer::markDirty()
3474 DEPCLEAN * tmp = dep_clean;
3482 string const & Buffer::fileName() const
3488 string const & Buffer::filePath() const
3494 bool Buffer::isReadonly() const
3500 BufferView * Buffer::getUser() const
3506 void Buffer::setParentName(string const & name)
3508 params.parentname = name;
3512 Buffer::inset_iterator::inset_iterator()
3517 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3524 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3528 if (it == pit->insetlist.end()) {
3537 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3539 inset_iterator tmp = *this;
3545 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3547 return *it.getInset();
3551 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3553 return it.getInset();
3557 Paragraph * Buffer::inset_iterator::getPar()
3563 lyx::pos_type Buffer::inset_iterator::getPos() const
3569 bool operator==(Buffer::inset_iterator const & iter1,
3570 Buffer::inset_iterator const & iter2)
3572 return iter1.pit == iter2.pit
3573 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3577 bool operator!=(Buffer::inset_iterator const & iter1,
3578 Buffer::inset_iterator const & iter2)
3580 return !(iter1 == iter2);