1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * This file is Copyright 1996-2001
12 * ======================================================
18 #pragma implementation
22 #include "bufferlist.h"
23 #include "LyXAction.h"
26 #include "tex-strings.h"
28 #include "bufferview_funcs.h"
34 #include "LaTeXFeatures.h"
41 #include "converter.h"
42 #include "BufferView.h"
43 #include "ParagraphParameters.h"
44 #include "iterators.h"
45 #include "lyxtextclasslist.h"
47 #include "paragraph_funcs.h"
49 #include "frontends/LyXView.h"
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
54 #include "insets/inset.h"
55 #include "insets/inseterror.h"
56 #include "insets/insetlabel.h"
57 #include "insets/insetref.h"
58 #include "insets/inseturl.h"
59 #include "insets/insetnote.h"
60 #include "insets/insetquotes.h"
61 #include "insets/insetlatexaccent.h"
62 #include "insets/insetbib.h"
63 #include "insets/insetcite.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetindex.h"
66 #include "insets/insetinclude.h"
67 #include "insets/insettoc.h"
68 #include "insets/insetparent.h"
69 #include "insets/insetspecialchar.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetoptarg.h"
76 #include "insets/insetminipage.h"
77 #include "insets/insetfloat.h"
78 #include "insets/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 = 221;
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)
158 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
159 filepath_ = OnlyPath(file);
161 if (read_only || lyxrc.use_tempdir) {
162 tmppath = CreateBufferTmpDir();
171 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
172 // here the buffer should take care that it is
173 // saved properly, before it goes into the void.
175 // make sure that views using this buffer
180 if (!tmppath.empty()) {
181 DestroyBufferTmpDir(tmppath);
186 // Remove any previewed LaTeX snippets assocoated with this buffer.
187 grfx::Previews::get().removeLoader(this);
191 string const Buffer::getLatexName(bool no_path) const
193 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
195 return OnlyFilename(name);
201 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
203 string const filename = getLatexName(false);
205 if (filename.empty())
206 return make_pair(Buffer::latexlog, string());
208 string path = OnlyPath(filename);
210 if (lyxrc.use_tempdir || !IsDirWriteable(path))
213 string const fname = AddName(path,
214 OnlyFilename(ChangeExtension(filename,
217 AddName(path, OnlyFilename(
218 ChangeExtension(filename,
219 formats.extension("literate") + ".out")));
221 // If no Latex log or Build log is newer, show Build log
223 FileInfo const f_fi(fname);
224 FileInfo const b_fi(bname);
227 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
228 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
229 return make_pair(Buffer::buildlog, bname);
231 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
232 return make_pair(Buffer::latexlog, fname);
236 void Buffer::setReadonly(bool flag)
238 if (read_only != flag) {
241 users->owner()->getDialogs().updateBufferDependent(false);
246 /// Update window titles of all users
247 // Should work on a list
248 void Buffer::updateTitles() const
251 users->owner()->updateWindowTitle();
255 /// Reset autosave timer of all users
256 // Should work on a list
257 void Buffer::resetAutosaveTimers() const
260 users->owner()->resetAutosaveTimer();
264 void Buffer::setFileName(string const & newfile)
266 filename_ = MakeAbsPath(newfile);
267 filepath_ = OnlyPath(filename_);
268 setReadonly(IsFileWriteable(filename_) == 0);
273 // We'll remove this later. (Lgb)
276 string last_inset_read;
279 #warning And _why_ is this here? (Lgb)
287 // candidate for move to BufferView
288 // (at least some parts in the beginning of the func)
291 // changed to be public and have one parameter
292 // if par = 0 normal behavior
293 // else insert behavior
294 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
295 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
301 Paragraph::depth_type depth = 0;
302 bool the_end_read = false;
304 Paragraph * first_par = 0;
305 LyXFont font(LyXFont::ALL_INHERIT, params.language);
308 if (file_format < 216 && params.language->lang() == "hebrew")
309 font.setLanguage(default_language);
314 par->layout(params.getLyXTextClass().defaultLayout());
316 // We are inserting into an existing document
317 users->text->breakParagraph(users);
318 first_par = users->text->ownerParagraph();
321 // We don't want to adopt the parameters from the
322 // document we insert, so we skip until the text begins:
325 string const pretoken = lex.getString();
326 if (pretoken == "\\layout") {
327 lex.pushToken(pretoken);
335 string const token = lex.getString();
337 if (token.empty()) continue;
339 lyxerr[Debug::PARSER] << "Handling token: `"
340 << token << "'" << endl;
343 parseSingleLyXformat2Token(lex, par, first_par,
351 paragraphs.set(first_par);
353 if (unknown_layouts > 0) {
354 string s = _("Couldn't set the layout for ");
355 if (unknown_layouts == 1) {
356 s += _("one paragraph");
358 s += tostr(unknown_layouts);
359 s += _(" paragraphs");
361 Alert::alert(_("Textclass Loading Error!"), s,
362 _("When reading " + fileName()));
365 if (unknown_tokens > 0) {
366 string s = _("Encountered ");
367 if (unknown_tokens == 1) {
368 s += _("one unknown token");
370 s += tostr(unknown_tokens);
371 s += _(" unknown tokens");
373 Alert::alert(_("Textclass Loading Error!"), s,
374 _("When reading " + fileName()));
382 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
383 Paragraph *& first_par,
384 string const & token, int & pos,
385 Paragraph::depth_type & depth,
389 bool the_end_read = false;
391 // The order of the tags tested may seem unnatural, but this
392 // has been done in order to reduce the number of string
393 // comparisons needed to recognize a given token. This leads
394 // on large documents like UserGuide to a reduction of a
396 if (token[0] != '\\') {
397 for (string::const_iterator cit = token.begin();
398 cit != token.end(); ++cit) {
399 par->insertChar(pos, (*cit), font);
402 } else if (token == "\\layout") {
403 // reset the font as we start a new layout and if the font is
404 // not ALL_INHERIT,document_language then it will be set to the
405 // right values after this tag (Jug 20020420)
406 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
409 if (file_format < 216 && params.language->lang() == "hebrew")
410 font.setLanguage(default_language);
414 string layoutname = lex.getString();
416 LyXTextClass const & tclass = params.getLyXTextClass();
418 if (layoutname.empty()) {
419 layoutname = tclass.defaultLayoutName();
421 bool hasLayout = tclass.hasLayout(layoutname);
423 lyxerr << "Layout '" << layoutname << "' does not"
424 << " exist in textclass '" << tclass.name()
426 lyxerr << "Trying to use default layout instead."
428 layoutname = tclass.defaultLayoutName();
432 // The is the compability reading of layout caption.
433 // It can be removed in LyX version 1.3.0. (Lgb)
434 if (compare_ascii_no_case(layoutname, "caption") == 0) {
435 // We expect that the par we are now working on is
436 // really inside a InsetText inside a InsetFloat.
437 // We also know that captions can only be
438 // one paragraph. (Lgb)
440 // We should now read until the next "\layout"
442 // This is probably not good enough, what if the
443 // caption is the last par in the document (Lgb)
444 istream & ist = lex.getStream();
450 if (prefixIs(line, "\\layout")) {
454 if (prefixIs(line, "\\begin_inset"))
456 if (prefixIs(line, "\\end_inset")) {
467 // Now we should have the whole layout in ss
468 // we should now be able to give this to the
470 ss << "\\end_inset\n";
472 // This seems like a bug in stringstream.
473 // We really should be able to use ss
475 istringstream is(ss.str());
477 tmplex.setStream(is);
478 Inset * inset = new InsetCaption;
479 inset->Read(this, tmplex);
480 par->InsertInset(pos, inset, font);
487 par = new Paragraph(par);
488 par->layout(params.getLyXTextClass().defaultLayout());
491 par->layout(params.getLyXTextClass()[layoutname]);
492 // Test whether the layout is obsolete.
493 LyXLayout_ptr const & layout = par->layout();
494 if (!layout->obsoleted_by().empty())
495 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
496 par->params().depth(depth);
501 } else if (token == "\\end_inset") {
502 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
503 << "Last inset read was: " << last_inset_read
505 // Simply ignore this. The insets do not have
507 // But insets should read it, it is a part of
508 // the inset isn't it? Lgb.
509 } else if (token == "\\begin_inset") {
510 readInset(lex, par, pos, font);
511 } else if (token == "\\family") {
513 font.setLyXFamily(lex.getString());
514 } else if (token == "\\series") {
516 font.setLyXSeries(lex.getString());
517 } else if (token == "\\shape") {
519 font.setLyXShape(lex.getString());
520 } else if (token == "\\size") {
522 font.setLyXSize(lex.getString());
523 } else if (token == "\\lang") {
525 string const tok = lex.getString();
526 Language const * lang = languages.getLanguage(tok);
528 font.setLanguage(lang);
530 font.setLanguage(params.language);
531 lex.printError("Unknown language `$$Token'");
533 } else if (token == "\\numeric") {
535 font.setNumber(font.setLyXMisc(lex.getString()));
536 } else if (token == "\\emph") {
538 font.setEmph(font.setLyXMisc(lex.getString()));
539 } else if (token == "\\bar") {
541 string const tok = lex.getString();
542 // This is dirty, but gone with LyX3. (Asger)
544 font.setUnderbar(LyXFont::ON);
545 else if (tok == "no")
546 font.setUnderbar(LyXFont::OFF);
547 else if (tok == "default")
548 font.setUnderbar(LyXFont::INHERIT);
550 lex.printError("Unknown bar font flag "
552 } else if (token == "\\noun") {
554 font.setNoun(font.setLyXMisc(lex.getString()));
555 } else if (token == "\\color") {
557 font.setLyXColor(lex.getString());
558 } else if (token == "\\SpecialChar") {
559 LyXLayout_ptr const & layout = par->layout();
561 // Insets don't make sense in a free-spacing context! ---Kayvan
562 if (layout->free_spacing || par->isFreeSpacing()) {
565 string next_token = lex.getString();
566 if (next_token == "\\-") {
567 par->insertChar(pos, '-', font);
568 } else if (next_token == "\\protected_separator"
569 || next_token == "~") {
570 par->insertChar(pos, ' ', font);
572 lex.printError("Token `$$Token' "
574 "paragraph layout!");
579 Inset * inset = new InsetSpecialChar;
580 inset->read(this, lex);
581 par->insertInset(pos, inset, font);
584 } else if (token == "\\i") {
585 Inset * inset = new InsetLatexAccent;
586 inset->read(this, lex);
587 par->insertInset(pos, inset, font);
589 } else if (token == "\\backslash") {
590 par->insertChar(pos, '\\', font);
592 } else if (token == "\\begin_deeper") {
594 } else if (token == "\\end_deeper") {
596 lex.printError("\\end_deeper: "
597 "depth is already null");
601 } else if (token == "\\begin_preamble") {
602 params.readPreamble(lex);
603 } else if (token == "\\textclass") {
605 pair<bool, textclass_type> pp =
606 textclasslist.NumberOfClass(lex.getString());
608 params.textclass = pp.second;
610 Alert::alert(string(_("Textclass error")),
611 string(_("The document uses an unknown textclass \"")) +
612 lex.getString() + string("\"."),
613 string(_("LyX will not be able to produce output correctly.")));
614 params.textclass = 0;
616 if (!params.getLyXTextClass().load()) {
617 // if the textclass wasn't loaded properly
618 // we need to either substitute another
619 // or stop loading the file.
620 // I can substitute but I don't see how I can
621 // stop loading... ideas?? ARRae980418
622 Alert::alert(_("Textclass Loading Error!"),
623 string(_("Can't load textclass ")) +
624 params.getLyXTextClass().name(),
625 _("-- substituting default"));
626 params.textclass = 0;
628 } else if (token == "\\options") {
630 params.options = lex.getString();
631 } else if (token == "\\language") {
632 params.readLanguage(lex);
633 } else if (token == "\\fontencoding") {
635 } else if (token == "\\inputencoding") {
637 params.inputenc = lex.getString();
638 } else if (token == "\\graphics") {
639 params.readGraphicsDriver(lex);
640 } else if (token == "\\fontscheme") {
642 params.fonts = lex.getString();
643 } else if (token == "\\noindent") {
644 par->params().noindent(true);
645 } else if (token == "\\leftindent") {
647 LyXLength value(lex.getString());
648 par->params().leftIndent(value);
649 } else if (token == "\\fill_top") {
650 par->params().spaceTop(VSpace(VSpace::VFILL));
651 } else if (token == "\\fill_bottom") {
652 par->params().spaceBottom(VSpace(VSpace::VFILL));
653 } else if (token == "\\line_top") {
654 par->params().lineTop(true);
655 } else if (token == "\\line_bottom") {
656 par->params().lineBottom(true);
657 } else if (token == "\\pagebreak_top") {
658 par->params().pagebreakTop(true);
659 } else if (token == "\\pagebreak_bottom") {
660 par->params().pagebreakBottom(true);
661 } else if (token == "\\start_of_appendix") {
662 par->params().startOfAppendix(true);
663 } else if (token == "\\paragraph_separation") {
664 int tmpret = lex.findToken(string_paragraph_separation);
667 params.paragraph_separation =
668 static_cast<BufferParams::PARSEP>(tmpret);
669 } else if (token == "\\defskip") {
671 params.defskip = VSpace(lex.getString());
672 } else if (token == "\\quotes_language") {
673 int tmpret = lex.findToken(string_quotes_language);
676 InsetQuotes::quote_language tmpl =
677 InsetQuotes::EnglishQ;
680 tmpl = InsetQuotes::EnglishQ;
683 tmpl = InsetQuotes::SwedishQ;
686 tmpl = InsetQuotes::GermanQ;
689 tmpl = InsetQuotes::PolishQ;
692 tmpl = InsetQuotes::FrenchQ;
695 tmpl = InsetQuotes::DanishQ;
698 params.quotes_language = tmpl;
699 } else if (token == "\\quotes_times") {
701 switch (lex.getInteger()) {
703 params.quotes_times = InsetQuotes::SingleQ;
706 params.quotes_times = InsetQuotes::DoubleQ;
709 } else if (token == "\\papersize") {
710 int tmpret = lex.findToken(string_papersize);
714 params.papersize2 = tmpret;
715 } else if (token == "\\paperpackage") {
716 int tmpret = lex.findToken(string_paperpackages);
719 params.paperpackage = BufferParams::PACKAGE_NONE;
721 params.paperpackage = tmpret;
722 } else if (token == "\\use_geometry") {
724 params.use_geometry = lex.getInteger();
725 } else if (token == "\\use_amsmath") {
727 params.use_amsmath = lex.getInteger();
728 } else if (token == "\\use_natbib") {
730 params.use_natbib = lex.getInteger();
731 } else if (token == "\\use_numerical_citations") {
733 params.use_numerical_citations = lex.getInteger();
734 } else if (token == "\\paperorientation") {
735 int tmpret = lex.findToken(string_orientation);
739 static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
740 } else if (token == "\\paperwidth") {
742 params.paperwidth = lex.getString();
743 } else if (token == "\\paperheight") {
745 params.paperheight = lex.getString();
746 } else if (token == "\\leftmargin") {
748 params.leftmargin = lex.getString();
749 } else if (token == "\\topmargin") {
751 params.topmargin = lex.getString();
752 } else if (token == "\\rightmargin") {
754 params.rightmargin = lex.getString();
755 } else if (token == "\\bottommargin") {
757 params.bottommargin = lex.getString();
758 } else if (token == "\\headheight") {
760 params.headheight = lex.getString();
761 } else if (token == "\\headsep") {
763 params.headsep = lex.getString();
764 } else if (token == "\\footskip") {
766 params.footskip = lex.getString();
767 } else if (token == "\\paperfontsize") {
769 params.fontsize = rtrim(lex.getString());
770 } else if (token == "\\papercolumns") {
772 params.columns = lex.getInteger();
773 } else if (token == "\\papersides") {
775 switch (lex.getInteger()) {
777 case 1: params.sides = LyXTextClass::OneSide; break;
778 case 2: params.sides = LyXTextClass::TwoSides; break;
780 } else if (token == "\\paperpagestyle") {
782 params.pagestyle = rtrim(lex.getString());
783 } else if (token == "\\bullet") {
785 int const index = lex.getInteger();
787 int temp_int = lex.getInteger();
788 params.user_defined_bullets[index].setFont(temp_int);
789 params.temp_bullets[index].setFont(temp_int);
791 temp_int = lex.getInteger();
792 params.user_defined_bullets[index].setCharacter(temp_int);
793 params.temp_bullets[index].setCharacter(temp_int);
795 temp_int = lex.getInteger();
796 params.user_defined_bullets[index].setSize(temp_int);
797 params.temp_bullets[index].setSize(temp_int);
799 string const temp_str = lex.getString();
800 if (temp_str != "\\end_bullet") {
801 // this element isn't really necessary for
802 // parsing but is easier for humans
803 // to understand bullets. Put it back and
804 // set a debug message?
805 lex.printError("\\end_bullet expected, got" + temp_str);
806 //how can I put it back?
808 } else if (token == "\\bulletLaTeX") {
809 // The bullet class should be able to read this.
811 int const index = lex.getInteger();
813 string temp_str = lex.getString();
815 while (temp_str != "\\end_bullet") {
816 // this loop structure is needed when user
817 // enters an empty string since the first
818 // thing returned will be the \\end_bullet
820 // if the LaTeX entry has spaces. Each element
821 // therefore needs to be read in turn
824 temp_str = lex.getString();
827 params.user_defined_bullets[index].setText(sum_str);
828 params.temp_bullets[index].setText(sum_str);
829 } else if (token == "\\secnumdepth") {
831 params.secnumdepth = lex.getInteger();
832 } else if (token == "\\tocdepth") {
834 params.tocdepth = lex.getInteger();
835 } else if (token == "\\spacing") {
837 string const tmp = rtrim(lex.getString());
838 Spacing::Space tmp_space = Spacing::Default;
840 if (tmp == "single") {
841 tmp_space = Spacing::Single;
842 } else if (tmp == "onehalf") {
843 tmp_space = Spacing::Onehalf;
844 } else if (tmp == "double") {
845 tmp_space = Spacing::Double;
846 } else if (tmp == "other") {
848 tmp_space = Spacing::Other;
849 tmp_val = lex.getFloat();
851 lex.printError("Unknown spacing token: '$$Token'");
853 // Small hack so that files written with klyx will be
856 par->params().spacing(Spacing(tmp_space, tmp_val));
858 params.spacing.set(tmp_space, tmp_val);
860 } else if (token == "\\paragraph_spacing") {
862 string const tmp = rtrim(lex.getString());
863 if (tmp == "single") {
864 par->params().spacing(Spacing(Spacing::Single));
865 } else if (tmp == "onehalf") {
866 par->params().spacing(Spacing(Spacing::Onehalf));
867 } else if (tmp == "double") {
868 par->params().spacing(Spacing(Spacing::Double));
869 } else if (tmp == "other") {
871 par->params().spacing(Spacing(Spacing::Other,
874 lex.printError("Unknown spacing token: '$$Token'");
876 } else if (token == "\\float_placement") {
878 params.float_placement = lex.getString();
879 } else if (token == "\\align") {
880 int tmpret = lex.findToken(string_align);
881 if (tmpret == -1) ++tmpret;
882 int const tmpret2 = int(pow(2.0, tmpret));
883 par->params().align(LyXAlignment(tmpret2));
884 } else if (token == "\\added_space_top") {
886 VSpace value = VSpace(lex.getString());
887 // only add the length when value > 0 or
889 if ((value.length().len().value() != 0) ||
891 (value.kind() != VSpace::LENGTH))
892 par->params().spaceTop(value);
893 } else if (token == "\\added_space_bottom") {
895 VSpace value = VSpace(lex.getString());
896 // only add the length when value > 0 or
898 if ((value.length().len().value() != 0) ||
900 (value.kind() != VSpace::LENGTH))
901 par->params().spaceBottom(value);
902 } else if (token == "\\labelwidthstring") {
904 par->params().labelWidthString(lex.getString());
905 // do not delete this token, it is still needed!
906 } else if (token == "\\newline") {
907 par->insertChar(pos, Paragraph::META_NEWLINE, font);
909 } else if (token == "\\LyXTable") {
910 Inset * inset = new InsetTabular(*this);
911 inset->read(this, lex);
912 par->insertInset(pos, inset, font);
914 } else if (token == "\\hfill") {
915 par->insertChar(pos, Paragraph::META_HFILL, font);
917 } else if (token == "\\protected_separator") { // obsolete
918 // This is a backward compability thingie. (Lgb)
919 // Remove it later some time...introduced with fileformat
921 LyXLayout_ptr const & layout = par->layout();
923 if (layout->free_spacing || par->isFreeSpacing()) {
924 par->insertChar(pos, ' ', font);
926 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
927 par->insertInset(pos, inset, font);
930 } else if (token == "\\bibitem") { // ale970302
932 InsetCommandParams p("bibitem", "dummy");
933 par->bibkey = new InsetBibKey(p);
935 par->bibkey->read(this, lex);
936 } else if (token == "\\the_end") {
939 // This should be insurance for the future: (Asger)
942 string const s = _("Unknown token: ") + token
943 + " " + lex.text() + "\n";
944 // we can do this here this way because we're actually reading
945 // the buffer and don't care about LyXText right now.
946 InsetError * new_inset = new InsetError(s);
947 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
955 // needed to insert the selection
956 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
957 LyXFont const & fn,string const & str) const
959 LyXLayout_ptr const & layout = par->layout();
963 par->checkInsertChar(font);
964 // insert the string, don't insert doublespace
965 bool space_inserted = true;
966 bool autobreakrows = !par->inInset() ||
967 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
968 for(string::const_iterator cit = str.begin();
969 cit != str.end(); ++cit) {
971 if (autobreakrows && (!par->empty() || layout->keepempty)) {
972 breakParagraph(params, par, pos,
973 layout->isEnvironment());
976 space_inserted = true;
980 // do not insert consecutive spaces if !free_spacing
981 } else if ((*cit == ' ' || *cit == '\t') &&
982 space_inserted && !layout->free_spacing &&
983 !par->isFreeSpacing())
986 } else if (*cit == '\t') {
987 if (!layout->free_spacing && !par->isFreeSpacing()) {
988 // tabs are like spaces here
989 par->insertChar(pos, ' ', font);
991 space_inserted = true;
993 const pos_type nb = 8 - pos % 8;
994 for (pos_type a = 0; a < nb ; ++a) {
995 par->insertChar(pos, ' ', font);
998 space_inserted = true;
1000 } else if (!IsPrintable(*cit)) {
1001 // Ignore unprintables
1004 // just insert the character
1005 par->insertChar(pos, *cit, font);
1007 space_inserted = (*cit == ' ');
1014 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1015 int & pos, LyXFont & font)
1017 // consistency check
1018 if (lex.getString() != "\\begin_inset") {
1019 lyxerr << "Buffer::readInset: Consistency check failed."
1026 string const tmptok = lex.getString();
1027 last_inset_read = tmptok;
1029 // test the different insets
1030 if (tmptok == "LatexCommand") {
1031 InsetCommandParams inscmd;
1034 string const cmdName = inscmd.getCmdName();
1036 // This strange command allows LyX to recognize "natbib" style
1037 // citations: citet, citep, Citet etc.
1038 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1039 inset = new InsetCitation(inscmd);
1040 } else if (cmdName == "bibitem") {
1041 lex.printError("Wrong place for bibitem");
1042 inset = new InsetBibKey(inscmd);
1043 } else if (cmdName == "BibTeX") {
1044 inset = new InsetBibtex(inscmd);
1045 } else if (cmdName == "index") {
1046 inset = new InsetIndex(inscmd);
1047 } else if (cmdName == "include") {
1048 inset = new InsetInclude(inscmd, *this);
1049 } else if (cmdName == "label") {
1050 inset = new InsetLabel(inscmd);
1051 } else if (cmdName == "url"
1052 || cmdName == "htmlurl") {
1053 inset = new InsetUrl(inscmd);
1054 } else if (cmdName == "ref"
1055 || cmdName == "pageref"
1056 || cmdName == "vref"
1057 || cmdName == "vpageref"
1058 || cmdName == "prettyref") {
1059 if (!inscmd.getOptions().empty()
1060 || !inscmd.getContents().empty()) {
1061 inset = new InsetRef(inscmd, *this);
1063 } else if (cmdName == "tableofcontents") {
1064 inset = new InsetTOC(inscmd);
1065 } else if (cmdName == "listofalgorithms") {
1066 inset = new InsetFloatList("algorithm");
1067 } else if (cmdName == "listoffigures") {
1068 inset = new InsetFloatList("figure");
1069 } else if (cmdName == "listoftables") {
1070 inset = new InsetFloatList("table");
1071 } else if (cmdName == "printindex") {
1072 inset = new InsetPrintIndex(inscmd);
1073 } else if (cmdName == "lyxparent") {
1074 inset = new InsetParent(inscmd, *this);
1077 bool alreadyread = false;
1078 if (tmptok == "Quotes") {
1079 inset = new InsetQuotes;
1080 } else if (tmptok == "External") {
1081 inset = new InsetExternal;
1082 } else if (tmptok == "FormulaMacro") {
1083 inset = new InsetFormulaMacro;
1084 } else if (tmptok == "Formula") {
1085 inset = new InsetFormula;
1086 } else if (tmptok == "Figure") { // Backward compatibility
1087 // inset = new InsetFig(100, 100, *this);
1088 inset = new InsetGraphics;
1089 } else if (tmptok == "Graphics") {
1090 inset = new InsetGraphics;
1091 } else if (tmptok == "Info") {// backwards compatibility
1092 inset = new InsetNote(this,
1093 lex.getLongString("\\end_inset"),
1096 } else if (tmptok == "Note") {
1097 inset = new InsetNote(params);
1098 } else if (tmptok == "Include") {
1099 InsetCommandParams p("Include");
1100 inset = new InsetInclude(p, *this);
1101 } else if (tmptok == "ERT") {
1102 inset = new InsetERT(params);
1103 } else if (tmptok == "Tabular") {
1104 inset = new InsetTabular(*this);
1105 } else if (tmptok == "Text") {
1106 inset = new InsetText(params);
1107 } else if (tmptok == "Foot") {
1108 inset = new InsetFoot(params);
1109 } else if (tmptok == "Marginal") {
1110 inset = new InsetMarginal(params);
1111 } else if (tmptok == "OptArg") {
1112 inset = new InsetOptArg(params);
1113 } else if (tmptok == "Minipage") {
1114 inset = new InsetMinipage(params);
1115 } else if (tmptok == "Float") {
1117 string tmptok = lex.getString();
1118 inset = new InsetFloat(params, tmptok);
1120 } else if (tmptok == "List") {
1121 inset = new InsetList;
1122 } else if (tmptok == "Theorem") {
1123 inset = new InsetList;
1125 } else if (tmptok == "Caption") {
1126 inset = new InsetCaption(params);
1127 } else if (tmptok == "FloatList") {
1128 inset = new InsetFloatList;
1131 if (inset && !alreadyread) inset->read(this, lex);
1135 par->insertInset(pos, inset, font);
1141 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1145 string const token(lex.getString());
1146 if (token == "\\lyxformat") { // the first token _must_ be...
1148 string tmp_format = lex.getString();
1149 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1150 // if present remove ".," from string.
1151 string::size_type dot = tmp_format.find_first_of(".,");
1152 //lyxerr << " dot found at " << dot << endl;
1153 if (dot != string::npos)
1154 tmp_format.erase(dot, 1);
1155 file_format = strToInt(tmp_format);
1156 //lyxerr << "format: " << file_format << endl;
1157 if (file_format == LYX_FORMAT) {
1159 } else if (file_format > LYX_FORMAT) {
1161 Alert::alert(_("Warning!"),
1162 _("LyX file format is newer that what"),
1163 _("is supported in this LyX version. Expect some problems."));
1165 } else if (file_format < LYX_FORMAT) {
1167 if (file_format < 200) {
1168 Alert::alert(_("ERROR!"),
1169 _("Old LyX file format found. "
1170 "Use LyX 0.10.x to read this!"));
1174 LibFileSearch("lyx2lyx", "lyx2lyx");
1175 if (command.empty()) {
1176 Alert::alert(_("ERROR!"),
1177 _("Can't find conversion script."));
1181 +tostr(LYX_FORMAT)+" "
1182 + QuoteName(filename_);
1183 cmd_ret const ret = RunCommand(command);
1185 Alert::alert(_("ERROR!"),
1186 _("An error occured while "
1187 "running the conversion script."));
1190 istringstream is(ret.second);
1191 LyXLex tmplex(0, 0);
1192 tmplex.setStream(is);
1193 return readFile(tmplex);
1196 bool the_end = readLyXformat2(lex, par);
1197 params.setPaperStuff();
1200 // the_end was added in 213
1201 if (file_format < 213)
1206 Alert::alert(_("Warning!"),
1207 _("Reading of document is not complete"),
1208 _("Maybe the document is truncated"));
1211 } else { // "\\lyxformat" not found
1212 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1215 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1220 // Should probably be moved to somewhere else: BufferView? LyXView?
1221 bool Buffer::save() const
1223 // We don't need autosaves in the immediate future. (Asger)
1224 resetAutosaveTimers();
1228 if (lyxrc.make_backup) {
1229 s = fileName() + '~';
1230 if (!lyxrc.backupdir_path.empty())
1231 s = AddName(lyxrc.backupdir_path,
1232 subst(os::slashify_path(s),'/','!'));
1234 // Rename is the wrong way of making a backup,
1235 // this is the correct way.
1236 /* truss cp fil fil2:
1237 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1238 stat("LyXVC.lyx", 0xEFFFF688) = 0
1239 open("LyXVC.lyx", O_RDONLY) = 3
1240 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1241 fstat(4, 0xEFFFF508) = 0
1242 fstat(3, 0xEFFFF508) = 0
1243 read(3, " # T h i s f i l e w".., 8192) = 5579
1244 write(4, " # T h i s f i l e w".., 5579) = 5579
1245 read(3, 0xEFFFD4A0, 8192) = 0
1248 chmod("LyXVC3.lyx", 0100644) = 0
1249 lseek(0, 0, SEEK_CUR) = 46440
1253 // Should probably have some more error checking here.
1254 // Doing it this way, also makes the inodes stay the same.
1255 // This is still not a very good solution, in particular we
1256 // might loose the owner of the backup.
1257 FileInfo finfo(fileName());
1258 if (finfo.exist()) {
1259 mode_t fmode = finfo.getMode();
1260 struct utimbuf times = {
1261 finfo.getAccessTime(),
1262 finfo.getModificationTime() };
1264 ifstream ifs(fileName().c_str());
1265 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1270 ::chmod(s.c_str(), fmode);
1272 if (::utime(s.c_str(), ×)) {
1273 lyxerr << "utime error." << endl;
1276 lyxerr << "LyX was not able to make "
1277 "backup copy. Beware." << endl;
1282 if (writeFile(fileName())) {
1284 removeAutosaveFile(fileName());
1286 // Saving failed, so backup is not backup
1287 if (lyxrc.make_backup) {
1288 lyx::rename(s, fileName());
1296 bool Buffer::writeFile(string const & fname) const
1298 if (read_only && (fname == fileName())) {
1302 FileInfo finfo(fname);
1303 if (finfo.exist() && !finfo.writable()) {
1307 ofstream ofs(fname.c_str());
1313 // Use the standard "C" locale for file output.
1314 ofs.imbue(std::locale::classic());
1317 // The top of the file should not be written by params.
1319 // write out a comment in the top of the file
1320 ofs << '#' << lyx_docversion
1321 << " created this file. For more info see http://www.lyx.org/\n"
1322 << "\\lyxformat " << LYX_FORMAT << "\n";
1324 // now write out the buffer paramters.
1325 params.writeFile(ofs);
1327 Paragraph::depth_type depth = 0;
1329 // this will write out all the paragraphs
1330 // using recursive descent.
1331 ParagraphList::iterator pit = paragraphs.begin();
1332 ParagraphList::iterator pend = paragraphs.end();
1333 for (; pit != pend; ++pit)
1334 pit->write(this, ofs, params, depth);
1336 // Write marker that shows file is complete
1337 ofs << "\n\\the_end" << endl;
1341 // how to check if close went ok?
1342 // Following is an attempt... (BE 20001011)
1344 // good() returns false if any error occured, including some
1345 // formatting error.
1346 // bad() returns true if something bad happened in the buffer,
1347 // which should include file system full errors.
1354 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1356 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1368 pair<int, string> const addDepth(int depth, int ldepth)
1372 d += (ldepth - depth) * 2;
1373 return make_pair(d, string(d, ' '));
1379 string const Buffer::asciiParagraph(Paragraph const & par,
1380 unsigned int linelen,
1381 bool noparbreak) const
1383 ostringstream buffer;
1384 Paragraph::depth_type depth = 0;
1386 Paragraph::depth_type ltype_depth = 0;
1387 bool ref_printed = false;
1388 // if (!par->previous()) {
1390 // begins or ends a deeper area ?
1391 if (depth != par->params().depth()) {
1392 if (par->params().depth() > depth) {
1393 while (par->params().depth() > depth) {
1397 while (par->params().depth() < depth) {
1403 depth = par.params().depth();
1406 // First write the layout
1407 string const & tmp = par.layout()->name();
1408 if (compare_no_case(tmp, "itemize") == 0) {
1410 ltype_depth = depth + 1;
1411 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1413 ltype_depth = depth + 1;
1414 } else if (contains(ascii_lowercase(tmp), "ection")) {
1416 ltype_depth = depth + 1;
1417 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1419 ltype_depth = depth + 1;
1420 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1422 ltype_depth = depth + 1;
1423 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1426 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1434 /* maybe some vertical spaces */
1436 /* the labelwidthstring used in lists */
1440 /* some pagebreaks? */
1444 /* what about the alignment */
1446 // lyxerr << "Should this ever happen?" << endl;
1449 // linelen <= 0 is special and means we don't have paragraph breaks
1451 string::size_type currlinelen = 0;
1457 buffer << string(depth * 2, ' ');
1458 currlinelen += depth * 2;
1461 // we should probably change to the paragraph language in the
1462 // gettext here (if possible) so that strings are outputted in
1463 // the correct language! (20012712 Jug)
1467 case 4: // (Sub)Paragraph
1468 case 5: // Description
1472 buffer << _("Abstract") << "\n\n";
1475 string const abst = _("Abstract: ");
1477 currlinelen += abst.length();
1480 case 7: // Bibliography
1483 buffer << _("References") << "\n\n";
1486 string const refs = _("References: ");
1488 currlinelen += refs.length();
1496 string const parlab = par.params().labelString();
1497 buffer << parlab << " ";
1498 currlinelen += parlab.length() + 1;
1506 pair<int, string> p = addDepth(depth, ltype_depth);
1508 currlinelen += p.first;
1511 // this is to change the linebreak to do it by word a bit more
1512 // intelligent hopefully! (only in the case where we have a
1513 // max linelenght!) (Jug)
1517 for (pos_type i = 0; i < par.size(); ++i) {
1518 char c = par.getUChar(params, i);
1520 case Paragraph::META_INSET:
1522 Inset const * inset = par.getInset(i);
1526 currlinelen += word.length();
1529 if (inset->ascii(this, buffer, linelen)) {
1530 // to be sure it breaks paragraph
1531 currlinelen += linelen;
1537 case Paragraph::META_NEWLINE:
1539 buffer << word << "\n";
1542 pair<int, string> p = addDepth(depth,
1545 currlinelen = p.first;
1549 case Paragraph::META_HFILL:
1550 buffer << word << "\t";
1551 currlinelen += word.length() + 1;
1558 currlinelen + word.length() > linelen - 10) {
1560 pair<int, string> p =
1561 addDepth(depth, ltype_depth);
1563 currlinelen = p.first;
1566 buffer << word << ' ';
1567 currlinelen += word.length() + 1;
1574 lyxerr[Debug::INFO] <<
1575 "writeAsciiFile: NULL char in structure." << endl;
1577 if ((linelen > 0) &&
1578 (currlinelen + word.length()) > linelen)
1582 pair<int, string> p =
1583 addDepth(depth, ltype_depth);
1585 currlinelen = p.first;
1592 return buffer.str().c_str();
1596 void Buffer::writeFileAscii(string const & fname, int linelen)
1598 ofstream ofs(fname.c_str());
1600 Alert::err_alert(_("Error: Cannot write file:"), fname);
1603 writeFileAscii(ofs, linelen);
1607 void Buffer::writeFileAscii(ostream & os, int linelen)
1609 ParagraphList::iterator beg = paragraphs.begin();
1610 ParagraphList::iterator end = paragraphs.end();
1611 ParagraphList::iterator it = beg;
1612 for (; it != end; ++it) {
1613 os << asciiParagraph(*it, linelen, it == beg);
1622 void Buffer::makeLaTeXFile(string const & fname,
1623 string const & original_path,
1624 bool nice, bool only_body, bool only_preamble)
1626 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1628 ofstream ofs(fname.c_str());
1630 Alert::err_alert(_("Error: Cannot open file: "), fname);
1634 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1638 lyxerr << "File was not closed properly." << endl;
1643 void Buffer::makeLaTeXFile(ostream & os,
1644 string const & original_path,
1645 bool nice, bool only_body, bool only_preamble)
1647 niceFile = nice; // this will be used by Insetincludes.
1649 // validate the buffer.
1650 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1651 LaTeXFeatures features(params);
1653 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1656 // The starting paragraph of the coming rows is the
1657 // first paragraph of the document. (Asger)
1658 texrow.start(&*(paragraphs.begin()), 0);
1660 if (!only_body && nice) {
1661 os << "%% " << lyx_docversion << " created this file. "
1662 "For more info, see http://www.lyx.org/.\n"
1663 "%% Do not edit unless you really know what "
1668 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1669 // There are a few differences between nice LaTeX and usual files:
1670 // usual is \batchmode and has a
1671 // special input@path to allow the including of figures
1672 // with either \input or \includegraphics (what figinsets do).
1673 // input@path is set when the actual parameter
1674 // original_path is set. This is done for usual tex-file, but not
1675 // for nice-latex-file. (Matthias 250696)
1678 // code for usual, NOT nice-latex-file
1679 os << "\\batchmode\n"; // changed
1680 // from \nonstopmode
1683 if (!original_path.empty()) {
1684 string inputpath = os::external_path(original_path);
1685 subst(inputpath, "~", "\\string~");
1686 os << "\\makeatletter\n"
1687 << "\\def\\input@path{{"
1688 << inputpath << "/}}\n"
1689 << "\\makeatother\n";
1695 os << "\\documentclass";
1697 LyXTextClass const & tclass = params.getLyXTextClass();
1699 ostringstream options; // the document class options.
1701 if (tokenPos(tclass.opt_fontsize(),
1702 '|', params.fontsize) >= 0) {
1703 // only write if existing in list (and not default)
1704 options << params.fontsize << "pt,";
1708 if (!params.use_geometry &&
1709 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1710 switch (params.papersize) {
1711 case BufferParams::PAPER_A4PAPER:
1712 options << "a4paper,";
1714 case BufferParams::PAPER_USLETTER:
1715 options << "letterpaper,";
1717 case BufferParams::PAPER_A5PAPER:
1718 options << "a5paper,";
1720 case BufferParams::PAPER_B5PAPER:
1721 options << "b5paper,";
1723 case BufferParams::PAPER_EXECUTIVEPAPER:
1724 options << "executivepaper,";
1726 case BufferParams::PAPER_LEGALPAPER:
1727 options << "legalpaper,";
1733 if (params.sides != tclass.sides()) {
1734 switch (params.sides) {
1735 case LyXTextClass::OneSide:
1736 options << "oneside,";
1738 case LyXTextClass::TwoSides:
1739 options << "twoside,";
1745 if (params.columns != tclass.columns()) {
1746 if (params.columns == 2)
1747 options << "twocolumn,";
1749 options << "onecolumn,";
1752 if (!params.use_geometry
1753 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1754 options << "landscape,";
1756 // language should be a parameter to \documentclass
1758 ostringstream language_options;
1759 if (params.language->babel() == "hebrew"
1760 && default_language->babel() != "hebrew")
1761 // This seems necessary
1762 features.useLanguage(default_language);
1764 if (lyxrc.language_use_babel ||
1765 params.language->lang() != lyxrc.default_language ||
1766 features.hasLanguages()) {
1768 language_options << features.getLanguages();
1769 language_options << params.language->babel();
1770 if (lyxrc.language_global_options)
1771 options << language_options.str() << ',';
1774 // the user-defined options
1775 if (!params.options.empty()) {
1776 options << params.options << ',';
1779 string strOptions(options.str().c_str());
1780 if (!strOptions.empty()) {
1781 strOptions = rtrim(strOptions, ",");
1782 os << '[' << strOptions << ']';
1785 os << '{' << tclass.latexname() << "}\n";
1787 // end of \documentclass defs
1789 // font selection must be done before loading fontenc.sty
1790 // The ae package is not needed when using OT1 font encoding.
1791 if (params.fonts != "default" &&
1792 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1793 os << "\\usepackage{" << params.fonts << "}\n";
1795 if (params.fonts == "ae") {
1796 os << "\\usepackage{aecompl}\n";
1800 // this one is not per buffer
1801 if (lyxrc.fontenc != "default") {
1802 os << "\\usepackage[" << lyxrc.fontenc
1807 if (params.inputenc == "auto") {
1808 string const doc_encoding =
1809 params.language->encoding()->LatexName();
1811 // Create a list with all the input encodings used
1813 set<string> encodings = features.getEncodingSet(doc_encoding);
1815 os << "\\usepackage[";
1816 std::copy(encodings.begin(), encodings.end(),
1817 std::ostream_iterator<string>(os, ","));
1818 os << doc_encoding << "]{inputenc}\n";
1820 } else if (params.inputenc != "default") {
1821 os << "\\usepackage[" << params.inputenc
1826 // At the very beginning the text parameters.
1827 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1828 switch (params.paperpackage) {
1829 case BufferParams::PACKAGE_A4:
1830 os << "\\usepackage{a4}\n";
1833 case BufferParams::PACKAGE_A4WIDE:
1834 os << "\\usepackage{a4wide}\n";
1837 case BufferParams::PACKAGE_WIDEMARGINSA4:
1838 os << "\\usepackage[widemargins]{a4}\n";
1843 if (params.use_geometry) {
1844 os << "\\usepackage{geometry}\n";
1846 os << "\\geometry{verbose";
1847 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1849 switch (params.papersize2) {
1850 case BufferParams::VM_PAPER_CUSTOM:
1851 if (!params.paperwidth.empty())
1852 os << ",paperwidth="
1853 << params.paperwidth;
1854 if (!params.paperheight.empty())
1855 os << ",paperheight="
1856 << params.paperheight;
1858 case BufferParams::VM_PAPER_USLETTER:
1859 os << ",letterpaper";
1861 case BufferParams::VM_PAPER_USLEGAL:
1862 os << ",legalpaper";
1864 case BufferParams::VM_PAPER_USEXECUTIVE:
1865 os << ",executivepaper";
1867 case BufferParams::VM_PAPER_A3:
1870 case BufferParams::VM_PAPER_A4:
1873 case BufferParams::VM_PAPER_A5:
1876 case BufferParams::VM_PAPER_B3:
1879 case BufferParams::VM_PAPER_B4:
1882 case BufferParams::VM_PAPER_B5:
1886 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1887 switch (lyxrc.default_papersize) {
1888 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1889 case BufferParams::PAPER_USLETTER:
1890 os << ",letterpaper";
1892 case BufferParams::PAPER_LEGALPAPER:
1893 os << ",legalpaper";
1895 case BufferParams::PAPER_EXECUTIVEPAPER:
1896 os << ",executivepaper";
1898 case BufferParams::PAPER_A3PAPER:
1901 case BufferParams::PAPER_A4PAPER:
1904 case BufferParams::PAPER_A5PAPER:
1907 case BufferParams::PAPER_B5PAPER:
1912 if (!params.topmargin.empty())
1913 os << ",tmargin=" << params.topmargin;
1914 if (!params.bottommargin.empty())
1915 os << ",bmargin=" << params.bottommargin;
1916 if (!params.leftmargin.empty())
1917 os << ",lmargin=" << params.leftmargin;
1918 if (!params.rightmargin.empty())
1919 os << ",rmargin=" << params.rightmargin;
1920 if (!params.headheight.empty())
1921 os << ",headheight=" << params.headheight;
1922 if (!params.headsep.empty())
1923 os << ",headsep=" << params.headsep;
1924 if (!params.footskip.empty())
1925 os << ",footskip=" << params.footskip;
1930 if (tokenPos(tclass.opt_pagestyle(),
1931 '|', params.pagestyle) >= 0) {
1932 if (params.pagestyle == "fancy") {
1933 os << "\\usepackage{fancyhdr}\n";
1936 os << "\\pagestyle{" << params.pagestyle << "}\n";
1940 if (params.secnumdepth != tclass.secnumdepth()) {
1941 os << "\\setcounter{secnumdepth}{"
1942 << params.secnumdepth
1946 if (params.tocdepth != tclass.tocdepth()) {
1947 os << "\\setcounter{tocdepth}{"
1953 if (params.paragraph_separation) {
1954 switch (params.defskip.kind()) {
1955 case VSpace::SMALLSKIP:
1956 os << "\\setlength\\parskip{\\smallskipamount}\n";
1958 case VSpace::MEDSKIP:
1959 os << "\\setlength\\parskip{\\medskipamount}\n";
1961 case VSpace::BIGSKIP:
1962 os << "\\setlength\\parskip{\\bigskipamount}\n";
1964 case VSpace::LENGTH:
1965 os << "\\setlength\\parskip{"
1966 << params.defskip.length().asLatexString()
1969 default: // should never happen // Then delete it.
1970 os << "\\setlength\\parskip{\\medskipamount}\n";
1975 os << "\\setlength\\parindent{0pt}\n";
1979 // Now insert the LyX specific LaTeX commands...
1981 // The optional packages;
1982 string preamble(features.getPackages());
1984 // this might be useful...
1985 preamble += "\n\\makeatletter\n";
1987 // Some macros LyX will need
1988 string tmppreamble(features.getMacros());
1990 if (!tmppreamble.empty()) {
1991 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1992 "LyX specific LaTeX commands.\n"
1993 + tmppreamble + '\n';
1996 // the text class specific preamble
1997 tmppreamble = features.getTClassPreamble();
1998 if (!tmppreamble.empty()) {
1999 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2000 "Textclass specific LaTeX commands.\n"
2001 + tmppreamble + '\n';
2004 /* the user-defined preamble */
2005 if (!params.preamble.empty()) {
2006 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2007 "User specified LaTeX commands.\n"
2008 + params.preamble + '\n';
2011 // Itemize bullet settings need to be last in case the user
2012 // defines their own bullets that use a package included
2013 // in the user-defined preamble -- ARRae
2014 // Actually it has to be done much later than that
2015 // since some packages like frenchb make modifications
2016 // at \begin{document} time -- JMarc
2018 for (int i = 0; i < 4; ++i) {
2019 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2020 if (bullets_def.empty())
2021 bullets_def="\\AtBeginDocument{\n";
2022 bullets_def += " \\renewcommand{\\labelitemi";
2024 // `i' is one less than the item to modify
2031 bullets_def += "ii";
2037 bullets_def += "}{" +
2038 params.user_defined_bullets[i].getText()
2043 if (!bullets_def.empty())
2044 preamble += bullets_def + "}\n\n";
2047 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2048 for (int j = 0; j != nlines; ++j) {
2052 // We try to load babel late, in case it interferes
2053 // with other packages.
2055 string tmp = lyxrc.language_package;
2056 if (!lyxrc.language_global_options
2057 && tmp == "\\usepackage{babel}")
2058 tmp = string("\\usepackage[") +
2059 language_options.str().c_str() +
2061 preamble += tmp + "\n";
2062 preamble += features.getBabelOptions();
2065 preamble += "\\makeatother\n";
2073 os << "\\begin{document}\n";
2076 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2078 if (!lyxrc.language_auto_begin) {
2079 os << subst(lyxrc.language_command_begin, "$$lang",
2080 params.language->babel())
2085 latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2087 // add this just in case after all the paragraphs
2091 if (!lyxrc.language_auto_end) {
2092 os << subst(lyxrc.language_command_end, "$$lang",
2093 params.language->babel())
2099 os << "\\end{document}\n";
2102 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2104 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2108 // Just to be sure. (Asger)
2111 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2112 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2114 // we want this to be true outside previews (for insetexternal)
2120 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2122 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2123 Paragraph * endpar, TexRow & texrow,
2124 bool moving_arg) const
2126 bool was_title = false;
2127 bool already_title = false;
2130 while (par != endpar) {
2131 Inset * in = par->inInset();
2132 // well we have to check if we are in an inset with unlimited
2133 // length (all in one row) if that is true then we don't allow
2134 // any special options in the paragraph and also we don't allow
2135 // any environment other then "Standard" to be valid!
2136 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2137 LyXLayout_ptr const & layout = par->layout();
2139 if (layout->intitle) {
2140 if (already_title) {
2141 lyxerr <<"Error in latexParagraphs: You"
2142 " should not mix title layouts"
2143 " with normal ones." << endl;
2146 } else if (was_title && !already_title) {
2147 ofs << "\\maketitle\n";
2149 already_title = true;
2153 if (layout->isEnvironment() ||
2154 !par->params().leftIndent().zero())
2156 par = par->TeXEnvironment(this, params, ofs, texrow);
2158 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2161 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2164 // It might be that we only have a title in this document
2165 if (was_title && !already_title) {
2166 ofs << "\\maketitle\n";
2172 bool Buffer::isLatex() const
2174 return params.getLyXTextClass().outputType() == LATEX;
2178 bool Buffer::isLinuxDoc() const
2180 return params.getLyXTextClass().outputType() == LINUXDOC;
2184 bool Buffer::isLiterate() const
2186 return params.getLyXTextClass().outputType() == LITERATE;
2190 bool Buffer::isDocBook() const
2192 return params.getLyXTextClass().outputType() == DOCBOOK;
2196 bool Buffer::isSGML() const
2198 LyXTextClass const & tclass = params.getLyXTextClass();
2200 return tclass.outputType() == LINUXDOC ||
2201 tclass.outputType() == DOCBOOK;
2205 int Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2206 string const & latexname) const
2208 if (!latexname.empty() && latexname != "!-- --") {
2210 os << string(" ",depth);
2211 os << "<" << latexname << ">";
2221 int Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2222 string const & latexname) const
2224 if (!latexname.empty() && latexname != "!-- --") {
2226 os << endl << string(" ",depth);
2227 os << "</" << latexname << ">";
2237 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2239 ofstream ofs(fname.c_str());
2242 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2246 niceFile = nice; // this will be used by included files.
2248 LaTeXFeatures features(params);
2254 LyXTextClass const & tclass = params.getLyXTextClass();
2256 string top_element = tclass.latexname();
2259 ofs << "<!doctype linuxdoc system";
2261 string preamble = params.preamble;
2262 const string name = nice ? ChangeExtension(filename_, ".sgml")
2264 preamble += features.getIncludedFiles(name);
2265 preamble += features.getLyXSGMLEntities();
2267 if (!preamble.empty()) {
2268 ofs << " [ " << preamble << " ]";
2272 if (params.options.empty())
2273 sgmlOpenTag(ofs, 0, false, top_element);
2275 string top = top_element;
2277 top += params.options;
2278 sgmlOpenTag(ofs, 0, false, top);
2282 ofs << "<!-- " << lyx_docversion
2283 << " created this file. For more info see http://www.lyx.org/"
2286 Paragraph::depth_type depth = 0; // paragraph depth
2287 Paragraph * par = &*(paragraphs.begin());
2289 vector<string> environment_stack(5);
2292 LyXLayout_ptr const & style = par->layout();
2293 // treat <toc> as a special case for compatibility with old code
2294 if (par->isInset(0)) {
2295 Inset * inset = par->getInset(0);
2296 Inset::Code lyx_code = inset->lyxCode();
2297 if (lyx_code == Inset::TOC_CODE) {
2298 string const temp = "toc";
2299 sgmlOpenTag(ofs, depth, false, temp);
2306 // environment tag closing
2307 for (; depth > par->params().depth(); --depth) {
2308 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2309 environment_stack[depth].erase();
2312 // write opening SGML tags
2313 switch (style->latextype) {
2314 case LATEX_PARAGRAPH:
2315 if (depth == par->params().depth()
2316 && !environment_stack[depth].empty()) {
2317 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2318 environment_stack[depth].erase();
2324 sgmlOpenTag(ofs, depth, false, style->latexname());
2330 _("Error : Wrong depth for"
2331 " LatexType Command.\n"));
2333 if (!environment_stack[depth].empty()) {
2334 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2338 environment_stack[depth].erase();
2339 sgmlOpenTag(ofs, depth, false, style->latexname());
2342 case LATEX_ENVIRONMENT:
2343 case LATEX_ITEM_ENVIRONMENT:
2345 string const & latexname = style->latexname();
2347 if (depth == par->params().depth()
2348 && environment_stack[depth] != latexname) {
2349 sgmlCloseTag(ofs, depth, false,
2350 environment_stack[depth]);
2351 environment_stack[depth].erase();
2353 if (depth < par->params().depth()) {
2354 depth = par->params().depth();
2355 environment_stack[depth].erase();
2357 if (environment_stack[depth] != latexname) {
2359 sgmlOpenTag(ofs, depth, false, "p");
2361 sgmlOpenTag(ofs, depth, false, latexname);
2363 if (environment_stack.size() == depth + 1)
2364 environment_stack.push_back("!-- --");
2365 environment_stack[depth] = latexname;
2368 if (style->latexparam() == "CDATA")
2371 if (style->latextype == LATEX_ENVIRONMENT) break;
2373 if (style->labeltype == LABEL_MANUAL)
2378 sgmlOpenTag(ofs, depth + 1, false, item_name);
2383 sgmlOpenTag(ofs, depth, false, style->latexname());
2387 simpleLinuxDocOnePar(ofs, par, depth);
2392 // write closing SGML tags
2393 switch (style->latextype) {
2396 case LATEX_ENVIRONMENT:
2397 case LATEX_ITEM_ENVIRONMENT:
2398 if (style->latexparam() == "CDATA")
2402 sgmlCloseTag(ofs, depth, false, style->latexname());
2408 for (int i = depth; i >= 0; --i)
2409 sgmlCloseTag(ofs, depth, false, environment_stack[i]);
2413 sgmlCloseTag(ofs, 0, false, top_element);
2417 // How to check for successful close
2419 // we want this to be true outside previews (for insetexternal)
2424 // checks, if newcol chars should be put into this line
2425 // writes newline, if necessary.
2428 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2429 string::size_type newcol)
2432 if (colcount > lyxrc.ascii_linelen) {
2434 colcount = newcol; // assume write after this call
2449 string tag_name(PAR_TAG const & pt) {
2451 case NONE: return "!-- --";
2452 case TT: return "tt";
2453 case SF: return "sf";
2454 case BF: return "bf";
2455 case IT: return "it";
2456 case SL: return "sl";
2457 case EM: return "em";
2464 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2466 p1 = static_cast<PAR_TAG>(p1 | p2);
2471 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2473 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2479 // Handle internal paragraph parsing -- layout already processed.
2480 void Buffer::simpleLinuxDocOnePar(ostream & os,
2482 Paragraph::depth_type /*depth*/)
2484 LyXLayout_ptr const & style = par->layout();
2486 string::size_type char_line_count = 5; // Heuristic choice ;-)
2488 // gets paragraph main font
2491 if (style->labeltype == LABEL_MANUAL) {
2492 font_old = style->labelfont;
2495 font_old = style->font;
2499 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2500 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2501 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2504 stack<PAR_TAG> tag_state;
2505 // parsing main loop
2506 for (pos_type i = 0; i < par->size(); ++i) {
2508 PAR_TAG tag_close = NONE;
2509 list < PAR_TAG > tag_open;
2511 LyXFont const font = par->getFont(params, i);
2513 if (font_old.family() != font.family()) {
2514 switch (family_type) {
2515 case LyXFont::SANS_FAMILY:
2518 case LyXFont::TYPEWRITER_FAMILY:
2525 family_type = font.family();
2527 switch (family_type) {
2528 case LyXFont::SANS_FAMILY:
2529 tag_open.push_back(SF);
2531 case LyXFont::TYPEWRITER_FAMILY:
2532 tag_open.push_back(TT);
2539 if (font_old.series() != font.series()) {
2540 switch (series_type) {
2541 case LyXFont::BOLD_SERIES:
2548 series_type = font.series();
2550 switch (series_type) {
2551 case LyXFont::BOLD_SERIES:
2552 tag_open.push_back(BF);
2560 if (font_old.shape() != font.shape()) {
2561 switch (shape_type) {
2562 case LyXFont::ITALIC_SHAPE:
2565 case LyXFont::SLANTED_SHAPE:
2572 shape_type = font.shape();
2574 switch (shape_type) {
2575 case LyXFont::ITALIC_SHAPE:
2576 tag_open.push_back(IT);
2578 case LyXFont::SLANTED_SHAPE:
2579 tag_open.push_back(SL);
2586 if (font_old.emph() != font.emph()) {
2587 if (font.emph() == LyXFont::ON) {
2588 tag_open.push_back(EM);
2597 list < PAR_TAG > temp;
2598 while (!tag_state.empty() && tag_close) {
2599 PAR_TAG k = tag_state.top();
2601 os << "</" << tag_name(k) << ">";
2608 for(list< PAR_TAG >::const_iterator j = temp.begin();
2609 j != temp.end(); ++j) {
2611 os << "<" << tag_name(*j) << ">";
2614 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2615 j != tag_open.end(); ++j) {
2617 os << "<" << tag_name(*j) << ">";
2620 char c = par->getChar(i);
2622 if (c == Paragraph::META_INSET) {
2623 Inset * inset = par->getInset(i);
2624 inset->linuxdoc(this, os);
2629 if (style->latexparam() == "CDATA") {
2630 // "TeX"-Mode on == > SGML-Mode on.
2637 boost::tie(ws, str) = sgml::escapeChar(c);
2638 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2639 // in freespacing mode, spaces are
2640 // non-breaking characters
2641 if (desc_on) {// if char is ' ' then...
2644 sgmlLineBreak(os, char_line_count, 6);
2648 sgmlLineBreak(os, char_line_count, 1);
2653 char_line_count += str.length();
2659 while (!tag_state.empty()) {
2660 os << "</" << tag_name(tag_state.top()) << ">";
2664 // resets description flag correctly
2666 // <tag> not closed...
2667 sgmlLineBreak(os, char_line_count, 6);
2673 // Print an error message.
2674 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2675 string const & /*message*/) const
2677 #ifdef WITH_WARNINGS
2678 #warning This is wrong we cannot insert an inset like this!!!
2679 // I guess this was Jose' so I explain you more or less why this
2680 // is wrong. This way you insert something in the paragraph and
2681 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2682 // I deactivate this code, have a look at BufferView::insertErrors
2683 // how you should do this correctly! (Jug 20020315)
2686 // insert an error marker in text
2687 InsetError * new_inset = new InsetError(message);
2688 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2694 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2696 ofstream ofs(fname.c_str());
2698 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2702 Paragraph * par = &*(paragraphs.begin());
2704 niceFile = nice; // this will be used by Insetincludes.
2706 LaTeXFeatures features(params);
2711 LyXTextClass const & tclass = params.getLyXTextClass();
2712 string top_element = tclass.latexname();
2715 ofs << "<!DOCTYPE " << top_element
2716 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2718 string preamble = params.preamble;
2719 const string name = nice ? ChangeExtension(filename_, ".sgml")
2721 preamble += features.getIncludedFiles(name);
2722 preamble += features.getLyXSGMLEntities();
2724 if (!preamble.empty()) {
2725 ofs << "\n [ " << preamble << " ]";
2730 string top = top_element;
2732 top += params.language->code();
2735 if (!params.options.empty()) {
2737 top += params.options;
2739 sgmlOpenTag(ofs, 0, false, top);
2741 ofs << "<!-- DocBook file was created by " << lyx_docversion
2742 << "\n See http://www.lyx.org/ for more information -->\n";
2744 vector<string> environment_stack(10);
2745 vector<string> environment_inner(10);
2746 vector<string> command_stack(10);
2748 bool command_flag = false;
2749 Paragraph::depth_type command_depth = 0;
2750 Paragraph::depth_type command_base = 0;
2751 Paragraph::depth_type cmd_depth = 0;
2752 Paragraph::depth_type depth = 0; // paragraph depth
2755 string command_name;
2761 int desc_on = 0; // description mode
2763 LyXLayout_ptr const & style = par->layout();
2765 // environment tag closing
2766 for (; depth > par->params().depth(); --depth) {
2767 if (environment_inner[depth] != "!-- --") {
2768 item_name = "listitem";
2769 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2770 if (environment_inner[depth] == "varlistentry")
2771 sgmlCloseTag(ofs, depth+command_depth, false, environment_inner[depth]);
2773 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2774 environment_stack[depth].erase();
2775 environment_inner[depth].erase();
2778 if (depth == par->params().depth()
2779 && environment_stack[depth] != style->latexname()
2780 && !environment_stack[depth].empty()) {
2781 if (environment_inner[depth] != "!-- --") {
2782 item_name= "listitem";
2783 sgmlCloseTag(ofs, command_depth+depth, false, item_name);
2784 if (environment_inner[depth] == "varlistentry")
2785 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2788 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2790 environment_stack[depth].erase();
2791 environment_inner[depth].erase();
2794 // Write opening SGML tags.
2795 switch (style->latextype) {
2796 case LATEX_PARAGRAPH:
2797 sgmlOpenTag(ofs, depth + command_depth,
2798 false, style->latexname());
2804 _("Error : Wrong depth for "
2805 "LatexType Command.\n"));
2807 command_name = style->latexname();
2809 sgmlparam = style->latexparam();
2810 c_params = split(sgmlparam, c_depth,'|');
2812 cmd_depth = lyx::atoi(c_depth);
2815 if (cmd_depth < command_base) {
2816 for (Paragraph::depth_type j = command_depth;
2817 j >= command_base; --j) {
2818 sgmlCloseTag(ofs, j, false, command_stack[j]);
2821 command_depth = command_base = cmd_depth;
2822 } else if (cmd_depth <= command_depth) {
2823 for (int j = command_depth;
2824 j >= int(cmd_depth); --j) {
2825 sgmlCloseTag(ofs, j, false, command_stack[j]);
2828 command_depth = cmd_depth;
2830 command_depth = cmd_depth;
2832 command_depth = command_base = cmd_depth;
2833 command_flag = true;
2835 if (command_stack.size() == command_depth + 1)
2836 command_stack.push_back(string());
2837 command_stack[command_depth] = command_name;
2839 // treat label as a special case for
2840 // more WYSIWYM handling.
2841 // This is a hack while paragraphs can't have
2842 // attributes, like id in this case.
2843 if (par->isInset(0)) {
2844 Inset * inset = par->getInset(0);
2845 Inset::Code lyx_code = inset->lyxCode();
2846 if (lyx_code == Inset::LABEL_CODE) {
2847 command_name += " id=\"";
2848 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2849 command_name += "\"";
2854 sgmlOpenTag(ofs, depth + command_depth, false, command_name);
2856 item_name = c_params.empty()?"title":c_params;
2857 sgmlOpenTag(ofs, depth + 1 + command_depth, false, item_name);
2860 case LATEX_ENVIRONMENT:
2861 case LATEX_ITEM_ENVIRONMENT:
2862 if (depth < par->params().depth()) {
2863 depth = par->params().depth();
2864 environment_stack[depth].erase();
2867 if (environment_stack[depth] != style->latexname()) {
2868 if (environment_stack.size() == depth + 1) {
2869 environment_stack.push_back("!-- --");
2870 environment_inner.push_back("!-- --");
2872 environment_stack[depth] = style->latexname();
2873 environment_inner[depth] = "!-- --";
2874 sgmlOpenTag(ofs, depth + command_depth, false, environment_stack[depth]);
2876 if (environment_inner[depth] != "!-- --") {
2877 item_name= "listitem";
2878 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2879 if (environment_inner[depth] == "varlistentry")
2880 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2884 if (style->latextype == LATEX_ENVIRONMENT) {
2885 if (!style->latexparam().empty()) {
2886 if (style->latexparam() == "CDATA")
2889 sgmlOpenTag(ofs, depth + command_depth, false, style->latexparam());
2894 desc_on = (style->labeltype == LABEL_MANUAL);
2896 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2897 sgmlOpenTag(ofs, depth + 1 + command_depth,
2898 false, environment_inner[depth]);
2900 item_name = desc_on ? "term" : "para";
2901 sgmlOpenTag(ofs, depth + 1 + command_depth,
2905 sgmlOpenTag(ofs, depth + command_depth,
2906 false, style->latexname());
2910 simpleDocBookOnePar(ofs, par, desc_on,
2911 depth + 1 + command_depth);
2915 // write closing SGML tags
2916 switch (style->latextype) {
2918 end_tag = c_params.empty() ? "title" : c_params;
2919 sgmlCloseTag(ofs, depth + command_depth,
2922 case LATEX_ENVIRONMENT:
2923 if (!style->latexparam().empty()) {
2924 if (style->latexparam() == "CDATA")
2927 sgmlCloseTag(ofs, depth + command_depth, false, style->latexparam());
2930 case LATEX_ITEM_ENVIRONMENT:
2931 if (desc_on == 1) break;
2933 sgmlCloseTag(ofs, depth + 1 + command_depth, false, end_tag);
2935 case LATEX_PARAGRAPH:
2936 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2939 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2945 for (int d = depth; d >= 0; --d) {
2946 if (!environment_stack[depth].empty()) {
2947 if (environment_inner[depth] != "!-- --") {
2948 item_name = "listitem";
2949 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2950 if (environment_inner[depth] == "varlistentry")
2951 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2954 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2958 for (int j = command_depth; j >= 0 ; --j)
2959 if (!command_stack[j].empty()) {
2960 sgmlCloseTag(ofs, j, false, command_stack[j]);
2965 sgmlCloseTag(ofs, 0, false, top_element);
2968 // How to check for successful close
2970 // we want this to be true outside previews (for insetexternal)
2975 void Buffer::simpleDocBookOnePar(ostream & os,
2976 Paragraph * par, int & desc_on,
2977 Paragraph::depth_type depth) const
2979 bool emph_flag = false;
2981 LyXLayout_ptr const & style = par->layout();
2983 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2985 int char_line_count = depth;
2986 //if (!style.free_spacing)
2987 // os << string(depth,' ');
2989 // parsing main loop
2990 for (pos_type i = 0; i < par->size(); ++i) {
2991 LyXFont font = par->getFont(params, i);
2993 // handle <emphasis> tag
2994 if (font_old.emph() != font.emph()) {
2995 if (font.emph() == LyXFont::ON) {
2996 if (style->latexparam() == "CDATA")
2999 if (style->latexparam() == "CDATA")
3003 if (style->latexparam() == "CDATA")
3005 os << "</emphasis>";
3006 if (style->latexparam() == "CDATA")
3013 if (par->isInset(i)) {
3014 Inset * inset = par->getInset(i);
3015 // don't print the inset in position 0 if desc_on == 3 (label)
3016 if (i || desc_on != 3) {
3017 if (style->latexparam() == "CDATA")
3019 inset->docbook(this, os, false);
3020 if (style->latexparam() == "CDATA")
3024 char c = par->getChar(i);
3027 boost::tie(ws, str) = sgml::escapeChar(c);
3029 if (style->pass_thru) {
3031 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3033 } else if (desc_on ==1) {
3035 os << "\n</term><listitem><para>";
3045 if (style->latexparam() == "CDATA")
3047 os << "</emphasis>";
3048 if (style->latexparam() == "CDATA")
3052 // resets description flag correctly
3054 // <term> not closed...
3055 os << "</term>\n<listitem><para> </para>";
3057 if (style->free_spacing)
3062 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3063 // Other flags: -wall -v0 -x
3064 int Buffer::runChktex()
3066 if (!users->text) return 0;
3068 users->owner()->prohibitInput();
3070 // get LaTeX-Filename
3071 string const name = getLatexName();
3072 string path = filePath();
3074 string const org_path = path;
3075 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3079 Path p(path); // path to LaTeX file
3080 users->owner()->message(_("Running chktex..."));
3082 // Remove all error insets
3083 bool const removedErrorInsets = users->removeAutoInsets();
3085 // Generate the LaTeX file if neccessary
3086 makeLaTeXFile(name, org_path, false);
3089 Chktex chktex(lyxrc.chktex_command, name, filePath());
3090 int res = chktex.run(terr); // run chktex
3093 Alert::alert(_("chktex did not work!"),
3094 _("Could not run with file:"), name);
3095 } else if (res > 0) {
3096 // Insert all errors as errors boxes
3097 users->insertErrors(terr);
3100 // if we removed error insets before we ran chktex or if we inserted
3101 // error insets after we ran chktex, this must be run:
3102 if (removedErrorInsets || res) {
3103 #warning repaint needed here, or do you mean update() ?
3107 users->owner()->allowInput();
3113 void Buffer::validate(LaTeXFeatures & features) const
3115 LyXTextClass const & tclass = params.getLyXTextClass();
3117 // AMS Style is at document level
3118 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3119 features.require("amsmath");
3121 for_each(paragraphs.begin(), paragraphs.end(),
3122 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3124 // the bullet shapes are buffer level not paragraph level
3125 // so they are tested here
3126 for (int i = 0; i < 4; ++i) {
3127 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3128 int const font = params.user_defined_bullets[i].getFont();
3130 int const c = params
3131 .user_defined_bullets[i]
3138 features.require("latexsym");
3140 } else if (font == 1) {
3141 features.require("amssymb");
3142 } else if ((font >= 2 && font <= 5)) {
3143 features.require("pifont");
3148 if (lyxerr.debugging(Debug::LATEX)) {
3149 features.showStruct();
3154 // This function should be in Buffer because it's a buffer's property (ale)
3155 string const Buffer::getIncludeonlyList(char delim)
3158 for (inset_iterator it = inset_iterator_begin();
3159 it != inset_iterator_end(); ++it) {
3160 if (it->lyxCode() == Inset::INCLUDE_CODE) {
3161 InsetInclude & inc = static_cast<InsetInclude &>(*it);
3162 if (inc.isIncludeOnly()) {
3165 lst += inc.getRelFileBaseName();
3169 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3174 vector<string> const Buffer::getLabelList() const
3176 /// if this is a child document and the parent is already loaded
3177 /// Use the parent's list instead [ale990407]
3178 if (!params.parentname.empty()
3179 && bufferlist.exists(params.parentname)) {
3180 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3182 return tmp->getLabelList();
3185 vector<string> label_list;
3186 for (inset_iterator it = inset_const_iterator_begin();
3187 it != inset_const_iterator_end(); ++it) {
3188 vector<string> const l = it->getLabelList();
3189 label_list.insert(label_list.end(), l.begin(), l.end());
3195 // This is also a buffer property (ale)
3196 vector<pair<string, string> > const Buffer::getBibkeyList() const
3198 typedef pair<string, string> StringPair;
3199 /// if this is a child document and the parent is already loaded
3200 /// Use the parent's list instead [ale990412]
3201 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3202 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3204 return tmp->getBibkeyList();
3207 vector<StringPair> keys;
3208 ParagraphList::iterator pit = paragraphs.begin();
3209 ParagraphList::iterator pend = paragraphs.end();
3210 for (; pit != pend; ++pit) {
3212 string const key = pit->bibkey->getContents();
3213 string const opt = pit->bibkey->getOptions();
3214 string const ref = pit->asString(this, false);
3215 string const info = opt + "TheBibliographyRef" + ref;
3217 keys.push_back(StringPair(key, info));
3224 // Might be either using bibtex or a child has bibliography
3225 for (inset_iterator it = inset_const_iterator_begin();
3226 it != inset_const_iterator_end(); ++it) {
3227 // Search for Bibtex or Include inset
3228 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3229 vector<StringPair> tmp =
3230 static_cast<InsetBibtex &>(*it).getKeys(this);
3231 keys.insert(keys.end(), tmp.begin(), tmp.end());
3232 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3233 vector<StringPair> const tmp =
3234 static_cast<InsetInclude &>(*it).getKeys();
3235 keys.insert(keys.end(), tmp.begin(), tmp.end());
3243 bool Buffer::isDepClean(string const & name) const
3245 DEPCLEAN * item = dep_clean;
3246 while (item && item->master != name)
3248 if (!item) return true;
3253 void Buffer::markDepClean(string const & name)
3256 dep_clean = new DEPCLEAN;
3257 dep_clean->clean = true;
3258 dep_clean->master = name;
3259 dep_clean->next = 0;
3261 DEPCLEAN * item = dep_clean;
3262 while (item && item->master != name)
3267 item = new DEPCLEAN;
3269 item->master = name;
3276 bool Buffer::dispatch(string const & command, bool * result)
3278 // Split command string into command and argument
3280 string line = ltrim(command);
3281 string const arg = trim(split(line, cmd, ' '));
3283 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3287 bool Buffer::dispatch(int action, string const & argument, bool * result)
3289 bool dispatched = true;
3293 bool const tmp = Exporter::Export(this, argument, false);
3306 void Buffer::resizeInsets(BufferView * bv)
3308 /// then remove all LyXText in text-insets
3309 for_each(paragraphs.begin(), paragraphs.end(),
3310 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3314 void Buffer::redraw()
3316 #warning repaint needed here, or do you mean update() ?
3322 void Buffer::changeLanguage(Language const * from, Language const * to)
3325 ParIterator end = par_iterator_end();
3326 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3327 (*it)->changeLanguage(params, from, to);
3331 bool Buffer::isMultiLingual()
3333 ParIterator end = par_iterator_end();
3334 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3335 if ((*it)->isMultiLingual(params))
3342 void Buffer::inset_iterator::setParagraph()
3344 while (pit != pend) {
3345 it = pit->insetlist.begin();
3346 if (it != pit->insetlist.end())
3353 Inset * Buffer::getInsetFromID(int id_arg) const
3355 for (inset_iterator it = inset_const_iterator_begin();
3356 it != inset_const_iterator_end(); ++it)
3358 if (it->id() == id_arg)
3360 Inset * in = it->getInsetFromID(id_arg);
3368 Paragraph * Buffer::getParFromID(int id) const
3373 ParagraphList::iterator it = paragraphs.begin();
3374 ParagraphList::iterator end = paragraphs.end();
3375 for (; it != end; ++it) {
3376 if (it->id() == id) {
3379 Paragraph * tmp = it->getParFromID(id);
3388 ParIterator Buffer::par_iterator_begin()
3390 return ParIterator(&*(paragraphs.begin()));
3394 ParIterator Buffer::par_iterator_end()
3396 return ParIterator();
3400 void Buffer::addUser(BufferView * u)
3406 void Buffer::delUser(BufferView *)
3412 Language const * Buffer::getLanguage() const
3414 return params.language;
3418 bool Buffer::isClean() const
3424 bool Buffer::isBakClean() const
3430 void Buffer::markClean() const
3436 // if the .lyx file has been saved, we don't need an
3442 void Buffer::markBakClean()
3448 void Buffer::setUnnamed(bool flag)
3454 bool Buffer::isUnnamed()
3460 void Buffer::markDirty()
3467 DEPCLEAN * tmp = dep_clean;
3475 string const & Buffer::fileName() const
3481 string const & Buffer::filePath() const
3487 bool Buffer::isReadonly() const
3493 BufferView * Buffer::getUser() const
3499 void Buffer::setParentName(string const & name)
3501 params.parentname = name;
3505 Buffer::inset_iterator::inset_iterator()
3510 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3517 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3521 if (it == pit->insetlist.end()) {
3530 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3532 inset_iterator tmp = *this;
3538 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3540 return *it.getInset();
3544 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3546 return it.getInset();
3550 Paragraph * Buffer::inset_iterator::getPar()
3556 lyx::pos_type Buffer::inset_iterator::getPos() const
3562 bool operator==(Buffer::inset_iterator const & iter1,
3563 Buffer::inset_iterator const & iter2)
3565 return iter1.pit == iter2.pit
3566 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3570 bool operator!=(Buffer::inset_iterator const & iter1,
3571 Buffer::inset_iterator const & iter2)
3573 return !(iter1 == iter2);