1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * This file is Copyright 1996-2001
12 * ======================================================
18 #pragma implementation
22 #include "bufferlist.h"
23 #include "LyXAction.h"
26 #include "tex-strings.h"
28 #include "bufferview_funcs.h"
34 #include "LaTeXFeatures.h"
41 #include "converter.h"
42 #include "BufferView.h"
43 #include "ParagraphParameters.h"
44 #include "iterators.h"
45 #include "lyxtextclasslist.h"
47 #include "paragraph_funcs.h"
49 #include "frontends/LyXView.h"
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
54 #include "insets/inset.h"
55 #include "insets/inseterror.h"
56 #include "insets/insetlabel.h"
57 #include "insets/insetref.h"
58 #include "insets/inseturl.h"
59 #include "insets/insetnote.h"
60 #include "insets/insetquotes.h"
61 #include "insets/insetlatexaccent.h"
62 #include "insets/insetbib.h"
63 #include "insets/insetcite.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetindex.h"
66 #include "insets/insetinclude.h"
67 #include "insets/insettoc.h"
68 #include "insets/insetparent.h"
69 #include "insets/insetspecialchar.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetoptarg.h"
76 #include "insets/insetminipage.h"
77 #include "insets/insetfloat.h"
78 #include "insets/insetwrap.h"
79 #include "insets/insettabular.h"
81 #include "insets/insettheorem.h"
82 #include "insets/insetlist.h"
84 #include "insets/insetcaption.h"
85 #include "insets/insetfloatlist.h"
87 #include "frontends/Dialogs.h"
88 #include "frontends/Alert.h"
90 #include "graphics/Previews.h"
92 #include "support/textutils.h"
93 #include "support/filetools.h"
94 #include "support/path.h"
95 #include "support/os.h"
96 #include "support/lyxlib.h"
97 #include "support/FileInfo.h"
98 #include "support/lyxmanip.h"
99 #include "support/lyxalgo.h" // for lyx::count
101 #include <boost/bind.hpp>
102 #include <boost/tuple/tuple.hpp>
114 #include <sys/types.h>
121 #ifndef CXX_GLOBAL_CSTD
133 using std::make_pair;
143 using lyx::textclass_type;
145 // all these externs should eventually be removed.
146 extern BufferList bufferlist;
150 const int LYX_FORMAT = 221;
154 Buffer::Buffer(string const & file, bool ronly)
155 : niceFile(true), lyx_clean(true), bak_clean(true),
156 unnamed(false), dep_clean(0), read_only(ronly),
157 filename_(file), users(0)
159 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
160 filepath_ = OnlyPath(file);
162 if (read_only || lyxrc.use_tempdir) {
163 tmppath = CreateBufferTmpDir();
172 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
173 // here the buffer should take care that it is
174 // saved properly, before it goes into the void.
176 // make sure that views using this buffer
181 if (!tmppath.empty()) {
182 DestroyBufferTmpDir(tmppath);
187 // Remove any previewed LaTeX snippets assocoated with this buffer.
188 grfx::Previews::get().removeLoader(this);
192 string const Buffer::getLatexName(bool no_path) const
194 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
196 return OnlyFilename(name);
202 pair<Buffer::LogType, string> const Buffer::getLogName() const
204 string const filename = getLatexName(false);
206 if (filename.empty())
207 return make_pair(Buffer::latexlog, string());
209 string path = OnlyPath(filename);
211 if (lyxrc.use_tempdir || !IsDirWriteable(path))
214 string const fname = AddName(path,
215 OnlyFilename(ChangeExtension(filename,
218 AddName(path, OnlyFilename(
219 ChangeExtension(filename,
220 formats.extension("literate") + ".out")));
222 // If no Latex log or Build log is newer, show Build log
224 FileInfo const f_fi(fname);
225 FileInfo const b_fi(bname);
228 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
229 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
230 return make_pair(Buffer::buildlog, bname);
232 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
233 return make_pair(Buffer::latexlog, fname);
237 void Buffer::setReadonly(bool flag)
239 if (read_only != flag) {
242 users->owner()->getDialogs().updateBufferDependent(false);
247 /// Update window titles of all users
248 // Should work on a list
249 void Buffer::updateTitles() const
252 users->owner()->updateWindowTitle();
256 /// Reset autosave timer of all users
257 // Should work on a list
258 void Buffer::resetAutosaveTimers() const
261 users->owner()->resetAutosaveTimer();
265 void Buffer::setFileName(string const & newfile)
267 filename_ = MakeAbsPath(newfile);
268 filepath_ = OnlyPath(filename_);
269 setReadonly(IsFileWriteable(filename_) == 0);
274 // We'll remove this later. (Lgb)
277 string last_inset_read;
280 #warning And _why_ is this here? (Lgb)
288 // candidate for move to BufferView
289 // (at least some parts in the beginning of the func)
292 // changed to be public and have one parameter
293 // if par = 0 normal behavior
294 // else insert behavior
295 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
296 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
302 Paragraph::depth_type depth = 0;
303 bool the_end_read = false;
305 Paragraph * first_par = 0;
306 LyXFont font(LyXFont::ALL_INHERIT, params.language);
309 if (file_format < 216 && params.language->lang() == "hebrew")
310 font.setLanguage(default_language);
315 par->layout(params.getLyXTextClass().defaultLayout());
317 // We are inserting into an existing document
318 users->text->breakParagraph(users);
319 first_par = users->text->ownerParagraph();
322 // We don't want to adopt the parameters from the
323 // document we insert, so we skip until the text begins:
326 string const pretoken = lex.getString();
327 if (pretoken == "\\layout") {
328 lex.pushToken(pretoken);
336 string const token = lex.getString();
338 if (token.empty()) continue;
340 lyxerr[Debug::PARSER] << "Handling token: `"
341 << token << "'" << endl;
344 parseSingleLyXformat2Token(lex, par, first_par,
352 paragraphs.set(first_par);
354 if (unknown_layouts > 0) {
355 string s = _("Couldn't set the layout for ");
356 if (unknown_layouts == 1) {
357 s += _("one paragraph");
359 s += tostr(unknown_layouts);
360 s += _(" paragraphs");
362 Alert::alert(_("Textclass Loading Error!"), s,
363 _("When reading " + fileName()));
366 if (unknown_tokens > 0) {
367 string s = _("Encountered ");
368 if (unknown_tokens == 1) {
369 s += _("one unknown token");
371 s += tostr(unknown_tokens);
372 s += _(" unknown tokens");
374 Alert::alert(_("Textclass Loading Error!"), s,
375 _("When reading " + fileName()));
383 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
384 Paragraph *& first_par,
385 string const & token, int & pos,
386 Paragraph::depth_type & depth,
390 bool the_end_read = false;
392 // The order of the tags tested may seem unnatural, but this
393 // has been done in order to reduce the number of string
394 // comparisons needed to recognize a given token. This leads
395 // on large documents like UserGuide to a reduction of a
397 if (token[0] != '\\') {
398 for (string::const_iterator cit = token.begin();
399 cit != token.end(); ++cit) {
400 par->insertChar(pos, (*cit), font);
403 } else if (token == "\\layout") {
404 // reset the font as we start a new layout and if the font is
405 // not ALL_INHERIT,document_language then it will be set to the
406 // right values after this tag (Jug 20020420)
407 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
410 if (file_format < 216 && params.language->lang() == "hebrew")
411 font.setLanguage(default_language);
415 string layoutname = lex.getString();
417 LyXTextClass const & tclass = params.getLyXTextClass();
419 if (layoutname.empty()) {
420 layoutname = tclass.defaultLayoutName();
422 bool hasLayout = tclass.hasLayout(layoutname);
424 lyxerr << "Layout '" << layoutname << "' does not"
425 << " exist in textclass '" << tclass.name()
427 lyxerr << "Trying to use default layout instead."
429 layoutname = tclass.defaultLayoutName();
433 // The is the compability reading of layout caption.
434 // It can be removed in LyX version 1.3.0. (Lgb)
435 if (compare_ascii_no_case(layoutname, "caption") == 0) {
436 // We expect that the par we are now working on is
437 // really inside a InsetText inside a InsetFloat.
438 // We also know that captions can only be
439 // one paragraph. (Lgb)
441 // We should now read until the next "\layout"
443 // This is probably not good enough, what if the
444 // caption is the last par in the document (Lgb)
445 istream & ist = lex.getStream();
451 if (prefixIs(line, "\\layout")) {
455 if (prefixIs(line, "\\begin_inset"))
457 if (prefixIs(line, "\\end_inset")) {
468 // Now we should have the whole layout in ss
469 // we should now be able to give this to the
471 ss << "\\end_inset\n";
473 // This seems like a bug in stringstream.
474 // We really should be able to use ss
476 istringstream is(ss.str());
478 tmplex.setStream(is);
479 Inset * inset = new InsetCaption;
480 inset->Read(this, tmplex);
481 par->InsertInset(pos, inset, font);
488 par = new Paragraph(par);
489 par->layout(params.getLyXTextClass().defaultLayout());
492 par->layout(params.getLyXTextClass()[layoutname]);
493 // Test whether the layout is obsolete.
494 LyXLayout_ptr const & layout = par->layout();
495 if (!layout->obsoleted_by().empty())
496 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
497 par->params().depth(depth);
502 } else if (token == "\\end_inset") {
503 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
504 << "Last inset read was: " << last_inset_read
506 // Simply ignore this. The insets do not have
508 // But insets should read it, it is a part of
509 // the inset isn't it? Lgb.
510 } else if (token == "\\begin_inset") {
511 readInset(lex, par, pos, font);
512 } else if (token == "\\family") {
514 font.setLyXFamily(lex.getString());
515 } else if (token == "\\series") {
517 font.setLyXSeries(lex.getString());
518 } else if (token == "\\shape") {
520 font.setLyXShape(lex.getString());
521 } else if (token == "\\size") {
523 font.setLyXSize(lex.getString());
524 } else if (token == "\\lang") {
526 string const tok = lex.getString();
527 Language const * lang = languages.getLanguage(tok);
529 font.setLanguage(lang);
531 font.setLanguage(params.language);
532 lex.printError("Unknown language `$$Token'");
534 } else if (token == "\\numeric") {
536 font.setNumber(font.setLyXMisc(lex.getString()));
537 } else if (token == "\\emph") {
539 font.setEmph(font.setLyXMisc(lex.getString()));
540 } else if (token == "\\bar") {
542 string const tok = lex.getString();
543 // This is dirty, but gone with LyX3. (Asger)
545 font.setUnderbar(LyXFont::ON);
546 else if (tok == "no")
547 font.setUnderbar(LyXFont::OFF);
548 else if (tok == "default")
549 font.setUnderbar(LyXFont::INHERIT);
551 lex.printError("Unknown bar font flag "
553 } else if (token == "\\noun") {
555 font.setNoun(font.setLyXMisc(lex.getString()));
556 } else if (token == "\\color") {
558 font.setLyXColor(lex.getString());
559 } else if (token == "\\SpecialChar") {
560 LyXLayout_ptr const & layout = par->layout();
562 // Insets don't make sense in a free-spacing context! ---Kayvan
563 if (layout->free_spacing || par->isFreeSpacing()) {
566 string next_token = lex.getString();
567 if (next_token == "\\-") {
568 par->insertChar(pos, '-', font);
569 } else if (next_token == "~") {
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 == "\\bibitem") { // ale970302
919 InsetCommandParams p("bibitem", "dummy");
920 par->bibkey = new InsetBibKey(p);
922 par->bibkey->read(this, lex);
923 } else if (token == "\\the_end") {
926 // This should be insurance for the future: (Asger)
929 string const s = _("Unknown token: ") + token
930 + " " + lex.text() + "\n";
931 // we can do this here this way because we're actually reading
932 // the buffer and don't care about LyXText right now.
933 InsetError * new_inset = new InsetError(s);
934 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
942 // needed to insert the selection
943 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
944 LyXFont const & fn,string const & str) const
946 LyXLayout_ptr const & layout = par->layout();
950 par->checkInsertChar(font);
951 // insert the string, don't insert doublespace
952 bool space_inserted = true;
953 bool autobreakrows = !par->inInset() ||
954 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
955 for(string::const_iterator cit = str.begin();
956 cit != str.end(); ++cit) {
958 if (autobreakrows && (!par->empty() || layout->keepempty)) {
959 breakParagraph(params, par, pos,
960 layout->isEnvironment());
963 space_inserted = true;
967 // do not insert consecutive spaces if !free_spacing
968 } else if ((*cit == ' ' || *cit == '\t') &&
969 space_inserted && !layout->free_spacing &&
970 !par->isFreeSpacing())
973 } else if (*cit == '\t') {
974 if (!layout->free_spacing && !par->isFreeSpacing()) {
975 // tabs are like spaces here
976 par->insertChar(pos, ' ', font);
978 space_inserted = true;
980 const pos_type nb = 8 - pos % 8;
981 for (pos_type a = 0; a < nb ; ++a) {
982 par->insertChar(pos, ' ', font);
985 space_inserted = true;
987 } else if (!IsPrintable(*cit)) {
988 // Ignore unprintables
991 // just insert the character
992 par->insertChar(pos, *cit, font);
994 space_inserted = (*cit == ' ');
1001 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1002 int & pos, LyXFont & font)
1004 // consistency check
1005 if (lex.getString() != "\\begin_inset") {
1006 lyxerr << "Buffer::readInset: Consistency check failed."
1013 string const tmptok = lex.getString();
1014 last_inset_read = tmptok;
1016 // test the different insets
1017 if (tmptok == "LatexCommand") {
1018 InsetCommandParams inscmd;
1021 string const cmdName = inscmd.getCmdName();
1023 // This strange command allows LyX to recognize "natbib" style
1024 // citations: citet, citep, Citet etc.
1025 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1026 inset = new InsetCitation(inscmd);
1027 } else if (cmdName == "bibitem") {
1028 lex.printError("Wrong place for bibitem");
1029 inset = new InsetBibKey(inscmd);
1030 } else if (cmdName == "BibTeX") {
1031 inset = new InsetBibtex(inscmd);
1032 } else if (cmdName == "index") {
1033 inset = new InsetIndex(inscmd);
1034 } else if (cmdName == "include") {
1035 inset = new InsetInclude(inscmd, *this);
1036 } else if (cmdName == "label") {
1037 inset = new InsetLabel(inscmd);
1038 } else if (cmdName == "url"
1039 || cmdName == "htmlurl") {
1040 inset = new InsetUrl(inscmd);
1041 } else if (cmdName == "ref"
1042 || cmdName == "pageref"
1043 || cmdName == "vref"
1044 || cmdName == "vpageref"
1045 || cmdName == "prettyref") {
1046 if (!inscmd.getOptions().empty()
1047 || !inscmd.getContents().empty()) {
1048 inset = new InsetRef(inscmd, *this);
1050 } else if (cmdName == "tableofcontents") {
1051 inset = new InsetTOC(inscmd);
1052 } else if (cmdName == "listofalgorithms") {
1053 inset = new InsetFloatList("algorithm");
1054 } else if (cmdName == "listoffigures") {
1055 inset = new InsetFloatList("figure");
1056 } else if (cmdName == "listoftables") {
1057 inset = new InsetFloatList("table");
1058 } else if (cmdName == "printindex") {
1059 inset = new InsetPrintIndex(inscmd);
1060 } else if (cmdName == "lyxparent") {
1061 inset = new InsetParent(inscmd, *this);
1064 bool alreadyread = false;
1065 if (tmptok == "Quotes") {
1066 inset = new InsetQuotes;
1067 } else if (tmptok == "External") {
1068 inset = new InsetExternal;
1069 } else if (tmptok == "FormulaMacro") {
1070 inset = new InsetFormulaMacro;
1071 } else if (tmptok == "Formula") {
1072 inset = new InsetFormula;
1073 } else if (tmptok == "Figure") { // Backward compatibility
1074 // inset = new InsetFig(100, 100, *this);
1075 inset = new InsetGraphics;
1076 } else if (tmptok == "Graphics") {
1077 inset = new InsetGraphics;
1078 } else if (tmptok == "Info") {// backwards compatibility
1079 inset = new InsetNote(this,
1080 lex.getLongString("\\end_inset"),
1083 } else if (tmptok == "Note") {
1084 inset = new InsetNote(params);
1085 } else if (tmptok == "Include") {
1086 InsetCommandParams p("Include");
1087 inset = new InsetInclude(p, *this);
1088 } else if (tmptok == "ERT") {
1089 inset = new InsetERT(params);
1090 } else if (tmptok == "Tabular") {
1091 inset = new InsetTabular(*this);
1092 } else if (tmptok == "Text") {
1093 inset = new InsetText(params);
1094 } else if (tmptok == "Foot") {
1095 inset = new InsetFoot(params);
1096 } else if (tmptok == "Marginal") {
1097 inset = new InsetMarginal(params);
1098 } else if (tmptok == "OptArg") {
1099 inset = new InsetOptArg(params);
1100 } else if (tmptok == "Minipage") {
1101 inset = new InsetMinipage(params);
1102 } else if (tmptok == "Float") {
1104 string tmptok = lex.getString();
1105 inset = new InsetFloat(params, tmptok);
1106 } else if (tmptok == "Wrap") {
1108 string tmptok = lex.getString();
1109 inset = new InsetWrap(params, tmptok);
1111 } else if (tmptok == "List") {
1112 inset = new InsetList;
1113 } else if (tmptok == "Theorem") {
1114 inset = new InsetList;
1116 } else if (tmptok == "Caption") {
1117 inset = new InsetCaption(params);
1118 } else if (tmptok == "FloatList") {
1119 inset = new InsetFloatList;
1122 if (inset && !alreadyread) inset->read(this, lex);
1126 par->insertInset(pos, inset, font);
1132 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
1136 string const token(lex.getString());
1137 if (token == "\\lyxformat") { // the first token _must_ be...
1139 string tmp_format = lex.getString();
1140 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1141 // if present remove ".," from string.
1142 string::size_type dot = tmp_format.find_first_of(".,");
1143 //lyxerr << " dot found at " << dot << endl;
1144 if (dot != string::npos)
1145 tmp_format.erase(dot, 1);
1146 file_format = strToInt(tmp_format);
1147 //lyxerr << "format: " << file_format << endl;
1148 if (file_format == LYX_FORMAT) {
1150 } else if (file_format > LYX_FORMAT) {
1152 Alert::alert(_("Warning!"),
1153 _("The file was created with a newer version of"
1154 "LyX. This is likely to cause problems."));
1156 } else if (file_format < LYX_FORMAT) {
1158 if (file_format < 200) {
1159 Alert::alert(_("ERROR!"),
1160 _("Old LyX file format found. "
1161 "Use LyX 0.10.x to read this!"));
1163 } else if (!filename.empty()) {
1165 LibFileSearch("lyx2lyx", "lyx2lyx");
1166 if (command.empty()) {
1167 Alert::alert(_("ERROR!"),
1168 _("Can't find conversion script."));
1172 +tostr(LYX_FORMAT)+" "
1173 + QuoteName(filename);
1174 lyxerr[Debug::INFO] << "Running '"
1175 << command << "'" << endl;
1176 cmd_ret const ret = RunCommand(command);
1178 Alert::alert(_("ERROR!"),
1179 _("An error occured while "
1180 "running the conversion script."));
1183 istringstream is(ret.second);
1184 LyXLex tmplex(0, 0);
1185 tmplex.setStream(is);
1186 return readFile(tmplex, string());
1188 // This code is reached if lyx2lyx failed (for
1189 // some reason) to change the file format of
1195 bool the_end = readLyXformat2(lex, par);
1196 params.setPaperStuff();
1199 // the_end was added in 213
1200 if (file_format < 213)
1205 Alert::alert(_("Warning!"),
1206 _("Reading of document is not complete"),
1207 _("Maybe the document is truncated"));
1210 } else { // "\\lyxformat" not found
1211 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1214 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1219 // Should probably be moved to somewhere else: BufferView? LyXView?
1220 bool Buffer::save() const
1222 // We don't need autosaves in the immediate future. (Asger)
1223 resetAutosaveTimers();
1227 if (lyxrc.make_backup) {
1228 s = fileName() + '~';
1229 if (!lyxrc.backupdir_path.empty())
1230 s = AddName(lyxrc.backupdir_path,
1231 subst(os::slashify_path(s),'/','!'));
1233 // Rename is the wrong way of making a backup,
1234 // this is the correct way.
1235 /* truss cp fil fil2:
1236 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1237 stat("LyXVC.lyx", 0xEFFFF688) = 0
1238 open("LyXVC.lyx", O_RDONLY) = 3
1239 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1240 fstat(4, 0xEFFFF508) = 0
1241 fstat(3, 0xEFFFF508) = 0
1242 read(3, " # T h i s f i l e w".., 8192) = 5579
1243 write(4, " # T h i s f i l e w".., 5579) = 5579
1244 read(3, 0xEFFFD4A0, 8192) = 0
1247 chmod("LyXVC3.lyx", 0100644) = 0
1248 lseek(0, 0, SEEK_CUR) = 46440
1252 // Should probably have some more error checking here.
1253 // Doing it this way, also makes the inodes stay the same.
1254 // This is still not a very good solution, in particular we
1255 // might loose the owner of the backup.
1256 FileInfo finfo(fileName());
1257 if (finfo.exist()) {
1258 mode_t fmode = finfo.getMode();
1259 struct utimbuf times = {
1260 finfo.getAccessTime(),
1261 finfo.getModificationTime() };
1263 ifstream ifs(fileName().c_str());
1264 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1269 ::chmod(s.c_str(), fmode);
1271 if (::utime(s.c_str(), ×)) {
1272 lyxerr << "utime error." << endl;
1275 lyxerr << "LyX was not able to make "
1276 "backup copy. Beware." << endl;
1281 if (writeFile(fileName())) {
1283 removeAutosaveFile(fileName());
1285 // Saving failed, so backup is not backup
1286 if (lyxrc.make_backup) {
1287 lyx::rename(s, fileName());
1295 bool Buffer::writeFile(string const & fname) const
1297 if (read_only && (fname == fileName())) {
1301 FileInfo finfo(fname);
1302 if (finfo.exist() && !finfo.writable()) {
1306 ofstream ofs(fname.c_str());
1312 // Use the standard "C" locale for file output.
1313 ofs.imbue(std::locale::classic());
1316 // The top of the file should not be written by params.
1318 // write out a comment in the top of the file
1319 ofs << '#' << lyx_docversion
1320 << " created this file. For more info see http://www.lyx.org/\n"
1321 << "\\lyxformat " << LYX_FORMAT << "\n";
1323 // now write out the buffer paramters.
1324 params.writeFile(ofs);
1326 Paragraph::depth_type depth = 0;
1328 // this will write out all the paragraphs
1329 // using recursive descent.
1330 ParagraphList::iterator pit = paragraphs.begin();
1331 ParagraphList::iterator pend = paragraphs.end();
1332 for (; pit != pend; ++pit)
1333 pit->write(this, ofs, params, depth);
1335 // Write marker that shows file is complete
1336 ofs << "\n\\the_end" << endl;
1340 // how to check if close went ok?
1341 // Following is an attempt... (BE 20001011)
1343 // good() returns false if any error occured, including some
1344 // formatting error.
1345 // bad() returns true if something bad happened in the buffer,
1346 // which should include file system full errors.
1353 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1355 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1367 pair<int, string> const addDepth(int depth, int ldepth)
1371 d += (ldepth - depth) * 2;
1372 return make_pair(d, string(d, ' '));
1378 string const Buffer::asciiParagraph(Paragraph const & par,
1379 unsigned int linelen,
1380 bool noparbreak) const
1382 ostringstream buffer;
1383 Paragraph::depth_type depth = 0;
1385 Paragraph::depth_type ltype_depth = 0;
1386 bool ref_printed = false;
1387 // if (!par->previous()) {
1389 // begins or ends a deeper area ?
1390 if (depth != par->params().depth()) {
1391 if (par->params().depth() > depth) {
1392 while (par->params().depth() > depth) {
1396 while (par->params().depth() < depth) {
1402 depth = par.params().depth();
1405 // First write the layout
1406 string const & tmp = par.layout()->name();
1407 if (compare_no_case(tmp, "itemize") == 0) {
1409 ltype_depth = depth + 1;
1410 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1412 ltype_depth = depth + 1;
1413 } else if (contains(ascii_lowercase(tmp), "ection")) {
1415 ltype_depth = depth + 1;
1416 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1418 ltype_depth = depth + 1;
1419 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1421 ltype_depth = depth + 1;
1422 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1425 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1433 /* maybe some vertical spaces */
1435 /* the labelwidthstring used in lists */
1439 /* some pagebreaks? */
1443 /* what about the alignment */
1445 // lyxerr << "Should this ever happen?" << endl;
1448 // linelen <= 0 is special and means we don't have paragraph breaks
1450 string::size_type currlinelen = 0;
1456 buffer << string(depth * 2, ' ');
1457 currlinelen += depth * 2;
1460 // we should probably change to the paragraph language in the
1461 // gettext here (if possible) so that strings are outputted in
1462 // the correct language! (20012712 Jug)
1466 case 4: // (Sub)Paragraph
1467 case 5: // Description
1471 buffer << _("Abstract") << "\n\n";
1474 string const abst = _("Abstract: ");
1476 currlinelen += abst.length();
1479 case 7: // Bibliography
1482 buffer << _("References") << "\n\n";
1485 string const refs = _("References: ");
1487 currlinelen += refs.length();
1495 string const parlab = par.params().labelString();
1496 buffer << parlab << " ";
1497 currlinelen += parlab.length() + 1;
1505 pair<int, string> p = addDepth(depth, ltype_depth);
1507 currlinelen += p.first;
1510 // this is to change the linebreak to do it by word a bit more
1511 // intelligent hopefully! (only in the case where we have a
1512 // max linelenght!) (Jug)
1516 for (pos_type i = 0; i < par.size(); ++i) {
1517 char c = par.getUChar(params, i);
1519 case Paragraph::META_INSET:
1521 Inset const * inset = par.getInset(i);
1525 currlinelen += word.length();
1528 if (inset->ascii(this, buffer, linelen)) {
1529 // to be sure it breaks paragraph
1530 currlinelen += linelen;
1536 case Paragraph::META_NEWLINE:
1538 buffer << word << "\n";
1541 pair<int, string> p = addDepth(depth,
1544 currlinelen = p.first;
1548 case Paragraph::META_HFILL:
1549 buffer << word << "\t";
1550 currlinelen += word.length() + 1;
1557 currlinelen + word.length() > linelen - 10) {
1559 pair<int, string> p =
1560 addDepth(depth, ltype_depth);
1562 currlinelen = p.first;
1565 buffer << word << ' ';
1566 currlinelen += word.length() + 1;
1573 lyxerr[Debug::INFO] <<
1574 "writeAsciiFile: NULL char in structure." << endl;
1576 if ((linelen > 0) &&
1577 (currlinelen + word.length()) > linelen)
1581 pair<int, string> p =
1582 addDepth(depth, ltype_depth);
1584 currlinelen = p.first;
1591 return buffer.str().c_str();
1595 void Buffer::writeFileAscii(string const & fname, int linelen)
1597 ofstream ofs(fname.c_str());
1599 Alert::err_alert(_("Error: Cannot write file:"), fname);
1602 writeFileAscii(ofs, linelen);
1606 void Buffer::writeFileAscii(ostream & os, int linelen)
1608 ParagraphList::iterator beg = paragraphs.begin();
1609 ParagraphList::iterator end = paragraphs.end();
1610 ParagraphList::iterator it = beg;
1611 for (; it != end; ++it) {
1612 os << asciiParagraph(*it, linelen, it == beg);
1621 void Buffer::makeLaTeXFile(string const & fname,
1622 string const & original_path,
1623 bool nice, bool only_body, bool only_preamble)
1625 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1627 ofstream ofs(fname.c_str());
1629 Alert::err_alert(_("Error: Cannot open file: "), fname);
1633 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1637 lyxerr << "File was not closed properly." << endl;
1642 void Buffer::makeLaTeXFile(ostream & os,
1643 string const & original_path,
1644 bool nice, bool only_body, bool only_preamble)
1646 niceFile = nice; // this will be used by Insetincludes.
1648 // validate the buffer.
1649 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1650 LaTeXFeatures features(params);
1652 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1655 // The starting paragraph of the coming rows is the
1656 // first paragraph of the document. (Asger)
1657 texrow.start(&*(paragraphs.begin()), 0);
1659 if (!only_body && nice) {
1660 os << "%% " << lyx_docversion << " created this file. "
1661 "For more info, see http://www.lyx.org/.\n"
1662 "%% Do not edit unless you really know what "
1667 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1668 // There are a few differences between nice LaTeX and usual files:
1669 // usual is \batchmode and has a
1670 // special input@path to allow the including of figures
1671 // with either \input or \includegraphics (what figinsets do).
1672 // input@path is set when the actual parameter
1673 // original_path is set. This is done for usual tex-file, but not
1674 // for nice-latex-file. (Matthias 250696)
1677 // code for usual, NOT nice-latex-file
1678 os << "\\batchmode\n"; // changed
1679 // from \nonstopmode
1682 if (!original_path.empty()) {
1683 string inputpath = os::external_path(original_path);
1684 subst(inputpath, "~", "\\string~");
1685 os << "\\makeatletter\n"
1686 << "\\def\\input@path{{"
1687 << inputpath << "/}}\n"
1688 << "\\makeatother\n";
1694 os << "\\documentclass";
1696 LyXTextClass const & tclass = params.getLyXTextClass();
1698 ostringstream options; // the document class options.
1700 if (tokenPos(tclass.opt_fontsize(),
1701 '|', params.fontsize) >= 0) {
1702 // only write if existing in list (and not default)
1703 options << params.fontsize << "pt,";
1707 if (!params.use_geometry &&
1708 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1709 switch (params.papersize) {
1710 case BufferParams::PAPER_A4PAPER:
1711 options << "a4paper,";
1713 case BufferParams::PAPER_USLETTER:
1714 options << "letterpaper,";
1716 case BufferParams::PAPER_A5PAPER:
1717 options << "a5paper,";
1719 case BufferParams::PAPER_B5PAPER:
1720 options << "b5paper,";
1722 case BufferParams::PAPER_EXECUTIVEPAPER:
1723 options << "executivepaper,";
1725 case BufferParams::PAPER_LEGALPAPER:
1726 options << "legalpaper,";
1732 if (params.sides != tclass.sides()) {
1733 switch (params.sides) {
1734 case LyXTextClass::OneSide:
1735 options << "oneside,";
1737 case LyXTextClass::TwoSides:
1738 options << "twoside,";
1744 if (params.columns != tclass.columns()) {
1745 if (params.columns == 2)
1746 options << "twocolumn,";
1748 options << "onecolumn,";
1751 if (!params.use_geometry
1752 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1753 options << "landscape,";
1755 // language should be a parameter to \documentclass
1757 ostringstream language_options;
1758 if (params.language->babel() == "hebrew"
1759 && default_language->babel() != "hebrew")
1760 // This seems necessary
1761 features.useLanguage(default_language);
1763 if (lyxrc.language_use_babel ||
1764 params.language->lang() != lyxrc.default_language ||
1765 features.hasLanguages()) {
1767 language_options << features.getLanguages();
1768 language_options << params.language->babel();
1769 if (lyxrc.language_global_options)
1770 options << language_options.str() << ',';
1773 // the user-defined options
1774 if (!params.options.empty()) {
1775 options << params.options << ',';
1778 string strOptions(options.str().c_str());
1779 if (!strOptions.empty()) {
1780 strOptions = rtrim(strOptions, ",");
1781 os << '[' << strOptions << ']';
1784 os << '{' << tclass.latexname() << "}\n";
1786 // end of \documentclass defs
1788 // font selection must be done before loading fontenc.sty
1789 // The ae package is not needed when using OT1 font encoding.
1790 if (params.fonts != "default" &&
1791 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1792 os << "\\usepackage{" << params.fonts << "}\n";
1794 if (params.fonts == "ae") {
1795 os << "\\usepackage{aecompl}\n";
1799 // this one is not per buffer
1800 if (lyxrc.fontenc != "default") {
1801 os << "\\usepackage[" << lyxrc.fontenc
1806 if (params.inputenc == "auto") {
1807 string const doc_encoding =
1808 params.language->encoding()->LatexName();
1810 // Create a list with all the input encodings used
1812 set<string> encodings = features.getEncodingSet(doc_encoding);
1814 os << "\\usepackage[";
1815 std::copy(encodings.begin(), encodings.end(),
1816 std::ostream_iterator<string>(os, ","));
1817 os << doc_encoding << "]{inputenc}\n";
1819 } else if (params.inputenc != "default") {
1820 os << "\\usepackage[" << params.inputenc
1825 // At the very beginning the text parameters.
1826 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1827 switch (params.paperpackage) {
1828 case BufferParams::PACKAGE_A4:
1829 os << "\\usepackage{a4}\n";
1832 case BufferParams::PACKAGE_A4WIDE:
1833 os << "\\usepackage{a4wide}\n";
1836 case BufferParams::PACKAGE_WIDEMARGINSA4:
1837 os << "\\usepackage[widemargins]{a4}\n";
1842 if (params.use_geometry) {
1843 os << "\\usepackage{geometry}\n";
1845 os << "\\geometry{verbose";
1846 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1848 switch (params.papersize2) {
1849 case BufferParams::VM_PAPER_CUSTOM:
1850 if (!params.paperwidth.empty())
1851 os << ",paperwidth="
1852 << params.paperwidth;
1853 if (!params.paperheight.empty())
1854 os << ",paperheight="
1855 << params.paperheight;
1857 case BufferParams::VM_PAPER_USLETTER:
1858 os << ",letterpaper";
1860 case BufferParams::VM_PAPER_USLEGAL:
1861 os << ",legalpaper";
1863 case BufferParams::VM_PAPER_USEXECUTIVE:
1864 os << ",executivepaper";
1866 case BufferParams::VM_PAPER_A3:
1869 case BufferParams::VM_PAPER_A4:
1872 case BufferParams::VM_PAPER_A5:
1875 case BufferParams::VM_PAPER_B3:
1878 case BufferParams::VM_PAPER_B4:
1881 case BufferParams::VM_PAPER_B5:
1885 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1886 switch (lyxrc.default_papersize) {
1887 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1888 case BufferParams::PAPER_USLETTER:
1889 os << ",letterpaper";
1891 case BufferParams::PAPER_LEGALPAPER:
1892 os << ",legalpaper";
1894 case BufferParams::PAPER_EXECUTIVEPAPER:
1895 os << ",executivepaper";
1897 case BufferParams::PAPER_A3PAPER:
1900 case BufferParams::PAPER_A4PAPER:
1903 case BufferParams::PAPER_A5PAPER:
1906 case BufferParams::PAPER_B5PAPER:
1911 if (!params.topmargin.empty())
1912 os << ",tmargin=" << params.topmargin;
1913 if (!params.bottommargin.empty())
1914 os << ",bmargin=" << params.bottommargin;
1915 if (!params.leftmargin.empty())
1916 os << ",lmargin=" << params.leftmargin;
1917 if (!params.rightmargin.empty())
1918 os << ",rmargin=" << params.rightmargin;
1919 if (!params.headheight.empty())
1920 os << ",headheight=" << params.headheight;
1921 if (!params.headsep.empty())
1922 os << ",headsep=" << params.headsep;
1923 if (!params.footskip.empty())
1924 os << ",footskip=" << params.footskip;
1929 if (tokenPos(tclass.opt_pagestyle(),
1930 '|', params.pagestyle) >= 0) {
1931 if (params.pagestyle == "fancy") {
1932 os << "\\usepackage{fancyhdr}\n";
1935 os << "\\pagestyle{" << params.pagestyle << "}\n";
1939 if (params.secnumdepth != tclass.secnumdepth()) {
1940 os << "\\setcounter{secnumdepth}{"
1941 << params.secnumdepth
1945 if (params.tocdepth != tclass.tocdepth()) {
1946 os << "\\setcounter{tocdepth}{"
1952 if (params.paragraph_separation) {
1953 switch (params.defskip.kind()) {
1954 case VSpace::SMALLSKIP:
1955 os << "\\setlength\\parskip{\\smallskipamount}\n";
1957 case VSpace::MEDSKIP:
1958 os << "\\setlength\\parskip{\\medskipamount}\n";
1960 case VSpace::BIGSKIP:
1961 os << "\\setlength\\parskip{\\bigskipamount}\n";
1963 case VSpace::LENGTH:
1964 os << "\\setlength\\parskip{"
1965 << params.defskip.length().asLatexString()
1968 default: // should never happen // Then delete it.
1969 os << "\\setlength\\parskip{\\medskipamount}\n";
1974 os << "\\setlength\\parindent{0pt}\n";
1978 // Now insert the LyX specific LaTeX commands...
1980 // The optional packages;
1981 string preamble(features.getPackages());
1983 // this might be useful...
1984 preamble += "\n\\makeatletter\n";
1986 // Some macros LyX will need
1987 string tmppreamble(features.getMacros());
1989 if (!tmppreamble.empty()) {
1990 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1991 "LyX specific LaTeX commands.\n"
1992 + tmppreamble + '\n';
1995 // the text class specific preamble
1996 tmppreamble = features.getTClassPreamble();
1997 if (!tmppreamble.empty()) {
1998 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1999 "Textclass specific LaTeX commands.\n"
2000 + tmppreamble + '\n';
2003 /* the user-defined preamble */
2004 if (!params.preamble.empty()) {
2005 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2006 "User specified LaTeX commands.\n"
2007 + params.preamble + '\n';
2010 // Itemize bullet settings need to be last in case the user
2011 // defines their own bullets that use a package included
2012 // in the user-defined preamble -- ARRae
2013 // Actually it has to be done much later than that
2014 // since some packages like frenchb make modifications
2015 // at \begin{document} time -- JMarc
2017 for (int i = 0; i < 4; ++i) {
2018 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2019 if (bullets_def.empty())
2020 bullets_def="\\AtBeginDocument{\n";
2021 bullets_def += " \\renewcommand{\\labelitemi";
2023 // `i' is one less than the item to modify
2030 bullets_def += "ii";
2036 bullets_def += "}{" +
2037 params.user_defined_bullets[i].getText()
2042 if (!bullets_def.empty())
2043 preamble += bullets_def + "}\n\n";
2046 int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2047 for (int j = 0; j != nlines; ++j) {
2051 // We try to load babel late, in case it interferes
2052 // with other packages.
2054 string tmp = lyxrc.language_package;
2055 if (!lyxrc.language_global_options
2056 && tmp == "\\usepackage{babel}")
2057 tmp = string("\\usepackage[") +
2058 language_options.str().c_str() +
2060 preamble += tmp + "\n";
2061 preamble += features.getBabelOptions();
2064 preamble += "\\makeatother\n";
2072 os << "\\begin{document}\n";
2075 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2077 if (!lyxrc.language_auto_begin) {
2078 os << subst(lyxrc.language_command_begin, "$$lang",
2079 params.language->babel())
2084 latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2086 // add this just in case after all the paragraphs
2090 if (!lyxrc.language_auto_end) {
2091 os << subst(lyxrc.language_command_end, "$$lang",
2092 params.language->babel())
2098 os << "\\end{document}\n";
2101 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2103 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2107 // Just to be sure. (Asger)
2110 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2111 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2113 // we want this to be true outside previews (for insetexternal)
2119 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2121 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2122 Paragraph * endpar, TexRow & texrow,
2123 bool moving_arg) const
2125 bool was_title = false;
2126 bool already_title = false;
2129 while (par != endpar) {
2130 Inset * in = par->inInset();
2131 // well we have to check if we are in an inset with unlimited
2132 // length (all in one row) if that is true then we don't allow
2133 // any special options in the paragraph and also we don't allow
2134 // any environment other then "Standard" to be valid!
2135 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2136 LyXLayout_ptr const & layout = par->layout();
2138 if (layout->intitle) {
2139 if (already_title) {
2140 lyxerr <<"Error in latexParagraphs: You"
2141 " should not mix title layouts"
2142 " with normal ones." << endl;
2145 } else if (was_title && !already_title) {
2146 ofs << "\\maketitle\n";
2148 already_title = true;
2152 if (layout->isEnvironment() ||
2153 !par->params().leftIndent().zero())
2155 par = par->TeXEnvironment(this, params, ofs, texrow);
2157 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2160 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2163 // It might be that we only have a title in this document
2164 if (was_title && !already_title) {
2165 ofs << "\\maketitle\n";
2171 bool Buffer::isLatex() const
2173 return params.getLyXTextClass().outputType() == LATEX;
2177 bool Buffer::isLinuxDoc() const
2179 return params.getLyXTextClass().outputType() == LINUXDOC;
2183 bool Buffer::isLiterate() const
2185 return params.getLyXTextClass().outputType() == LITERATE;
2189 bool Buffer::isDocBook() const
2191 return params.getLyXTextClass().outputType() == DOCBOOK;
2195 bool Buffer::isSGML() const
2197 LyXTextClass const & tclass = params.getLyXTextClass();
2199 return tclass.outputType() == LINUXDOC ||
2200 tclass.outputType() == DOCBOOK;
2204 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2206 ofstream ofs(fname.c_str());
2209 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2213 niceFile = nice; // this will be used by included files.
2215 LaTeXFeatures features(params);
2221 LyXTextClass const & tclass = params.getLyXTextClass();
2223 string top_element = tclass.latexname();
2226 ofs << "<!doctype linuxdoc system";
2228 string preamble = params.preamble;
2229 const string name = nice ? ChangeExtension(filename_, ".sgml")
2231 preamble += features.getIncludedFiles(name);
2232 preamble += features.getLyXSGMLEntities();
2234 if (!preamble.empty()) {
2235 ofs << " [ " << preamble << " ]";
2239 if (params.options.empty())
2240 sgml::openTag(ofs, 0, false, top_element);
2242 string top = top_element;
2244 top += params.options;
2245 sgml::openTag(ofs, 0, false, top);
2249 ofs << "<!-- " << lyx_docversion
2250 << " created this file. For more info see http://www.lyx.org/"
2253 Paragraph::depth_type depth = 0; // paragraph depth
2254 Paragraph * par = &*(paragraphs.begin());
2256 vector<string> environment_stack(5);
2259 LyXLayout_ptr const & style = par->layout();
2260 // treat <toc> as a special case for compatibility with old code
2261 if (par->isInset(0)) {
2262 Inset * inset = par->getInset(0);
2263 Inset::Code lyx_code = inset->lyxCode();
2264 if (lyx_code == Inset::TOC_CODE) {
2265 string const temp = "toc";
2266 sgml::openTag(ofs, depth, false, temp);
2273 // environment tag closing
2274 for (; depth > par->params().depth(); --depth) {
2275 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2276 environment_stack[depth].erase();
2279 // write opening SGML tags
2280 switch (style->latextype) {
2281 case LATEX_PARAGRAPH:
2282 if (depth == par->params().depth()
2283 && !environment_stack[depth].empty()) {
2284 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2285 environment_stack[depth].erase();
2291 sgml::openTag(ofs, depth, false, style->latexname());
2297 _("Error : Wrong depth for"
2298 " LatexType Command.\n"));
2300 if (!environment_stack[depth].empty()) {
2301 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2305 environment_stack[depth].erase();
2306 sgml::openTag(ofs, depth, false, style->latexname());
2309 case LATEX_ENVIRONMENT:
2310 case LATEX_ITEM_ENVIRONMENT:
2312 string const & latexname = style->latexname();
2314 if (depth == par->params().depth()
2315 && environment_stack[depth] != latexname) {
2316 sgml::closeTag(ofs, depth, false,
2317 environment_stack[depth]);
2318 environment_stack[depth].erase();
2320 if (depth < par->params().depth()) {
2321 depth = par->params().depth();
2322 environment_stack[depth].erase();
2324 if (environment_stack[depth] != latexname) {
2326 sgml::openTag(ofs, depth, false, "p");
2328 sgml::openTag(ofs, depth, false, latexname);
2330 if (environment_stack.size() == depth + 1)
2331 environment_stack.push_back("!-- --");
2332 environment_stack[depth] = latexname;
2335 if (style->latexparam() == "CDATA")
2338 if (style->latextype == LATEX_ENVIRONMENT) break;
2340 if (style->labeltype == LABEL_MANUAL)
2345 sgml::openTag(ofs, depth + 1, false, item_name);
2350 sgml::openTag(ofs, depth, false, style->latexname());
2354 simpleLinuxDocOnePar(ofs, par, depth);
2359 // write closing SGML tags
2360 switch (style->latextype) {
2363 case LATEX_ENVIRONMENT:
2364 case LATEX_ITEM_ENVIRONMENT:
2365 if (style->latexparam() == "CDATA")
2369 sgml::closeTag(ofs, depth, false, style->latexname());
2375 for (int i = depth; i >= 0; --i)
2376 sgml::closeTag(ofs, depth, false, environment_stack[i]);
2380 sgml::closeTag(ofs, 0, false, top_element);
2384 // How to check for successful close
2386 // we want this to be true outside previews (for insetexternal)
2391 // checks, if newcol chars should be put into this line
2392 // writes newline, if necessary.
2395 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2396 string::size_type newcol)
2399 if (colcount > lyxrc.ascii_linelen) {
2401 colcount = newcol; // assume write after this call
2416 string tag_name(PAR_TAG const & pt) {
2418 case NONE: return "!-- --";
2419 case TT: return "tt";
2420 case SF: return "sf";
2421 case BF: return "bf";
2422 case IT: return "it";
2423 case SL: return "sl";
2424 case EM: return "em";
2431 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2433 p1 = static_cast<PAR_TAG>(p1 | p2);
2438 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2440 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2446 // Handle internal paragraph parsing -- layout already processed.
2447 void Buffer::simpleLinuxDocOnePar(ostream & os,
2449 Paragraph::depth_type /*depth*/)
2451 LyXLayout_ptr const & style = par->layout();
2453 string::size_type char_line_count = 5; // Heuristic choice ;-)
2455 // gets paragraph main font
2458 if (style->labeltype == LABEL_MANUAL) {
2459 font_old = style->labelfont;
2462 font_old = style->font;
2466 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2467 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2468 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2471 stack<PAR_TAG> tag_state;
2472 // parsing main loop
2473 for (pos_type i = 0; i < par->size(); ++i) {
2475 PAR_TAG tag_close = NONE;
2476 list < PAR_TAG > tag_open;
2478 LyXFont const font = par->getFont(params, i);
2480 if (font_old.family() != font.family()) {
2481 switch (family_type) {
2482 case LyXFont::SANS_FAMILY:
2485 case LyXFont::TYPEWRITER_FAMILY:
2492 family_type = font.family();
2494 switch (family_type) {
2495 case LyXFont::SANS_FAMILY:
2496 tag_open.push_back(SF);
2498 case LyXFont::TYPEWRITER_FAMILY:
2499 tag_open.push_back(TT);
2506 if (font_old.series() != font.series()) {
2507 switch (series_type) {
2508 case LyXFont::BOLD_SERIES:
2515 series_type = font.series();
2517 switch (series_type) {
2518 case LyXFont::BOLD_SERIES:
2519 tag_open.push_back(BF);
2527 if (font_old.shape() != font.shape()) {
2528 switch (shape_type) {
2529 case LyXFont::ITALIC_SHAPE:
2532 case LyXFont::SLANTED_SHAPE:
2539 shape_type = font.shape();
2541 switch (shape_type) {
2542 case LyXFont::ITALIC_SHAPE:
2543 tag_open.push_back(IT);
2545 case LyXFont::SLANTED_SHAPE:
2546 tag_open.push_back(SL);
2553 if (font_old.emph() != font.emph()) {
2554 if (font.emph() == LyXFont::ON) {
2555 tag_open.push_back(EM);
2564 list < PAR_TAG > temp;
2565 while (!tag_state.empty() && tag_close) {
2566 PAR_TAG k = tag_state.top();
2568 os << "</" << tag_name(k) << ">";
2575 for(list< PAR_TAG >::const_iterator j = temp.begin();
2576 j != temp.end(); ++j) {
2578 os << "<" << tag_name(*j) << ">";
2581 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2582 j != tag_open.end(); ++j) {
2584 os << "<" << tag_name(*j) << ">";
2587 char c = par->getChar(i);
2589 if (c == Paragraph::META_INSET) {
2590 Inset * inset = par->getInset(i);
2591 inset->linuxdoc(this, os);
2596 if (style->latexparam() == "CDATA") {
2597 // "TeX"-Mode on == > SGML-Mode on.
2604 boost::tie(ws, str) = sgml::escapeChar(c);
2605 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2606 // in freespacing mode, spaces are
2607 // non-breaking characters
2608 if (desc_on) {// if char is ' ' then...
2611 sgmlLineBreak(os, char_line_count, 6);
2615 sgmlLineBreak(os, char_line_count, 1);
2620 char_line_count += str.length();
2626 while (!tag_state.empty()) {
2627 os << "</" << tag_name(tag_state.top()) << ">";
2631 // resets description flag correctly
2633 // <tag> not closed...
2634 sgmlLineBreak(os, char_line_count, 6);
2640 // Print an error message.
2641 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2642 string const & /*message*/) const
2644 #ifdef WITH_WARNINGS
2645 #warning This is wrong we cannot insert an inset like this!!!
2646 // I guess this was Jose' so I explain you more or less why this
2647 // is wrong. This way you insert something in the paragraph and
2648 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2649 // I deactivate this code, have a look at BufferView::insertErrors
2650 // how you should do this correctly! (Jug 20020315)
2653 // insert an error marker in text
2654 InsetError * new_inset = new InsetError(message);
2655 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2661 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2663 ofstream ofs(fname.c_str());
2665 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2669 Paragraph * par = &*(paragraphs.begin());
2671 niceFile = nice; // this will be used by Insetincludes.
2673 LaTeXFeatures features(params);
2678 LyXTextClass const & tclass = params.getLyXTextClass();
2679 string top_element = tclass.latexname();
2682 ofs << "<!DOCTYPE " << top_element
2683 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2685 string preamble = params.preamble;
2686 const string name = nice ? ChangeExtension(filename_, ".sgml")
2688 preamble += features.getIncludedFiles(name);
2689 preamble += features.getLyXSGMLEntities();
2691 if (!preamble.empty()) {
2692 ofs << "\n [ " << preamble << " ]";
2697 string top = top_element;
2699 top += params.language->code();
2702 if (!params.options.empty()) {
2704 top += params.options;
2706 sgml::openTag(ofs, 0, false, top);
2708 ofs << "<!-- DocBook file was created by " << lyx_docversion
2709 << "\n See http://www.lyx.org/ for more information -->\n";
2711 vector<string> environment_stack(10);
2712 vector<string> environment_inner(10);
2713 vector<string> command_stack(10);
2715 bool command_flag = false;
2716 Paragraph::depth_type command_depth = 0;
2717 Paragraph::depth_type command_base = 0;
2718 Paragraph::depth_type cmd_depth = 0;
2719 Paragraph::depth_type depth = 0; // paragraph depth
2722 string command_name;
2728 int desc_on = 0; // description mode
2730 LyXLayout_ptr const & style = par->layout();
2732 // environment tag closing
2733 for (; depth > par->params().depth(); --depth) {
2734 if (environment_inner[depth] != "!-- --") {
2735 item_name = "listitem";
2736 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2737 if (environment_inner[depth] == "varlistentry")
2738 sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2740 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2741 environment_stack[depth].erase();
2742 environment_inner[depth].erase();
2745 if (depth == par->params().depth()
2746 && environment_stack[depth] != style->latexname()
2747 && !environment_stack[depth].empty()) {
2748 if (environment_inner[depth] != "!-- --") {
2749 item_name= "listitem";
2750 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2751 if (environment_inner[depth] == "varlistentry")
2752 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2755 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2757 environment_stack[depth].erase();
2758 environment_inner[depth].erase();
2761 // Write opening SGML tags.
2762 switch (style->latextype) {
2763 case LATEX_PARAGRAPH:
2764 sgml::openTag(ofs, depth + command_depth,
2765 false, style->latexname());
2771 _("Error : Wrong depth for "
2772 "LatexType Command.\n"));
2774 command_name = style->latexname();
2776 sgmlparam = style->latexparam();
2777 c_params = split(sgmlparam, c_depth,'|');
2779 cmd_depth = lyx::atoi(c_depth);
2782 if (cmd_depth < command_base) {
2783 for (Paragraph::depth_type j = command_depth;
2784 j >= command_base; --j) {
2785 sgml::closeTag(ofs, j, false, command_stack[j]);
2788 command_depth = command_base = cmd_depth;
2789 } else if (cmd_depth <= command_depth) {
2790 for (int j = command_depth;
2791 j >= int(cmd_depth); --j) {
2792 sgml::closeTag(ofs, j, false, command_stack[j]);
2795 command_depth = cmd_depth;
2797 command_depth = cmd_depth;
2799 command_depth = command_base = cmd_depth;
2800 command_flag = true;
2802 if (command_stack.size() == command_depth + 1)
2803 command_stack.push_back(string());
2804 command_stack[command_depth] = command_name;
2806 // treat label as a special case for
2807 // more WYSIWYM handling.
2808 // This is a hack while paragraphs can't have
2809 // attributes, like id in this case.
2810 if (par->isInset(0)) {
2811 Inset * inset = par->getInset(0);
2812 Inset::Code lyx_code = inset->lyxCode();
2813 if (lyx_code == Inset::LABEL_CODE) {
2814 command_name += " id=\"";
2815 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2816 command_name += "\"";
2821 sgml::openTag(ofs, depth + command_depth, false, command_name);
2823 item_name = c_params.empty()?"title":c_params;
2824 sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2827 case LATEX_ENVIRONMENT:
2828 case LATEX_ITEM_ENVIRONMENT:
2829 if (depth < par->params().depth()) {
2830 depth = par->params().depth();
2831 environment_stack[depth].erase();
2834 if (environment_stack[depth] != style->latexname()) {
2835 if (environment_stack.size() == depth + 1) {
2836 environment_stack.push_back("!-- --");
2837 environment_inner.push_back("!-- --");
2839 environment_stack[depth] = style->latexname();
2840 environment_inner[depth] = "!-- --";
2841 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2843 if (environment_inner[depth] != "!-- --") {
2844 item_name= "listitem";
2845 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2846 if (environment_inner[depth] == "varlistentry")
2847 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2851 if (style->latextype == LATEX_ENVIRONMENT) {
2852 if (!style->latexparam().empty()) {
2853 if (style->latexparam() == "CDATA")
2856 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2861 desc_on = (style->labeltype == LABEL_MANUAL);
2863 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2864 sgml::openTag(ofs, depth + 1 + command_depth,
2865 false, environment_inner[depth]);
2867 item_name = desc_on ? "term" : "para";
2868 sgml::openTag(ofs, depth + 1 + command_depth,
2872 sgml::openTag(ofs, depth + command_depth,
2873 false, style->latexname());
2877 simpleDocBookOnePar(ofs, par, desc_on,
2878 depth + 1 + command_depth);
2882 // write closing SGML tags
2883 switch (style->latextype) {
2885 end_tag = c_params.empty() ? "title" : c_params;
2886 sgml::closeTag(ofs, depth + command_depth,
2889 case LATEX_ENVIRONMENT:
2890 if (!style->latexparam().empty()) {
2891 if (style->latexparam() == "CDATA")
2894 sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2897 case LATEX_ITEM_ENVIRONMENT:
2898 if (desc_on == 1) break;
2900 sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2902 case LATEX_PARAGRAPH:
2903 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2906 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2912 for (int d = depth; d >= 0; --d) {
2913 if (!environment_stack[depth].empty()) {
2914 if (environment_inner[depth] != "!-- --") {
2915 item_name = "listitem";
2916 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2917 if (environment_inner[depth] == "varlistentry")
2918 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2921 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2925 for (int j = command_depth; j >= 0 ; --j)
2926 if (!command_stack[j].empty()) {
2927 sgml::closeTag(ofs, j, false, command_stack[j]);
2932 sgml::closeTag(ofs, 0, false, top_element);
2935 // How to check for successful close
2937 // we want this to be true outside previews (for insetexternal)
2942 void Buffer::simpleDocBookOnePar(ostream & os,
2943 Paragraph * par, int & desc_on,
2944 Paragraph::depth_type depth) const
2946 bool emph_flag = false;
2948 LyXLayout_ptr const & style = par->layout();
2950 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2952 int char_line_count = depth;
2953 //if (!style.free_spacing)
2954 // os << string(depth,' ');
2956 // parsing main loop
2957 for (pos_type i = 0; i < par->size(); ++i) {
2958 LyXFont font = par->getFont(params, i);
2960 // handle <emphasis> tag
2961 if (font_old.emph() != font.emph()) {
2962 if (font.emph() == LyXFont::ON) {
2963 if (style->latexparam() == "CDATA")
2966 if (style->latexparam() == "CDATA")
2970 if (style->latexparam() == "CDATA")
2972 os << "</emphasis>";
2973 if (style->latexparam() == "CDATA")
2980 if (par->isInset(i)) {
2981 Inset * inset = par->getInset(i);
2982 // don't print the inset in position 0 if desc_on == 3 (label)
2983 if (i || desc_on != 3) {
2984 if (style->latexparam() == "CDATA")
2986 inset->docbook(this, os, false);
2987 if (style->latexparam() == "CDATA")
2991 char c = par->getChar(i);
2994 boost::tie(ws, str) = sgml::escapeChar(c);
2996 if (style->pass_thru) {
2998 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3000 } else if (desc_on ==1) {
3002 os << "\n</term><listitem><para>";
3012 if (style->latexparam() == "CDATA")
3014 os << "</emphasis>";
3015 if (style->latexparam() == "CDATA")
3019 // resets description flag correctly
3021 // <term> not closed...
3022 os << "</term>\n<listitem><para> </para>";
3024 if (style->free_spacing)
3029 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3030 // Other flags: -wall -v0 -x
3031 int Buffer::runChktex()
3033 if (!users->text) return 0;
3035 users->owner()->prohibitInput();
3037 // get LaTeX-Filename
3038 string const name = getLatexName();
3039 string path = filePath();
3041 string const org_path = path;
3042 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3046 Path p(path); // path to LaTeX file
3047 users->owner()->message(_("Running chktex..."));
3049 // Remove all error insets
3050 bool const removedErrorInsets = users->removeAutoInsets();
3052 // Generate the LaTeX file if neccessary
3053 makeLaTeXFile(name, org_path, false);
3056 Chktex chktex(lyxrc.chktex_command, name, filePath());
3057 int res = chktex.run(terr); // run chktex
3060 Alert::alert(_("chktex did not work!"),
3061 _("Could not run with file:"), name);
3062 } else if (res > 0) {
3063 // Insert all errors as errors boxes
3064 users->insertErrors(terr);
3067 // if we removed error insets before we ran chktex or if we inserted
3068 // error insets after we ran chktex, this must be run:
3069 if (removedErrorInsets || res) {
3070 #warning repaint needed here, or do you mean update() ?
3074 users->owner()->allowInput();
3080 void Buffer::validate(LaTeXFeatures & features) const
3082 LyXTextClass const & tclass = params.getLyXTextClass();
3084 // AMS Style is at document level
3085 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3086 features.require("amsmath");
3088 for_each(paragraphs.begin(), paragraphs.end(),
3089 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3091 // the bullet shapes are buffer level not paragraph level
3092 // so they are tested here
3093 for (int i = 0; i < 4; ++i) {
3094 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3095 int const font = params.user_defined_bullets[i].getFont();
3097 int const c = params
3098 .user_defined_bullets[i]
3105 features.require("latexsym");
3107 } else if (font == 1) {
3108 features.require("amssymb");
3109 } else if ((font >= 2 && font <= 5)) {
3110 features.require("pifont");
3115 if (lyxerr.debugging(Debug::LATEX)) {
3116 features.showStruct();
3121 vector<string> const Buffer::getLabelList() const
3123 /// if this is a child document and the parent is already loaded
3124 /// Use the parent's list instead [ale990407]
3125 if (!params.parentname.empty()
3126 && bufferlist.exists(params.parentname)) {
3127 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3129 return tmp->getLabelList();
3132 vector<string> label_list;
3133 for (inset_iterator it = inset_const_iterator_begin();
3134 it != inset_const_iterator_end(); ++it) {
3135 vector<string> const l = it->getLabelList();
3136 label_list.insert(label_list.end(), l.begin(), l.end());
3142 // This is also a buffer property (ale)
3143 vector<pair<string, string> > const Buffer::getBibkeyList() const
3145 typedef pair<string, string> StringPair;
3146 /// if this is a child document and the parent is already loaded
3147 /// Use the parent's list instead [ale990412]
3148 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3149 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3151 return tmp->getBibkeyList();
3154 vector<StringPair> keys;
3155 ParagraphList::iterator pit = paragraphs.begin();
3156 ParagraphList::iterator pend = paragraphs.end();
3157 for (; pit != pend; ++pit) {
3159 string const key = pit->bibkey->getContents();
3160 string const opt = pit->bibkey->getOptions();
3161 string const ref = pit->asString(this, false);
3162 string const info = opt + "TheBibliographyRef" + ref;
3164 keys.push_back(StringPair(key, info));
3171 // Might be either using bibtex or a child has bibliography
3172 for (inset_iterator it = inset_const_iterator_begin();
3173 it != inset_const_iterator_end(); ++it) {
3174 // Search for Bibtex or Include inset
3175 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3176 vector<StringPair> tmp =
3177 static_cast<InsetBibtex &>(*it).getKeys(this);
3178 keys.insert(keys.end(), tmp.begin(), tmp.end());
3179 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3180 vector<StringPair> const tmp =
3181 static_cast<InsetInclude &>(*it).getKeys();
3182 keys.insert(keys.end(), tmp.begin(), tmp.end());
3190 bool Buffer::isDepClean(string const & name) const
3192 DEPCLEAN * item = dep_clean;
3193 while (item && item->master != name)
3195 if (!item) return true;
3200 void Buffer::markDepClean(string const & name)
3203 dep_clean = new DEPCLEAN;
3204 dep_clean->clean = true;
3205 dep_clean->master = name;
3206 dep_clean->next = 0;
3208 DEPCLEAN * item = dep_clean;
3209 while (item && item->master != name)
3214 item = new DEPCLEAN;
3216 item->master = name;
3223 bool Buffer::dispatch(string const & command, bool * result)
3225 // Split command string into command and argument
3227 string line = ltrim(command);
3228 string const arg = trim(split(line, cmd, ' '));
3230 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3234 bool Buffer::dispatch(int action, string const & argument, bool * result)
3236 bool dispatched = true;
3240 bool const tmp = Exporter::Export(this, argument, false);
3253 void Buffer::resizeInsets(BufferView * bv)
3255 /// then remove all LyXText in text-insets
3256 for_each(paragraphs.begin(), paragraphs.end(),
3257 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3261 void Buffer::redraw()
3263 #warning repaint needed here, or do you mean update() ?
3269 void Buffer::changeLanguage(Language const * from, Language const * to)
3272 ParIterator end = par_iterator_end();
3273 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3274 (*it)->changeLanguage(params, from, to);
3278 bool Buffer::isMultiLingual()
3280 ParIterator end = par_iterator_end();
3281 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3282 if ((*it)->isMultiLingual(params))
3289 void Buffer::inset_iterator::setParagraph()
3291 while (pit != pend) {
3292 it = pit->insetlist.begin();
3293 if (it != pit->insetlist.end())
3300 Inset * Buffer::getInsetFromID(int id_arg) const
3302 for (inset_iterator it = inset_const_iterator_begin();
3303 it != inset_const_iterator_end(); ++it)
3305 if (it->id() == id_arg)
3307 Inset * in = it->getInsetFromID(id_arg);
3315 Paragraph * Buffer::getParFromID(int id) const
3320 ParagraphList::iterator it = paragraphs.begin();
3321 ParagraphList::iterator end = paragraphs.end();
3322 for (; it != end; ++it) {
3323 if (it->id() == id) {
3326 Paragraph * tmp = it->getParFromID(id);
3335 ParIterator Buffer::par_iterator_begin()
3337 return ParIterator(&*(paragraphs.begin()));
3341 ParIterator Buffer::par_iterator_end()
3343 return ParIterator();
3347 void Buffer::addUser(BufferView * u)
3353 void Buffer::delUser(BufferView *)
3359 Language const * Buffer::getLanguage() const
3361 return params.language;
3365 bool Buffer::isClean() const
3371 bool Buffer::isBakClean() const
3377 void Buffer::markClean() const
3383 // if the .lyx file has been saved, we don't need an
3389 void Buffer::markBakClean()
3395 void Buffer::setUnnamed(bool flag)
3401 bool Buffer::isUnnamed()
3407 void Buffer::markDirty()
3414 DEPCLEAN * tmp = dep_clean;
3422 string const & Buffer::fileName() const
3428 string const & Buffer::filePath() const
3434 bool Buffer::isReadonly() const
3440 BufferView * Buffer::getUser() const
3446 void Buffer::setParentName(string const & name)
3448 params.parentname = name;
3452 Buffer::inset_iterator::inset_iterator()
3457 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3464 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3468 if (it == pit->insetlist.end()) {
3477 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3479 inset_iterator tmp = *this;
3485 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3487 return *it.getInset();
3491 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3493 return it.getInset();
3497 Paragraph * Buffer::inset_iterator::getPar()
3503 lyx::pos_type Buffer::inset_iterator::getPos() const
3509 bool operator==(Buffer::inset_iterator const & iter1,
3510 Buffer::inset_iterator const & iter2)
3512 return iter1.pit == iter2.pit
3513 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3517 bool operator!=(Buffer::inset_iterator const & iter1,
3518 Buffer::inset_iterator const & iter2)
3520 return !(iter1 == iter2);