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 #include "bufferlist.h"
19 #include "LyXAction.h"
22 #include "tex-strings.h"
24 #include "bufferview_funcs.h"
30 #include "LaTeXFeatures.h"
37 #include "BufferView.h"
38 #include "ParagraphParameters.h"
39 #include "iterators.h"
40 #include "lyxtextclasslist.h"
42 #include "paragraph_funcs.h"
45 #include "frontends/LyXView.h"
47 #include "mathed/formulamacro.h"
48 #include "mathed/formula.h"
50 #include "insets/inset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insethfill.h"
53 #include "insets/insetlabel.h"
54 #include "insets/insetref.h"
55 #include "insets/inseturl.h"
56 #include "insets/insetnote.h"
57 #include "insets/insetquotes.h"
58 #include "insets/insetlatexaccent.h"
59 #include "insets/insetbibitem.h"
60 #include "insets/insetbibtex.h"
61 #include "insets/insetcite.h"
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h"
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/insettext.h"
69 #include "insets/insetert.h"
70 #include "insets/insetgraphics.h"
71 #include "insets/insetfoot.h"
72 #include "insets/insetmarginal.h"
73 #include "insets/insetoptarg.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insetwrap.h"
77 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
85 #include "frontends/Dialogs.h"
86 #include "frontends/Alert.h"
88 #include "graphics/Previews.h"
90 #include "support/textutils.h"
91 #include "support/filetools.h"
92 #include "support/path.h"
93 #include "support/os.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
97 #include "support/lyxtime.h"
99 #include <boost/bind.hpp>
100 #include <boost/tuple/tuple.hpp>
101 #include "BoostFormat.h"
113 #include <sys/types.h>
120 #ifndef CXX_GLOBAL_CSTD
132 using std::make_pair;
140 using lyx::textclass_type;
142 // all these externs should eventually be removed.
143 extern BufferList bufferlist;
147 const int LYX_FORMAT = 222;
151 Buffer::Buffer(string const & file, bool ronly)
152 : niceFile(true), lyx_clean(true), bak_clean(true),
153 unnamed(false), read_only(ronly),
154 filename_(file), users(0)
156 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
157 filepath_ = OnlyPath(file);
159 if (read_only || lyxrc.use_tempdir) {
160 tmppath = CreateBufferTmpDir();
165 // set initial author
166 authors().record(Author(lyxrc.user_name, lyxrc.user_email));
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 AuthorList & Buffer::authors()
249 return params.authorlist;
253 /// Update window titles of all users
254 // Should work on a list
255 void Buffer::updateTitles() const
258 users->owner()->updateWindowTitle();
262 /// Reset autosave timer of all users
263 // Should work on a list
264 void Buffer::resetAutosaveTimers() const
267 users->owner()->resetAutosaveTimer();
271 void Buffer::setFileName(string const & newfile)
273 filename_ = MakeAbsPath(newfile);
274 filepath_ = OnlyPath(filename_);
275 setReadonly(IsFileWriteable(filename_) == 0);
280 // We'll remove this later. (Lgb)
284 #warning this is never set to != 0 !!! - remove ?
288 void unknownClass(string const & unknown)
292 boost::io::str(boost::format(
293 _("The document uses an unknown textclass \"%1$s\".")) % unknown)
294 + _("-- substituting default.");
296 _("The document uses an unknown textclass ")
297 + unknown + _("-- substituting default.");
299 Alert::alert(_("Textclass error"), msg);
304 int Buffer::readHeader(LyXLex & lex)
306 int unknown_tokens = 0;
310 string const token = lex.getString();
315 if (token == "\\end_header")
318 lyxerr[Debug::PARSER] << "Handling header token: `"
319 << token << '\'' << endl;
321 string unknown = params.readToken(lex, token);
322 if (!unknown.empty()) {
323 if (unknown[0] != '\\') {
324 unknownClass(unknown);
330 return unknown_tokens;
334 // candidate for move to BufferView
335 // (at least some parts in the beginning of the func)
338 // changed to be public and have one parameter
339 // if par = 0 normal behavior
340 // else insert behavior
341 // Returns false if "\the_end" is not read (Asger)
342 bool Buffer::readBody(LyXLex & lex, Paragraph * par)
345 int unknown_tokens = 0;
348 Paragraph::depth_type depth = 0;
349 bool the_end_read = false;
351 Paragraph * first_par = 0;
352 LyXFont font(LyXFont::ALL_INHERIT, params.language);
357 par->layout(params.getLyXTextClass().defaultLayout());
358 // mark the first paragraph
359 if (params.tracking_changes)
362 unknown_tokens += readHeader(lex);
364 if (!params.getLyXTextClass().load()) {
366 Alert::alert(_("Textclass Loading Error!"),
367 boost::io::str(boost::format(_("Can't load textclass %1$s")) %
368 params.getLyXTextClass().name()),
369 _("-- substituting default."));
371 Alert::alert(_("Textclass Loading Error!"),
372 _("Can't load textclass ")
373 + params.getLyXTextClass().name(),
374 _("-- substituting default."));
376 params.textclass = 0;
379 // We are inserting into an existing document
380 users->text->breakParagraph(users, paragraphs);
381 first_par = users->text->ownerParagraph();
385 // We don't want to adopt the parameters from the
386 // document we insert, so read them into a temporary buffer
387 // and then discard it
389 Buffer tmpbuf("", false);
390 tmpbuf.readHeader(lex);
395 string const token = lex.getString();
400 lyxerr[Debug::PARSER] << "Handling token: `"
401 << token << '\'' << endl;
403 if (token == "\\the_end") {
408 unknown_tokens += readToken(lex, par, first_par,
409 token, pos, depth, font);
415 paragraphs.set(first_par);
417 if (unknown_layouts > 0) {
418 string s = _("Couldn't set the layout for ");
419 if (unknown_layouts == 1) {
420 s += _("one paragraph");
422 s += tostr(unknown_layouts);
423 s += _(" paragraphs");
426 Alert::alert(_("Textclass Loading Error!"), s,
427 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
429 Alert::alert(_("Textclass Loading Error!"), s,
430 _("When reading ") + fileName());
434 if (unknown_tokens > 0) {
435 string s = _("Encountered ");
436 if (unknown_tokens == 1) {
437 s += _("one unknown token");
439 s += tostr(unknown_tokens);
440 s += _(" unknown tokens");
443 Alert::alert(_("Textclass Loading Error!"), s,
444 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
446 Alert::alert(_("Textclass Loading Error!"), s,
447 _("When reading ") + fileName());
456 Buffer::readToken(LyXLex & lex, Paragraph *& par,
457 Paragraph *& first_par,
458 string const & token, int & pos,
459 Paragraph::depth_type & depth,
463 static Change current_change;
466 // The order of the tags tested may seem unnatural, but this
467 // has been done in order to reduce the number of string
468 // comparisons needed to recognize a given token. This leads
469 // on large documents like UserGuide to a reduction of a
471 if (token[0] != '\\') {
472 for (string::const_iterator cit = token.begin();
473 cit != token.end(); ++cit) {
474 par->insertChar(pos, (*cit), font, current_change);
477 } else if (token == "\\layout") {
478 // reset the font as we start a new layout and if the font is
479 // not ALL_INHERIT,document_language then it will be set to the
480 // right values after this tag (Jug 20020420)
481 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
484 string layoutname = lex.getString();
486 LyXTextClass const & tclass = params.getLyXTextClass();
488 if (layoutname.empty()) {
489 layoutname = tclass.defaultLayoutName();
491 bool hasLayout = tclass.hasLayout(layoutname);
493 lyxerr << "Layout '" << layoutname << "' does not"
494 << " exist in textclass '" << tclass.name()
496 lyxerr << "Trying to use default layout instead."
498 layoutname = tclass.defaultLayoutName();
502 // The is the compability reading of layout caption.
503 // It can be removed in LyX version 1.3.0. (Lgb)
504 if (compare_ascii_no_case(layoutname, "caption") == 0) {
505 // We expect that the par we are now working on is
506 // really inside a InsetText inside a InsetFloat.
507 // We also know that captions can only be
508 // one paragraph. (Lgb)
510 // We should now read until the next "\layout"
512 // This is probably not good enough, what if the
513 // caption is the last par in the document (Lgb)
514 istream & ist = lex.getStream();
520 if (prefixIs(line, "\\layout")) {
524 if (prefixIs(line, "\\begin_inset"))
526 if (prefixIs(line, "\\end_inset")) {
537 // Now we should have the whole layout in ss
538 // we should now be able to give this to the
540 ss << "\\end_inset\n";
542 // This seems like a bug in stringstream.
543 // We really should be able to use ss
545 istringstream is(ss.str());
547 tmplex.setStream(is);
548 Inset * inset = new InsetCaption;
549 inset->Read(this, tmplex);
550 par->InsertInset(pos, inset, font);
557 par = new Paragraph(par);
558 par->layout(params.getLyXTextClass().defaultLayout());
559 if (params.tracking_changes)
563 par->layout(params.getLyXTextClass()[layoutname]);
564 // Test whether the layout is obsolete.
565 LyXLayout_ptr const & layout = par->layout();
566 if (!layout->obsoleted_by().empty())
567 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
568 par->params().depth(depth);
573 } else if (token == "\\end_inset") {
574 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
575 << "Missing \\begin_inset?.\n";
576 // Simply ignore this. The insets do not have
578 // But insets should read it, it is a part of
579 // the inset isn't it? Lgb.
580 } else if (token == "\\begin_inset") {
581 readInset(lex, par, pos, font, current_change);
582 } else if (token == "\\family") {
584 font.setLyXFamily(lex.getString());
585 } else if (token == "\\series") {
587 font.setLyXSeries(lex.getString());
588 } else if (token == "\\shape") {
590 font.setLyXShape(lex.getString());
591 } else if (token == "\\size") {
593 font.setLyXSize(lex.getString());
594 } else if (token == "\\lang") {
596 string const tok = lex.getString();
597 Language const * lang = languages.getLanguage(tok);
599 font.setLanguage(lang);
601 font.setLanguage(params.language);
602 lex.printError("Unknown language `$$Token'");
604 } else if (token == "\\numeric") {
606 font.setNumber(font.setLyXMisc(lex.getString()));
607 } else if (token == "\\emph") {
609 font.setEmph(font.setLyXMisc(lex.getString()));
610 } else if (token == "\\bar") {
612 string const tok = lex.getString();
613 // This is dirty, but gone with LyX3. (Asger)
615 font.setUnderbar(LyXFont::ON);
616 else if (tok == "no")
617 font.setUnderbar(LyXFont::OFF);
618 else if (tok == "default")
619 font.setUnderbar(LyXFont::INHERIT);
621 lex.printError("Unknown bar font flag "
623 } else if (token == "\\noun") {
625 font.setNoun(font.setLyXMisc(lex.getString()));
626 } else if (token == "\\color") {
628 font.setLyXColor(lex.getString());
629 } else if (token == "\\SpecialChar") {
630 LyXLayout_ptr const & layout = par->layout();
632 // Insets don't make sense in a free-spacing context! ---Kayvan
633 if (layout->free_spacing || par->isFreeSpacing()) {
636 string const next_token = lex.getString();
637 if (next_token == "\\-") {
638 par->insertChar(pos, '-', font, current_change);
639 } else if (next_token == "~") {
640 par->insertChar(pos, ' ', font, current_change);
642 lex.printError("Token `$$Token' "
644 "paragraph layout!");
649 Inset * inset = new InsetSpecialChar;
650 inset->read(this, lex);
651 par->insertInset(pos, inset, font, current_change);
654 } else if (token == "\\i") {
655 Inset * inset = new InsetLatexAccent;
656 inset->read(this, lex);
657 par->insertInset(pos, inset, font, current_change);
659 } else if (token == "\\backslash") {
660 par->insertChar(pos, '\\', font, current_change);
662 } else if (token == "\\begin_deeper") {
664 } else if (token == "\\end_deeper") {
666 lex.printError("\\end_deeper: "
667 "depth is already null");
671 } else if (token == "\\noindent") {
672 par->params().noindent(true);
673 } else if (token == "\\leftindent") {
675 LyXLength value(lex.getString());
676 par->params().leftIndent(value);
677 } else if (token == "\\fill_top") {
678 par->params().spaceTop(VSpace(VSpace::VFILL));
679 } else if (token == "\\fill_bottom") {
680 par->params().spaceBottom(VSpace(VSpace::VFILL));
681 } else if (token == "\\line_top") {
682 par->params().lineTop(true);
683 } else if (token == "\\line_bottom") {
684 par->params().lineBottom(true);
685 } else if (token == "\\pagebreak_top") {
686 par->params().pagebreakTop(true);
687 } else if (token == "\\pagebreak_bottom") {
688 par->params().pagebreakBottom(true);
689 } else if (token == "\\start_of_appendix") {
690 par->params().startOfAppendix(true);
691 } else if (token == "\\paragraph_spacing") {
693 string const tmp = rtrim(lex.getString());
694 if (tmp == "single") {
695 par->params().spacing(Spacing(Spacing::Single));
696 } else if (tmp == "onehalf") {
697 par->params().spacing(Spacing(Spacing::Onehalf));
698 } else if (tmp == "double") {
699 par->params().spacing(Spacing(Spacing::Double));
700 } else if (tmp == "other") {
702 par->params().spacing(Spacing(Spacing::Other,
705 lex.printError("Unknown spacing token: '$$Token'");
707 } else if (token == "\\align") {
708 int tmpret = lex.findToken(string_align);
711 int const tmpret2 = int(pow(2.0, tmpret));
712 par->params().align(LyXAlignment(tmpret2));
713 } else if (token == "\\added_space_top") {
715 VSpace value = VSpace(lex.getString());
716 // only add the length when value > 0 or
718 if ((value.length().len().value() != 0) ||
720 (value.kind() != VSpace::LENGTH))
721 par->params().spaceTop(value);
722 } else if (token == "\\added_space_bottom") {
724 VSpace value = VSpace(lex.getString());
725 // only add the length when value > 0 or
727 if ((value.length().len().value() != 0) ||
729 (value.kind() != VSpace::LENGTH))
730 par->params().spaceBottom(value);
731 } else if (token == "\\labelwidthstring") {
733 par->params().labelWidthString(lex.getString());
734 // do not delete this token, it is still needed!
735 } else if (token == "\\newline") {
736 par->insertChar(pos, Paragraph::META_NEWLINE, font, current_change);
738 } else if (token == "\\LyXTable") {
739 Inset * inset = new InsetTabular(*this);
740 inset->read(this, lex);
741 par->insertInset(pos, inset, font, current_change);
743 } else if (token == "\\bibitem") { // ale970302
744 InsetCommandParams p("bibitem", "dummy");
745 InsetBibitem * inset = new InsetBibitem(p);
746 inset->read(this, lex);
747 par->insertInset(pos, inset, font, current_change);
749 } else if (token == "\\hfill") {
750 par->insertInset(pos, new InsetHFill(),
751 LyXFont(LyXFont::ALL_INHERIT, params.language));
753 } else if (token == "\\change_unchanged") {
754 // Hack ! Needed for empty paragraphs :/
757 current_change = Change(Change::UNCHANGED);
758 } else if (token == "\\change_inserted") {
760 istringstream istr(lex.getString());
765 current_change = Change(Change::INSERTED, params.author_ids[aid], ct);
766 } else if (token == "\\change_deleted") {
768 istringstream istr(lex.getString());
773 current_change = Change(Change::DELETED, params.author_ids[aid], ct);
775 // This should be insurance for the future: (Asger)
779 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
780 fmt % token % lex.text();
781 string const s = fmt.str();
783 string const s = _("Unknown token: ") + token
784 + ' ' + lex.text() + '\n';
786 // we can do this here this way because we're actually reading
787 // the buffer and don't care about LyXText right now.
788 InsetError * new_inset = new InsetError(s);
789 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
798 // needed to insert the selection
799 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
800 LyXFont const & fn,string const & str)
802 LyXLayout_ptr const & layout = par->layout();
806 par->checkInsertChar(font);
807 // insert the string, don't insert doublespace
808 bool space_inserted = true;
809 bool autobreakrows = !par->inInset() ||
810 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
811 for(string::const_iterator cit = str.begin();
812 cit != str.end(); ++cit) {
814 if (autobreakrows && (!par->empty() || layout->keepempty)) {
815 breakParagraph(params, paragraphs, par, pos,
816 layout->isEnvironment());
819 space_inserted = true;
823 // do not insert consecutive spaces if !free_spacing
824 } else if ((*cit == ' ' || *cit == '\t') &&
825 space_inserted && !layout->free_spacing &&
826 !par->isFreeSpacing())
829 } else if (*cit == '\t') {
830 if (!layout->free_spacing && !par->isFreeSpacing()) {
831 // tabs are like spaces here
832 par->insertChar(pos, ' ', font);
834 space_inserted = true;
836 const pos_type nb = 8 - pos % 8;
837 for (pos_type a = 0; a < nb ; ++a) {
838 par->insertChar(pos, ' ', font);
841 space_inserted = true;
843 } else if (!IsPrintable(*cit)) {
844 // Ignore unprintables
847 // just insert the character
848 par->insertChar(pos, *cit, font);
850 space_inserted = (*cit == ' ');
857 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
858 int & pos, LyXFont & font, Change current_change)
861 if (lex.getString() != "\\begin_inset") {
862 lyxerr << "Buffer::readInset: Consistency check failed."
869 string const tmptok = lex.getString();
871 // test the different insets
872 if (tmptok == "LatexCommand") {
873 InsetCommandParams inscmd;
876 string const cmdName = inscmd.getCmdName();
878 // This strange command allows LyX to recognize "natbib" style
879 // citations: citet, citep, Citet etc.
880 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
881 inset = new InsetCitation(inscmd);
882 } else if (cmdName == "bibitem") {
883 lex.printError("Wrong place for bibitem");
884 inset = new InsetBibitem(inscmd);
885 } else if (cmdName == "BibTeX") {
886 inset = new InsetBibtex(inscmd);
887 } else if (cmdName == "index") {
888 inset = new InsetIndex(inscmd);
889 } else if (cmdName == "include") {
890 inset = new InsetInclude(inscmd, *this);
891 } else if (cmdName == "label") {
892 inset = new InsetLabel(inscmd);
893 } else if (cmdName == "url"
894 || cmdName == "htmlurl") {
895 inset = new InsetUrl(inscmd);
896 } else if (cmdName == "ref"
897 || cmdName == "pageref"
899 || cmdName == "vpageref"
900 || cmdName == "prettyref") {
901 if (!inscmd.getOptions().empty()
902 || !inscmd.getContents().empty()) {
903 inset = new InsetRef(inscmd, *this);
905 } else if (cmdName == "tableofcontents") {
906 inset = new InsetTOC(inscmd);
907 } else if (cmdName == "listofalgorithms") {
908 inset = new InsetFloatList("algorithm");
909 } else if (cmdName == "listoffigures") {
910 inset = new InsetFloatList("figure");
911 } else if (cmdName == "listoftables") {
912 inset = new InsetFloatList("table");
913 } else if (cmdName == "printindex") {
914 inset = new InsetPrintIndex(inscmd);
915 } else if (cmdName == "lyxparent") {
916 inset = new InsetParent(inscmd, *this);
919 if (tmptok == "Quotes") {
920 inset = new InsetQuotes;
921 } else if (tmptok == "External") {
922 inset = new InsetExternal;
923 } else if (tmptok == "FormulaMacro") {
924 inset = new InsetFormulaMacro;
925 } else if (tmptok == "Formula") {
926 inset = new InsetFormula;
927 } else if (tmptok == "Graphics") {
928 inset = new InsetGraphics;
929 } else if (tmptok == "Note") {
930 inset = new InsetNote(params);
931 } else if (tmptok == "Include") {
932 InsetCommandParams p("Include");
933 inset = new InsetInclude(p, *this);
934 } else if (tmptok == "ERT") {
935 inset = new InsetERT(params);
936 } else if (tmptok == "Tabular") {
937 inset = new InsetTabular(*this);
938 } else if (tmptok == "Text") {
939 inset = new InsetText(params);
940 } else if (tmptok == "Foot") {
941 inset = new InsetFoot(params);
942 } else if (tmptok == "Marginal") {
943 inset = new InsetMarginal(params);
944 } else if (tmptok == "OptArg") {
945 inset = new InsetOptArg(params);
946 } else if (tmptok == "Minipage") {
947 inset = new InsetMinipage(params);
948 } else if (tmptok == "Float") {
950 string tmptok = lex.getString();
951 inset = new InsetFloat(params, tmptok);
952 } else if (tmptok == "Wrap") {
954 string tmptok = lex.getString();
955 inset = new InsetWrap(params, tmptok);
957 } else if (tmptok == "List") {
958 inset = new InsetList;
959 } else if (tmptok == "Theorem") {
960 inset = new InsetList;
962 } else if (tmptok == "Caption") {
963 inset = new InsetCaption(params);
964 } else if (tmptok == "FloatList") {
965 inset = new InsetFloatList;
969 inset->read(this, lex);
973 par->insertInset(pos, inset, font, current_change);
979 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
983 string const token(lex.getString());
984 if (token == "\\lyxformat") { // the first token _must_ be...
986 string tmp_format = lex.getString();
987 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
988 // if present remove ".," from string.
989 string::size_type dot = tmp_format.find_first_of(".,");
990 //lyxerr << " dot found at " << dot << endl;
991 if (dot != string::npos)
992 tmp_format.erase(dot, 1);
993 file_format = strToInt(tmp_format);
994 //lyxerr << "format: " << file_format << endl;
995 if (file_format == LYX_FORMAT) {
997 } else if (file_format > LYX_FORMAT) {
999 Alert::alert(_("Warning!"),
1000 _("The file was created with a newer version of "
1001 "LyX. This is likely to cause problems."));
1003 } else if (file_format < LYX_FORMAT) {
1005 if (file_format < 200) {
1006 Alert::alert(_("ERROR!"),
1007 _("Old LyX file format found. "
1008 "Use LyX 0.10.x to read this!"));
1010 } else if (!filename.empty()) {
1012 LibFileSearch("lyx2lyx", "lyx2lyx");
1013 if (command.empty()) {
1014 Alert::alert(_("ERROR!"),
1015 _("Can't find conversion script."));
1019 +tostr(LYX_FORMAT) + ' '
1020 + QuoteName(filename);
1021 lyxerr[Debug::INFO] << "Running '"
1024 cmd_ret const ret = RunCommand(command);
1026 Alert::alert(_("ERROR!"),
1027 _("An error occured while "
1028 "running the conversion script."));
1031 istringstream is(STRCONV(ret.second));
1032 LyXLex tmplex(0, 0);
1033 tmplex.setStream(is);
1034 return readFile(tmplex, string(), par);
1036 // This code is reached if lyx2lyx failed (for
1037 // some reason) to change the file format of
1043 bool the_end = readBody(lex, par);
1044 params.setPaperStuff();
1047 Alert::alert(_("Warning!"),
1048 _("Reading of document is not complete"),
1049 _("Maybe the document is truncated"));
1052 } else { // "\\lyxformat" not found
1053 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1056 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1061 // Should probably be moved to somewhere else: BufferView? LyXView?
1062 bool Buffer::save() const
1064 // We don't need autosaves in the immediate future. (Asger)
1065 resetAutosaveTimers();
1069 if (lyxrc.make_backup) {
1070 s = fileName() + '~';
1071 if (!lyxrc.backupdir_path.empty())
1072 s = AddName(lyxrc.backupdir_path,
1073 subst(os::slashify_path(s),'/','!'));
1075 // Rename is the wrong way of making a backup,
1076 // this is the correct way.
1077 /* truss cp fil fil2:
1078 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1079 stat("LyXVC.lyx", 0xEFFFF688) = 0
1080 open("LyXVC.lyx", O_RDONLY) = 3
1081 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1082 fstat(4, 0xEFFFF508) = 0
1083 fstat(3, 0xEFFFF508) = 0
1084 read(3, " # T h i s f i l e w".., 8192) = 5579
1085 write(4, " # T h i s f i l e w".., 5579) = 5579
1086 read(3, 0xEFFFD4A0, 8192) = 0
1089 chmod("LyXVC3.lyx", 0100644) = 0
1090 lseek(0, 0, SEEK_CUR) = 46440
1094 // Should probably have some more error checking here.
1095 // Doing it this way, also makes the inodes stay the same.
1096 // This is still not a very good solution, in particular we
1097 // might loose the owner of the backup.
1098 FileInfo finfo(fileName());
1099 if (finfo.exist()) {
1100 mode_t fmode = finfo.getMode();
1101 struct utimbuf times = {
1102 finfo.getAccessTime(),
1103 finfo.getModificationTime() };
1105 ifstream ifs(fileName().c_str());
1106 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1111 ::chmod(s.c_str(), fmode);
1113 if (::utime(s.c_str(), ×)) {
1114 lyxerr << "utime error." << endl;
1117 lyxerr << "LyX was not able to make "
1118 "backup copy. Beware." << endl;
1123 if (writeFile(fileName())) {
1125 removeAutosaveFile(fileName());
1127 // Saving failed, so backup is not backup
1128 if (lyxrc.make_backup) {
1129 lyx::rename(s, fileName());
1137 bool Buffer::writeFile(string const & fname) const
1139 if (read_only && (fname == fileName())) {
1143 FileInfo finfo(fname);
1144 if (finfo.exist() && !finfo.writable()) {
1148 ofstream ofs(fname.c_str());
1154 // Use the standard "C" locale for file output.
1155 ofs.imbue(std::locale::classic());
1158 // The top of the file should not be written by params.
1160 // write out a comment in the top of the file
1161 ofs << '#' << lyx_docversion
1162 << " created this file. For more info see http://www.lyx.org/\n"
1163 << "\\lyxformat " << LYX_FORMAT << "\n";
1165 // now write out the buffer paramters.
1166 params.writeFile(ofs);
1168 ofs << "\\end_header\n";
1170 Paragraph::depth_type depth = 0;
1172 // this will write out all the paragraphs
1173 // using recursive descent.
1174 ParagraphList::iterator pit = paragraphs.begin();
1175 ParagraphList::iterator pend = paragraphs.end();
1176 for (; pit != pend; ++pit)
1177 pit->write(this, ofs, params, depth);
1179 // Write marker that shows file is complete
1180 ofs << "\n\\the_end" << endl;
1184 // how to check if close went ok?
1185 // Following is an attempt... (BE 20001011)
1187 // good() returns false if any error occured, including some
1188 // formatting error.
1189 // bad() returns true if something bad happened in the buffer,
1190 // which should include file system full errors.
1197 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1199 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1211 pair<int, string> const addDepth(int depth, int ldepth)
1215 d += (ldepth - depth) * 2;
1216 return make_pair(d, string(d, ' '));
1222 string const Buffer::asciiParagraph(Paragraph const & par,
1223 unsigned int linelen,
1224 bool noparbreak) const
1226 ostringstream buffer;
1227 Paragraph::depth_type depth = 0;
1229 Paragraph::depth_type ltype_depth = 0;
1230 bool ref_printed = false;
1231 // if (!par->previous()) {
1233 // begins or ends a deeper area ?
1234 if (depth != par->params().depth()) {
1235 if (par->params().depth() > depth) {
1236 while (par->params().depth() > depth) {
1240 while (par->params().depth() < depth) {
1246 depth = par.params().depth();
1249 // First write the layout
1250 string const & tmp = par.layout()->name();
1251 if (compare_no_case(tmp, "itemize") == 0) {
1253 ltype_depth = depth + 1;
1254 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1256 ltype_depth = depth + 1;
1257 } else if (contains(ascii_lowercase(tmp), "ection")) {
1259 ltype_depth = depth + 1;
1260 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1262 ltype_depth = depth + 1;
1263 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1265 ltype_depth = depth + 1;
1266 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1269 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1277 /* maybe some vertical spaces */
1279 /* the labelwidthstring used in lists */
1283 /* some pagebreaks? */
1287 /* what about the alignment */
1289 // lyxerr << "Should this ever happen?" << endl;
1292 // linelen <= 0 is special and means we don't have paragraph breaks
1294 string::size_type currlinelen = 0;
1300 buffer << string(depth * 2, ' ');
1301 currlinelen += depth * 2;
1304 // we should probably change to the paragraph language in the
1305 // gettext here (if possible) so that strings are outputted in
1306 // the correct language! (20012712 Jug)
1310 case 4: // (Sub)Paragraph
1311 case 5: // Description
1315 buffer << _("Abstract") << "\n\n";
1318 string const abst = _("Abstract: ");
1320 currlinelen += abst.length();
1323 case 7: // Bibliography
1326 buffer << _("References") << "\n\n";
1329 string const refs = _("References: ");
1331 currlinelen += refs.length();
1339 string const parlab = par.params().labelString();
1340 buffer << parlab << ' ';
1341 currlinelen += parlab.length() + 1;
1349 pair<int, string> p = addDepth(depth, ltype_depth);
1351 currlinelen += p.first;
1354 // this is to change the linebreak to do it by word a bit more
1355 // intelligent hopefully! (only in the case where we have a
1356 // max linelength!) (Jug)
1360 for (pos_type i = 0; i < par.size(); ++i) {
1361 char c = par.getUChar(params, i);
1363 case Paragraph::META_INSET:
1365 Inset const * inset = par.getInset(i);
1369 currlinelen += word.length();
1372 if (inset->ascii(this, buffer, linelen)) {
1373 // to be sure it breaks paragraph
1374 currlinelen += linelen;
1380 case Paragraph::META_NEWLINE:
1382 buffer << word << "\n";
1385 pair<int, string> p = addDepth(depth,
1388 currlinelen = p.first;
1395 currlinelen + word.length() > linelen - 10) {
1397 pair<int, string> p = addDepth(depth, ltype_depth);
1399 currlinelen = p.first;
1402 buffer << word << ' ';
1403 currlinelen += word.length() + 1;
1410 lyxerr[Debug::INFO] <<
1411 "writeAsciiFile: NULL char in structure." << endl;
1413 if ((linelen > 0) &&
1414 (currlinelen + word.length()) > linelen)
1418 pair<int, string> p =
1419 addDepth(depth, ltype_depth);
1421 currlinelen = p.first;
1428 return STRCONV(buffer.str());
1432 void Buffer::writeFileAscii(string const & fname, int linelen)
1434 ofstream ofs(fname.c_str());
1436 Alert::err_alert(_("Error: Cannot write file:"), fname);
1439 writeFileAscii(ofs, linelen);
1443 void Buffer::writeFileAscii(ostream & os, int linelen)
1445 ParagraphList::iterator beg = paragraphs.begin();
1446 ParagraphList::iterator end = paragraphs.end();
1447 ParagraphList::iterator it = beg;
1448 for (; it != end; ++it) {
1449 os << asciiParagraph(*it, linelen, it == beg);
1456 void Buffer::makeLaTeXFile(string const & fname,
1457 string const & original_path,
1458 bool nice, bool only_body, bool only_preamble)
1460 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1462 ofstream ofs(fname.c_str());
1464 Alert::err_alert(_("Error: Cannot open file: "), fname);
1468 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1472 lyxerr << "File was not closed properly." << endl;
1477 void Buffer::makeLaTeXFile(ostream & os,
1478 string const & original_path,
1479 bool nice, bool only_body, bool only_preamble)
1481 niceFile = nice; // this will be used by Insetincludes.
1483 // validate the buffer.
1484 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1485 LaTeXFeatures features(params);
1487 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1490 // The starting paragraph of the coming rows is the
1491 // first paragraph of the document. (Asger)
1492 texrow.start(&*(paragraphs.begin()), 0);
1494 if (!only_body && nice) {
1495 os << "%% " << lyx_docversion << " created this file. "
1496 "For more info, see http://www.lyx.org/.\n"
1497 "%% Do not edit unless you really know what "
1502 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1503 // There are a few differences between nice LaTeX and usual files:
1504 // usual is \batchmode and has a
1505 // special input@path to allow the including of figures
1506 // with either \input or \includegraphics (what figinsets do).
1507 // input@path is set when the actual parameter
1508 // original_path is set. This is done for usual tex-file, but not
1509 // for nice-latex-file. (Matthias 250696)
1512 // code for usual, NOT nice-latex-file
1513 os << "\\batchmode\n"; // changed
1514 // from \nonstopmode
1517 if (!original_path.empty()) {
1518 string inputpath = os::external_path(original_path);
1519 subst(inputpath, "~", "\\string~");
1520 os << "\\makeatletter\n"
1521 << "\\def\\input@path{{"
1522 << inputpath << "/}}\n"
1523 << "\\makeatother\n";
1529 // Write the preamble
1530 params.writeLaTeX(os, features, texrow);
1536 os << "\\begin{document}\n";
1539 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1541 if (!lyxrc.language_auto_begin) {
1542 os << subst(lyxrc.language_command_begin, "$$lang",
1543 params.language->babel())
1548 latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1550 // add this just in case after all the paragraphs
1554 if (!lyxrc.language_auto_end) {
1555 os << subst(lyxrc.language_command_end, "$$lang",
1556 params.language->babel())
1562 os << "\\end{document}\n";
1565 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1567 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1571 // Just to be sure. (Asger)
1574 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1575 lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1578 // we want this to be true outside previews (for insetexternal)
1583 bool Buffer::isLatex() const
1585 return params.getLyXTextClass().outputType() == LATEX;
1589 bool Buffer::isLinuxDoc() const
1591 return params.getLyXTextClass().outputType() == LINUXDOC;
1595 bool Buffer::isLiterate() const
1597 return params.getLyXTextClass().outputType() == LITERATE;
1601 bool Buffer::isDocBook() const
1603 return params.getLyXTextClass().outputType() == DOCBOOK;
1607 bool Buffer::isSGML() const
1609 LyXTextClass const & tclass = params.getLyXTextClass();
1611 return tclass.outputType() == LINUXDOC ||
1612 tclass.outputType() == DOCBOOK;
1616 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1618 ofstream ofs(fname.c_str());
1621 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
1625 niceFile = nice; // this will be used by included files.
1627 LaTeXFeatures features(params);
1633 LyXTextClass const & tclass = params.getLyXTextClass();
1635 string top_element = tclass.latexname();
1638 ofs << "<!doctype linuxdoc system";
1640 string preamble = params.preamble;
1641 const string name = nice ? ChangeExtension(filename_, ".sgml")
1643 preamble += features.getIncludedFiles(name);
1644 preamble += features.getLyXSGMLEntities();
1646 if (!preamble.empty()) {
1647 ofs << " [ " << preamble << " ]";
1651 if (params.options.empty())
1652 sgml::openTag(ofs, 0, false, top_element);
1654 string top = top_element;
1656 top += params.options;
1657 sgml::openTag(ofs, 0, false, top);
1661 ofs << "<!-- " << lyx_docversion
1662 << " created this file. For more info see http://www.lyx.org/"
1665 Paragraph::depth_type depth = 0; // paragraph depth
1666 Paragraph * par = &*(paragraphs.begin());
1668 vector<string> environment_stack(5);
1671 LyXLayout_ptr const & style = par->layout();
1672 // treat <toc> as a special case for compatibility with old code
1673 if (par->isInset(0)) {
1674 Inset * inset = par->getInset(0);
1675 Inset::Code lyx_code = inset->lyxCode();
1676 if (lyx_code == Inset::TOC_CODE) {
1677 string const temp = "toc";
1678 sgml::openTag(ofs, depth, false, temp);
1685 // environment tag closing
1686 for (; depth > par->params().depth(); --depth) {
1687 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1688 environment_stack[depth].erase();
1691 // write opening SGML tags
1692 switch (style->latextype) {
1693 case LATEX_PARAGRAPH:
1694 if (depth == par->params().depth()
1695 && !environment_stack[depth].empty()) {
1696 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1697 environment_stack[depth].erase();
1703 sgml::openTag(ofs, depth, false, style->latexname());
1709 _("Error: Wrong depth for LatexType Command.\n"));
1711 if (!environment_stack[depth].empty()) {
1712 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1716 environment_stack[depth].erase();
1717 sgml::openTag(ofs, depth, false, style->latexname());
1720 case LATEX_ENVIRONMENT:
1721 case LATEX_ITEM_ENVIRONMENT:
1722 case LATEX_BIB_ENVIRONMENT:
1724 string const & latexname = style->latexname();
1726 if (depth == par->params().depth()
1727 && environment_stack[depth] != latexname) {
1728 sgml::closeTag(ofs, depth, false,
1729 environment_stack[depth]);
1730 environment_stack[depth].erase();
1732 if (depth < par->params().depth()) {
1733 depth = par->params().depth();
1734 environment_stack[depth].erase();
1736 if (environment_stack[depth] != latexname) {
1738 sgml::openTag(ofs, depth, false, "p");
1740 sgml::openTag(ofs, depth, false, latexname);
1742 if (environment_stack.size() == depth + 1)
1743 environment_stack.push_back("!-- --");
1744 environment_stack[depth] = latexname;
1747 if (style->latexparam() == "CDATA")
1750 if (style->latextype == LATEX_ENVIRONMENT) break;
1752 if (style->labeltype == LABEL_MANUAL)
1757 sgml::openTag(ofs, depth + 1, false, item_name);
1762 sgml::openTag(ofs, depth, false, style->latexname());
1766 simpleLinuxDocOnePar(ofs, par, depth);
1771 // write closing SGML tags
1772 switch (style->latextype) {
1775 case LATEX_ENVIRONMENT:
1776 case LATEX_ITEM_ENVIRONMENT:
1777 case LATEX_BIB_ENVIRONMENT:
1778 if (style->latexparam() == "CDATA")
1782 sgml::closeTag(ofs, depth, false, style->latexname());
1788 for (int i = depth; i >= 0; --i)
1789 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1793 sgml::closeTag(ofs, 0, false, top_element);
1797 // How to check for successful close
1799 // we want this to be true outside previews (for insetexternal)
1804 // checks, if newcol chars should be put into this line
1805 // writes newline, if necessary.
1808 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1809 string::size_type newcol)
1812 if (colcount > lyxrc.ascii_linelen) {
1814 colcount = newcol; // assume write after this call
1829 string tag_name(PAR_TAG const & pt) {
1831 case NONE: return "!-- --";
1832 case TT: return "tt";
1833 case SF: return "sf";
1834 case BF: return "bf";
1835 case IT: return "it";
1836 case SL: return "sl";
1837 case EM: return "em";
1844 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1846 p1 = static_cast<PAR_TAG>(p1 | p2);
1851 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1853 p1 = static_cast<PAR_TAG>(p1 & ~p2);
1859 // Handle internal paragraph parsing -- layout already processed.
1860 void Buffer::simpleLinuxDocOnePar(ostream & os,
1862 Paragraph::depth_type /*depth*/)
1864 LyXLayout_ptr const & style = par->layout();
1866 string::size_type char_line_count = 5; // Heuristic choice ;-)
1868 // gets paragraph main font
1871 if (style->labeltype == LABEL_MANUAL) {
1872 font_old = style->labelfont;
1875 font_old = style->font;
1879 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1880 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1881 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
1884 stack<PAR_TAG> tag_state;
1885 // parsing main loop
1886 for (pos_type i = 0; i < par->size(); ++i) {
1888 PAR_TAG tag_close = NONE;
1889 list < PAR_TAG > tag_open;
1891 LyXFont const font = par->getFont(params, i);
1893 if (font_old.family() != font.family()) {
1894 switch (family_type) {
1895 case LyXFont::SANS_FAMILY:
1898 case LyXFont::TYPEWRITER_FAMILY:
1905 family_type = font.family();
1907 switch (family_type) {
1908 case LyXFont::SANS_FAMILY:
1909 tag_open.push_back(SF);
1911 case LyXFont::TYPEWRITER_FAMILY:
1912 tag_open.push_back(TT);
1919 if (font_old.series() != font.series()) {
1920 switch (series_type) {
1921 case LyXFont::BOLD_SERIES:
1928 series_type = font.series();
1930 switch (series_type) {
1931 case LyXFont::BOLD_SERIES:
1932 tag_open.push_back(BF);
1940 if (font_old.shape() != font.shape()) {
1941 switch (shape_type) {
1942 case LyXFont::ITALIC_SHAPE:
1945 case LyXFont::SLANTED_SHAPE:
1952 shape_type = font.shape();
1954 switch (shape_type) {
1955 case LyXFont::ITALIC_SHAPE:
1956 tag_open.push_back(IT);
1958 case LyXFont::SLANTED_SHAPE:
1959 tag_open.push_back(SL);
1966 if (font_old.emph() != font.emph()) {
1967 if (font.emph() == LyXFont::ON) {
1968 tag_open.push_back(EM);
1977 list < PAR_TAG > temp;
1978 while (!tag_state.empty() && tag_close) {
1979 PAR_TAG k = tag_state.top();
1981 os << "</" << tag_name(k) << '>';
1988 for(list< PAR_TAG >::const_iterator j = temp.begin();
1989 j != temp.end(); ++j) {
1991 os << '<' << tag_name(*j) << '>';
1994 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1995 j != tag_open.end(); ++j) {
1997 os << '<' << tag_name(*j) << '>';
2000 char c = par->getChar(i);
2002 if (c == Paragraph::META_INSET) {
2003 Inset * inset = par->getInset(i);
2004 inset->linuxdoc(this, os);
2009 if (style->latexparam() == "CDATA") {
2010 // "TeX"-Mode on == > SGML-Mode on.
2017 boost::tie(ws, str) = sgml::escapeChar(c);
2018 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2019 // in freespacing mode, spaces are
2020 // non-breaking characters
2021 if (desc_on) {// if char is ' ' then...
2024 sgmlLineBreak(os, char_line_count, 6);
2028 sgmlLineBreak(os, char_line_count, 1);
2033 char_line_count += str.length();
2039 while (!tag_state.empty()) {
2040 os << "</" << tag_name(tag_state.top()) << '>';
2044 // resets description flag correctly
2046 // <tag> not closed...
2047 sgmlLineBreak(os, char_line_count, 6);
2053 // Print an error message.
2054 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2055 string const & /*message*/) const
2057 #ifdef WITH_WARNINGS
2058 #warning This is wrong we cannot insert an inset like this!!!
2059 // I guess this was Jose' so I explain you more or less why this
2060 // is wrong. This way you insert something in the paragraph and
2061 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2062 // I deactivate this code, have a look at BufferView::insertErrors
2063 // how you should do this correctly! (Jug 20020315)
2066 // insert an error marker in text
2067 InsetError * new_inset = new InsetError(message);
2068 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2074 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2076 ofstream ofs(fname.c_str());
2078 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2082 Paragraph * par = &*(paragraphs.begin());
2084 niceFile = nice; // this will be used by Insetincludes.
2086 LaTeXFeatures features(params);
2091 LyXTextClass const & tclass = params.getLyXTextClass();
2092 string top_element = tclass.latexname();
2095 ofs << "<!DOCTYPE " << top_element
2096 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2098 string preamble = params.preamble;
2099 const string name = nice ? ChangeExtension(filename_, ".sgml")
2101 preamble += features.getIncludedFiles(name);
2102 preamble += features.getLyXSGMLEntities();
2104 if (!preamble.empty()) {
2105 ofs << "\n [ " << preamble << " ]";
2110 string top = top_element;
2112 top += params.language->code();
2115 if (!params.options.empty()) {
2117 top += params.options;
2119 sgml::openTag(ofs, 0, false, top);
2121 ofs << "<!-- DocBook file was created by " << lyx_docversion
2122 << "\n See http://www.lyx.org/ for more information -->\n";
2124 vector<string> environment_stack(10);
2125 vector<string> environment_inner(10);
2126 vector<string> command_stack(10);
2128 bool command_flag = false;
2129 Paragraph::depth_type command_depth = 0;
2130 Paragraph::depth_type command_base = 0;
2131 Paragraph::depth_type cmd_depth = 0;
2132 Paragraph::depth_type depth = 0; // paragraph depth
2135 string command_name;
2141 int desc_on = 0; // description mode
2143 LyXLayout_ptr const & style = par->layout();
2145 // environment tag closing
2146 for (; depth > par->params().depth(); --depth) {
2147 if (environment_inner[depth] != "!-- --") {
2148 item_name = "listitem";
2149 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2150 if (environment_inner[depth] == "varlistentry")
2151 sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2153 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2154 environment_stack[depth].erase();
2155 environment_inner[depth].erase();
2158 if (depth == par->params().depth()
2159 && environment_stack[depth] != style->latexname()
2160 && !environment_stack[depth].empty()) {
2161 if (environment_inner[depth] != "!-- --") {
2162 item_name= "listitem";
2163 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2164 if (environment_inner[depth] == "varlistentry")
2165 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2168 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2170 environment_stack[depth].erase();
2171 environment_inner[depth].erase();
2174 // Write opening SGML tags.
2175 switch (style->latextype) {
2176 case LATEX_PARAGRAPH:
2177 sgml::openTag(ofs, depth + command_depth,
2178 false, style->latexname());
2184 _("Error: Wrong depth for LatexType Command.\n"));
2186 command_name = style->latexname();
2188 sgmlparam = style->latexparam();
2189 c_params = split(sgmlparam, c_depth,'|');
2191 cmd_depth = lyx::atoi(c_depth);
2194 if (cmd_depth < command_base) {
2195 for (Paragraph::depth_type j = command_depth;
2196 j >= command_base; --j) {
2197 sgml::closeTag(ofs, j, false, command_stack[j]);
2200 command_depth = command_base = cmd_depth;
2201 } else if (cmd_depth <= command_depth) {
2202 for (int j = command_depth;
2203 j >= int(cmd_depth); --j) {
2204 sgml::closeTag(ofs, j, false, command_stack[j]);
2207 command_depth = cmd_depth;
2209 command_depth = cmd_depth;
2211 command_depth = command_base = cmd_depth;
2212 command_flag = true;
2214 if (command_stack.size() == command_depth + 1)
2215 command_stack.push_back(string());
2216 command_stack[command_depth] = command_name;
2218 // treat label as a special case for
2219 // more WYSIWYM handling.
2220 // This is a hack while paragraphs can't have
2221 // attributes, like id in this case.
2222 if (par->isInset(0)) {
2223 Inset * inset = par->getInset(0);
2224 Inset::Code lyx_code = inset->lyxCode();
2225 if (lyx_code == Inset::LABEL_CODE) {
2226 command_name += " id=\"";
2227 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2228 command_name += '"';
2233 sgml::openTag(ofs, depth + command_depth, false, command_name);
2235 item_name = c_params.empty() ? "title" : c_params;
2236 sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2239 case LATEX_ENVIRONMENT:
2240 case LATEX_ITEM_ENVIRONMENT:
2241 if (depth < par->params().depth()) {
2242 depth = par->params().depth();
2243 environment_stack[depth].erase();
2246 if (environment_stack[depth] != style->latexname()) {
2247 if (environment_stack.size() == depth + 1) {
2248 environment_stack.push_back("!-- --");
2249 environment_inner.push_back("!-- --");
2251 environment_stack[depth] = style->latexname();
2252 environment_inner[depth] = "!-- --";
2253 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2255 if (environment_inner[depth] != "!-- --") {
2256 item_name= "listitem";
2257 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2258 if (environment_inner[depth] == "varlistentry")
2259 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2263 if (style->latextype == LATEX_ENVIRONMENT) {
2264 if (!style->latexparam().empty()) {
2265 if (style->latexparam() == "CDATA")
2268 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2273 desc_on = (style->labeltype == LABEL_MANUAL);
2275 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2276 sgml::openTag(ofs, depth + 1 + command_depth,
2277 false, environment_inner[depth]);
2279 item_name = desc_on ? "term" : "para";
2280 sgml::openTag(ofs, depth + 1 + command_depth,
2284 sgml::openTag(ofs, depth + command_depth,
2285 false, style->latexname());
2289 simpleDocBookOnePar(ofs, par, desc_on,
2290 depth + 1 + command_depth);
2294 // write closing SGML tags
2295 switch (style->latextype) {
2297 end_tag = c_params.empty() ? "title" : c_params;
2298 sgml::closeTag(ofs, depth + command_depth,
2301 case LATEX_ENVIRONMENT:
2302 if (!style->latexparam().empty()) {
2303 if (style->latexparam() == "CDATA")
2306 sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2309 case LATEX_ITEM_ENVIRONMENT:
2310 if (desc_on == 1) break;
2312 sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2314 case LATEX_PARAGRAPH:
2315 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2318 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2324 for (int d = depth; d >= 0; --d) {
2325 if (!environment_stack[depth].empty()) {
2326 if (environment_inner[depth] != "!-- --") {
2327 item_name = "listitem";
2328 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2329 if (environment_inner[depth] == "varlistentry")
2330 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2333 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2337 for (int j = command_depth; j >= 0 ; --j)
2338 if (!command_stack[j].empty()) {
2339 sgml::closeTag(ofs, j, false, command_stack[j]);
2344 sgml::closeTag(ofs, 0, false, top_element);
2347 // How to check for successful close
2349 // we want this to be true outside previews (for insetexternal)
2354 void Buffer::simpleDocBookOnePar(ostream & os,
2355 Paragraph * par, int & desc_on,
2356 Paragraph::depth_type depth) const
2358 bool emph_flag = false;
2360 LyXLayout_ptr const & style = par->layout();
2362 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2364 int char_line_count = depth;
2365 //if (!style.free_spacing)
2366 // os << string(depth,' ');
2368 // parsing main loop
2369 for (pos_type i = 0; i < par->size(); ++i) {
2370 LyXFont font = par->getFont(params, i);
2372 // handle <emphasis> tag
2373 if (font_old.emph() != font.emph()) {
2374 if (font.emph() == LyXFont::ON) {
2375 if (style->latexparam() == "CDATA")
2378 if (style->latexparam() == "CDATA")
2382 if (style->latexparam() == "CDATA")
2384 os << "</emphasis>";
2385 if (style->latexparam() == "CDATA")
2392 if (par->isInset(i)) {
2393 Inset * inset = par->getInset(i);
2394 // don't print the inset in position 0 if desc_on == 3 (label)
2395 if (i || desc_on != 3) {
2396 if (style->latexparam() == "CDATA")
2398 inset->docbook(this, os, false);
2399 if (style->latexparam() == "CDATA")
2403 char c = par->getChar(i);
2406 boost::tie(ws, str) = sgml::escapeChar(c);
2408 if (style->pass_thru) {
2410 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
2412 } else if (desc_on ==1) {
2414 os << "\n</term><listitem><para>";
2424 if (style->latexparam() == "CDATA")
2426 os << "</emphasis>";
2427 if (style->latexparam() == "CDATA")
2431 // resets description flag correctly
2433 // <term> not closed...
2434 os << "</term>\n<listitem><para> </para>";
2436 if (style->free_spacing)
2441 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2442 // Other flags: -wall -v0 -x
2443 int Buffer::runChktex()
2445 if (!users->text) return 0;
2447 users->owner()->busy(true);
2449 // get LaTeX-Filename
2450 string const name = getLatexName();
2451 string path = filePath();
2453 string const org_path = path;
2454 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2458 Path p(path); // path to LaTeX file
2459 users->owner()->message(_("Running chktex..."));
2461 // Remove all error insets
2462 bool const removedErrorInsets = users->removeAutoInsets();
2464 // Generate the LaTeX file if neccessary
2465 makeLaTeXFile(name, org_path, false);
2468 Chktex chktex(lyxrc.chktex_command, name, filePath());
2469 int res = chktex.run(terr); // run chktex
2472 Alert::alert(_("chktex did not work!"),
2473 _("Could not run with file:"), name);
2474 } else if (res > 0) {
2475 // Insert all errors as errors boxes
2476 users->insertErrors(terr);
2479 // if we removed error insets before we ran chktex or if we inserted
2480 // error insets after we ran chktex, this must be run:
2481 if (removedErrorInsets || res) {
2482 #warning repaint needed here, or do you mean update() ?
2486 users->owner()->busy(false);
2492 void Buffer::validate(LaTeXFeatures & features) const
2494 LyXTextClass const & tclass = params.getLyXTextClass();
2496 if (params.tracking_changes) {
2497 features.require("dvipost");
2498 features.require("color");
2501 // AMS Style is at document level
2502 if (params.use_amsmath == BufferParams::AMS_ON
2503 || tclass.provides(LyXTextClass::amsmath))
2504 features.require("amsmath");
2506 for_each(paragraphs.begin(), paragraphs.end(),
2507 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2509 // the bullet shapes are buffer level not paragraph level
2510 // so they are tested here
2511 for (int i = 0; i < 4; ++i) {
2512 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2513 int const font = params.user_defined_bullets[i].getFont();
2515 int const c = params
2516 .user_defined_bullets[i]
2523 features.require("latexsym");
2525 } else if (font == 1) {
2526 features.require("amssymb");
2527 } else if ((font >= 2 && font <= 5)) {
2528 features.require("pifont");
2533 if (lyxerr.debugging(Debug::LATEX)) {
2534 features.showStruct();
2539 vector<string> const Buffer::getLabelList() const
2541 /// if this is a child document and the parent is already loaded
2542 /// Use the parent's list instead [ale990407]
2543 if (!params.parentname.empty()
2544 && bufferlist.exists(params.parentname)) {
2545 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2547 return tmp->getLabelList();
2550 vector<string> label_list;
2551 for (inset_iterator it = inset_const_iterator_begin();
2552 it != inset_const_iterator_end(); ++it) {
2553 vector<string> const l = it->getLabelList();
2554 label_list.insert(label_list.end(), l.begin(), l.end());
2560 // This is also a buffer property (ale)
2561 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2563 /// if this is a child document and the parent is already loaded
2564 /// use the parent's list instead [ale990412]
2565 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2566 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2568 tmp->fillWithBibKeys(keys);
2573 for (inset_iterator it = inset_const_iterator_begin();
2574 it != inset_const_iterator_end(); ++it) {
2575 if (it->lyxCode() == Inset::BIBTEX_CODE)
2576 static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2577 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2578 static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2579 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2580 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2581 string const key = bib.getContents();
2582 string const opt = bib.getOptions();
2583 string const ref; // = pit->asString(this, false);
2584 string const info = opt + "TheBibliographyRef" + ref;
2585 keys.push_back(pair<string, string>(key, info));
2591 bool Buffer::isDepClean(string const & name) const
2593 DepClean::const_iterator it = dep_clean_.find(name);
2594 if (it == dep_clean_.end())
2600 void Buffer::markDepClean(string const & name)
2602 dep_clean_[name] = true;
2606 bool Buffer::dispatch(string const & command, bool * result)
2608 // Split command string into command and argument
2610 string line = ltrim(command);
2611 string const arg = trim(split(line, cmd, ' '));
2613 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2617 bool Buffer::dispatch(int action, string const & argument, bool * result)
2619 bool dispatched = true;
2623 bool const tmp = Exporter::Export(this, argument, false);
2636 void Buffer::resizeInsets(BufferView * bv)
2638 /// then remove all LyXText in text-insets
2639 for_each(paragraphs.begin(), paragraphs.end(),
2640 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2644 void Buffer::redraw()
2646 #warning repaint needed here, or do you mean update() ?
2652 void Buffer::changeLanguage(Language const * from, Language const * to)
2655 ParIterator end = par_iterator_end();
2656 for (ParIterator it = par_iterator_begin(); it != end; ++it)
2657 (*it)->changeLanguage(params, from, to);
2661 bool Buffer::isMultiLingual()
2663 ParIterator end = par_iterator_end();
2664 for (ParIterator it = par_iterator_begin(); it != end; ++it)
2665 if ((*it)->isMultiLingual(params))
2672 void Buffer::inset_iterator::setParagraph()
2674 while (pit != pend) {
2675 it = pit->insetlist.begin();
2676 if (it != pit->insetlist.end())
2683 Inset * Buffer::getInsetFromID(int id_arg) const
2685 for (inset_iterator it = inset_const_iterator_begin();
2686 it != inset_const_iterator_end(); ++it)
2688 if (it->id() == id_arg)
2690 Inset * in = it->getInsetFromID(id_arg);
2698 Paragraph * Buffer::getParFromID(int id) const
2703 // why should we allow < 0 ??
2704 //lyx::Assert(id >= 0);
2706 ParConstIterator it(par_iterator_begin());
2707 ParConstIterator end(par_iterator_end());
2709 for (; it != end; ++it) {
2710 // go on then, show me how to remove
2712 if ((*it)->id() == id) {
2713 return const_cast<Paragraph*>(*it);
2721 ParIterator Buffer::par_iterator_begin()
2723 return ParIterator(&*(paragraphs.begin()));
2727 ParIterator Buffer::par_iterator_end()
2729 return ParIterator();
2732 ParConstIterator Buffer::par_iterator_begin() const
2734 return ParConstIterator(&*(paragraphs.begin()));
2738 ParConstIterator Buffer::par_iterator_end() const
2740 return ParConstIterator();
2745 void Buffer::addUser(BufferView * u)
2751 void Buffer::delUser(BufferView *)
2757 Language const * Buffer::getLanguage() const
2759 return params.language;
2763 bool Buffer::isClean() const
2769 bool Buffer::isBakClean() const
2775 void Buffer::markClean() const
2781 // if the .lyx file has been saved, we don't need an
2787 void Buffer::markBakClean()
2793 void Buffer::setUnnamed(bool flag)
2799 bool Buffer::isUnnamed()
2805 void Buffer::markDirty()
2813 DepClean::iterator it = dep_clean_.begin();
2814 DepClean::const_iterator const end = dep_clean_.end();
2816 for (; it != end; ++it) {
2822 string const & Buffer::fileName() const
2828 string const & Buffer::filePath() const
2834 bool Buffer::isReadonly() const
2840 BufferView * Buffer::getUser() const
2846 void Buffer::setParentName(string const & name)
2848 params.parentname = name;
2852 Buffer::inset_iterator::inset_iterator()
2857 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2864 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2868 if (it == pit->insetlist.end()) {
2877 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2879 inset_iterator tmp = *this;
2885 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2887 return *it.getInset();
2891 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2893 return it.getInset();
2897 Paragraph * Buffer::inset_iterator::getPar()
2903 lyx::pos_type Buffer::inset_iterator::getPos() const
2909 bool operator==(Buffer::inset_iterator const & iter1,
2910 Buffer::inset_iterator const & iter2)
2912 return iter1.pit == iter2.pit
2913 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2917 bool operator!=(Buffer::inset_iterator const & iter1,
2918 Buffer::inset_iterator const & iter2)
2920 return !(iter1 == iter2);