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/insetminipage.h"
77 #include "insets/insetfloat.h"
78 #include "insets/insettabular.h"
80 #include "insets/insettheorem.h"
81 #include "insets/insetlist.h"
83 #include "insets/insetcaption.h"
84 #include "insets/insetfloatlist.h"
86 #include "frontends/Dialogs.h"
87 #include "frontends/Alert.h"
89 #include "graphics/Previews.h"
91 #include "support/textutils.h"
92 #include "support/filetools.h"
93 #include "support/path.h"
94 #include "support/os.h"
95 #include "support/lyxlib.h"
96 #include "support/FileInfo.h"
97 #include "support/lyxmanip.h"
98 #include "support/lyxalgo.h" // for lyx::count
100 #include <boost/bind.hpp>
101 #include <boost/tuple/tuple.hpp>
113 #include <sys/types.h>
120 #ifndef CXX_GLOBAL_CSTD
132 using std::make_pair;
142 using lyx::textclass_type;
144 // all these externs should eventually be removed.
145 extern BufferList bufferlist;
149 const int LYX_FORMAT = 220;
153 Buffer::Buffer(string const & file, bool ronly)
154 : niceFile(true), lyx_clean(true), bak_clean(true),
155 unnamed(false), dep_clean(0), read_only(ronly),
156 filename_(file), users(0), ctrs(new Counters)
158 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
160 filepath_ = OnlyPath(file);
164 // read_only = ronly;
168 if (read_only || lyxrc.use_tempdir) {
169 tmppath = CreateBufferTmpDir();
178 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
179 // here the buffer should take care that it is
180 // saved properly, before it goes into the void.
182 // make sure that views using this buffer
187 if (!tmppath.empty()) {
188 DestroyBufferTmpDir(tmppath);
193 // Remove any previewed LaTeX snippets assocoated with this buffer.
194 grfx::Previews::get().removeLoader(this);
198 string const Buffer::getLatexName(bool no_path) const
200 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
202 return OnlyFilename(name);
208 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
210 string const filename = getLatexName(false);
212 if (filename.empty())
213 return make_pair(Buffer::latexlog, string());
215 string path = OnlyPath(filename);
217 if (lyxrc.use_tempdir || !IsDirWriteable(path))
220 string const fname = AddName(path,
221 OnlyFilename(ChangeExtension(filename,
224 AddName(path, OnlyFilename(
225 ChangeExtension(filename,
226 formats.extension("literate") + ".out")));
228 // If no Latex log or Build log is newer, show Build log
230 FileInfo const f_fi(fname);
231 FileInfo const b_fi(bname);
234 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
235 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
236 return make_pair(Buffer::buildlog, bname);
238 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
239 return make_pair(Buffer::latexlog, fname);
243 void Buffer::setReadonly(bool flag)
245 if (read_only != flag) {
248 users->owner()->getDialogs().updateBufferDependent(false);
253 /// Update window titles of all users
254 // Should work on a list
255 void Buffer::updateTitles() const
258 users->owner()->updateWindowTitle();
262 /// Reset autosave timer of all users
263 // Should work on a list
264 void Buffer::resetAutosaveTimers() const
267 users->owner()->resetAutosaveTimer();
271 void Buffer::setFileName(string const & newfile)
273 filename_ = MakeAbsPath(newfile);
274 filepath_ = OnlyPath(filename_);
275 setReadonly(IsFileWriteable(filename_) == 0);
280 // We'll remove this later. (Lgb)
283 string last_inset_read;
286 #warning And _why_ is this here? (Lgb)
294 // candidate for move to BufferView
295 // (at least some parts in the beginning of the func)
298 // changed to be public and have one parameter
299 // if par = 0 normal behavior
300 // else insert behavior
301 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
302 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
308 Paragraph::depth_type depth = 0;
309 bool the_end_read = false;
311 Paragraph * first_par = 0;
312 LyXFont font(LyXFont::ALL_INHERIT, params.language);
315 if (file_format < 216 && params.language->lang() == "hebrew")
316 font.setLanguage(default_language);
321 par->layout(params.getLyXTextClass().defaultLayout());
323 // We are inserting into an existing document
324 users->text->breakParagraph(users);
325 first_par = users->text->ownerParagraph();
328 // We don't want to adopt the parameters from the
329 // document we insert, so we skip until the text begins:
332 string const pretoken = lex.getString();
333 if (pretoken == "\\layout") {
334 lex.pushToken(pretoken);
342 string const token = lex.getString();
344 if (token.empty()) continue;
346 lyxerr[Debug::PARSER] << "Handling token: `"
347 << token << "'" << endl;
350 parseSingleLyXformat2Token(lex, par, first_par,
358 paragraphs.set(first_par);
360 if (unknown_layouts > 0) {
361 string s = _("Couldn't set the layout for ");
362 if (unknown_layouts == 1) {
363 s += _("one paragraph");
365 s += tostr(unknown_layouts);
366 s += _(" paragraphs");
368 Alert::alert(_("Textclass Loading Error!"), s,
369 _("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");
380 Alert::alert(_("Textclass Loading Error!"), s,
381 _("When reading " + fileName()));
389 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
390 Paragraph *& first_par,
391 string const & token, int & pos,
392 Paragraph::depth_type & depth,
396 bool the_end_read = false;
398 // The order of the tags tested may seem unnatural, but this
399 // has been done in order to reduce the number of string
400 // comparisons needed to recognize a given token. This leads
401 // on large documents like UserGuide to a reduction of a
403 if (token[0] != '\\') {
404 for (string::const_iterator cit = token.begin();
405 cit != token.end(); ++cit) {
406 par->insertChar(pos, (*cit), font);
409 } else if (token == "\\layout") {
410 // reset the font as we start a new layout and if the font is
411 // not ALL_INHERIT,document_language then it will be set to the
412 // right values after this tag (Jug 20020420)
413 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
416 if (file_format < 216 && params.language->lang() == "hebrew")
417 font.setLanguage(default_language);
421 string layoutname = lex.getString();
423 LyXTextClass const & tclass = params.getLyXTextClass();
425 if (layoutname.empty()) {
426 layoutname = tclass.defaultLayoutName();
428 bool hasLayout = tclass.hasLayout(layoutname);
430 lyxerr << "Layout '" << layoutname << "' does not"
431 << " exist in textclass '" << tclass.name()
433 lyxerr << "Trying to use default layout instead."
435 layoutname = tclass.defaultLayoutName();
439 // The is the compability reading of layout caption.
440 // It can be removed in LyX version 1.3.0. (Lgb)
441 if (compare_ascii_no_case(layoutname, "caption") == 0) {
442 // We expect that the par we are now working on is
443 // really inside a InsetText inside a InsetFloat.
444 // We also know that captions can only be
445 // one paragraph. (Lgb)
447 // We should now read until the next "\layout"
449 // This is probably not good enough, what if the
450 // caption is the last par in the document (Lgb)
451 istream & ist = lex.getStream();
457 if (prefixIs(line, "\\layout")) {
461 if (prefixIs(line, "\\begin_inset"))
463 if (prefixIs(line, "\\end_inset")) {
474 // Now we should have the whole layout in ss
475 // we should now be able to give this to the
477 ss << "\\end_inset\n";
479 // This seems like a bug in stringstream.
480 // We really should be able to use ss
482 istringstream is(ss.str());
484 tmplex.setStream(is);
485 Inset * inset = new InsetCaption;
486 inset->Read(this, tmplex);
487 par->InsertInset(pos, inset, font);
494 par = new Paragraph(par);
495 par->layout(params.getLyXTextClass().defaultLayout());
498 par->layout(params.getLyXTextClass()[layoutname]);
499 // Test whether the layout is obsolete.
500 LyXLayout_ptr const & layout = par->layout();
501 if (!layout->obsoleted_by().empty())
502 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
503 par->params().depth(depth);
508 } else if (token == "\\end_inset") {
509 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
510 << "Last inset read was: " << last_inset_read
512 // Simply ignore this. The insets do not have
514 // But insets should read it, it is a part of
515 // the inset isn't it? Lgb.
516 } else if (token == "\\begin_inset") {
517 readInset(lex, par, pos, font);
518 } else if (token == "\\family") {
520 font.setLyXFamily(lex.getString());
521 } else if (token == "\\series") {
523 font.setLyXSeries(lex.getString());
524 } else if (token == "\\shape") {
526 font.setLyXShape(lex.getString());
527 } else if (token == "\\size") {
529 font.setLyXSize(lex.getString());
530 } else if (token == "\\lang") {
532 string const tok = lex.getString();
533 Language const * lang = languages.getLanguage(tok);
535 font.setLanguage(lang);
537 font.setLanguage(params.language);
538 lex.printError("Unknown language `$$Token'");
540 } else if (token == "\\numeric") {
542 font.setNumber(font.setLyXMisc(lex.getString()));
543 } else if (token == "\\emph") {
545 font.setEmph(font.setLyXMisc(lex.getString()));
546 } else if (token == "\\bar") {
548 string const tok = lex.getString();
549 // This is dirty, but gone with LyX3. (Asger)
551 font.setUnderbar(LyXFont::ON);
552 else if (tok == "no")
553 font.setUnderbar(LyXFont::OFF);
554 else if (tok == "default")
555 font.setUnderbar(LyXFont::INHERIT);
557 lex.printError("Unknown bar font flag "
559 } else if (token == "\\noun") {
561 font.setNoun(font.setLyXMisc(lex.getString()));
562 } else if (token == "\\color") {
564 font.setLyXColor(lex.getString());
565 } else if (token == "\\SpecialChar") {
566 LyXLayout_ptr const & layout = par->layout();
568 // Insets don't make sense in a free-spacing context! ---Kayvan
569 if (layout->free_spacing || par->isFreeSpacing()) {
572 string next_token = lex.getString();
573 if (next_token == "\\-") {
574 par->insertChar(pos, '-', font);
575 } else if (next_token == "\\protected_separator"
576 || next_token == "~") {
577 par->insertChar(pos, ' ', font);
579 lex.printError("Token `$$Token' "
581 "paragraph layout!");
586 Inset * inset = new InsetSpecialChar;
587 inset->read(this, lex);
588 par->insertInset(pos, inset, font);
591 } else if (token == "\\i") {
592 Inset * inset = new InsetLatexAccent;
593 inset->read(this, lex);
594 par->insertInset(pos, inset, font);
596 } else if (token == "\\backslash") {
597 par->insertChar(pos, '\\', font);
599 } else if (token == "\\begin_deeper") {
601 } else if (token == "\\end_deeper") {
603 lex.printError("\\end_deeper: "
604 "depth is already null");
608 } else if (token == "\\begin_preamble") {
609 params.readPreamble(lex);
610 } else if (token == "\\textclass") {
612 pair<bool, textclass_type> pp =
613 textclasslist.NumberOfClass(lex.getString());
615 params.textclass = pp.second;
617 Alert::alert(string(_("Textclass error")),
618 string(_("The document uses an unknown textclass \"")) +
619 lex.getString() + string("\"."),
620 string(_("LyX will not be able to produce output correctly.")));
621 params.textclass = 0;
623 if (!params.getLyXTextClass().load()) {
624 // if the textclass wasn't loaded properly
625 // we need to either substitute another
626 // or stop loading the file.
627 // I can substitute but I don't see how I can
628 // stop loading... ideas?? ARRae980418
629 Alert::alert(_("Textclass Loading Error!"),
630 string(_("Can't load textclass ")) +
631 params.getLyXTextClass().name(),
632 _("-- substituting default"));
633 params.textclass = 0;
635 } else if (token == "\\options") {
637 params.options = lex.getString();
638 } else if (token == "\\language") {
639 params.readLanguage(lex);
640 } else if (token == "\\fontencoding") {
642 } else if (token == "\\inputencoding") {
644 params.inputenc = lex.getString();
645 } else if (token == "\\graphics") {
646 params.readGraphicsDriver(lex);
647 } else if (token == "\\fontscheme") {
649 params.fonts = lex.getString();
650 } else if (token == "\\noindent") {
651 par->params().noindent(true);
652 } else if (token == "\\leftindent") {
654 LyXLength value(lex.getString());
655 par->params().leftIndent(value);
656 } else if (token == "\\fill_top") {
657 par->params().spaceTop(VSpace(VSpace::VFILL));
658 } else if (token == "\\fill_bottom") {
659 par->params().spaceBottom(VSpace(VSpace::VFILL));
660 } else if (token == "\\line_top") {
661 par->params().lineTop(true);
662 } else if (token == "\\line_bottom") {
663 par->params().lineBottom(true);
664 } else if (token == "\\pagebreak_top") {
665 par->params().pagebreakTop(true);
666 } else if (token == "\\pagebreak_bottom") {
667 par->params().pagebreakBottom(true);
668 } else if (token == "\\start_of_appendix") {
669 par->params().startOfAppendix(true);
670 } else if (token == "\\paragraph_separation") {
671 int tmpret = lex.findToken(string_paragraph_separation);
674 params.paragraph_separation =
675 static_cast<BufferParams::PARSEP>(tmpret);
676 } else if (token == "\\defskip") {
678 params.defskip = VSpace(lex.getString());
679 } else if (token == "\\quotes_language") {
680 int tmpret = lex.findToken(string_quotes_language);
683 InsetQuotes::quote_language tmpl =
684 InsetQuotes::EnglishQ;
687 tmpl = InsetQuotes::EnglishQ;
690 tmpl = InsetQuotes::SwedishQ;
693 tmpl = InsetQuotes::GermanQ;
696 tmpl = InsetQuotes::PolishQ;
699 tmpl = InsetQuotes::FrenchQ;
702 tmpl = InsetQuotes::DanishQ;
705 params.quotes_language = tmpl;
706 } else if (token == "\\quotes_times") {
708 switch (lex.getInteger()) {
710 params.quotes_times = InsetQuotes::SingleQ;
713 params.quotes_times = InsetQuotes::DoubleQ;
716 } else if (token == "\\papersize") {
717 int tmpret = lex.findToken(string_papersize);
721 params.papersize2 = tmpret;
722 } else if (token == "\\paperpackage") {
723 int tmpret = lex.findToken(string_paperpackages);
726 params.paperpackage = BufferParams::PACKAGE_NONE;
728 params.paperpackage = tmpret;
729 } else if (token == "\\use_geometry") {
731 params.use_geometry = lex.getInteger();
732 } else if (token == "\\use_amsmath") {
734 params.use_amsmath = lex.getInteger();
735 } else if (token == "\\use_natbib") {
737 params.use_natbib = lex.getInteger();
738 } else if (token == "\\use_numerical_citations") {
740 params.use_numerical_citations = lex.getInteger();
741 } else if (token == "\\paperorientation") {
742 int tmpret = lex.findToken(string_orientation);
746 static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
747 } else if (token == "\\paperwidth") {
749 params.paperwidth = lex.getString();
750 } else if (token == "\\paperheight") {
752 params.paperheight = lex.getString();
753 } else if (token == "\\leftmargin") {
755 params.leftmargin = lex.getString();
756 } else if (token == "\\topmargin") {
758 params.topmargin = lex.getString();
759 } else if (token == "\\rightmargin") {
761 params.rightmargin = lex.getString();
762 } else if (token == "\\bottommargin") {
764 params.bottommargin = lex.getString();
765 } else if (token == "\\headheight") {
767 params.headheight = lex.getString();
768 } else if (token == "\\headsep") {
770 params.headsep = lex.getString();
771 } else if (token == "\\footskip") {
773 params.footskip = lex.getString();
774 } else if (token == "\\paperfontsize") {
776 params.fontsize = rtrim(lex.getString());
777 } else if (token == "\\papercolumns") {
779 params.columns = lex.getInteger();
780 } else if (token == "\\papersides") {
782 switch (lex.getInteger()) {
784 case 1: params.sides = LyXTextClass::OneSide; break;
785 case 2: params.sides = LyXTextClass::TwoSides; break;
787 } else if (token == "\\paperpagestyle") {
789 params.pagestyle = rtrim(lex.getString());
790 } else if (token == "\\bullet") {
792 int const index = lex.getInteger();
794 int temp_int = lex.getInteger();
795 params.user_defined_bullets[index].setFont(temp_int);
796 params.temp_bullets[index].setFont(temp_int);
798 temp_int = lex.getInteger();
799 params.user_defined_bullets[index].setCharacter(temp_int);
800 params.temp_bullets[index].setCharacter(temp_int);
802 temp_int = lex.getInteger();
803 params.user_defined_bullets[index].setSize(temp_int);
804 params.temp_bullets[index].setSize(temp_int);
806 string const temp_str = lex.getString();
807 if (temp_str != "\\end_bullet") {
808 // this element isn't really necessary for
809 // parsing but is easier for humans
810 // to understand bullets. Put it back and
811 // set a debug message?
812 lex.printError("\\end_bullet expected, got" + temp_str);
813 //how can I put it back?
815 } else if (token == "\\bulletLaTeX") {
816 // The bullet class should be able to read this.
818 int const index = lex.getInteger();
820 string temp_str = lex.getString();
822 while (temp_str != "\\end_bullet") {
823 // this loop structure is needed when user
824 // enters an empty string since the first
825 // thing returned will be the \\end_bullet
827 // if the LaTeX entry has spaces. Each element
828 // therefore needs to be read in turn
831 temp_str = lex.getString();
834 params.user_defined_bullets[index].setText(sum_str);
835 params.temp_bullets[index].setText(sum_str);
836 } else if (token == "\\secnumdepth") {
838 params.secnumdepth = lex.getInteger();
839 } else if (token == "\\tocdepth") {
841 params.tocdepth = lex.getInteger();
842 } else if (token == "\\spacing") {
844 string const tmp = rtrim(lex.getString());
845 Spacing::Space tmp_space = Spacing::Default;
847 if (tmp == "single") {
848 tmp_space = Spacing::Single;
849 } else if (tmp == "onehalf") {
850 tmp_space = Spacing::Onehalf;
851 } else if (tmp == "double") {
852 tmp_space = Spacing::Double;
853 } else if (tmp == "other") {
855 tmp_space = Spacing::Other;
856 tmp_val = lex.getFloat();
858 lex.printError("Unknown spacing token: '$$Token'");
860 // Small hack so that files written with klyx will be
863 par->params().spacing(Spacing(tmp_space, tmp_val));
865 params.spacing.set(tmp_space, tmp_val);
867 } else if (token == "\\paragraph_spacing") {
869 string const tmp = rtrim(lex.getString());
870 if (tmp == "single") {
871 par->params().spacing(Spacing(Spacing::Single));
872 } else if (tmp == "onehalf") {
873 par->params().spacing(Spacing(Spacing::Onehalf));
874 } else if (tmp == "double") {
875 par->params().spacing(Spacing(Spacing::Double));
876 } else if (tmp == "other") {
878 par->params().spacing(Spacing(Spacing::Other,
881 lex.printError("Unknown spacing token: '$$Token'");
883 } else if (token == "\\float_placement") {
885 params.float_placement = lex.getString();
886 } else if (token == "\\align") {
887 int tmpret = lex.findToken(string_align);
888 if (tmpret == -1) ++tmpret;
889 int const tmpret2 = int(pow(2.0, tmpret));
890 par->params().align(LyXAlignment(tmpret2));
891 } else if (token == "\\added_space_top") {
893 VSpace value = VSpace(lex.getString());
894 // only add the length when value > 0 or
896 if ((value.length().len().value() != 0) ||
898 (value.kind() != VSpace::LENGTH))
899 par->params().spaceTop(value);
900 } else if (token == "\\added_space_bottom") {
902 VSpace value = VSpace(lex.getString());
903 // only add the length when value > 0 or
905 if ((value.length().len().value() != 0) ||
907 (value.kind() != VSpace::LENGTH))
908 par->params().spaceBottom(value);
909 } else if (token == "\\labelwidthstring") {
911 par->params().labelWidthString(lex.getString());
912 // do not delete this token, it is still needed!
913 } else if (token == "\\newline") {
914 par->insertChar(pos, Paragraph::META_NEWLINE, font);
916 } else if (token == "\\LyXTable") {
917 Inset * inset = new InsetTabular(*this);
918 inset->read(this, lex);
919 par->insertInset(pos, inset, font);
921 } else if (token == "\\hfill") {
922 par->insertChar(pos, Paragraph::META_HFILL, font);
924 } else if (token == "\\protected_separator") { // obsolete
925 // This is a backward compability thingie. (Lgb)
926 // Remove it later some time...introduced with fileformat
928 LyXLayout_ptr const & layout = par->layout();
930 if (layout->free_spacing || par->isFreeSpacing()) {
931 par->insertChar(pos, ' ', font);
933 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
934 par->insertInset(pos, inset, font);
937 } else if (token == "\\bibitem") { // ale970302
939 InsetCommandParams p("bibitem", "dummy");
940 par->bibkey = new InsetBibKey(p);
942 par->bibkey->read(this, lex);
943 } else if (token == "\\the_end") {
946 // This should be insurance for the future: (Asger)
949 string const s = _("Unknown token: ") + token
950 + " " + lex.text() + "\n";
951 // we can do this here this way because we're actually reading
952 // the buffer and don't care about LyXText right now.
953 InsetError * new_inset = new InsetError(s);
954 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
962 // needed to insert the selection
963 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
964 LyXFont const & fn,string const & str) const
966 LyXLayout_ptr const & layout = par->layout();
970 par->checkInsertChar(font);
971 // insert the string, don't insert doublespace
972 bool space_inserted = true;
973 bool autobreakrows = !par->inInset() ||
974 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
975 for(string::const_iterator cit = str.begin();
976 cit != str.end(); ++cit) {
978 if (autobreakrows && (!par->empty() || layout->keepempty)) {
979 breakParagraph(params, par, pos,
980 layout->isEnvironment());
983 space_inserted = true;
987 // do not insert consecutive spaces if !free_spacing
988 } else if ((*cit == ' ' || *cit == '\t') &&
989 space_inserted && !layout->free_spacing &&
990 !par->isFreeSpacing())
993 } else if (*cit == '\t') {
994 if (!layout->free_spacing && !par->isFreeSpacing()) {
995 // tabs are like spaces here
996 par->insertChar(pos, ' ', font);
998 space_inserted = true;
1000 const pos_type nb = 8 - pos % 8;
1001 for (pos_type a = 0; a < nb ; ++a) {
1002 par->insertChar(pos, ' ', font);
1005 space_inserted = true;
1007 } else if (!IsPrintable(*cit)) {
1008 // Ignore unprintables
1011 // just insert the character
1012 par->insertChar(pos, *cit, font);
1014 space_inserted = (*cit == ' ');
1021 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1022 int & pos, LyXFont & font)
1024 // consistency check
1025 if (lex.getString() != "\\begin_inset") {
1026 lyxerr << "Buffer::readInset: Consistency check failed."
1033 string const tmptok = lex.getString();
1034 last_inset_read = tmptok;
1036 // test the different insets
1037 if (tmptok == "LatexCommand") {
1038 InsetCommandParams inscmd;
1041 string const cmdName = inscmd.getCmdName();
1043 // This strange command allows LyX to recognize "natbib" style
1044 // citations: citet, citep, Citet etc.
1045 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1046 inset = new InsetCitation(inscmd);
1047 } else if (cmdName == "bibitem") {
1048 lex.printError("Wrong place for bibitem");
1049 inset = new InsetBibKey(inscmd);
1050 } else if (cmdName == "BibTeX") {
1051 inset = new InsetBibtex(inscmd);
1052 } else if (cmdName == "index") {
1053 inset = new InsetIndex(inscmd);
1054 } else if (cmdName == "include") {
1055 inset = new InsetInclude(inscmd, *this);
1056 } else if (cmdName == "label") {
1057 inset = new InsetLabel(inscmd);
1058 } else if (cmdName == "url"
1059 || cmdName == "htmlurl") {
1060 inset = new InsetUrl(inscmd);
1061 } else if (cmdName == "ref"
1062 || cmdName == "pageref"
1063 || cmdName == "vref"
1064 || cmdName == "vpageref"
1065 || cmdName == "prettyref") {
1066 if (!inscmd.getOptions().empty()
1067 || !inscmd.getContents().empty()) {
1068 inset = new InsetRef(inscmd, *this);
1070 } else if (cmdName == "tableofcontents") {
1071 inset = new InsetTOC(inscmd);
1072 } else if (cmdName == "listofalgorithms") {
1073 inset = new InsetFloatList("algorithm");
1074 } else if (cmdName == "listoffigures") {
1075 inset = new InsetFloatList("figure");
1076 } else if (cmdName == "listoftables") {
1077 inset = new InsetFloatList("table");
1078 } else if (cmdName == "printindex") {
1079 inset = new InsetPrintIndex(inscmd);
1080 } else if (cmdName == "lyxparent") {
1081 inset = new InsetParent(inscmd, *this);
1084 bool alreadyread = false;
1085 if (tmptok == "Quotes") {
1086 inset = new InsetQuotes;
1087 } else if (tmptok == "External") {
1088 inset = new InsetExternal;
1089 } else if (tmptok == "FormulaMacro") {
1090 inset = new InsetFormulaMacro;
1091 } else if (tmptok == "Formula") {
1092 inset = new InsetFormula;
1093 } else if (tmptok == "Figure") { // Backward compatibility
1094 // inset = new InsetFig(100, 100, *this);
1095 inset = new InsetGraphics;
1096 } else if (tmptok == "Graphics") {
1097 inset = new InsetGraphics;
1098 } else if (tmptok == "Info") {// backwards compatibility
1099 inset = new InsetNote(this,
1100 lex.getLongString("\\end_inset"),
1103 } else if (tmptok == "Note") {
1104 inset = new InsetNote(params);
1105 } else if (tmptok == "Include") {
1106 InsetCommandParams p("Include");
1107 inset = new InsetInclude(p, *this);
1108 } else if (tmptok == "ERT") {
1109 inset = new InsetERT(params);
1110 } else if (tmptok == "Tabular") {
1111 inset = new InsetTabular(*this);
1112 } else if (tmptok == "Text") {
1113 inset = new InsetText(params);
1114 } else if (tmptok == "Foot") {
1115 inset = new InsetFoot(params);
1116 } else if (tmptok == "Marginal") {
1117 inset = new InsetMarginal(params);
1118 } else if (tmptok == "Minipage") {
1119 inset = new InsetMinipage(params);
1120 } else if (tmptok == "Float") {
1122 string tmptok = lex.getString();
1123 inset = new InsetFloat(params, tmptok);
1125 } else if (tmptok == "List") {
1126 inset = new InsetList;
1127 } else if (tmptok == "Theorem") {
1128 inset = new InsetList;
1130 } else if (tmptok == "Caption") {
1131 inset = new InsetCaption(params);
1132 } else if (tmptok == "FloatList") {
1133 inset = new InsetFloatList;
1136 if (inset && !alreadyread) inset->read(this, lex);
1140 par->insertInset(pos, inset, font);
1146 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1150 string const token(lex.getString());
1151 if (token == "\\lyxformat") { // the first token _must_ be...
1153 string tmp_format = lex.getString();
1154 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1155 // if present remove ".," from string.
1156 string::size_type dot = tmp_format.find_first_of(".,");
1157 //lyxerr << " dot found at " << dot << endl;
1158 if (dot != string::npos)
1159 tmp_format.erase(dot, 1);
1160 file_format = strToInt(tmp_format);
1161 if (file_format == LYX_FORMAT) {
1163 } else if (file_format > LYX_FORMAT) {
1165 Alert::alert(_("Warning!"),
1166 _("LyX file format is newer that what"),
1167 _("is supported in this LyX version. Expect some problems."));
1169 } else if (file_format < LYX_FORMAT) {
1171 if (file_format < 200) {
1172 Alert::alert(_("ERROR!"),
1173 _("Old LyX file format found. "
1174 "Use LyX 0.10.x to read this!"));
1176 } else if (file_format < 220) {
1177 string const command = "lyx2lyx "
1178 + QuoteName(filename_);
1179 cmd_ret const ret = RunCommand(command);
1181 Alert::alert(_("ERROR!"),
1182 _("An error occured while "
1183 "running the conversion script."));
1186 istringstream is(ret.second);
1187 LyXLex tmplex(0, 0);
1188 tmplex.setStream(is);
1189 return readFile(tmplex);
1192 bool the_end = readLyXformat2(lex, par);
1193 params.setPaperStuff();
1196 // the_end was added in 213
1197 if (file_format < 213)
1202 Alert::alert(_("Warning!"),
1203 _("Reading of document is not complete"),
1204 _("Maybe the document is truncated"));
1207 } else { // "\\lyxformat" not found
1208 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1211 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1216 // Should probably be moved to somewhere else: BufferView? LyXView?
1217 bool Buffer::save() const
1219 // We don't need autosaves in the immediate future. (Asger)
1220 resetAutosaveTimers();
1224 if (lyxrc.make_backup) {
1225 s = fileName() + '~';
1226 if (!lyxrc.backupdir_path.empty())
1227 s = AddName(lyxrc.backupdir_path,
1228 subst(os::slashify_path(s),'/','!'));
1230 // Rename is the wrong way of making a backup,
1231 // this is the correct way.
1232 /* truss cp fil fil2:
1233 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1234 stat("LyXVC.lyx", 0xEFFFF688) = 0
1235 open("LyXVC.lyx", O_RDONLY) = 3
1236 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1237 fstat(4, 0xEFFFF508) = 0
1238 fstat(3, 0xEFFFF508) = 0
1239 read(3, " # T h i s f i l e w".., 8192) = 5579
1240 write(4, " # T h i s f i l e w".., 5579) = 5579
1241 read(3, 0xEFFFD4A0, 8192) = 0
1244 chmod("LyXVC3.lyx", 0100644) = 0
1245 lseek(0, 0, SEEK_CUR) = 46440
1249 // Should probably have some more error checking here.
1250 // Doing it this way, also makes the inodes stay the same.
1251 // This is still not a very good solution, in particular we
1252 // might loose the owner of the backup.
1253 FileInfo finfo(fileName());
1254 if (finfo.exist()) {
1255 mode_t fmode = finfo.getMode();
1256 struct utimbuf times = {
1257 finfo.getAccessTime(),
1258 finfo.getModificationTime() };
1260 ifstream ifs(fileName().c_str());
1261 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1266 ::chmod(s.c_str(), fmode);
1268 if (::utime(s.c_str(), ×)) {
1269 lyxerr << "utime error." << endl;
1272 lyxerr << "LyX was not able to make "
1273 "backup copy. Beware." << endl;
1278 if (writeFile(fileName())) {
1280 removeAutosaveFile(fileName());
1282 // Saving failed, so backup is not backup
1283 if (lyxrc.make_backup) {
1284 lyx::rename(s, fileName());
1292 bool Buffer::writeFile(string const & fname) const
1294 if (read_only && (fname == fileName())) {
1298 FileInfo finfo(fname);
1299 if (finfo.exist() && !finfo.writable()) {
1303 ofstream ofs(fname.c_str());
1309 // Use the standard "C" locale for file output.
1310 ofs.imbue(std::locale::classic());
1313 // The top of the file should not be written by params.
1315 // write out a comment in the top of the file
1316 ofs << '#' << lyx_docversion
1317 << " created this file. For more info see http://www.lyx.org/\n"
1318 << "\\lyxformat " << LYX_FORMAT << "\n";
1320 // now write out the buffer paramters.
1321 params.writeFile(ofs);
1323 Paragraph::depth_type depth = 0;
1325 // this will write out all the paragraphs
1326 // using recursive descent.
1327 ParagraphList::iterator pit = paragraphs.begin();
1328 ParagraphList::iterator pend = paragraphs.end();
1329 for (; pit != pend; ++pit)
1330 pit->write(this, ofs, params, depth);
1332 // Write marker that shows file is complete
1333 ofs << "\n\\the_end" << endl;
1337 // how to check if close went ok?
1338 // Following is an attempt... (BE 20001011)
1340 // good() returns false if any error occured, including some
1341 // formatting error.
1342 // bad() returns true if something bad happened in the buffer,
1343 // which should include file system full errors.
1350 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1352 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1364 pair<int, string> const addDepth(int depth, int ldepth)
1368 d += (ldepth - depth) * 2;
1369 return make_pair(d, string(d, ' '));
1375 string const Buffer::asciiParagraph(Paragraph const & par,
1376 unsigned int linelen,
1377 bool noparbreak) const
1379 ostringstream buffer;
1380 Paragraph::depth_type depth = 0;
1382 Paragraph::depth_type ltype_depth = 0;
1383 bool ref_printed = false;
1384 // if (!par->previous()) {
1386 // begins or ends a deeper area ?
1387 if (depth != par->params().depth()) {
1388 if (par->params().depth() > depth) {
1389 while (par->params().depth() > depth) {
1393 while (par->params().depth() < depth) {
1399 depth = par.params().depth();
1402 // First write the layout
1403 string const & tmp = par.layout()->name();
1404 if (compare_no_case(tmp, "itemize") == 0) {
1406 ltype_depth = depth + 1;
1407 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1409 ltype_depth = depth + 1;
1410 } else if (contains(ascii_lowercase(tmp), "ection")) {
1412 ltype_depth = depth + 1;
1413 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1415 ltype_depth = depth + 1;
1416 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1418 ltype_depth = depth + 1;
1419 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1422 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1430 /* maybe some vertical spaces */
1432 /* the labelwidthstring used in lists */
1436 /* some pagebreaks? */
1440 /* what about the alignment */
1442 // lyxerr << "Should this ever happen?" << endl;
1445 // linelen <= 0 is special and means we don't have paragraph breaks
1447 string::size_type currlinelen = 0;
1453 buffer << string(depth * 2, ' ');
1454 currlinelen += depth * 2;
1457 // we should probably change to the paragraph language in the
1458 // gettext here (if possible) so that strings are outputted in
1459 // the correct language! (20012712 Jug)
1463 case 4: // (Sub)Paragraph
1464 case 5: // Description
1468 buffer << _("Abstract") << "\n\n";
1471 string const abst = _("Abstract: ");
1473 currlinelen += abst.length();
1476 case 7: // Bibliography
1479 buffer << _("References") << "\n\n";
1482 string const refs = _("References: ");
1484 currlinelen += refs.length();
1492 string const parlab = par.params().labelString();
1493 buffer << parlab << " ";
1494 currlinelen += parlab.length() + 1;
1502 pair<int, string> p = addDepth(depth, ltype_depth);
1504 currlinelen += p.first;
1507 // this is to change the linebreak to do it by word a bit more
1508 // intelligent hopefully! (only in the case where we have a
1509 // max linelenght!) (Jug)
1513 for (pos_type i = 0; i < par.size(); ++i) {
1514 char c = par.getUChar(params, i);
1516 case Paragraph::META_INSET:
1518 Inset const * inset = par.getInset(i);
1522 currlinelen += word.length();
1525 if (inset->ascii(this, buffer, linelen)) {
1526 // to be sure it breaks paragraph
1527 currlinelen += linelen;
1533 case Paragraph::META_NEWLINE:
1535 buffer << word << "\n";
1538 pair<int, string> p = addDepth(depth,
1541 currlinelen = p.first;
1545 case Paragraph::META_HFILL:
1546 buffer << word << "\t";
1547 currlinelen += word.length() + 1;
1554 currlinelen + word.length() > linelen - 10) {
1556 pair<int, string> p =
1557 addDepth(depth, ltype_depth);
1559 currlinelen = p.first;
1562 buffer << word << ' ';
1563 currlinelen += word.length() + 1;
1570 lyxerr[Debug::INFO] <<
1571 "writeAsciiFile: NULL char in structure." << endl;
1573 if ((linelen > 0) &&
1574 (currlinelen + word.length()) > linelen)
1578 pair<int, string> p =
1579 addDepth(depth, ltype_depth);
1581 currlinelen = p.first;
1588 return buffer.str().c_str();
1592 void Buffer::writeFileAscii(string const & fname, int linelen)
1594 ofstream ofs(fname.c_str());
1596 Alert::err_alert(_("Error: Cannot write file:"), fname);
1599 writeFileAscii(ofs, linelen);
1603 void Buffer::writeFileAscii(ostream & os, int linelen)
1605 ParagraphList::iterator beg = paragraphs.begin();
1606 ParagraphList::iterator end = paragraphs.end();
1607 ParagraphList::iterator it = beg;
1608 for (; it != end; ++it) {
1609 os << asciiParagraph(*it, linelen, it == beg);
1618 void Buffer::makeLaTeXFile(string const & fname,
1619 string const & original_path,
1620 bool nice, bool only_body, bool only_preamble)
1622 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1624 ofstream ofs(fname.c_str());
1626 Alert::err_alert(_("Error: Cannot open file: "), fname);
1630 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1634 lyxerr << "File was not closed properly." << endl;
1639 void Buffer::makeLaTeXFile(ostream & os,
1640 string const & original_path,
1641 bool nice, bool only_body, bool only_preamble)
1643 niceFile = nice; // this will be used by Insetincludes.
1645 // validate the buffer.
1646 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1647 LaTeXFeatures features(params);
1649 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1652 // The starting paragraph of the coming rows is the
1653 // first paragraph of the document. (Asger)
1654 texrow.start(&*(paragraphs.begin()), 0);
1656 if (!only_body && nice) {
1657 os << "%% " << lyx_docversion << " created this file. "
1658 "For more info, see http://www.lyx.org/.\n"
1659 "%% Do not edit unless you really know what "
1664 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1665 // There are a few differences between nice LaTeX and usual files:
1666 // usual is \batchmode and has a
1667 // special input@path to allow the including of figures
1668 // with either \input or \includegraphics (what figinsets do).
1669 // input@path is set when the actual parameter
1670 // original_path is set. This is done for usual tex-file, but not
1671 // for nice-latex-file. (Matthias 250696)
1674 // code for usual, NOT nice-latex-file
1675 os << "\\batchmode\n"; // changed
1676 // from \nonstopmode
1679 if (!original_path.empty()) {
1680 string inputpath = os::external_path(original_path);
1681 subst(inputpath, "~", "\\string~");
1682 os << "\\makeatletter\n"
1683 << "\\def\\input@path{{"
1684 << inputpath << "/}}\n"
1685 << "\\makeatother\n";
1691 os << "\\documentclass";
1693 LyXTextClass const & tclass = params.getLyXTextClass();
1695 ostringstream options; // the document class options.
1697 if (tokenPos(tclass.opt_fontsize(),
1698 '|', params.fontsize) >= 0) {
1699 // only write if existing in list (and not default)
1700 options << params.fontsize << "pt,";
1704 if (!params.use_geometry &&
1705 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1706 switch (params.papersize) {
1707 case BufferParams::PAPER_A4PAPER:
1708 options << "a4paper,";
1710 case BufferParams::PAPER_USLETTER:
1711 options << "letterpaper,";
1713 case BufferParams::PAPER_A5PAPER:
1714 options << "a5paper,";
1716 case BufferParams::PAPER_B5PAPER:
1717 options << "b5paper,";
1719 case BufferParams::PAPER_EXECUTIVEPAPER:
1720 options << "executivepaper,";
1722 case BufferParams::PAPER_LEGALPAPER:
1723 options << "legalpaper,";
1729 if (params.sides != tclass.sides()) {
1730 switch (params.sides) {
1731 case LyXTextClass::OneSide:
1732 options << "oneside,";
1734 case LyXTextClass::TwoSides:
1735 options << "twoside,";
1741 if (params.columns != tclass.columns()) {
1742 if (params.columns == 2)
1743 options << "twocolumn,";
1745 options << "onecolumn,";
1748 if (!params.use_geometry
1749 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1750 options << "landscape,";
1752 // language should be a parameter to \documentclass
1754 ostringstream language_options;
1755 if (params.language->babel() == "hebrew"
1756 && default_language->babel() != "hebrew")
1757 // This seems necessary
1758 features.useLanguage(default_language);
1760 if (lyxrc.language_use_babel ||
1761 params.language->lang() != lyxrc.default_language ||
1762 features.hasLanguages()) {
1764 language_options << features.getLanguages();
1765 language_options << params.language->babel();
1766 if (lyxrc.language_global_options)
1767 options << language_options.str() << ',';
1770 // the user-defined options
1771 if (!params.options.empty()) {
1772 options << params.options << ',';
1775 string strOptions(options.str().c_str());
1776 if (!strOptions.empty()) {
1777 strOptions = rtrim(strOptions, ",");
1778 os << '[' << strOptions << ']';
1781 os << '{' << tclass.latexname() << "}\n";
1783 // end of \documentclass defs
1785 // font selection must be done before loading fontenc.sty
1786 // The ae package is not needed when using OT1 font encoding.
1787 if (params.fonts != "default" &&
1788 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1789 os << "\\usepackage{" << params.fonts << "}\n";
1791 if (params.fonts == "ae") {
1792 os << "\\usepackage{aecompl}\n";
1796 // this one is not per buffer
1797 if (lyxrc.fontenc != "default") {
1798 os << "\\usepackage[" << lyxrc.fontenc
1803 if (params.inputenc == "auto") {
1804 string const doc_encoding =
1805 params.language->encoding()->LatexName();
1807 // Create a list with all the input encodings used
1809 set<string> encodings = features.getEncodingSet(doc_encoding);
1811 os << "\\usepackage[";
1812 std::copy(encodings.begin(), encodings.end(),
1813 std::ostream_iterator<string>(os, ","));
1814 os << doc_encoding << "]{inputenc}\n";
1816 } else if (params.inputenc != "default") {
1817 os << "\\usepackage[" << params.inputenc
1822 // At the very beginning the text parameters.
1823 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1824 switch (params.paperpackage) {
1825 case BufferParams::PACKAGE_A4:
1826 os << "\\usepackage{a4}\n";
1829 case BufferParams::PACKAGE_A4WIDE:
1830 os << "\\usepackage{a4wide}\n";
1833 case BufferParams::PACKAGE_WIDEMARGINSA4:
1834 os << "\\usepackage[widemargins]{a4}\n";
1839 if (params.use_geometry) {
1840 os << "\\usepackage{geometry}\n";
1842 os << "\\geometry{verbose";
1843 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1845 switch (params.papersize2) {
1846 case BufferParams::VM_PAPER_CUSTOM:
1847 if (!params.paperwidth.empty())
1848 os << ",paperwidth="
1849 << params.paperwidth;
1850 if (!params.paperheight.empty())
1851 os << ",paperheight="
1852 << params.paperheight;
1854 case BufferParams::VM_PAPER_USLETTER:
1855 os << ",letterpaper";
1857 case BufferParams::VM_PAPER_USLEGAL:
1858 os << ",legalpaper";
1860 case BufferParams::VM_PAPER_USEXECUTIVE:
1861 os << ",executivepaper";
1863 case BufferParams::VM_PAPER_A3:
1866 case BufferParams::VM_PAPER_A4:
1869 case BufferParams::VM_PAPER_A5:
1872 case BufferParams::VM_PAPER_B3:
1875 case BufferParams::VM_PAPER_B4:
1878 case BufferParams::VM_PAPER_B5:
1882 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1883 switch (lyxrc.default_papersize) {
1884 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1885 case BufferParams::PAPER_USLETTER:
1886 os << ",letterpaper";
1888 case BufferParams::PAPER_LEGALPAPER:
1889 os << ",legalpaper";
1891 case BufferParams::PAPER_EXECUTIVEPAPER:
1892 os << ",executivepaper";
1894 case BufferParams::PAPER_A3PAPER:
1897 case BufferParams::PAPER_A4PAPER:
1900 case BufferParams::PAPER_A5PAPER:
1903 case BufferParams::PAPER_B5PAPER:
1908 if (!params.topmargin.empty())
1909 os << ",tmargin=" << params.topmargin;
1910 if (!params.bottommargin.empty())
1911 os << ",bmargin=" << params.bottommargin;
1912 if (!params.leftmargin.empty())
1913 os << ",lmargin=" << params.leftmargin;
1914 if (!params.rightmargin.empty())
1915 os << ",rmargin=" << params.rightmargin;
1916 if (!params.headheight.empty())
1917 os << ",headheight=" << params.headheight;
1918 if (!params.headsep.empty())
1919 os << ",headsep=" << params.headsep;
1920 if (!params.footskip.empty())
1921 os << ",footskip=" << params.footskip;
1926 if (tokenPos(tclass.opt_pagestyle(),
1927 '|', params.pagestyle) >= 0) {
1928 if (params.pagestyle == "fancy") {
1929 os << "\\usepackage{fancyhdr}\n";
1932 os << "\\pagestyle{" << params.pagestyle << "}\n";
1936 if (params.secnumdepth != tclass.secnumdepth()) {
1937 os << "\\setcounter{secnumdepth}{"
1938 << params.secnumdepth
1942 if (params.tocdepth != tclass.tocdepth()) {
1943 os << "\\setcounter{tocdepth}{"
1949 if (params.paragraph_separation) {
1950 switch (params.defskip.kind()) {
1951 case VSpace::SMALLSKIP:
1952 os << "\\setlength\\parskip{\\smallskipamount}\n";
1954 case VSpace::MEDSKIP:
1955 os << "\\setlength\\parskip{\\medskipamount}\n";
1957 case VSpace::BIGSKIP:
1958 os << "\\setlength\\parskip{\\bigskipamount}\n";
1960 case VSpace::LENGTH:
1961 os << "\\setlength\\parskip{"
1962 << params.defskip.length().asLatexString()
1965 default: // should never happen // Then delete it.
1966 os << "\\setlength\\parskip{\\medskipamount}\n";
1971 os << "\\setlength\\parindent{0pt}\n";
1975 // Now insert the LyX specific LaTeX commands...
1977 // The optional packages;
1978 string preamble(features.getPackages());
1980 // this might be useful...
1981 preamble += "\n\\makeatletter\n";
1983 // Some macros LyX will need
1984 string tmppreamble(features.getMacros());
1986 if (!tmppreamble.empty()) {
1987 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1988 "LyX specific LaTeX commands.\n"
1989 + tmppreamble + '\n';
1992 // the text class specific preamble
1993 tmppreamble = features.getTClassPreamble();
1994 if (!tmppreamble.empty()) {
1995 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1996 "Textclass specific LaTeX commands.\n"
1997 + tmppreamble + '\n';
2000 /* the user-defined preamble */
2001 if (!params.preamble.empty()) {
2002 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2003 "User specified LaTeX commands.\n"
2004 + params.preamble + '\n';
2007 // Itemize bullet settings need to be last in case the user
2008 // defines their own bullets that use a package included
2009 // in the user-defined preamble -- ARRae
2010 // Actually it has to be done much later than that
2011 // since some packages like frenchb make modifications
2012 // at \begin{document} time -- JMarc
2014 for (int i = 0; i < 4; ++i) {
2015 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2016 if (bullets_def.empty())
2017 bullets_def="\\AtBeginDocument{\n";
2018 bullets_def += " \\renewcommand{\\labelitemi";
2020 // `i' is one less than the item to modify
2027 bullets_def += "ii";
2033 bullets_def += "}{" +
2034 params.user_defined_bullets[i].getText()
2039 if (!bullets_def.empty())
2040 preamble += bullets_def + "}\n\n";
2043 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2044 for (int j = 0; j != nlines; ++j) {
2048 // We try to load babel late, in case it interferes
2049 // with other packages.
2051 string tmp = lyxrc.language_package;
2052 if (!lyxrc.language_global_options
2053 && tmp == "\\usepackage{babel}")
2054 tmp = string("\\usepackage[") +
2055 language_options.str().c_str() +
2057 preamble += tmp + "\n";
2058 preamble += features.getBabelOptions();
2061 preamble += "\\makeatother\n";
2069 os << "\\begin{document}\n";
2072 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2074 if (!lyxrc.language_auto_begin) {
2075 os << subst(lyxrc.language_command_begin, "$$lang",
2076 params.language->babel())
2081 latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2083 // add this just in case after all the paragraphs
2087 if (!lyxrc.language_auto_end) {
2088 os << subst(lyxrc.language_command_end, "$$lang",
2089 params.language->babel())
2095 os << "\\end{document}\n";
2098 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2100 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2104 // Just to be sure. (Asger)
2107 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2108 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2110 // we want this to be true outside previews (for insetexternal)
2116 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2118 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2119 Paragraph * endpar, TexRow & texrow,
2120 bool moving_arg) const
2122 bool was_title = false;
2123 bool already_title = false;
2126 while (par != endpar) {
2127 Inset * in = par->inInset();
2128 // well we have to check if we are in an inset with unlimited
2129 // length (all in one row) if that is true then we don't allow
2130 // any special options in the paragraph and also we don't allow
2131 // any environment other then "Standard" to be valid!
2132 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2133 LyXLayout_ptr const & layout = par->layout();
2135 if (layout->intitle) {
2136 if (already_title) {
2137 lyxerr <<"Error in latexParagraphs: You"
2138 " should not mix title layouts"
2139 " with normal ones." << endl;
2142 } else if (was_title && !already_title) {
2143 ofs << "\\maketitle\n";
2145 already_title = true;
2149 if (layout->isEnvironment() ||
2150 !par->params().leftIndent().zero())
2152 par = par->TeXEnvironment(this, params, ofs, texrow);
2154 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2157 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2160 // It might be that we only have a title in this document
2161 if (was_title && !already_title) {
2162 ofs << "\\maketitle\n";
2168 bool Buffer::isLatex() const
2170 return params.getLyXTextClass().outputType() == LATEX;
2174 bool Buffer::isLinuxDoc() const
2176 return params.getLyXTextClass().outputType() == LINUXDOC;
2180 bool Buffer::isLiterate() const
2182 return params.getLyXTextClass().outputType() == LITERATE;
2186 bool Buffer::isDocBook() const
2188 return params.getLyXTextClass().outputType() == DOCBOOK;
2192 bool Buffer::isSGML() const
2194 LyXTextClass const & tclass = params.getLyXTextClass();
2196 return tclass.outputType() == LINUXDOC ||
2197 tclass.outputType() == DOCBOOK;
2201 int Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2202 string const & latexname) const
2204 if (!latexname.empty() && latexname != "!-- --") {
2206 os << string(" ",depth);
2207 os << "<" << latexname << ">";
2217 int Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2218 string const & latexname) const
2220 if (!latexname.empty() && latexname != "!-- --") {
2222 os << endl << string(" ",depth);
2223 os << "</" << latexname << ">";
2233 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2235 ofstream ofs(fname.c_str());
2238 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2242 niceFile = nice; // this will be used by included files.
2244 LaTeXFeatures features(params);
2250 LyXTextClass const & tclass = params.getLyXTextClass();
2252 string top_element = tclass.latexname();
2255 ofs << "<!doctype linuxdoc system";
2257 string preamble = params.preamble;
2258 const string name = nice ? ChangeExtension(filename_, ".sgml")
2260 preamble += features.getIncludedFiles(name);
2261 preamble += features.getLyXSGMLEntities();
2263 if (!preamble.empty()) {
2264 ofs << " [ " << preamble << " ]";
2268 if (params.options.empty())
2269 sgmlOpenTag(ofs, 0, false, top_element);
2271 string top = top_element;
2273 top += params.options;
2274 sgmlOpenTag(ofs, 0, false, top);
2278 ofs << "<!-- " << lyx_docversion
2279 << " created this file. For more info see http://www.lyx.org/"
2282 Paragraph::depth_type depth = 0; // paragraph depth
2283 Paragraph * par = &*(paragraphs.begin());
2285 vector<string> environment_stack(5);
2288 LyXLayout_ptr const & style = par->layout();
2289 // treat <toc> as a special case for compatibility with old code
2290 if (par->isInset(0)) {
2291 Inset * inset = par->getInset(0);
2292 Inset::Code lyx_code = inset->lyxCode();
2293 if (lyx_code == Inset::TOC_CODE) {
2294 string const temp = "toc";
2295 sgmlOpenTag(ofs, depth, false, temp);
2302 // environment tag closing
2303 for (; depth > par->params().depth(); --depth) {
2304 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2305 environment_stack[depth].erase();
2308 // write opening SGML tags
2309 switch (style->latextype) {
2310 case LATEX_PARAGRAPH:
2311 if (depth == par->params().depth()
2312 && !environment_stack[depth].empty()) {
2313 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2314 environment_stack[depth].erase();
2320 sgmlOpenTag(ofs, depth, false, style->latexname());
2326 _("Error : Wrong depth for"
2327 " LatexType Command.\n"));
2329 if (!environment_stack[depth].empty()) {
2330 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2334 environment_stack[depth].erase();
2335 sgmlOpenTag(ofs, depth, false, style->latexname());
2338 case LATEX_ENVIRONMENT:
2339 case LATEX_ITEM_ENVIRONMENT:
2341 string const & latexname = style->latexname();
2343 if (depth == par->params().depth()
2344 && environment_stack[depth] != latexname) {
2345 sgmlCloseTag(ofs, depth, false,
2346 environment_stack[depth]);
2347 environment_stack[depth].erase();
2349 if (depth < par->params().depth()) {
2350 depth = par->params().depth();
2351 environment_stack[depth].erase();
2353 if (environment_stack[depth] != latexname) {
2355 sgmlOpenTag(ofs, depth, false, "p");
2357 sgmlOpenTag(ofs, depth, false, latexname);
2359 if (environment_stack.size() == depth + 1)
2360 environment_stack.push_back("!-- --");
2361 environment_stack[depth] = latexname;
2364 if (style->latexparam() == "CDATA")
2367 if (style->latextype == LATEX_ENVIRONMENT) break;
2369 if (style->labeltype == LABEL_MANUAL)
2374 sgmlOpenTag(ofs, depth + 1, false, item_name);
2379 sgmlOpenTag(ofs, depth, false, style->latexname());
2383 simpleLinuxDocOnePar(ofs, par, depth);
2388 // write closing SGML tags
2389 switch (style->latextype) {
2392 case LATEX_ENVIRONMENT:
2393 case LATEX_ITEM_ENVIRONMENT:
2394 if (style->latexparam() == "CDATA")
2398 sgmlCloseTag(ofs, depth, false, style->latexname());
2404 for (int i = depth; i >= 0; --i)
2405 sgmlCloseTag(ofs, depth, false, environment_stack[i]);
2409 sgmlCloseTag(ofs, 0, false, top_element);
2413 // How to check for successful close
2415 // we want this to be true outside previews (for insetexternal)
2420 // checks, if newcol chars should be put into this line
2421 // writes newline, if necessary.
2424 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2425 string::size_type newcol)
2428 if (colcount > lyxrc.ascii_linelen) {
2430 colcount = newcol; // assume write after this call
2445 string tag_name(PAR_TAG const & pt) {
2447 case NONE: return "!-- --";
2448 case TT: return "tt";
2449 case SF: return "sf";
2450 case BF: return "bf";
2451 case IT: return "it";
2452 case SL: return "sl";
2453 case EM: return "em";
2460 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2462 p1 = static_cast<PAR_TAG>(p1 | p2);
2467 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2469 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2475 // Handle internal paragraph parsing -- layout already processed.
2476 void Buffer::simpleLinuxDocOnePar(ostream & os,
2478 Paragraph::depth_type /*depth*/)
2480 LyXLayout_ptr const & style = par->layout();
2482 string::size_type char_line_count = 5; // Heuristic choice ;-)
2484 // gets paragraph main font
2487 if (style->labeltype == LABEL_MANUAL) {
2488 font_old = style->labelfont;
2491 font_old = style->font;
2495 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2496 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2497 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2500 stack<PAR_TAG> tag_state;
2501 // parsing main loop
2502 for (pos_type i = 0; i < par->size(); ++i) {
2504 PAR_TAG tag_close = NONE;
2505 list < PAR_TAG > tag_open;
2507 LyXFont const font = par->getFont(params, i);
2509 if (font_old.family() != font.family()) {
2510 switch (family_type) {
2511 case LyXFont::SANS_FAMILY:
2514 case LyXFont::TYPEWRITER_FAMILY:
2521 family_type = font.family();
2523 switch (family_type) {
2524 case LyXFont::SANS_FAMILY:
2525 tag_open.push_back(SF);
2527 case LyXFont::TYPEWRITER_FAMILY:
2528 tag_open.push_back(TT);
2535 if (font_old.series() != font.series()) {
2536 switch (series_type) {
2537 case LyXFont::BOLD_SERIES:
2544 series_type = font.series();
2546 switch (series_type) {
2547 case LyXFont::BOLD_SERIES:
2548 tag_open.push_back(BF);
2556 if (font_old.shape() != font.shape()) {
2557 switch (shape_type) {
2558 case LyXFont::ITALIC_SHAPE:
2561 case LyXFont::SLANTED_SHAPE:
2568 shape_type = font.shape();
2570 switch (shape_type) {
2571 case LyXFont::ITALIC_SHAPE:
2572 tag_open.push_back(IT);
2574 case LyXFont::SLANTED_SHAPE:
2575 tag_open.push_back(SL);
2582 if (font_old.emph() != font.emph()) {
2583 if (font.emph() == LyXFont::ON) {
2584 tag_open.push_back(EM);
2593 list < PAR_TAG > temp;
2594 while (!tag_state.empty() && tag_close) {
2595 PAR_TAG k = tag_state.top();
2597 os << "</" << tag_name(k) << ">";
2604 for(list< PAR_TAG >::const_iterator j = temp.begin();
2605 j != temp.end(); ++j) {
2607 os << "<" << tag_name(*j) << ">";
2610 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2611 j != tag_open.end(); ++j) {
2613 os << "<" << tag_name(*j) << ">";
2616 char c = par->getChar(i);
2618 if (c == Paragraph::META_INSET) {
2619 Inset * inset = par->getInset(i);
2620 inset->linuxdoc(this, os);
2625 if (style->latexparam() == "CDATA") {
2626 // "TeX"-Mode on == > SGML-Mode on.
2633 boost::tie(ws, str) = sgml::escapeChar(c);
2634 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2635 // in freespacing mode, spaces are
2636 // non-breaking characters
2637 if (desc_on) {// if char is ' ' then...
2640 sgmlLineBreak(os, char_line_count, 6);
2644 sgmlLineBreak(os, char_line_count, 1);
2649 char_line_count += str.length();
2655 while (!tag_state.empty()) {
2656 os << "</" << tag_name(tag_state.top()) << ">";
2660 // resets description flag correctly
2662 // <tag> not closed...
2663 sgmlLineBreak(os, char_line_count, 6);
2669 // Print an error message.
2670 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2671 string const & /*message*/) const
2673 #ifdef WITH_WARNINGS
2674 #warning This is wrong we cannot insert an inset like this!!!
2675 // I guess this was Jose' so I explain you more or less why this
2676 // is wrong. This way you insert something in the paragraph and
2677 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2678 // I deactivate this code, have a look at BufferView::insertErrors
2679 // how you should do this correctly! (Jug 20020315)
2682 // insert an error marker in text
2683 InsetError * new_inset = new InsetError(message);
2684 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2690 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2692 ofstream ofs(fname.c_str());
2694 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2698 Paragraph * par = &*(paragraphs.begin());
2700 niceFile = nice; // this will be used by Insetincludes.
2702 LaTeXFeatures features(params);
2707 LyXTextClass const & tclass = params.getLyXTextClass();
2708 string top_element = tclass.latexname();
2711 ofs << "<!DOCTYPE " << top_element
2712 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2714 string preamble = params.preamble;
2715 const string name = nice ? ChangeExtension(filename_, ".sgml")
2717 preamble += features.getIncludedFiles(name);
2718 preamble += features.getLyXSGMLEntities();
2720 if (!preamble.empty()) {
2721 ofs << "\n [ " << preamble << " ]";
2726 string top = top_element;
2728 top += params.language->code();
2731 if (!params.options.empty()) {
2733 top += params.options;
2735 sgmlOpenTag(ofs, 0, false, top);
2737 ofs << "<!-- DocBook file was created by " << lyx_docversion
2738 << "\n See http://www.lyx.org/ for more information -->\n";
2740 vector<string> environment_stack(10);
2741 vector<string> environment_inner(10);
2742 vector<string> command_stack(10);
2744 bool command_flag = false;
2745 Paragraph::depth_type command_depth = 0;
2746 Paragraph::depth_type command_base = 0;
2747 Paragraph::depth_type cmd_depth = 0;
2748 Paragraph::depth_type depth = 0; // paragraph depth
2751 string command_name;
2757 int desc_on = 0; // description mode
2759 LyXLayout_ptr const & style = par->layout();
2761 // environment tag closing
2762 for (; depth > par->params().depth(); --depth) {
2763 if (environment_inner[depth] != "!-- --") {
2764 item_name = "listitem";
2765 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2766 if (environment_inner[depth] == "varlistentry")
2767 sgmlCloseTag(ofs, depth+command_depth, false, environment_inner[depth]);
2769 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2770 environment_stack[depth].erase();
2771 environment_inner[depth].erase();
2774 if (depth == par->params().depth()
2775 && environment_stack[depth] != style->latexname()
2776 && !environment_stack[depth].empty()) {
2777 if (environment_inner[depth] != "!-- --") {
2778 item_name= "listitem";
2779 sgmlCloseTag(ofs, command_depth+depth, false, item_name);
2780 if (environment_inner[depth] == "varlistentry")
2781 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2784 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2786 environment_stack[depth].erase();
2787 environment_inner[depth].erase();
2790 // Write opening SGML tags.
2791 switch (style->latextype) {
2792 case LATEX_PARAGRAPH:
2793 sgmlOpenTag(ofs, depth + command_depth,
2794 false, style->latexname());
2800 _("Error : Wrong depth for "
2801 "LatexType Command.\n"));
2803 command_name = style->latexname();
2805 sgmlparam = style->latexparam();
2806 c_params = split(sgmlparam, c_depth,'|');
2808 cmd_depth = lyx::atoi(c_depth);
2811 if (cmd_depth < command_base) {
2812 for (Paragraph::depth_type j = command_depth;
2813 j >= command_base; --j) {
2814 sgmlCloseTag(ofs, j, false, command_stack[j]);
2817 command_depth = command_base = cmd_depth;
2818 } else if (cmd_depth <= command_depth) {
2819 for (int j = command_depth;
2820 j >= int(cmd_depth); --j) {
2821 sgmlCloseTag(ofs, j, false, command_stack[j]);
2824 command_depth = cmd_depth;
2826 command_depth = cmd_depth;
2828 command_depth = command_base = cmd_depth;
2829 command_flag = true;
2831 if (command_stack.size() == command_depth + 1)
2832 command_stack.push_back(string());
2833 command_stack[command_depth] = command_name;
2835 // treat label as a special case for
2836 // more WYSIWYM handling.
2837 // This is a hack while paragraphs can't have
2838 // attributes, like id in this case.
2839 if (par->isInset(0)) {
2840 Inset * inset = par->getInset(0);
2841 Inset::Code lyx_code = inset->lyxCode();
2842 if (lyx_code == Inset::LABEL_CODE) {
2843 command_name += " id=\"";
2844 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2845 command_name += "\"";
2850 sgmlOpenTag(ofs, depth + command_depth, false, command_name);
2852 item_name = c_params.empty()?"title":c_params;
2853 sgmlOpenTag(ofs, depth + 1 + command_depth, false, item_name);
2856 case LATEX_ENVIRONMENT:
2857 case LATEX_ITEM_ENVIRONMENT:
2858 if (depth < par->params().depth()) {
2859 depth = par->params().depth();
2860 environment_stack[depth].erase();
2863 if (environment_stack[depth] != style->latexname()) {
2864 if (environment_stack.size() == depth + 1) {
2865 environment_stack.push_back("!-- --");
2866 environment_inner.push_back("!-- --");
2868 environment_stack[depth] = style->latexname();
2869 environment_inner[depth] = "!-- --";
2870 sgmlOpenTag(ofs, depth + command_depth, false, environment_stack[depth]);
2872 if (environment_inner[depth] != "!-- --") {
2873 item_name= "listitem";
2874 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2875 if (environment_inner[depth] == "varlistentry")
2876 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2880 if (style->latextype == LATEX_ENVIRONMENT) {
2881 if (!style->latexparam().empty()) {
2882 if (style->latexparam() == "CDATA")
2885 sgmlOpenTag(ofs, depth + command_depth, false, style->latexparam());
2890 desc_on = (style->labeltype == LABEL_MANUAL);
2892 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2893 sgmlOpenTag(ofs, depth + 1 + command_depth,
2894 false, environment_inner[depth]);
2896 item_name = desc_on ? "term" : "para";
2897 sgmlOpenTag(ofs, depth + 1 + command_depth,
2901 sgmlOpenTag(ofs, depth + command_depth,
2902 false, style->latexname());
2906 simpleDocBookOnePar(ofs, par, desc_on,
2907 depth + 1 + command_depth);
2911 // write closing SGML tags
2912 switch (style->latextype) {
2914 end_tag = c_params.empty() ? "title" : c_params;
2915 sgmlCloseTag(ofs, depth + command_depth,
2918 case LATEX_ENVIRONMENT:
2919 if (!style->latexparam().empty()) {
2920 if (style->latexparam() == "CDATA")
2923 sgmlCloseTag(ofs, depth + command_depth, false, style->latexparam());
2926 case LATEX_ITEM_ENVIRONMENT:
2927 if (desc_on == 1) break;
2929 sgmlCloseTag(ofs, depth + 1 + command_depth, false, end_tag);
2931 case LATEX_PARAGRAPH:
2932 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2935 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2941 for (int d = depth; d >= 0; --d) {
2942 if (!environment_stack[depth].empty()) {
2943 if (environment_inner[depth] != "!-- --") {
2944 item_name = "listitem";
2945 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2946 if (environment_inner[depth] == "varlistentry")
2947 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2950 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2954 for (int j = command_depth; j >= 0 ; --j)
2955 if (!command_stack[j].empty()) {
2956 sgmlCloseTag(ofs, j, false, command_stack[j]);
2961 sgmlCloseTag(ofs, 0, false, top_element);
2964 // How to check for successful close
2966 // we want this to be true outside previews (for insetexternal)
2971 void Buffer::simpleDocBookOnePar(ostream & os,
2972 Paragraph * par, int & desc_on,
2973 Paragraph::depth_type depth) const
2975 bool emph_flag = false;
2977 LyXLayout_ptr const & style = par->layout();
2979 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2981 int char_line_count = depth;
2982 //if (!style.free_spacing)
2983 // os << string(depth,' ');
2985 // parsing main loop
2986 for (pos_type i = 0; i < par->size(); ++i) {
2987 LyXFont font = par->getFont(params, i);
2989 // handle <emphasis> tag
2990 if (font_old.emph() != font.emph()) {
2991 if (font.emph() == LyXFont::ON) {
2992 if (style->latexparam() == "CDATA")
2995 if (style->latexparam() == "CDATA")
2999 if (style->latexparam() == "CDATA")
3001 os << "</emphasis>";
3002 if (style->latexparam() == "CDATA")
3009 if (par->isInset(i)) {
3010 Inset * inset = par->getInset(i);
3011 // don't print the inset in position 0 if desc_on == 3 (label)
3012 if (i || desc_on != 3) {
3013 if (style->latexparam() == "CDATA")
3015 inset->docbook(this, os, false);
3016 if (style->latexparam() == "CDATA")
3020 char c = par->getChar(i);
3023 boost::tie(ws, str) = sgml::escapeChar(c);
3025 if (style->pass_thru) {
3027 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3029 } else if (desc_on ==1) {
3031 os << "\n</term><listitem><para>";
3041 if (style->latexparam() == "CDATA")
3043 os << "</emphasis>";
3044 if (style->latexparam() == "CDATA")
3048 // resets description flag correctly
3050 // <term> not closed...
3051 os << "</term>\n<listitem><para> </para>";
3053 if (style->free_spacing)
3058 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3059 // Other flags: -wall -v0 -x
3060 int Buffer::runChktex()
3062 if (!users->text) return 0;
3064 users->owner()->prohibitInput();
3066 // get LaTeX-Filename
3067 string const name = getLatexName();
3068 string path = filePath();
3070 string const org_path = path;
3071 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3075 Path p(path); // path to LaTeX file
3076 users->owner()->message(_("Running chktex..."));
3078 // Remove all error insets
3079 bool const removedErrorInsets = users->removeAutoInsets();
3081 // Generate the LaTeX file if neccessary
3082 makeLaTeXFile(name, org_path, false);
3085 Chktex chktex(lyxrc.chktex_command, name, filePath());
3086 int res = chktex.run(terr); // run chktex
3089 Alert::alert(_("chktex did not work!"),
3090 _("Could not run with file:"), name);
3091 } else if (res > 0) {
3092 // Insert all errors as errors boxes
3093 users->insertErrors(terr);
3096 // if we removed error insets before we ran chktex or if we inserted
3097 // error insets after we ran chktex, this must be run:
3098 if (removedErrorInsets || res) {
3099 #warning repaint needed here, or do you mean update() ?
3103 users->owner()->allowInput();
3109 void Buffer::validate(LaTeXFeatures & features) const
3111 LyXTextClass const & tclass = params.getLyXTextClass();
3113 // AMS Style is at document level
3114 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3115 features.require("amsmath");
3117 for_each(paragraphs.begin(), paragraphs.end(),
3118 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3120 // the bullet shapes are buffer level not paragraph level
3121 // so they are tested here
3122 for (int i = 0; i < 4; ++i) {
3123 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3124 int const font = params.user_defined_bullets[i].getFont();
3126 int const c = params
3127 .user_defined_bullets[i]
3134 features.require("latexsym");
3136 } else if (font == 1) {
3137 features.require("amssymb");
3138 } else if ((font >= 2 && font <= 5)) {
3139 features.require("pifont");
3144 if (lyxerr.debugging(Debug::LATEX)) {
3145 features.showStruct();
3150 // This function should be in Buffer because it's a buffer's property (ale)
3151 string const Buffer::getIncludeonlyList(char delim)
3154 for (inset_iterator it = inset_iterator_begin();
3155 it != inset_iterator_end(); ++it) {
3156 if (it->lyxCode() == Inset::INCLUDE_CODE) {
3157 InsetInclude & inc = static_cast<InsetInclude &>(*it);
3158 if (inc.isIncludeOnly()) {
3161 lst += inc.getRelFileBaseName();
3165 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3170 vector<string> const Buffer::getLabelList() const
3172 /// if this is a child document and the parent is already loaded
3173 /// Use the parent's list instead [ale990407]
3174 if (!params.parentname.empty()
3175 && bufferlist.exists(params.parentname)) {
3176 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3178 return tmp->getLabelList();
3181 vector<string> label_list;
3182 for (inset_iterator it = inset_const_iterator_begin();
3183 it != inset_const_iterator_end(); ++it) {
3184 vector<string> const l = it->getLabelList();
3185 label_list.insert(label_list.end(), l.begin(), l.end());
3191 // This is also a buffer property (ale)
3192 vector<pair<string, string> > const Buffer::getBibkeyList() const
3194 typedef pair<string, string> StringPair;
3195 /// if this is a child document and the parent is already loaded
3196 /// Use the parent's list instead [ale990412]
3197 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3198 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3200 return tmp->getBibkeyList();
3203 vector<StringPair> keys;
3204 ParagraphList::iterator pit = paragraphs.begin();
3205 ParagraphList::iterator pend = paragraphs.end();
3206 for (; pit != pend; ++pit) {
3208 string const key = pit->bibkey->getContents();
3209 string const opt = pit->bibkey->getOptions();
3210 string const ref = pit->asString(this, false);
3211 string const info = opt + "TheBibliographyRef" + ref;
3213 keys.push_back(StringPair(key, info));
3217 // Might be either using bibtex or a child has bibliography
3219 for (inset_iterator it = inset_const_iterator_begin();
3220 it != inset_const_iterator_end(); ++it) {
3221 // Search for Bibtex or Include inset
3222 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3223 vector<StringPair> tmp =
3224 static_cast<InsetBibtex &>(*it).getKeys(this);
3225 keys.insert(keys.end(), tmp.begin(), tmp.end());
3226 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3227 vector<StringPair> const tmp =
3228 static_cast<InsetInclude &>(*it).getKeys();
3229 keys.insert(keys.end(), tmp.begin(), tmp.end());
3238 bool Buffer::isDepClean(string const & name) const
3240 DEPCLEAN * item = dep_clean;
3241 while (item && item->master != name)
3243 if (!item) return true;
3248 void Buffer::markDepClean(string const & name)
3251 dep_clean = new DEPCLEAN;
3252 dep_clean->clean = true;
3253 dep_clean->master = name;
3254 dep_clean->next = 0;
3256 DEPCLEAN * item = dep_clean;
3257 while (item && item->master != name)
3262 item = new DEPCLEAN;
3264 item->master = name;
3271 bool Buffer::dispatch(string const & command, bool * result)
3273 // Split command string into command and argument
3275 string line = ltrim(command);
3276 string const arg = trim(split(line, cmd, ' '));
3278 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3282 bool Buffer::dispatch(int action, string const & argument, bool * result)
3284 bool dispatched = true;
3288 bool const tmp = Exporter::Export(this, argument, false);
3301 void Buffer::resizeInsets(BufferView * bv)
3303 /// then remove all LyXText in text-insets
3304 for_each(paragraphs.begin(), paragraphs.end(),
3305 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3309 void Buffer::redraw()
3311 #warning repaint needed here, or do you mean update() ?
3317 void Buffer::changeLanguage(Language const * from, Language const * to)
3320 ParIterator end = par_iterator_end();
3321 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3322 (*it)->changeLanguage(params, from, to);
3326 bool Buffer::isMultiLingual()
3328 ParIterator end = par_iterator_end();
3329 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3330 if ((*it)->isMultiLingual(params))
3337 Counters & Buffer::counters() const
3343 void Buffer::inset_iterator::setParagraph()
3345 while (pit != pend) {
3346 it = pit->insetlist.begin();
3347 if (it != pit->insetlist.end())
3354 Inset * Buffer::getInsetFromID(int id_arg) const
3356 for (inset_iterator it = inset_const_iterator_begin();
3357 it != inset_const_iterator_end(); ++it)
3359 if (it->id() == id_arg)
3361 Inset * in = it->getInsetFromID(id_arg);
3369 Paragraph * Buffer::getParFromID(int id) const
3374 ParagraphList::iterator it = paragraphs.begin();
3375 ParagraphList::iterator end = paragraphs.end();
3376 for (; it != end; ++it) {
3377 if (it->id() == id) {
3380 Paragraph * tmp = it->getParFromID(id);
3389 ParIterator Buffer::par_iterator_begin()
3391 return ParIterator(&*(paragraphs.begin()));
3395 ParIterator Buffer::par_iterator_end()
3397 return ParIterator();
3401 void Buffer::addUser(BufferView * u)
3407 void Buffer::delUser(BufferView *)
3413 Language const * Buffer::getLanguage() const
3415 return params.language;
3419 bool Buffer::isClean() const
3425 bool Buffer::isBakClean() const
3431 void Buffer::markClean() const
3437 // if the .lyx file has been saved, we don't need an
3443 void Buffer::markBakClean()
3449 void Buffer::setUnnamed(bool flag)
3455 bool Buffer::isUnnamed()
3461 void Buffer::markDirty()
3468 DEPCLEAN * tmp = dep_clean;
3476 string const & Buffer::fileName() const
3482 string const & Buffer::filePath() const
3488 bool Buffer::isReadonly() const
3494 BufferView * Buffer::getUser() const
3500 void Buffer::setParentName(string const & name)
3502 params.parentname = name;
3506 Buffer::inset_iterator::inset_iterator()
3511 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3518 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3522 if (it == pit->insetlist.end()) {
3531 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3533 inset_iterator tmp = *this;
3539 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3541 return *it.getInset();
3545 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3547 return it.getInset();
3551 Paragraph * Buffer::inset_iterator::getPar()
3557 lyx::pos_type Buffer::inset_iterator::getPos() const
3563 bool operator==(Buffer::inset_iterator const & iter1,
3564 Buffer::inset_iterator const & iter2)
3566 return iter1.pit == iter2.pit
3567 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3571 bool operator!=(Buffer::inset_iterator const & iter1,
3572 Buffer::inset_iterator const & iter2)
3574 return !(iter1 == iter2);