1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * This file is Copyright 1996-2001
12 * ======================================================
18 #pragma implementation
22 #include "bufferlist.h"
24 #include "LyXAction.h"
27 #include "tex-strings.h"
29 #include "bufferview_funcs.h"
35 #include "LaTeXFeatures.h"
42 #include "converter.h"
43 #include "BufferView.h"
44 #include "ParagraphParameters.h"
45 #include "iterators.h"
46 #include "lyxtextclasslist.h"
48 #include "paragraph_funcs.h"
50 #include "frontends/LyXView.h"
52 #include "mathed/formulamacro.h"
53 #include "mathed/formula.h"
55 #include "insets/inset.h"
56 #include "insets/inseterror.h"
57 #include "insets/insetlabel.h"
58 #include "insets/insetref.h"
59 #include "insets/inseturl.h"
60 #include "insets/insetnote.h"
61 #include "insets/insetquotes.h"
62 #include "insets/insetlatexaccent.h"
63 #include "insets/insetbib.h"
64 #include "insets/insetcite.h"
65 #include "insets/insetexternal.h"
66 #include "insets/insetindex.h"
67 #include "insets/insetinclude.h"
68 #include "insets/insettoc.h"
69 #include "insets/insetparent.h"
70 #include "insets/insetspecialchar.h"
71 #include "insets/insettext.h"
72 #include "insets/insetert.h"
73 #include "insets/insetgraphics.h"
74 #include "insets/insetfoot.h"
75 #include "insets/insetmarginal.h"
76 #include "insets/insetoptarg.h"
77 #include "insets/insetminipage.h"
78 #include "insets/insetfloat.h"
79 #include "insets/insettabular.h"
81 #include "insets/insettheorem.h"
82 #include "insets/insetlist.h"
84 #include "insets/insetcaption.h"
85 #include "insets/insetfloatlist.h"
87 #include "frontends/Dialogs.h"
88 #include "frontends/Alert.h"
90 #include "graphics/Previews.h"
92 #include "support/textutils.h"
93 #include "support/filetools.h"
94 #include "support/path.h"
95 #include "support/os.h"
96 #include "support/lyxlib.h"
97 #include "support/FileInfo.h"
98 #include "support/lyxmanip.h"
99 #include "support/lyxalgo.h" // for lyx::count
101 #include <boost/bind.hpp>
102 #include <boost/tuple/tuple.hpp>
114 #include <sys/types.h>
121 #ifndef CXX_GLOBAL_CSTD
133 using std::make_pair;
143 using lyx::textclass_type;
145 // all these externs should eventually be removed.
146 extern BufferList bufferlist;
150 const int LYX_FORMAT = 220;
154 Buffer::Buffer(string const & file, bool ronly)
155 : niceFile(true), lyx_clean(true), bak_clean(true),
156 unnamed(false), dep_clean(0), read_only(ronly),
157 filename_(file), users(0), ctrs(new Counters)
159 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
161 filepath_ = OnlyPath(file);
165 // read_only = ronly;
169 if (read_only || lyxrc.use_tempdir) {
170 tmppath = CreateBufferTmpDir();
179 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
180 // here the buffer should take care that it is
181 // saved properly, before it goes into the void.
183 // make sure that views using this buffer
188 if (!tmppath.empty()) {
189 DestroyBufferTmpDir(tmppath);
194 // Remove any previewed LaTeX snippets assocoated with this buffer.
195 grfx::Previews::get().removeLoader(this);
199 string const Buffer::getLatexName(bool no_path) const
201 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
203 return OnlyFilename(name);
209 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
211 string const filename = getLatexName(false);
213 if (filename.empty())
214 return make_pair(Buffer::latexlog, string());
216 string path = OnlyPath(filename);
218 if (lyxrc.use_tempdir || !IsDirWriteable(path))
221 string const fname = AddName(path,
222 OnlyFilename(ChangeExtension(filename,
225 AddName(path, OnlyFilename(
226 ChangeExtension(filename,
227 formats.extension("literate") + ".out")));
229 // If no Latex log or Build log is newer, show Build log
231 FileInfo const f_fi(fname);
232 FileInfo const b_fi(bname);
235 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
236 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
237 return make_pair(Buffer::buildlog, bname);
239 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
240 return make_pair(Buffer::latexlog, fname);
244 void Buffer::setReadonly(bool flag)
246 if (read_only != flag) {
249 users->owner()->getDialogs().updateBufferDependent(false);
254 /// Update window titles of all users
255 // Should work on a list
256 void Buffer::updateTitles() const
259 users->owner()->updateWindowTitle();
263 /// Reset autosave timer of all users
264 // Should work on a list
265 void Buffer::resetAutosaveTimers() const
268 users->owner()->resetAutosaveTimer();
272 void Buffer::setFileName(string const & newfile)
274 filename_ = MakeAbsPath(newfile);
275 filepath_ = OnlyPath(filename_);
276 setReadonly(IsFileWriteable(filename_) == 0);
281 // We'll remove this later. (Lgb)
284 string last_inset_read;
287 #warning And _why_ is this here? (Lgb)
295 // candidate for move to BufferView
296 // (at least some parts in the beginning of the func)
299 // changed to be public and have one parameter
300 // if par = 0 normal behavior
301 // else insert behavior
302 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
303 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
309 Paragraph::depth_type depth = 0;
310 bool the_end_read = false;
312 Paragraph * first_par = 0;
313 LyXFont font(LyXFont::ALL_INHERIT, params.language);
316 if (file_format < 216 && params.language->lang() == "hebrew")
317 font.setLanguage(default_language);
322 par->layout(params.getLyXTextClass().defaultLayout());
324 // We are inserting into an existing document
325 users->text->breakParagraph(users);
326 first_par = users->text->ownerParagraph();
329 // We don't want to adopt the parameters from the
330 // document we insert, so we skip until the text begins:
333 string const pretoken = lex.getString();
334 if (pretoken == "\\layout") {
335 lex.pushToken(pretoken);
343 string const token = lex.getString();
345 if (token.empty()) continue;
347 lyxerr[Debug::PARSER] << "Handling token: `"
348 << token << "'" << endl;
351 parseSingleLyXformat2Token(lex, par, first_par,
359 paragraphs.set(first_par);
361 if (unknown_layouts > 0) {
362 string s = _("Couldn't set the layout for ");
363 if (unknown_layouts == 1) {
364 s += _("one paragraph");
366 s += tostr(unknown_layouts);
367 s += _(" paragraphs");
369 Alert::alert(_("Textclass Loading Error!"), s,
370 _("When reading " + fileName()));
373 if (unknown_tokens > 0) {
374 string s = _("Encountered ");
375 if (unknown_tokens == 1) {
376 s += _("one unknown token");
378 s += tostr(unknown_tokens);
379 s += _(" unknown tokens");
381 Alert::alert(_("Textclass Loading Error!"), s,
382 _("When reading " + fileName()));
390 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
391 Paragraph *& first_par,
392 string const & token, int & pos,
393 Paragraph::depth_type & depth,
397 bool the_end_read = false;
399 // The order of the tags tested may seem unnatural, but this
400 // has been done in order to reduce the number of string
401 // comparisons needed to recognize a given token. This leads
402 // on large documents like UserGuide to a reduction of a
404 if (token[0] != '\\') {
405 for (string::const_iterator cit = token.begin();
406 cit != token.end(); ++cit) {
407 par->insertChar(pos, (*cit), font);
410 } else if (token == "\\layout") {
411 // reset the font as we start a new layout and if the font is
412 // not ALL_INHERIT,document_language then it will be set to the
413 // right values after this tag (Jug 20020420)
414 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
417 if (file_format < 216 && params.language->lang() == "hebrew")
418 font.setLanguage(default_language);
422 string layoutname = lex.getString();
424 LyXTextClass const & tclass = params.getLyXTextClass();
426 if (layoutname.empty()) {
427 layoutname = tclass.defaultLayoutName();
429 bool hasLayout = tclass.hasLayout(layoutname);
431 lyxerr << "Layout '" << layoutname << "' does not"
432 << " exist in textclass '" << tclass.name()
434 lyxerr << "Trying to use default layout instead."
436 layoutname = tclass.defaultLayoutName();
440 // The is the compability reading of layout caption.
441 // It can be removed in LyX version 1.3.0. (Lgb)
442 if (compare_ascii_no_case(layoutname, "caption") == 0) {
443 // We expect that the par we are now working on is
444 // really inside a InsetText inside a InsetFloat.
445 // We also know that captions can only be
446 // one paragraph. (Lgb)
448 // We should now read until the next "\layout"
450 // This is probably not good enough, what if the
451 // caption is the last par in the document (Lgb)
452 istream & ist = lex.getStream();
458 if (prefixIs(line, "\\layout")) {
462 if (prefixIs(line, "\\begin_inset"))
464 if (prefixIs(line, "\\end_inset")) {
475 // Now we should have the whole layout in ss
476 // we should now be able to give this to the
478 ss << "\\end_inset\n";
480 // This seems like a bug in stringstream.
481 // We really should be able to use ss
483 istringstream is(ss.str());
485 tmplex.setStream(is);
486 Inset * inset = new InsetCaption;
487 inset->Read(this, tmplex);
488 par->InsertInset(pos, inset, font);
495 par = new Paragraph(par);
496 par->layout(params.getLyXTextClass().defaultLayout());
499 par->layout(params.getLyXTextClass()[layoutname]);
500 // Test whether the layout is obsolete.
501 LyXLayout_ptr const & layout = par->layout();
502 if (!layout->obsoleted_by().empty())
503 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
504 par->params().depth(depth);
509 } else if (token == "\\end_inset") {
510 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
511 << "Last inset read was: " << last_inset_read
513 // Simply ignore this. The insets do not have
515 // But insets should read it, it is a part of
516 // the inset isn't it? Lgb.
517 } else if (token == "\\begin_inset") {
518 readInset(lex, par, pos, font);
519 } else if (token == "\\family") {
521 font.setLyXFamily(lex.getString());
522 } else if (token == "\\series") {
524 font.setLyXSeries(lex.getString());
525 } else if (token == "\\shape") {
527 font.setLyXShape(lex.getString());
528 } else if (token == "\\size") {
530 font.setLyXSize(lex.getString());
531 } else if (token == "\\lang") {
533 string const tok = lex.getString();
534 Language const * lang = languages.getLanguage(tok);
536 font.setLanguage(lang);
538 font.setLanguage(params.language);
539 lex.printError("Unknown language `$$Token'");
541 } else if (token == "\\numeric") {
543 font.setNumber(font.setLyXMisc(lex.getString()));
544 } else if (token == "\\emph") {
546 font.setEmph(font.setLyXMisc(lex.getString()));
547 } else if (token == "\\bar") {
549 string const tok = lex.getString();
550 // This is dirty, but gone with LyX3. (Asger)
552 font.setUnderbar(LyXFont::ON);
553 else if (tok == "no")
554 font.setUnderbar(LyXFont::OFF);
555 else if (tok == "default")
556 font.setUnderbar(LyXFont::INHERIT);
558 lex.printError("Unknown bar font flag "
560 } else if (token == "\\noun") {
562 font.setNoun(font.setLyXMisc(lex.getString()));
563 } else if (token == "\\color") {
565 font.setLyXColor(lex.getString());
566 } else if (token == "\\SpecialChar") {
567 LyXLayout_ptr const & layout = par->layout();
569 // Insets don't make sense in a free-spacing context! ---Kayvan
570 if (layout->free_spacing || par->isFreeSpacing()) {
573 string next_token = lex.getString();
574 if (next_token == "\\-") {
575 par->insertChar(pos, '-', font);
576 } else if (next_token == "\\protected_separator"
577 || next_token == "~") {
578 par->insertChar(pos, ' ', font);
580 lex.printError("Token `$$Token' "
582 "paragraph layout!");
587 Inset * inset = new InsetSpecialChar;
588 inset->read(this, lex);
589 par->insertInset(pos, inset, font);
592 } else if (token == "\\i") {
593 Inset * inset = new InsetLatexAccent;
594 inset->read(this, lex);
595 par->insertInset(pos, inset, font);
597 } else if (token == "\\backslash") {
598 par->insertChar(pos, '\\', font);
600 } else if (token == "\\begin_deeper") {
602 } else if (token == "\\end_deeper") {
604 lex.printError("\\end_deeper: "
605 "depth is already null");
609 } else if (token == "\\begin_preamble") {
610 params.readPreamble(lex);
611 } else if (token == "\\textclass") {
613 pair<bool, textclass_type> pp =
614 textclasslist.NumberOfClass(lex.getString());
616 params.textclass = pp.second;
618 Alert::alert(string(_("Textclass error")),
619 string(_("The document uses an unknown textclass \"")) +
620 lex.getString() + string("\"."),
621 string(_("LyX will not be able to produce output correctly.")));
622 params.textclass = 0;
624 if (!params.getLyXTextClass().load()) {
625 // if the textclass wasn't loaded properly
626 // we need to either substitute another
627 // or stop loading the file.
628 // I can substitute but I don't see how I can
629 // stop loading... ideas?? ARRae980418
630 Alert::alert(_("Textclass Loading Error!"),
631 string(_("Can't load textclass ")) +
632 params.getLyXTextClass().name(),
633 _("-- substituting default"));
634 params.textclass = 0;
636 } else if (token == "\\options") {
638 params.options = lex.getString();
639 } else if (token == "\\language") {
640 params.readLanguage(lex);
641 } else if (token == "\\fontencoding") {
643 } else if (token == "\\inputencoding") {
645 params.inputenc = lex.getString();
646 } else if (token == "\\graphics") {
647 params.readGraphicsDriver(lex);
648 } else if (token == "\\fontscheme") {
650 params.fonts = lex.getString();
651 } else if (token == "\\noindent") {
652 par->params().noindent(true);
653 } else if (token == "\\leftindent") {
655 LyXLength value(lex.getString());
656 par->params().leftIndent(value);
657 } else if (token == "\\fill_top") {
658 par->params().spaceTop(VSpace(VSpace::VFILL));
659 } else if (token == "\\fill_bottom") {
660 par->params().spaceBottom(VSpace(VSpace::VFILL));
661 } else if (token == "\\line_top") {
662 par->params().lineTop(true);
663 } else if (token == "\\line_bottom") {
664 par->params().lineBottom(true);
665 } else if (token == "\\pagebreak_top") {
666 par->params().pagebreakTop(true);
667 } else if (token == "\\pagebreak_bottom") {
668 par->params().pagebreakBottom(true);
669 } else if (token == "\\start_of_appendix") {
670 par->params().startOfAppendix(true);
671 } else if (token == "\\paragraph_separation") {
672 int tmpret = lex.findToken(string_paragraph_separation);
675 params.paragraph_separation =
676 static_cast<BufferParams::PARSEP>(tmpret);
677 } else if (token == "\\defskip") {
679 params.defskip = VSpace(lex.getString());
680 } else if (token == "\\quotes_language") {
681 int tmpret = lex.findToken(string_quotes_language);
684 InsetQuotes::quote_language tmpl =
685 InsetQuotes::EnglishQ;
688 tmpl = InsetQuotes::EnglishQ;
691 tmpl = InsetQuotes::SwedishQ;
694 tmpl = InsetQuotes::GermanQ;
697 tmpl = InsetQuotes::PolishQ;
700 tmpl = InsetQuotes::FrenchQ;
703 tmpl = InsetQuotes::DanishQ;
706 params.quotes_language = tmpl;
707 } else if (token == "\\quotes_times") {
709 switch (lex.getInteger()) {
711 params.quotes_times = InsetQuotes::SingleQ;
714 params.quotes_times = InsetQuotes::DoubleQ;
717 } else if (token == "\\papersize") {
718 int tmpret = lex.findToken(string_papersize);
722 params.papersize2 = tmpret;
723 } else if (token == "\\paperpackage") {
724 int tmpret = lex.findToken(string_paperpackages);
727 params.paperpackage = BufferParams::PACKAGE_NONE;
729 params.paperpackage = tmpret;
730 } else if (token == "\\use_geometry") {
732 params.use_geometry = lex.getInteger();
733 } else if (token == "\\use_amsmath") {
735 params.use_amsmath = lex.getInteger();
736 } else if (token == "\\use_natbib") {
738 params.use_natbib = lex.getInteger();
739 } else if (token == "\\use_numerical_citations") {
741 params.use_numerical_citations = lex.getInteger();
742 } else if (token == "\\paperorientation") {
743 int tmpret = lex.findToken(string_orientation);
747 static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
748 } else if (token == "\\paperwidth") {
750 params.paperwidth = lex.getString();
751 } else if (token == "\\paperheight") {
753 params.paperheight = lex.getString();
754 } else if (token == "\\leftmargin") {
756 params.leftmargin = lex.getString();
757 } else if (token == "\\topmargin") {
759 params.topmargin = lex.getString();
760 } else if (token == "\\rightmargin") {
762 params.rightmargin = lex.getString();
763 } else if (token == "\\bottommargin") {
765 params.bottommargin = lex.getString();
766 } else if (token == "\\headheight") {
768 params.headheight = lex.getString();
769 } else if (token == "\\headsep") {
771 params.headsep = lex.getString();
772 } else if (token == "\\footskip") {
774 params.footskip = lex.getString();
775 } else if (token == "\\paperfontsize") {
777 params.fontsize = rtrim(lex.getString());
778 } else if (token == "\\papercolumns") {
780 params.columns = lex.getInteger();
781 } else if (token == "\\papersides") {
783 switch (lex.getInteger()) {
785 case 1: params.sides = LyXTextClass::OneSide; break;
786 case 2: params.sides = LyXTextClass::TwoSides; break;
788 } else if (token == "\\paperpagestyle") {
790 params.pagestyle = rtrim(lex.getString());
791 } else if (token == "\\bullet") {
793 int const index = lex.getInteger();
795 int temp_int = lex.getInteger();
796 params.user_defined_bullets[index].setFont(temp_int);
797 params.temp_bullets[index].setFont(temp_int);
799 temp_int = lex.getInteger();
800 params.user_defined_bullets[index].setCharacter(temp_int);
801 params.temp_bullets[index].setCharacter(temp_int);
803 temp_int = lex.getInteger();
804 params.user_defined_bullets[index].setSize(temp_int);
805 params.temp_bullets[index].setSize(temp_int);
807 string const temp_str = lex.getString();
808 if (temp_str != "\\end_bullet") {
809 // this element isn't really necessary for
810 // parsing but is easier for humans
811 // to understand bullets. Put it back and
812 // set a debug message?
813 lex.printError("\\end_bullet expected, got" + temp_str);
814 //how can I put it back?
816 } else if (token == "\\bulletLaTeX") {
817 // The bullet class should be able to read this.
819 int const index = lex.getInteger();
821 string temp_str = lex.getString();
823 while (temp_str != "\\end_bullet") {
824 // this loop structure is needed when user
825 // enters an empty string since the first
826 // thing returned will be the \\end_bullet
828 // if the LaTeX entry has spaces. Each element
829 // therefore needs to be read in turn
832 temp_str = lex.getString();
835 params.user_defined_bullets[index].setText(sum_str);
836 params.temp_bullets[index].setText(sum_str);
837 } else if (token == "\\secnumdepth") {
839 params.secnumdepth = lex.getInteger();
840 } else if (token == "\\tocdepth") {
842 params.tocdepth = lex.getInteger();
843 } else if (token == "\\spacing") {
845 string const tmp = rtrim(lex.getString());
846 Spacing::Space tmp_space = Spacing::Default;
848 if (tmp == "single") {
849 tmp_space = Spacing::Single;
850 } else if (tmp == "onehalf") {
851 tmp_space = Spacing::Onehalf;
852 } else if (tmp == "double") {
853 tmp_space = Spacing::Double;
854 } else if (tmp == "other") {
856 tmp_space = Spacing::Other;
857 tmp_val = lex.getFloat();
859 lex.printError("Unknown spacing token: '$$Token'");
861 // Small hack so that files written with klyx will be
864 par->params().spacing(Spacing(tmp_space, tmp_val));
866 params.spacing.set(tmp_space, tmp_val);
868 } else if (token == "\\paragraph_spacing") {
870 string const tmp = rtrim(lex.getString());
871 if (tmp == "single") {
872 par->params().spacing(Spacing(Spacing::Single));
873 } else if (tmp == "onehalf") {
874 par->params().spacing(Spacing(Spacing::Onehalf));
875 } else if (tmp == "double") {
876 par->params().spacing(Spacing(Spacing::Double));
877 } else if (tmp == "other") {
879 par->params().spacing(Spacing(Spacing::Other,
882 lex.printError("Unknown spacing token: '$$Token'");
884 } else if (token == "\\float_placement") {
886 params.float_placement = lex.getString();
887 } else if (token == "\\align") {
888 int tmpret = lex.findToken(string_align);
889 if (tmpret == -1) ++tmpret;
890 int const tmpret2 = int(pow(2.0, tmpret));
891 par->params().align(LyXAlignment(tmpret2));
892 } else if (token == "\\added_space_top") {
894 VSpace value = VSpace(lex.getString());
895 // only add the length when value > 0 or
897 if ((value.length().len().value() != 0) ||
899 (value.kind() != VSpace::LENGTH))
900 par->params().spaceTop(value);
901 } else if (token == "\\added_space_bottom") {
903 VSpace value = VSpace(lex.getString());
904 // only add the length when value > 0 or
906 if ((value.length().len().value() != 0) ||
908 (value.kind() != VSpace::LENGTH))
909 par->params().spaceBottom(value);
910 } else if (token == "\\labelwidthstring") {
912 par->params().labelWidthString(lex.getString());
913 // do not delete this token, it is still needed!
914 } else if (token == "\\newline") {
915 par->insertChar(pos, Paragraph::META_NEWLINE, font);
917 } else if (token == "\\LyXTable") {
918 Inset * inset = new InsetTabular(*this);
919 inset->read(this, lex);
920 par->insertInset(pos, inset, font);
922 } else if (token == "\\hfill") {
923 par->insertChar(pos, Paragraph::META_HFILL, font);
925 } else if (token == "\\protected_separator") { // obsolete
926 // This is a backward compability thingie. (Lgb)
927 // Remove it later some time...introduced with fileformat
929 LyXLayout_ptr const & layout = par->layout();
931 if (layout->free_spacing || par->isFreeSpacing()) {
932 par->insertChar(pos, ' ', font);
934 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
935 par->insertInset(pos, inset, font);
938 } else if (token == "\\bibitem") { // ale970302
940 InsetCommandParams p("bibitem", "dummy");
941 par->bibkey = new InsetBibKey(p);
943 par->bibkey->read(this, lex);
944 } else if (token == "\\the_end") {
947 // This should be insurance for the future: (Asger)
950 string const s = _("Unknown token: ") + token
951 + " " + lex.text() + "\n";
952 // we can do this here this way because we're actually reading
953 // the buffer and don't care about LyXText right now.
954 InsetError * new_inset = new InsetError(s);
955 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
963 // needed to insert the selection
964 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
965 LyXFont const & fn,string const & str) const
967 LyXLayout_ptr const & layout = par->layout();
971 par->checkInsertChar(font);
972 // insert the string, don't insert doublespace
973 bool space_inserted = true;
974 bool autobreakrows = !par->inInset() ||
975 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
976 for(string::const_iterator cit = str.begin();
977 cit != str.end(); ++cit) {
979 if (autobreakrows && (!par->empty() || layout->keepempty)) {
980 breakParagraph(params, par, pos,
981 layout->isEnvironment());
984 space_inserted = true;
988 // do not insert consecutive spaces if !free_spacing
989 } else if ((*cit == ' ' || *cit == '\t') &&
990 space_inserted && !layout->free_spacing &&
991 !par->isFreeSpacing())
994 } else if (*cit == '\t') {
995 if (!layout->free_spacing && !par->isFreeSpacing()) {
996 // tabs are like spaces here
997 par->insertChar(pos, ' ', font);
999 space_inserted = true;
1001 const pos_type nb = 8 - pos % 8;
1002 for (pos_type a = 0; a < nb ; ++a) {
1003 par->insertChar(pos, ' ', font);
1006 space_inserted = true;
1008 } else if (!IsPrintable(*cit)) {
1009 // Ignore unprintables
1012 // just insert the character
1013 par->insertChar(pos, *cit, font);
1015 space_inserted = (*cit == ' ');
1022 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1023 int & pos, LyXFont & font)
1025 // consistency check
1026 if (lex.getString() != "\\begin_inset") {
1027 lyxerr << "Buffer::readInset: Consistency check failed."
1034 string const tmptok = lex.getString();
1035 last_inset_read = tmptok;
1037 // test the different insets
1038 if (tmptok == "LatexCommand") {
1039 InsetCommandParams inscmd;
1042 string const cmdName = inscmd.getCmdName();
1044 // This strange command allows LyX to recognize "natbib" style
1045 // citations: citet, citep, Citet etc.
1046 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1047 inset = new InsetCitation(inscmd);
1048 } else if (cmdName == "bibitem") {
1049 lex.printError("Wrong place for bibitem");
1050 inset = new InsetBibKey(inscmd);
1051 } else if (cmdName == "BibTeX") {
1052 inset = new InsetBibtex(inscmd);
1053 } else if (cmdName == "index") {
1054 inset = new InsetIndex(inscmd);
1055 } else if (cmdName == "include") {
1056 inset = new InsetInclude(inscmd, *this);
1057 } else if (cmdName == "label") {
1058 inset = new InsetLabel(inscmd);
1059 } else if (cmdName == "url"
1060 || cmdName == "htmlurl") {
1061 inset = new InsetUrl(inscmd);
1062 } else if (cmdName == "ref"
1063 || cmdName == "pageref"
1064 || cmdName == "vref"
1065 || cmdName == "vpageref"
1066 || cmdName == "prettyref") {
1067 if (!inscmd.getOptions().empty()
1068 || !inscmd.getContents().empty()) {
1069 inset = new InsetRef(inscmd, *this);
1071 } else if (cmdName == "tableofcontents") {
1072 inset = new InsetTOC(inscmd);
1073 } else if (cmdName == "listofalgorithms") {
1074 inset = new InsetFloatList("algorithm");
1075 } else if (cmdName == "listoffigures") {
1076 inset = new InsetFloatList("figure");
1077 } else if (cmdName == "listoftables") {
1078 inset = new InsetFloatList("table");
1079 } else if (cmdName == "printindex") {
1080 inset = new InsetPrintIndex(inscmd);
1081 } else if (cmdName == "lyxparent") {
1082 inset = new InsetParent(inscmd, *this);
1085 bool alreadyread = false;
1086 if (tmptok == "Quotes") {
1087 inset = new InsetQuotes;
1088 } else if (tmptok == "External") {
1089 inset = new InsetExternal;
1090 } else if (tmptok == "FormulaMacro") {
1091 inset = new InsetFormulaMacro;
1092 } else if (tmptok == "Formula") {
1093 inset = new InsetFormula;
1094 } else if (tmptok == "Figure") { // Backward compatibility
1095 // inset = new InsetFig(100, 100, *this);
1096 inset = new InsetGraphics;
1097 } else if (tmptok == "Graphics") {
1098 inset = new InsetGraphics;
1099 } else if (tmptok == "Info") {// backwards compatibility
1100 inset = new InsetNote(this,
1101 lex.getLongString("\\end_inset"),
1104 } else if (tmptok == "Note") {
1105 inset = new InsetNote(params);
1106 } else if (tmptok == "Include") {
1107 InsetCommandParams p("Include");
1108 inset = new InsetInclude(p, *this);
1109 } else if (tmptok == "ERT") {
1110 inset = new InsetERT(params);
1111 } else if (tmptok == "Tabular") {
1112 inset = new InsetTabular(*this);
1113 } else if (tmptok == "Text") {
1114 inset = new InsetText(params);
1115 } else if (tmptok == "Foot") {
1116 inset = new InsetFoot(params);
1117 } else if (tmptok == "Marginal") {
1118 inset = new InsetMarginal(params);
1119 } else if (tmptok == "OptArg") {
1120 inset = new InsetOptArg(params);
1121 } else if (tmptok == "Minipage") {
1122 inset = new InsetMinipage(params);
1123 } else if (tmptok == "Float") {
1125 string tmptok = lex.getString();
1126 inset = new InsetFloat(params, tmptok);
1128 } else if (tmptok == "List") {
1129 inset = new InsetList;
1130 } else if (tmptok == "Theorem") {
1131 inset = new InsetList;
1133 } else if (tmptok == "Caption") {
1134 inset = new InsetCaption(params);
1135 } else if (tmptok == "FloatList") {
1136 inset = new InsetFloatList;
1139 if (inset && !alreadyread) inset->read(this, lex);
1143 par->insertInset(pos, inset, font);
1149 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1153 string const token(lex.getString());
1154 if (token == "\\lyxformat") { // the first token _must_ be...
1156 string tmp_format = lex.getString();
1157 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1158 // if present remove ".," from string.
1159 string::size_type dot = tmp_format.find_first_of(".,");
1160 //lyxerr << " dot found at " << dot << endl;
1161 if (dot != string::npos)
1162 tmp_format.erase(dot, 1);
1163 file_format = strToInt(tmp_format);
1164 if (file_format == LYX_FORMAT) {
1166 } else if (file_format > LYX_FORMAT) {
1168 Alert::alert(_("Warning!"),
1169 _("LyX file format is newer that what"),
1170 _("is supported in this LyX version. Expect some problems."));
1172 } else if (file_format < LYX_FORMAT) {
1174 if (file_format < 200) {
1175 Alert::alert(_("ERROR!"),
1176 _("Old LyX file format found. "
1177 "Use LyX 0.10.x to read this!"));
1179 } else if (file_format < 220) {
1180 string const command = "lyx2lyx "
1181 + QuoteName(filename_);
1182 cmd_ret const ret = RunCommand(command);
1184 Alert::alert(_("ERROR!"),
1185 _("An error occured while "
1186 "running the conversion script."));
1189 istringstream is(ret.second);
1190 LyXLex tmplex(0, 0);
1191 tmplex.setStream(is);
1192 return readFile(tmplex);
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 int Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2205 string const & latexname) const
2207 if (!latexname.empty() && latexname != "!-- --") {
2209 os << string(" ",depth);
2210 os << "<" << latexname << ">";
2220 int Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2221 string const & latexname) const
2223 if (!latexname.empty() && latexname != "!-- --") {
2225 os << endl << string(" ",depth);
2226 os << "</" << latexname << ">";
2236 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2238 ofstream ofs(fname.c_str());
2241 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2245 niceFile = nice; // this will be used by included files.
2247 LaTeXFeatures features(params);
2253 LyXTextClass const & tclass = params.getLyXTextClass();
2255 string top_element = tclass.latexname();
2258 ofs << "<!doctype linuxdoc system";
2260 string preamble = params.preamble;
2261 const string name = nice ? ChangeExtension(filename_, ".sgml")
2263 preamble += features.getIncludedFiles(name);
2264 preamble += features.getLyXSGMLEntities();
2266 if (!preamble.empty()) {
2267 ofs << " [ " << preamble << " ]";
2271 if (params.options.empty())
2272 sgmlOpenTag(ofs, 0, false, top_element);
2274 string top = top_element;
2276 top += params.options;
2277 sgmlOpenTag(ofs, 0, false, top);
2281 ofs << "<!-- " << lyx_docversion
2282 << " created this file. For more info see http://www.lyx.org/"
2285 Paragraph::depth_type depth = 0; // paragraph depth
2286 Paragraph * par = &*(paragraphs.begin());
2288 vector<string> environment_stack(5);
2291 LyXLayout_ptr const & style = par->layout();
2292 // treat <toc> as a special case for compatibility with old code
2293 if (par->isInset(0)) {
2294 Inset * inset = par->getInset(0);
2295 Inset::Code lyx_code = inset->lyxCode();
2296 if (lyx_code == Inset::TOC_CODE) {
2297 string const temp = "toc";
2298 sgmlOpenTag(ofs, depth, false, temp);
2305 // environment tag closing
2306 for (; depth > par->params().depth(); --depth) {
2307 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2308 environment_stack[depth].erase();
2311 // write opening SGML tags
2312 switch (style->latextype) {
2313 case LATEX_PARAGRAPH:
2314 if (depth == par->params().depth()
2315 && !environment_stack[depth].empty()) {
2316 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2317 environment_stack[depth].erase();
2323 sgmlOpenTag(ofs, depth, false, style->latexname());
2329 _("Error : Wrong depth for"
2330 " LatexType Command.\n"));
2332 if (!environment_stack[depth].empty()) {
2333 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2337 environment_stack[depth].erase();
2338 sgmlOpenTag(ofs, depth, false, style->latexname());
2341 case LATEX_ENVIRONMENT:
2342 case LATEX_ITEM_ENVIRONMENT:
2344 string const & latexname = style->latexname();
2346 if (depth == par->params().depth()
2347 && environment_stack[depth] != latexname) {
2348 sgmlCloseTag(ofs, depth, false,
2349 environment_stack[depth]);
2350 environment_stack[depth].erase();
2352 if (depth < par->params().depth()) {
2353 depth = par->params().depth();
2354 environment_stack[depth].erase();
2356 if (environment_stack[depth] != latexname) {
2358 sgmlOpenTag(ofs, depth, false, "p");
2360 sgmlOpenTag(ofs, depth, false, latexname);
2362 if (environment_stack.size() == depth + 1)
2363 environment_stack.push_back("!-- --");
2364 environment_stack[depth] = latexname;
2367 if (style->latexparam() == "CDATA")
2370 if (style->latextype == LATEX_ENVIRONMENT) break;
2372 if (style->labeltype == LABEL_MANUAL)
2377 sgmlOpenTag(ofs, depth + 1, false, item_name);
2382 sgmlOpenTag(ofs, depth, false, style->latexname());
2386 simpleLinuxDocOnePar(ofs, par, depth);
2391 // write closing SGML tags
2392 switch (style->latextype) {
2395 case LATEX_ENVIRONMENT:
2396 case LATEX_ITEM_ENVIRONMENT:
2397 if (style->latexparam() == "CDATA")
2401 sgmlCloseTag(ofs, depth, false, style->latexname());
2407 for (int i = depth; i >= 0; --i)
2408 sgmlCloseTag(ofs, depth, false, environment_stack[i]);
2412 sgmlCloseTag(ofs, 0, false, top_element);
2416 // How to check for successful close
2418 // we want this to be true outside previews (for insetexternal)
2423 // checks, if newcol chars should be put into this line
2424 // writes newline, if necessary.
2427 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2428 string::size_type newcol)
2431 if (colcount > lyxrc.ascii_linelen) {
2433 colcount = newcol; // assume write after this call
2448 string tag_name(PAR_TAG const & pt) {
2450 case NONE: return "!-- --";
2451 case TT: return "tt";
2452 case SF: return "sf";
2453 case BF: return "bf";
2454 case IT: return "it";
2455 case SL: return "sl";
2456 case EM: return "em";
2463 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2465 p1 = static_cast<PAR_TAG>(p1 | p2);
2470 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2472 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2478 // Handle internal paragraph parsing -- layout already processed.
2479 void Buffer::simpleLinuxDocOnePar(ostream & os,
2481 Paragraph::depth_type /*depth*/)
2483 LyXLayout_ptr const & style = par->layout();
2485 string::size_type char_line_count = 5; // Heuristic choice ;-)
2487 // gets paragraph main font
2490 if (style->labeltype == LABEL_MANUAL) {
2491 font_old = style->labelfont;
2494 font_old = style->font;
2498 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2499 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2500 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2503 stack<PAR_TAG> tag_state;
2504 // parsing main loop
2505 for (pos_type i = 0; i < par->size(); ++i) {
2507 PAR_TAG tag_close = NONE;
2508 list < PAR_TAG > tag_open;
2510 LyXFont const font = par->getFont(params, i);
2512 if (font_old.family() != font.family()) {
2513 switch (family_type) {
2514 case LyXFont::SANS_FAMILY:
2517 case LyXFont::TYPEWRITER_FAMILY:
2524 family_type = font.family();
2526 switch (family_type) {
2527 case LyXFont::SANS_FAMILY:
2528 tag_open.push_back(SF);
2530 case LyXFont::TYPEWRITER_FAMILY:
2531 tag_open.push_back(TT);
2538 if (font_old.series() != font.series()) {
2539 switch (series_type) {
2540 case LyXFont::BOLD_SERIES:
2547 series_type = font.series();
2549 switch (series_type) {
2550 case LyXFont::BOLD_SERIES:
2551 tag_open.push_back(BF);
2559 if (font_old.shape() != font.shape()) {
2560 switch (shape_type) {
2561 case LyXFont::ITALIC_SHAPE:
2564 case LyXFont::SLANTED_SHAPE:
2571 shape_type = font.shape();
2573 switch (shape_type) {
2574 case LyXFont::ITALIC_SHAPE:
2575 tag_open.push_back(IT);
2577 case LyXFont::SLANTED_SHAPE:
2578 tag_open.push_back(SL);
2585 if (font_old.emph() != font.emph()) {
2586 if (font.emph() == LyXFont::ON) {
2587 tag_open.push_back(EM);
2596 list < PAR_TAG > temp;
2597 while (!tag_state.empty() && tag_close) {
2598 PAR_TAG k = tag_state.top();
2600 os << "</" << tag_name(k) << ">";
2607 for(list< PAR_TAG >::const_iterator j = temp.begin();
2608 j != temp.end(); ++j) {
2610 os << "<" << tag_name(*j) << ">";
2613 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2614 j != tag_open.end(); ++j) {
2616 os << "<" << tag_name(*j) << ">";
2619 char c = par->getChar(i);
2621 if (c == Paragraph::META_INSET) {
2622 Inset * inset = par->getInset(i);
2623 inset->linuxdoc(this, os);
2628 if (style->latexparam() == "CDATA") {
2629 // "TeX"-Mode on == > SGML-Mode on.
2636 boost::tie(ws, str) = sgml::escapeChar(c);
2637 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2638 // in freespacing mode, spaces are
2639 // non-breaking characters
2640 if (desc_on) {// if char is ' ' then...
2643 sgmlLineBreak(os, char_line_count, 6);
2647 sgmlLineBreak(os, char_line_count, 1);
2652 char_line_count += str.length();
2658 while (!tag_state.empty()) {
2659 os << "</" << tag_name(tag_state.top()) << ">";
2663 // resets description flag correctly
2665 // <tag> not closed...
2666 sgmlLineBreak(os, char_line_count, 6);
2672 // Print an error message.
2673 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2674 string const & /*message*/) const
2676 #ifdef WITH_WARNINGS
2677 #warning This is wrong we cannot insert an inset like this!!!
2678 // I guess this was Jose' so I explain you more or less why this
2679 // is wrong. This way you insert something in the paragraph and
2680 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2681 // I deactivate this code, have a look at BufferView::insertErrors
2682 // how you should do this correctly! (Jug 20020315)
2685 // insert an error marker in text
2686 InsetError * new_inset = new InsetError(message);
2687 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2693 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2695 ofstream ofs(fname.c_str());
2697 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2701 Paragraph * par = &*(paragraphs.begin());
2703 niceFile = nice; // this will be used by Insetincludes.
2705 LaTeXFeatures features(params);
2710 LyXTextClass const & tclass = params.getLyXTextClass();
2711 string top_element = tclass.latexname();
2714 ofs << "<!DOCTYPE " << top_element
2715 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2717 string preamble = params.preamble;
2718 const string name = nice ? ChangeExtension(filename_, ".sgml")
2720 preamble += features.getIncludedFiles(name);
2721 preamble += features.getLyXSGMLEntities();
2723 if (!preamble.empty()) {
2724 ofs << "\n [ " << preamble << " ]";
2729 string top = top_element;
2731 top += params.language->code();
2734 if (!params.options.empty()) {
2736 top += params.options;
2738 sgmlOpenTag(ofs, 0, false, top);
2740 ofs << "<!-- DocBook file was created by " << lyx_docversion
2741 << "\n See http://www.lyx.org/ for more information -->\n";
2743 vector<string> environment_stack(10);
2744 vector<string> environment_inner(10);
2745 vector<string> command_stack(10);
2747 bool command_flag = false;
2748 Paragraph::depth_type command_depth = 0;
2749 Paragraph::depth_type command_base = 0;
2750 Paragraph::depth_type cmd_depth = 0;
2751 Paragraph::depth_type depth = 0; // paragraph depth
2754 string command_name;
2760 int desc_on = 0; // description mode
2762 LyXLayout_ptr const & style = par->layout();
2764 // environment tag closing
2765 for (; depth > par->params().depth(); --depth) {
2766 if (environment_inner[depth] != "!-- --") {
2767 item_name = "listitem";
2768 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2769 if (environment_inner[depth] == "varlistentry")
2770 sgmlCloseTag(ofs, depth+command_depth, false, environment_inner[depth]);
2772 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2773 environment_stack[depth].erase();
2774 environment_inner[depth].erase();
2777 if (depth == par->params().depth()
2778 && environment_stack[depth] != style->latexname()
2779 && !environment_stack[depth].empty()) {
2780 if (environment_inner[depth] != "!-- --") {
2781 item_name= "listitem";
2782 sgmlCloseTag(ofs, command_depth+depth, false, item_name);
2783 if (environment_inner[depth] == "varlistentry")
2784 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2787 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2789 environment_stack[depth].erase();
2790 environment_inner[depth].erase();
2793 // Write opening SGML tags.
2794 switch (style->latextype) {
2795 case LATEX_PARAGRAPH:
2796 sgmlOpenTag(ofs, depth + command_depth,
2797 false, style->latexname());
2803 _("Error : Wrong depth for "
2804 "LatexType Command.\n"));
2806 command_name = style->latexname();
2808 sgmlparam = style->latexparam();
2809 c_params = split(sgmlparam, c_depth,'|');
2811 cmd_depth = lyx::atoi(c_depth);
2814 if (cmd_depth < command_base) {
2815 for (Paragraph::depth_type j = command_depth;
2816 j >= command_base; --j) {
2817 sgmlCloseTag(ofs, j, false, command_stack[j]);
2820 command_depth = command_base = cmd_depth;
2821 } else if (cmd_depth <= command_depth) {
2822 for (int j = command_depth;
2823 j >= int(cmd_depth); --j) {
2824 sgmlCloseTag(ofs, j, false, command_stack[j]);
2827 command_depth = cmd_depth;
2829 command_depth = cmd_depth;
2831 command_depth = command_base = cmd_depth;
2832 command_flag = true;
2834 if (command_stack.size() == command_depth + 1)
2835 command_stack.push_back(string());
2836 command_stack[command_depth] = command_name;
2838 // treat label as a special case for
2839 // more WYSIWYM handling.
2840 // This is a hack while paragraphs can't have
2841 // attributes, like id in this case.
2842 if (par->isInset(0)) {
2843 Inset * inset = par->getInset(0);
2844 Inset::Code lyx_code = inset->lyxCode();
2845 if (lyx_code == Inset::LABEL_CODE) {
2846 command_name += " id=\"";
2847 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2848 command_name += "\"";
2853 sgmlOpenTag(ofs, depth + command_depth, false, command_name);
2855 item_name = c_params.empty()?"title":c_params;
2856 sgmlOpenTag(ofs, depth + 1 + command_depth, false, item_name);
2859 case LATEX_ENVIRONMENT:
2860 case LATEX_ITEM_ENVIRONMENT:
2861 if (depth < par->params().depth()) {
2862 depth = par->params().depth();
2863 environment_stack[depth].erase();
2866 if (environment_stack[depth] != style->latexname()) {
2867 if (environment_stack.size() == depth + 1) {
2868 environment_stack.push_back("!-- --");
2869 environment_inner.push_back("!-- --");
2871 environment_stack[depth] = style->latexname();
2872 environment_inner[depth] = "!-- --";
2873 sgmlOpenTag(ofs, depth + command_depth, false, environment_stack[depth]);
2875 if (environment_inner[depth] != "!-- --") {
2876 item_name= "listitem";
2877 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2878 if (environment_inner[depth] == "varlistentry")
2879 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2883 if (style->latextype == LATEX_ENVIRONMENT) {
2884 if (!style->latexparam().empty()) {
2885 if (style->latexparam() == "CDATA")
2888 sgmlOpenTag(ofs, depth + command_depth, false, style->latexparam());
2893 desc_on = (style->labeltype == LABEL_MANUAL);
2895 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2896 sgmlOpenTag(ofs, depth + 1 + command_depth,
2897 false, environment_inner[depth]);
2899 item_name = desc_on ? "term" : "para";
2900 sgmlOpenTag(ofs, depth + 1 + command_depth,
2904 sgmlOpenTag(ofs, depth + command_depth,
2905 false, style->latexname());
2909 simpleDocBookOnePar(ofs, par, desc_on,
2910 depth + 1 + command_depth);
2914 // write closing SGML tags
2915 switch (style->latextype) {
2917 end_tag = c_params.empty() ? "title" : c_params;
2918 sgmlCloseTag(ofs, depth + command_depth,
2921 case LATEX_ENVIRONMENT:
2922 if (!style->latexparam().empty()) {
2923 if (style->latexparam() == "CDATA")
2926 sgmlCloseTag(ofs, depth + command_depth, false, style->latexparam());
2929 case LATEX_ITEM_ENVIRONMENT:
2930 if (desc_on == 1) break;
2932 sgmlCloseTag(ofs, depth + 1 + command_depth, false, end_tag);
2934 case LATEX_PARAGRAPH:
2935 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2938 sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2944 for (int d = depth; d >= 0; --d) {
2945 if (!environment_stack[depth].empty()) {
2946 if (environment_inner[depth] != "!-- --") {
2947 item_name = "listitem";
2948 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2949 if (environment_inner[depth] == "varlistentry")
2950 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2953 sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2957 for (int j = command_depth; j >= 0 ; --j)
2958 if (!command_stack[j].empty()) {
2959 sgmlCloseTag(ofs, j, false, command_stack[j]);
2964 sgmlCloseTag(ofs, 0, false, top_element);
2967 // How to check for successful close
2969 // we want this to be true outside previews (for insetexternal)
2974 void Buffer::simpleDocBookOnePar(ostream & os,
2975 Paragraph * par, int & desc_on,
2976 Paragraph::depth_type depth) const
2978 bool emph_flag = false;
2980 LyXLayout_ptr const & style = par->layout();
2982 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2984 int char_line_count = depth;
2985 //if (!style.free_spacing)
2986 // os << string(depth,' ');
2988 // parsing main loop
2989 for (pos_type i = 0; i < par->size(); ++i) {
2990 LyXFont font = par->getFont(params, i);
2992 // handle <emphasis> tag
2993 if (font_old.emph() != font.emph()) {
2994 if (font.emph() == LyXFont::ON) {
2995 if (style->latexparam() == "CDATA")
2998 if (style->latexparam() == "CDATA")
3002 if (style->latexparam() == "CDATA")
3004 os << "</emphasis>";
3005 if (style->latexparam() == "CDATA")
3012 if (par->isInset(i)) {
3013 Inset * inset = par->getInset(i);
3014 // don't print the inset in position 0 if desc_on == 3 (label)
3015 if (i || desc_on != 3) {
3016 if (style->latexparam() == "CDATA")
3018 inset->docbook(this, os, false);
3019 if (style->latexparam() == "CDATA")
3023 char c = par->getChar(i);
3026 boost::tie(ws, str) = sgml::escapeChar(c);
3028 if (style->pass_thru) {
3030 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3032 } else if (desc_on ==1) {
3034 os << "\n</term><listitem><para>";
3044 if (style->latexparam() == "CDATA")
3046 os << "</emphasis>";
3047 if (style->latexparam() == "CDATA")
3051 // resets description flag correctly
3053 // <term> not closed...
3054 os << "</term>\n<listitem><para> </para>";
3056 if (style->free_spacing)
3061 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3062 // Other flags: -wall -v0 -x
3063 int Buffer::runChktex()
3065 if (!users->text) return 0;
3067 users->owner()->prohibitInput();
3069 // get LaTeX-Filename
3070 string const name = getLatexName();
3071 string path = filePath();
3073 string const org_path = path;
3074 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3078 Path p(path); // path to LaTeX file
3079 users->owner()->message(_("Running chktex..."));
3081 // Remove all error insets
3082 bool const removedErrorInsets = users->removeAutoInsets();
3084 // Generate the LaTeX file if neccessary
3085 makeLaTeXFile(name, org_path, false);
3088 Chktex chktex(lyxrc.chktex_command, name, filePath());
3089 int res = chktex.run(terr); // run chktex
3092 Alert::alert(_("chktex did not work!"),
3093 _("Could not run with file:"), name);
3094 } else if (res > 0) {
3095 // Insert all errors as errors boxes
3096 users->insertErrors(terr);
3099 // if we removed error insets before we ran chktex or if we inserted
3100 // error insets after we ran chktex, this must be run:
3101 if (removedErrorInsets || res) {
3102 #warning repaint needed here, or do you mean update() ?
3106 users->owner()->allowInput();
3112 void Buffer::validate(LaTeXFeatures & features) const
3114 LyXTextClass const & tclass = params.getLyXTextClass();
3116 // AMS Style is at document level
3117 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3118 features.require("amsmath");
3120 for_each(paragraphs.begin(), paragraphs.end(),
3121 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3123 // the bullet shapes are buffer level not paragraph level
3124 // so they are tested here
3125 for (int i = 0; i < 4; ++i) {
3126 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3127 int const font = params.user_defined_bullets[i].getFont();
3129 int const c = params
3130 .user_defined_bullets[i]
3137 features.require("latexsym");
3139 } else if (font == 1) {
3140 features.require("amssymb");
3141 } else if ((font >= 2 && font <= 5)) {
3142 features.require("pifont");
3147 if (lyxerr.debugging(Debug::LATEX)) {
3148 features.showStruct();
3153 // This function should be in Buffer because it's a buffer's property (ale)
3154 string const Buffer::getIncludeonlyList(char delim)
3157 for (inset_iterator it = inset_iterator_begin();
3158 it != inset_iterator_end(); ++it) {
3159 if (it->lyxCode() == Inset::INCLUDE_CODE) {
3160 InsetInclude & inc = static_cast<InsetInclude &>(*it);
3161 if (inc.isIncludeOnly()) {
3164 lst += inc.getRelFileBaseName();
3168 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3173 vector<string> const Buffer::getLabelList() const
3175 /// if this is a child document and the parent is already loaded
3176 /// Use the parent's list instead [ale990407]
3177 if (!params.parentname.empty()
3178 && bufferlist.exists(params.parentname)) {
3179 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3181 return tmp->getLabelList();
3184 vector<string> label_list;
3185 for (inset_iterator it = inset_const_iterator_begin();
3186 it != inset_const_iterator_end(); ++it) {
3187 vector<string> const l = it->getLabelList();
3188 label_list.insert(label_list.end(), l.begin(), l.end());
3194 // This is also a buffer property (ale)
3195 vector<pair<string, string> > const Buffer::getBibkeyList() const
3197 typedef pair<string, string> StringPair;
3198 /// if this is a child document and the parent is already loaded
3199 /// Use the parent's list instead [ale990412]
3200 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3201 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3203 return tmp->getBibkeyList();
3206 vector<StringPair> keys;
3207 ParagraphList::iterator pit = paragraphs.begin();
3208 ParagraphList::iterator pend = paragraphs.end();
3209 for (; pit != pend; ++pit) {
3211 string const key = pit->bibkey->getContents();
3212 string const opt = pit->bibkey->getOptions();
3213 string const ref = pit->asString(this, false);
3214 string const info = opt + "TheBibliographyRef" + ref;
3216 keys.push_back(StringPair(key, info));
3220 // Might be either using bibtex or a child has bibliography
3222 for (inset_iterator it = inset_const_iterator_begin();
3223 it != inset_const_iterator_end(); ++it) {
3224 // Search for Bibtex or Include inset
3225 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3226 vector<StringPair> tmp =
3227 static_cast<InsetBibtex &>(*it).getKeys(this);
3228 keys.insert(keys.end(), tmp.begin(), tmp.end());
3229 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3230 vector<StringPair> const tmp =
3231 static_cast<InsetInclude &>(*it).getKeys();
3232 keys.insert(keys.end(), tmp.begin(), tmp.end());
3241 bool Buffer::isDepClean(string const & name) const
3243 DEPCLEAN * item = dep_clean;
3244 while (item && item->master != name)
3246 if (!item) return true;
3251 void Buffer::markDepClean(string const & name)
3254 dep_clean = new DEPCLEAN;
3255 dep_clean->clean = true;
3256 dep_clean->master = name;
3257 dep_clean->next = 0;
3259 DEPCLEAN * item = dep_clean;
3260 while (item && item->master != name)
3265 item = new DEPCLEAN;
3267 item->master = name;
3274 bool Buffer::dispatch(string const & command, bool * result)
3276 // Split command string into command and argument
3278 string line = ltrim(command);
3279 string const arg = trim(split(line, cmd, ' '));
3281 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3285 bool Buffer::dispatch(int action, string const & argument, bool * result)
3287 bool dispatched = true;
3291 bool const tmp = Exporter::Export(this, argument, false);
3304 void Buffer::resizeInsets(BufferView * bv)
3306 /// then remove all LyXText in text-insets
3307 for_each(paragraphs.begin(), paragraphs.end(),
3308 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3312 void Buffer::redraw()
3314 #warning repaint needed here, or do you mean update() ?
3320 void Buffer::changeLanguage(Language const * from, Language const * to)
3323 ParIterator end = par_iterator_end();
3324 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3325 (*it)->changeLanguage(params, from, to);
3329 bool Buffer::isMultiLingual()
3331 ParIterator end = par_iterator_end();
3332 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3333 if ((*it)->isMultiLingual(params))
3340 Counters & Buffer::counters() const
3346 void Buffer::inset_iterator::setParagraph()
3348 while (pit != pend) {
3349 it = pit->insetlist.begin();
3350 if (it != pit->insetlist.end())
3357 Inset * Buffer::getInsetFromID(int id_arg) const
3359 for (inset_iterator it = inset_const_iterator_begin();
3360 it != inset_const_iterator_end(); ++it)
3362 if (it->id() == id_arg)
3364 Inset * in = it->getInsetFromID(id_arg);
3372 Paragraph * Buffer::getParFromID(int id) const
3377 ParagraphList::iterator it = paragraphs.begin();
3378 ParagraphList::iterator end = paragraphs.end();
3379 for (; it != end; ++it) {
3380 if (it->id() == id) {
3383 Paragraph * tmp = it->getParFromID(id);
3392 ParIterator Buffer::par_iterator_begin()
3394 return ParIterator(&*(paragraphs.begin()));
3398 ParIterator Buffer::par_iterator_end()
3400 return ParIterator();
3404 void Buffer::addUser(BufferView * u)
3410 void Buffer::delUser(BufferView *)
3416 Language const * Buffer::getLanguage() const
3418 return params.language;
3422 bool Buffer::isClean() const
3428 bool Buffer::isBakClean() const
3434 void Buffer::markClean() const
3440 // if the .lyx file has been saved, we don't need an
3446 void Buffer::markBakClean()
3452 void Buffer::setUnnamed(bool flag)
3458 bool Buffer::isUnnamed()
3464 void Buffer::markDirty()
3471 DEPCLEAN * tmp = dep_clean;
3479 string const & Buffer::fileName() const
3485 string const & Buffer::filePath() const
3491 bool Buffer::isReadonly() const
3497 BufferView * Buffer::getUser() const
3503 void Buffer::setParentName(string const & name)
3505 params.parentname = name;
3509 Buffer::inset_iterator::inset_iterator()
3514 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3521 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3525 if (it == pit->insetlist.end()) {
3534 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3536 inset_iterator tmp = *this;
3542 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3544 return *it.getInset();
3548 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3550 return it.getInset();
3554 Paragraph * Buffer::inset_iterator::getPar()
3560 lyx::pos_type Buffer::inset_iterator::getPos() const
3566 bool operator==(Buffer::inset_iterator const & iter1,
3567 Buffer::inset_iterator const & iter2)
3569 return iter1.pit == iter2.pit
3570 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3574 bool operator!=(Buffer::inset_iterator const & iter1,
3575 Buffer::inset_iterator const & iter2)
3577 return !(iter1 == iter2);