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 // This stuff is, in the traditional LyX terminology, Super UGLY
457 // but this code is too b0rken to admit of a better solution yet
458 Change current_change;
463 Buffer::readToken(LyXLex & lex, Paragraph *& par,
464 Paragraph *& first_par,
465 string const & token, int & pos,
466 Paragraph::depth_type & depth,
472 // The order of the tags tested may seem unnatural, but this
473 // has been done in order to reduce the number of string
474 // comparisons needed to recognize a given token. This leads
475 // on large documents like UserGuide to a reduction of a
477 if (token[0] != '\\') {
478 for (string::const_iterator cit = token.begin();
479 cit != token.end(); ++cit) {
480 par->insertChar(pos, (*cit), font, current_change);
483 } else if (token == "\\layout") {
484 // reset the font as we start a new layout and if the font is
485 // not ALL_INHERIT,document_language then it will be set to the
486 // right values after this tag (Jug 20020420)
487 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
490 string layoutname = lex.getString();
492 LyXTextClass const & tclass = params.getLyXTextClass();
494 if (layoutname.empty()) {
495 layoutname = tclass.defaultLayoutName();
497 bool hasLayout = tclass.hasLayout(layoutname);
499 lyxerr << "Layout '" << layoutname << "' does not"
500 << " exist in textclass '" << tclass.name()
502 lyxerr << "Trying to use default layout instead."
504 layoutname = tclass.defaultLayoutName();
508 // The is the compability reading of layout caption.
509 // It can be removed in LyX version 1.3.0. (Lgb)
510 if (compare_ascii_no_case(layoutname, "caption") == 0) {
511 // We expect that the par we are now working on is
512 // really inside a InsetText inside a InsetFloat.
513 // We also know that captions can only be
514 // one paragraph. (Lgb)
516 // We should now read until the next "\layout"
518 // This is probably not good enough, what if the
519 // caption is the last par in the document (Lgb)
520 istream & ist = lex.getStream();
526 if (prefixIs(line, "\\layout")) {
530 if (prefixIs(line, "\\begin_inset"))
532 if (prefixIs(line, "\\end_inset")) {
543 // Now we should have the whole layout in ss
544 // we should now be able to give this to the
546 ss << "\\end_inset\n";
548 // This seems like a bug in stringstream.
549 // We really should be able to use ss
551 istringstream is(ss.str());
553 tmplex.setStream(is);
554 Inset * inset = new InsetCaption;
555 inset->Read(this, tmplex);
556 par->InsertInset(pos, inset, font);
563 par = new Paragraph(par);
564 par->layout(params.getLyXTextClass().defaultLayout());
565 if (params.tracking_changes)
569 par->layout(params.getLyXTextClass()[layoutname]);
570 // Test whether the layout is obsolete.
571 LyXLayout_ptr const & layout = par->layout();
572 if (!layout->obsoleted_by().empty())
573 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
574 par->params().depth(depth);
579 } else if (token == "\\end_inset") {
580 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
581 << "Missing \\begin_inset?.\n";
582 // Simply ignore this. The insets do not have
584 // But insets should read it, it is a part of
585 // the inset isn't it? Lgb.
586 } else if (token == "\\begin_inset") {
587 readInset(lex, par, pos, font);
588 } else if (token == "\\family") {
590 font.setLyXFamily(lex.getString());
591 } else if (token == "\\series") {
593 font.setLyXSeries(lex.getString());
594 } else if (token == "\\shape") {
596 font.setLyXShape(lex.getString());
597 } else if (token == "\\size") {
599 font.setLyXSize(lex.getString());
600 } else if (token == "\\lang") {
602 string const tok = lex.getString();
603 Language const * lang = languages.getLanguage(tok);
605 font.setLanguage(lang);
607 font.setLanguage(params.language);
608 lex.printError("Unknown language `$$Token'");
610 } else if (token == "\\numeric") {
612 font.setNumber(font.setLyXMisc(lex.getString()));
613 } else if (token == "\\emph") {
615 font.setEmph(font.setLyXMisc(lex.getString()));
616 } else if (token == "\\bar") {
618 string const tok = lex.getString();
619 // This is dirty, but gone with LyX3. (Asger)
621 font.setUnderbar(LyXFont::ON);
622 else if (tok == "no")
623 font.setUnderbar(LyXFont::OFF);
624 else if (tok == "default")
625 font.setUnderbar(LyXFont::INHERIT);
627 lex.printError("Unknown bar font flag "
629 } else if (token == "\\noun") {
631 font.setNoun(font.setLyXMisc(lex.getString()));
632 } else if (token == "\\color") {
634 font.setLyXColor(lex.getString());
635 } else if (token == "\\SpecialChar") {
636 LyXLayout_ptr const & layout = par->layout();
638 // Insets don't make sense in a free-spacing context! ---Kayvan
639 if (layout->free_spacing || par->isFreeSpacing()) {
642 string const next_token = lex.getString();
643 if (next_token == "\\-") {
644 par->insertChar(pos, '-', font, current_change);
645 } else if (next_token == "~") {
646 par->insertChar(pos, ' ', font, current_change);
648 lex.printError("Token `$$Token' "
650 "paragraph layout!");
655 Inset * inset = new InsetSpecialChar;
656 inset->read(this, lex);
657 par->insertInset(pos, inset, font, current_change);
660 } else if (token == "\\i") {
661 Inset * inset = new InsetLatexAccent;
662 inset->read(this, lex);
663 par->insertInset(pos, inset, font, current_change);
665 } else if (token == "\\backslash") {
666 par->insertChar(pos, '\\', font, current_change);
668 } else if (token == "\\begin_deeper") {
670 } else if (token == "\\end_deeper") {
672 lex.printError("\\end_deeper: "
673 "depth is already null");
677 } else if (token == "\\noindent") {
678 par->params().noindent(true);
679 } else if (token == "\\leftindent") {
681 LyXLength value(lex.getString());
682 par->params().leftIndent(value);
683 } else if (token == "\\fill_top") {
684 par->params().spaceTop(VSpace(VSpace::VFILL));
685 } else if (token == "\\fill_bottom") {
686 par->params().spaceBottom(VSpace(VSpace::VFILL));
687 } else if (token == "\\line_top") {
688 par->params().lineTop(true);
689 } else if (token == "\\line_bottom") {
690 par->params().lineBottom(true);
691 } else if (token == "\\pagebreak_top") {
692 par->params().pagebreakTop(true);
693 } else if (token == "\\pagebreak_bottom") {
694 par->params().pagebreakBottom(true);
695 } else if (token == "\\start_of_appendix") {
696 par->params().startOfAppendix(true);
697 } else if (token == "\\paragraph_spacing") {
699 string const tmp = rtrim(lex.getString());
700 if (tmp == "single") {
701 par->params().spacing(Spacing(Spacing::Single));
702 } else if (tmp == "onehalf") {
703 par->params().spacing(Spacing(Spacing::Onehalf));
704 } else if (tmp == "double") {
705 par->params().spacing(Spacing(Spacing::Double));
706 } else if (tmp == "other") {
708 par->params().spacing(Spacing(Spacing::Other,
711 lex.printError("Unknown spacing token: '$$Token'");
713 } else if (token == "\\align") {
714 int tmpret = lex.findToken(string_align);
717 int const tmpret2 = int(pow(2.0, tmpret));
718 par->params().align(LyXAlignment(tmpret2));
719 } else if (token == "\\added_space_top") {
721 VSpace value = VSpace(lex.getString());
722 // only add the length when value > 0 or
724 if ((value.length().len().value() != 0) ||
726 (value.kind() != VSpace::LENGTH))
727 par->params().spaceTop(value);
728 } else if (token == "\\added_space_bottom") {
730 VSpace value = VSpace(lex.getString());
731 // only add the length when value > 0 or
733 if ((value.length().len().value() != 0) ||
735 (value.kind() != VSpace::LENGTH))
736 par->params().spaceBottom(value);
737 } else if (token == "\\labelwidthstring") {
739 par->params().labelWidthString(lex.getString());
740 // do not delete this token, it is still needed!
741 } else if (token == "\\newline") {
742 par->insertChar(pos, Paragraph::META_NEWLINE, font, current_change);
744 } else if (token == "\\LyXTable") {
745 Inset * inset = new InsetTabular(*this);
746 inset->read(this, lex);
747 par->insertInset(pos, inset, font, current_change);
749 } else if (token == "\\bibitem") { // ale970302
750 InsetCommandParams p("bibitem", "dummy");
751 InsetBibitem * inset = new InsetBibitem(p);
752 inset->read(this, lex);
753 par->insertInset(pos, inset, font, current_change);
755 } else if (token == "\\hfill") {
756 par->insertInset(pos, new InsetHFill(),
757 LyXFont(LyXFont::ALL_INHERIT, params.language));
759 } else if (token == "\\change_unchanged") {
760 // Hack ! Needed for empty paragraphs :/
763 current_change = Change(Change::UNCHANGED);
764 } else if (token == "\\change_inserted") {
766 istringstream istr(lex.getString());
771 current_change = Change(Change::INSERTED, params.author_ids[aid], ct);
772 } else if (token == "\\change_deleted") {
774 istringstream istr(lex.getString());
779 current_change = Change(Change::DELETED, params.author_ids[aid], ct);
781 // This should be insurance for the future: (Asger)
785 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
786 fmt % token % lex.text();
787 string const s = fmt.str();
789 string const s = _("Unknown token: ") + token
790 + ' ' + lex.text() + '\n';
792 // we can do this here this way because we're actually reading
793 // the buffer and don't care about LyXText right now.
794 InsetError * new_inset = new InsetError(s);
795 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
804 // needed to insert the selection
805 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
806 LyXFont const & fn,string const & str)
808 LyXLayout_ptr const & layout = par->layout();
812 par->checkInsertChar(font);
813 // insert the string, don't insert doublespace
814 bool space_inserted = true;
815 bool autobreakrows = !par->inInset() ||
816 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
817 for(string::const_iterator cit = str.begin();
818 cit != str.end(); ++cit) {
820 if (autobreakrows && (!par->empty() || layout->keepempty)) {
821 breakParagraph(params, paragraphs, par, pos,
822 layout->isEnvironment());
825 space_inserted = true;
829 // do not insert consecutive spaces if !free_spacing
830 } else if ((*cit == ' ' || *cit == '\t') &&
831 space_inserted && !layout->free_spacing &&
832 !par->isFreeSpacing())
835 } else if (*cit == '\t') {
836 if (!layout->free_spacing && !par->isFreeSpacing()) {
837 // tabs are like spaces here
838 par->insertChar(pos, ' ', font, current_change);
840 space_inserted = true;
842 const pos_type nb = 8 - pos % 8;
843 for (pos_type a = 0; a < nb ; ++a) {
844 par->insertChar(pos, ' ', font, current_change);
847 space_inserted = true;
849 } else if (!IsPrintable(*cit)) {
850 // Ignore unprintables
853 // just insert the character
854 par->insertChar(pos, *cit, font);
856 space_inserted = (*cit == ' ');
863 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
864 int & pos, LyXFont & font)
867 if (lex.getString() != "\\begin_inset") {
868 lyxerr << "Buffer::readInset: Consistency check failed."
875 string const tmptok = lex.getString();
877 // test the different insets
878 if (tmptok == "LatexCommand") {
879 InsetCommandParams inscmd;
882 string const cmdName = inscmd.getCmdName();
884 // This strange command allows LyX to recognize "natbib" style
885 // citations: citet, citep, Citet etc.
886 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
887 inset = new InsetCitation(inscmd);
888 } else if (cmdName == "bibitem") {
889 lex.printError("Wrong place for bibitem");
890 inset = new InsetBibitem(inscmd);
891 } else if (cmdName == "BibTeX") {
892 inset = new InsetBibtex(inscmd);
893 } else if (cmdName == "index") {
894 inset = new InsetIndex(inscmd);
895 } else if (cmdName == "include") {
896 inset = new InsetInclude(inscmd, *this);
897 } else if (cmdName == "label") {
898 inset = new InsetLabel(inscmd);
899 } else if (cmdName == "url"
900 || cmdName == "htmlurl") {
901 inset = new InsetUrl(inscmd);
902 } else if (cmdName == "ref"
903 || cmdName == "pageref"
905 || cmdName == "vpageref"
906 || cmdName == "prettyref") {
907 if (!inscmd.getOptions().empty()
908 || !inscmd.getContents().empty()) {
909 inset = new InsetRef(inscmd, *this);
911 } else if (cmdName == "tableofcontents") {
912 inset = new InsetTOC(inscmd);
913 } else if (cmdName == "listofalgorithms") {
914 inset = new InsetFloatList("algorithm");
915 } else if (cmdName == "listoffigures") {
916 inset = new InsetFloatList("figure");
917 } else if (cmdName == "listoftables") {
918 inset = new InsetFloatList("table");
919 } else if (cmdName == "printindex") {
920 inset = new InsetPrintIndex(inscmd);
921 } else if (cmdName == "lyxparent") {
922 inset = new InsetParent(inscmd, *this);
925 if (tmptok == "Quotes") {
926 inset = new InsetQuotes;
927 } else if (tmptok == "External") {
928 inset = new InsetExternal;
929 } else if (tmptok == "FormulaMacro") {
930 inset = new InsetFormulaMacro;
931 } else if (tmptok == "Formula") {
932 inset = new InsetFormula;
933 } else if (tmptok == "Graphics") {
934 inset = new InsetGraphics;
935 } else if (tmptok == "Note") {
936 inset = new InsetNote(params);
937 } else if (tmptok == "Include") {
938 InsetCommandParams p("Include");
939 inset = new InsetInclude(p, *this);
940 } else if (tmptok == "ERT") {
941 inset = new InsetERT(params);
942 } else if (tmptok == "Tabular") {
943 inset = new InsetTabular(*this);
944 } else if (tmptok == "Text") {
945 inset = new InsetText(params);
946 } else if (tmptok == "Foot") {
947 inset = new InsetFoot(params);
948 } else if (tmptok == "Marginal") {
949 inset = new InsetMarginal(params);
950 } else if (tmptok == "OptArg") {
951 inset = new InsetOptArg(params);
952 } else if (tmptok == "Minipage") {
953 inset = new InsetMinipage(params);
954 } else if (tmptok == "Float") {
956 string tmptok = lex.getString();
957 inset = new InsetFloat(params, tmptok);
958 } else if (tmptok == "Wrap") {
960 string tmptok = lex.getString();
961 inset = new InsetWrap(params, tmptok);
963 } else if (tmptok == "List") {
964 inset = new InsetList;
965 } else if (tmptok == "Theorem") {
966 inset = new InsetList;
968 } else if (tmptok == "Caption") {
969 inset = new InsetCaption(params);
970 } else if (tmptok == "FloatList") {
971 inset = new InsetFloatList;
975 inset->read(this, lex);
979 par->insertInset(pos, inset, font, current_change);
985 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
989 string const token(lex.getString());
990 if (token == "\\lyxformat") { // the first token _must_ be...
992 string tmp_format = lex.getString();
993 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
994 // if present remove ".," from string.
995 string::size_type dot = tmp_format.find_first_of(".,");
996 //lyxerr << " dot found at " << dot << endl;
997 if (dot != string::npos)
998 tmp_format.erase(dot, 1);
999 file_format = strToInt(tmp_format);
1000 //lyxerr << "format: " << file_format << endl;
1001 if (file_format == LYX_FORMAT) {
1003 } else if (file_format > LYX_FORMAT) {
1005 Alert::alert(_("Warning!"),
1006 _("The file was created with a newer version of "
1007 "LyX. This is likely to cause problems."));
1009 } else if (file_format < LYX_FORMAT) {
1011 if (file_format < 200) {
1012 Alert::alert(_("ERROR!"),
1013 _("Old LyX file format found. "
1014 "Use LyX 0.10.x to read this!"));
1016 } else if (!filename.empty()) {
1018 LibFileSearch("lyx2lyx", "lyx2lyx");
1019 if (command.empty()) {
1020 Alert::alert(_("ERROR!"),
1021 _("Can't find conversion script."));
1025 +tostr(LYX_FORMAT) + ' '
1026 + QuoteName(filename);
1027 lyxerr[Debug::INFO] << "Running '"
1030 cmd_ret const ret = RunCommand(command);
1032 Alert::alert(_("ERROR!"),
1033 _("An error occured while "
1034 "running the conversion script."));
1037 istringstream is(STRCONV(ret.second));
1038 LyXLex tmplex(0, 0);
1039 tmplex.setStream(is);
1040 return readFile(tmplex, string(), par);
1042 // This code is reached if lyx2lyx failed (for
1043 // some reason) to change the file format of
1049 bool the_end = readBody(lex, par);
1050 params.setPaperStuff();
1053 Alert::alert(_("Warning!"),
1054 _("Reading of document is not complete"),
1055 _("Maybe the document is truncated"));
1058 } else { // "\\lyxformat" not found
1059 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1062 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1067 // Should probably be moved to somewhere else: BufferView? LyXView?
1068 bool Buffer::save() const
1070 // We don't need autosaves in the immediate future. (Asger)
1071 resetAutosaveTimers();
1075 if (lyxrc.make_backup) {
1076 s = fileName() + '~';
1077 if (!lyxrc.backupdir_path.empty())
1078 s = AddName(lyxrc.backupdir_path,
1079 subst(os::slashify_path(s),'/','!'));
1081 // Rename is the wrong way of making a backup,
1082 // this is the correct way.
1083 /* truss cp fil fil2:
1084 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1085 stat("LyXVC.lyx", 0xEFFFF688) = 0
1086 open("LyXVC.lyx", O_RDONLY) = 3
1087 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1088 fstat(4, 0xEFFFF508) = 0
1089 fstat(3, 0xEFFFF508) = 0
1090 read(3, " # T h i s f i l e w".., 8192) = 5579
1091 write(4, " # T h i s f i l e w".., 5579) = 5579
1092 read(3, 0xEFFFD4A0, 8192) = 0
1095 chmod("LyXVC3.lyx", 0100644) = 0
1096 lseek(0, 0, SEEK_CUR) = 46440
1100 // Should probably have some more error checking here.
1101 // Doing it this way, also makes the inodes stay the same.
1102 // This is still not a very good solution, in particular we
1103 // might loose the owner of the backup.
1104 FileInfo finfo(fileName());
1105 if (finfo.exist()) {
1106 mode_t fmode = finfo.getMode();
1107 struct utimbuf times = {
1108 finfo.getAccessTime(),
1109 finfo.getModificationTime() };
1111 ifstream ifs(fileName().c_str());
1112 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1117 ::chmod(s.c_str(), fmode);
1119 if (::utime(s.c_str(), ×)) {
1120 lyxerr << "utime error." << endl;
1123 lyxerr << "LyX was not able to make "
1124 "backup copy. Beware." << endl;
1129 if (writeFile(fileName())) {
1131 removeAutosaveFile(fileName());
1133 // Saving failed, so backup is not backup
1134 if (lyxrc.make_backup) {
1135 lyx::rename(s, fileName());
1143 bool Buffer::writeFile(string const & fname) const
1145 if (read_only && (fname == fileName())) {
1149 FileInfo finfo(fname);
1150 if (finfo.exist() && !finfo.writable()) {
1154 ofstream ofs(fname.c_str());
1160 // Use the standard "C" locale for file output.
1161 ofs.imbue(std::locale::classic());
1164 // The top of the file should not be written by params.
1166 // write out a comment in the top of the file
1167 ofs << '#' << lyx_docversion
1168 << " created this file. For more info see http://www.lyx.org/\n"
1169 << "\\lyxformat " << LYX_FORMAT << "\n";
1171 // now write out the buffer paramters.
1172 params.writeFile(ofs);
1174 ofs << "\\end_header\n";
1176 Paragraph::depth_type depth = 0;
1178 // this will write out all the paragraphs
1179 // using recursive descent.
1180 ParagraphList::iterator pit = paragraphs.begin();
1181 ParagraphList::iterator pend = paragraphs.end();
1182 for (; pit != pend; ++pit)
1183 pit->write(this, ofs, params, depth);
1185 // Write marker that shows file is complete
1186 ofs << "\n\\the_end" << endl;
1190 // how to check if close went ok?
1191 // Following is an attempt... (BE 20001011)
1193 // good() returns false if any error occured, including some
1194 // formatting error.
1195 // bad() returns true if something bad happened in the buffer,
1196 // which should include file system full errors.
1203 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1205 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1217 pair<int, string> const addDepth(int depth, int ldepth)
1221 d += (ldepth - depth) * 2;
1222 return make_pair(d, string(d, ' '));
1228 string const Buffer::asciiParagraph(Paragraph const & par,
1229 unsigned int linelen,
1230 bool noparbreak) const
1232 ostringstream buffer;
1233 Paragraph::depth_type depth = 0;
1235 Paragraph::depth_type ltype_depth = 0;
1236 bool ref_printed = false;
1237 // if (!par->previous()) {
1239 // begins or ends a deeper area ?
1240 if (depth != par->params().depth()) {
1241 if (par->params().depth() > depth) {
1242 while (par->params().depth() > depth) {
1246 while (par->params().depth() < depth) {
1252 depth = par.params().depth();
1255 // First write the layout
1256 string const & tmp = par.layout()->name();
1257 if (compare_no_case(tmp, "itemize") == 0) {
1259 ltype_depth = depth + 1;
1260 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1262 ltype_depth = depth + 1;
1263 } else if (contains(ascii_lowercase(tmp), "ection")) {
1265 ltype_depth = depth + 1;
1266 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1268 ltype_depth = depth + 1;
1269 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1271 ltype_depth = depth + 1;
1272 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1275 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1283 /* maybe some vertical spaces */
1285 /* the labelwidthstring used in lists */
1289 /* some pagebreaks? */
1293 /* what about the alignment */
1295 // lyxerr << "Should this ever happen?" << endl;
1298 // linelen <= 0 is special and means we don't have paragraph breaks
1300 string::size_type currlinelen = 0;
1306 buffer << string(depth * 2, ' ');
1307 currlinelen += depth * 2;
1310 // we should probably change to the paragraph language in the
1311 // gettext here (if possible) so that strings are outputted in
1312 // the correct language! (20012712 Jug)
1316 case 4: // (Sub)Paragraph
1317 case 5: // Description
1321 buffer << _("Abstract") << "\n\n";
1324 string const abst = _("Abstract: ");
1326 currlinelen += abst.length();
1329 case 7: // Bibliography
1332 buffer << _("References") << "\n\n";
1335 string const refs = _("References: ");
1337 currlinelen += refs.length();
1345 string const parlab = par.params().labelString();
1346 buffer << parlab << ' ';
1347 currlinelen += parlab.length() + 1;
1355 pair<int, string> p = addDepth(depth, ltype_depth);
1357 currlinelen += p.first;
1360 // this is to change the linebreak to do it by word a bit more
1361 // intelligent hopefully! (only in the case where we have a
1362 // max linelength!) (Jug)
1366 for (pos_type i = 0; i < par.size(); ++i) {
1367 char c = par.getUChar(params, i);
1369 case Paragraph::META_INSET:
1371 Inset const * inset = par.getInset(i);
1375 currlinelen += word.length();
1378 if (inset->ascii(this, buffer, linelen)) {
1379 // to be sure it breaks paragraph
1380 currlinelen += linelen;
1386 case Paragraph::META_NEWLINE:
1388 buffer << word << "\n";
1391 pair<int, string> p = addDepth(depth,
1394 currlinelen = p.first;
1401 currlinelen + word.length() > linelen - 10) {
1403 pair<int, string> p = addDepth(depth, ltype_depth);
1405 currlinelen = p.first;
1408 buffer << word << ' ';
1409 currlinelen += word.length() + 1;
1416 lyxerr[Debug::INFO] <<
1417 "writeAsciiFile: NULL char in structure." << endl;
1419 if ((linelen > 0) &&
1420 (currlinelen + word.length()) > linelen)
1424 pair<int, string> p =
1425 addDepth(depth, ltype_depth);
1427 currlinelen = p.first;
1434 return STRCONV(buffer.str());
1438 void Buffer::writeFileAscii(string const & fname, int linelen)
1440 ofstream ofs(fname.c_str());
1442 Alert::err_alert(_("Error: Cannot write file:"), fname);
1445 writeFileAscii(ofs, linelen);
1449 void Buffer::writeFileAscii(ostream & os, int linelen)
1451 ParagraphList::iterator beg = paragraphs.begin();
1452 ParagraphList::iterator end = paragraphs.end();
1453 ParagraphList::iterator it = beg;
1454 for (; it != end; ++it) {
1455 os << asciiParagraph(*it, linelen, it == beg);
1462 void Buffer::makeLaTeXFile(string const & fname,
1463 string const & original_path,
1464 bool nice, bool only_body, bool only_preamble)
1466 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1468 ofstream ofs(fname.c_str());
1470 Alert::err_alert(_("Error: Cannot open file: "), fname);
1474 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1478 lyxerr << "File was not closed properly." << endl;
1483 void Buffer::makeLaTeXFile(ostream & os,
1484 string const & original_path,
1485 bool nice, bool only_body, bool only_preamble)
1487 niceFile = nice; // this will be used by Insetincludes.
1489 // validate the buffer.
1490 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1491 LaTeXFeatures features(params);
1493 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1496 // The starting paragraph of the coming rows is the
1497 // first paragraph of the document. (Asger)
1498 texrow.start(&*(paragraphs.begin()), 0);
1500 if (!only_body && nice) {
1501 os << "%% " << lyx_docversion << " created this file. "
1502 "For more info, see http://www.lyx.org/.\n"
1503 "%% Do not edit unless you really know what "
1508 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1509 // There are a few differences between nice LaTeX and usual files:
1510 // usual is \batchmode and has a
1511 // special input@path to allow the including of figures
1512 // with either \input or \includegraphics (what figinsets do).
1513 // input@path is set when the actual parameter
1514 // original_path is set. This is done for usual tex-file, but not
1515 // for nice-latex-file. (Matthias 250696)
1518 // code for usual, NOT nice-latex-file
1519 os << "\\batchmode\n"; // changed
1520 // from \nonstopmode
1523 if (!original_path.empty()) {
1524 string inputpath = os::external_path(original_path);
1525 subst(inputpath, "~", "\\string~");
1526 os << "\\makeatletter\n"
1527 << "\\def\\input@path{{"
1528 << inputpath << "/}}\n"
1529 << "\\makeatother\n";
1535 // Write the preamble
1536 params.writeLaTeX(os, features, texrow);
1542 os << "\\begin{document}\n";
1545 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1547 if (!lyxrc.language_auto_begin) {
1548 os << subst(lyxrc.language_command_begin, "$$lang",
1549 params.language->babel())
1554 latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1556 // add this just in case after all the paragraphs
1560 if (!lyxrc.language_auto_end) {
1561 os << subst(lyxrc.language_command_end, "$$lang",
1562 params.language->babel())
1568 os << "\\end{document}\n";
1571 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1573 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1577 // Just to be sure. (Asger)
1580 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1581 lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1584 // we want this to be true outside previews (for insetexternal)
1589 bool Buffer::isLatex() const
1591 return params.getLyXTextClass().outputType() == LATEX;
1595 bool Buffer::isLinuxDoc() const
1597 return params.getLyXTextClass().outputType() == LINUXDOC;
1601 bool Buffer::isLiterate() const
1603 return params.getLyXTextClass().outputType() == LITERATE;
1607 bool Buffer::isDocBook() const
1609 return params.getLyXTextClass().outputType() == DOCBOOK;
1613 bool Buffer::isSGML() const
1615 LyXTextClass const & tclass = params.getLyXTextClass();
1617 return tclass.outputType() == LINUXDOC ||
1618 tclass.outputType() == DOCBOOK;
1622 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1624 ofstream ofs(fname.c_str());
1627 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
1631 niceFile = nice; // this will be used by included files.
1633 LaTeXFeatures features(params);
1639 LyXTextClass const & tclass = params.getLyXTextClass();
1641 string top_element = tclass.latexname();
1644 ofs << "<!doctype linuxdoc system";
1646 string preamble = params.preamble;
1647 const string name = nice ? ChangeExtension(filename_, ".sgml")
1649 preamble += features.getIncludedFiles(name);
1650 preamble += features.getLyXSGMLEntities();
1652 if (!preamble.empty()) {
1653 ofs << " [ " << preamble << " ]";
1657 if (params.options.empty())
1658 sgml::openTag(ofs, 0, false, top_element);
1660 string top = top_element;
1662 top += params.options;
1663 sgml::openTag(ofs, 0, false, top);
1667 ofs << "<!-- " << lyx_docversion
1668 << " created this file. For more info see http://www.lyx.org/"
1671 Paragraph::depth_type depth = 0; // paragraph depth
1672 Paragraph * par = &*(paragraphs.begin());
1674 vector<string> environment_stack(5);
1677 LyXLayout_ptr const & style = par->layout();
1678 // treat <toc> as a special case for compatibility with old code
1679 if (par->isInset(0)) {
1680 Inset * inset = par->getInset(0);
1681 Inset::Code lyx_code = inset->lyxCode();
1682 if (lyx_code == Inset::TOC_CODE) {
1683 string const temp = "toc";
1684 sgml::openTag(ofs, depth, false, temp);
1691 // environment tag closing
1692 for (; depth > par->params().depth(); --depth) {
1693 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1694 environment_stack[depth].erase();
1697 // write opening SGML tags
1698 switch (style->latextype) {
1699 case LATEX_PARAGRAPH:
1700 if (depth == par->params().depth()
1701 && !environment_stack[depth].empty()) {
1702 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1703 environment_stack[depth].erase();
1709 sgml::openTag(ofs, depth, false, style->latexname());
1715 _("Error: Wrong depth for LatexType Command.\n"));
1717 if (!environment_stack[depth].empty()) {
1718 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1722 environment_stack[depth].erase();
1723 sgml::openTag(ofs, depth, false, style->latexname());
1726 case LATEX_ENVIRONMENT:
1727 case LATEX_ITEM_ENVIRONMENT:
1728 case LATEX_BIB_ENVIRONMENT:
1730 string const & latexname = style->latexname();
1732 if (depth == par->params().depth()
1733 && environment_stack[depth] != latexname) {
1734 sgml::closeTag(ofs, depth, false,
1735 environment_stack[depth]);
1736 environment_stack[depth].erase();
1738 if (depth < par->params().depth()) {
1739 depth = par->params().depth();
1740 environment_stack[depth].erase();
1742 if (environment_stack[depth] != latexname) {
1744 sgml::openTag(ofs, depth, false, "p");
1746 sgml::openTag(ofs, depth, false, latexname);
1748 if (environment_stack.size() == depth + 1)
1749 environment_stack.push_back("!-- --");
1750 environment_stack[depth] = latexname;
1753 if (style->latexparam() == "CDATA")
1756 if (style->latextype == LATEX_ENVIRONMENT) break;
1758 if (style->labeltype == LABEL_MANUAL)
1763 sgml::openTag(ofs, depth + 1, false, item_name);
1768 sgml::openTag(ofs, depth, false, style->latexname());
1772 simpleLinuxDocOnePar(ofs, par, depth);
1777 // write closing SGML tags
1778 switch (style->latextype) {
1781 case LATEX_ENVIRONMENT:
1782 case LATEX_ITEM_ENVIRONMENT:
1783 case LATEX_BIB_ENVIRONMENT:
1784 if (style->latexparam() == "CDATA")
1788 sgml::closeTag(ofs, depth, false, style->latexname());
1794 for (int i = depth; i >= 0; --i)
1795 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1799 sgml::closeTag(ofs, 0, false, top_element);
1803 // How to check for successful close
1805 // we want this to be true outside previews (for insetexternal)
1810 // checks, if newcol chars should be put into this line
1811 // writes newline, if necessary.
1814 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1815 string::size_type newcol)
1818 if (colcount > lyxrc.ascii_linelen) {
1820 colcount = newcol; // assume write after this call
1835 string tag_name(PAR_TAG const & pt) {
1837 case NONE: return "!-- --";
1838 case TT: return "tt";
1839 case SF: return "sf";
1840 case BF: return "bf";
1841 case IT: return "it";
1842 case SL: return "sl";
1843 case EM: return "em";
1850 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1852 p1 = static_cast<PAR_TAG>(p1 | p2);
1857 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1859 p1 = static_cast<PAR_TAG>(p1 & ~p2);
1865 // Handle internal paragraph parsing -- layout already processed.
1866 void Buffer::simpleLinuxDocOnePar(ostream & os,
1868 Paragraph::depth_type /*depth*/)
1870 LyXLayout_ptr const & style = par->layout();
1872 string::size_type char_line_count = 5; // Heuristic choice ;-)
1874 // gets paragraph main font
1877 if (style->labeltype == LABEL_MANUAL) {
1878 font_old = style->labelfont;
1881 font_old = style->font;
1885 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1886 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1887 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
1890 stack<PAR_TAG> tag_state;
1891 // parsing main loop
1892 for (pos_type i = 0; i < par->size(); ++i) {
1894 PAR_TAG tag_close = NONE;
1895 list < PAR_TAG > tag_open;
1897 LyXFont const font = par->getFont(params, i);
1899 if (font_old.family() != font.family()) {
1900 switch (family_type) {
1901 case LyXFont::SANS_FAMILY:
1904 case LyXFont::TYPEWRITER_FAMILY:
1911 family_type = font.family();
1913 switch (family_type) {
1914 case LyXFont::SANS_FAMILY:
1915 tag_open.push_back(SF);
1917 case LyXFont::TYPEWRITER_FAMILY:
1918 tag_open.push_back(TT);
1925 if (font_old.series() != font.series()) {
1926 switch (series_type) {
1927 case LyXFont::BOLD_SERIES:
1934 series_type = font.series();
1936 switch (series_type) {
1937 case LyXFont::BOLD_SERIES:
1938 tag_open.push_back(BF);
1946 if (font_old.shape() != font.shape()) {
1947 switch (shape_type) {
1948 case LyXFont::ITALIC_SHAPE:
1951 case LyXFont::SLANTED_SHAPE:
1958 shape_type = font.shape();
1960 switch (shape_type) {
1961 case LyXFont::ITALIC_SHAPE:
1962 tag_open.push_back(IT);
1964 case LyXFont::SLANTED_SHAPE:
1965 tag_open.push_back(SL);
1972 if (font_old.emph() != font.emph()) {
1973 if (font.emph() == LyXFont::ON) {
1974 tag_open.push_back(EM);
1983 list < PAR_TAG > temp;
1984 while (!tag_state.empty() && tag_close) {
1985 PAR_TAG k = tag_state.top();
1987 os << "</" << tag_name(k) << '>';
1994 for(list< PAR_TAG >::const_iterator j = temp.begin();
1995 j != temp.end(); ++j) {
1997 os << '<' << tag_name(*j) << '>';
2000 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2001 j != tag_open.end(); ++j) {
2003 os << '<' << tag_name(*j) << '>';
2006 char c = par->getChar(i);
2008 if (c == Paragraph::META_INSET) {
2009 Inset * inset = par->getInset(i);
2010 inset->linuxdoc(this, os);
2015 if (style->latexparam() == "CDATA") {
2016 // "TeX"-Mode on == > SGML-Mode on.
2023 boost::tie(ws, str) = sgml::escapeChar(c);
2024 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2025 // in freespacing mode, spaces are
2026 // non-breaking characters
2027 if (desc_on) {// if char is ' ' then...
2030 sgmlLineBreak(os, char_line_count, 6);
2034 sgmlLineBreak(os, char_line_count, 1);
2039 char_line_count += str.length();
2045 while (!tag_state.empty()) {
2046 os << "</" << tag_name(tag_state.top()) << '>';
2050 // resets description flag correctly
2052 // <tag> not closed...
2053 sgmlLineBreak(os, char_line_count, 6);
2059 // Print an error message.
2060 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2061 string const & /*message*/) const
2063 #ifdef WITH_WARNINGS
2064 #warning This is wrong we cannot insert an inset like this!!!
2065 // I guess this was Jose' so I explain you more or less why this
2066 // is wrong. This way you insert something in the paragraph and
2067 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2068 // I deactivate this code, have a look at BufferView::insertErrors
2069 // how you should do this correctly! (Jug 20020315)
2072 // insert an error marker in text
2073 InsetError * new_inset = new InsetError(message);
2074 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2080 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2082 ofstream ofs(fname.c_str());
2084 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2088 Paragraph * par = &*(paragraphs.begin());
2090 niceFile = nice; // this will be used by Insetincludes.
2092 LaTeXFeatures features(params);
2097 LyXTextClass const & tclass = params.getLyXTextClass();
2098 string top_element = tclass.latexname();
2101 ofs << "<!DOCTYPE " << top_element
2102 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2104 string preamble = params.preamble;
2105 const string name = nice ? ChangeExtension(filename_, ".sgml")
2107 preamble += features.getIncludedFiles(name);
2108 preamble += features.getLyXSGMLEntities();
2110 if (!preamble.empty()) {
2111 ofs << "\n [ " << preamble << " ]";
2116 string top = top_element;
2118 top += params.language->code();
2121 if (!params.options.empty()) {
2123 top += params.options;
2125 sgml::openTag(ofs, 0, false, top);
2127 ofs << "<!-- DocBook file was created by " << lyx_docversion
2128 << "\n See http://www.lyx.org/ for more information -->\n";
2130 vector<string> environment_stack(10);
2131 vector<string> environment_inner(10);
2132 vector<string> command_stack(10);
2134 bool command_flag = false;
2135 Paragraph::depth_type command_depth = 0;
2136 Paragraph::depth_type command_base = 0;
2137 Paragraph::depth_type cmd_depth = 0;
2138 Paragraph::depth_type depth = 0; // paragraph depth
2141 string command_name;
2147 int desc_on = 0; // description mode
2149 LyXLayout_ptr const & style = par->layout();
2151 // environment tag closing
2152 for (; depth > par->params().depth(); --depth) {
2153 if (environment_inner[depth] != "!-- --") {
2154 item_name = "listitem";
2155 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2156 if (environment_inner[depth] == "varlistentry")
2157 sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2159 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2160 environment_stack[depth].erase();
2161 environment_inner[depth].erase();
2164 if (depth == par->params().depth()
2165 && environment_stack[depth] != style->latexname()
2166 && !environment_stack[depth].empty()) {
2167 if (environment_inner[depth] != "!-- --") {
2168 item_name= "listitem";
2169 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2170 if (environment_inner[depth] == "varlistentry")
2171 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2174 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2176 environment_stack[depth].erase();
2177 environment_inner[depth].erase();
2180 // Write opening SGML tags.
2181 switch (style->latextype) {
2182 case LATEX_PARAGRAPH:
2183 sgml::openTag(ofs, depth + command_depth,
2184 false, style->latexname());
2190 _("Error: Wrong depth for LatexType Command.\n"));
2192 command_name = style->latexname();
2194 sgmlparam = style->latexparam();
2195 c_params = split(sgmlparam, c_depth,'|');
2197 cmd_depth = lyx::atoi(c_depth);
2200 if (cmd_depth < command_base) {
2201 for (Paragraph::depth_type j = command_depth;
2202 j >= command_base; --j) {
2203 sgml::closeTag(ofs, j, false, command_stack[j]);
2206 command_depth = command_base = cmd_depth;
2207 } else if (cmd_depth <= command_depth) {
2208 for (int j = command_depth;
2209 j >= int(cmd_depth); --j) {
2210 sgml::closeTag(ofs, j, false, command_stack[j]);
2213 command_depth = cmd_depth;
2215 command_depth = cmd_depth;
2217 command_depth = command_base = cmd_depth;
2218 command_flag = true;
2220 if (command_stack.size() == command_depth + 1)
2221 command_stack.push_back(string());
2222 command_stack[command_depth] = command_name;
2224 // treat label as a special case for
2225 // more WYSIWYM handling.
2226 // This is a hack while paragraphs can't have
2227 // attributes, like id in this case.
2228 if (par->isInset(0)) {
2229 Inset * inset = par->getInset(0);
2230 Inset::Code lyx_code = inset->lyxCode();
2231 if (lyx_code == Inset::LABEL_CODE) {
2232 command_name += " id=\"";
2233 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2234 command_name += '"';
2239 sgml::openTag(ofs, depth + command_depth, false, command_name);
2241 item_name = c_params.empty() ? "title" : c_params;
2242 sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2245 case LATEX_ENVIRONMENT:
2246 case LATEX_ITEM_ENVIRONMENT:
2247 if (depth < par->params().depth()) {
2248 depth = par->params().depth();
2249 environment_stack[depth].erase();
2252 if (environment_stack[depth] != style->latexname()) {
2253 if (environment_stack.size() == depth + 1) {
2254 environment_stack.push_back("!-- --");
2255 environment_inner.push_back("!-- --");
2257 environment_stack[depth] = style->latexname();
2258 environment_inner[depth] = "!-- --";
2259 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2261 if (environment_inner[depth] != "!-- --") {
2262 item_name= "listitem";
2263 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2264 if (environment_inner[depth] == "varlistentry")
2265 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2269 if (style->latextype == LATEX_ENVIRONMENT) {
2270 if (!style->latexparam().empty()) {
2271 if (style->latexparam() == "CDATA")
2274 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2279 desc_on = (style->labeltype == LABEL_MANUAL);
2281 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2282 sgml::openTag(ofs, depth + 1 + command_depth,
2283 false, environment_inner[depth]);
2285 item_name = desc_on ? "term" : "para";
2286 sgml::openTag(ofs, depth + 1 + command_depth,
2290 sgml::openTag(ofs, depth + command_depth,
2291 false, style->latexname());
2295 simpleDocBookOnePar(ofs, par, desc_on,
2296 depth + 1 + command_depth);
2300 // write closing SGML tags
2301 switch (style->latextype) {
2303 end_tag = c_params.empty() ? "title" : c_params;
2304 sgml::closeTag(ofs, depth + command_depth,
2307 case LATEX_ENVIRONMENT:
2308 if (!style->latexparam().empty()) {
2309 if (style->latexparam() == "CDATA")
2312 sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2315 case LATEX_ITEM_ENVIRONMENT:
2316 if (desc_on == 1) break;
2318 sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2320 case LATEX_PARAGRAPH:
2321 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2324 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2330 for (int d = depth; d >= 0; --d) {
2331 if (!environment_stack[depth].empty()) {
2332 if (environment_inner[depth] != "!-- --") {
2333 item_name = "listitem";
2334 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2335 if (environment_inner[depth] == "varlistentry")
2336 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2339 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2343 for (int j = command_depth; j >= 0 ; --j)
2344 if (!command_stack[j].empty()) {
2345 sgml::closeTag(ofs, j, false, command_stack[j]);
2350 sgml::closeTag(ofs, 0, false, top_element);
2353 // How to check for successful close
2355 // we want this to be true outside previews (for insetexternal)
2360 void Buffer::simpleDocBookOnePar(ostream & os,
2361 Paragraph * par, int & desc_on,
2362 Paragraph::depth_type depth) const
2364 bool emph_flag = false;
2366 LyXLayout_ptr const & style = par->layout();
2368 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2370 int char_line_count = depth;
2371 //if (!style.free_spacing)
2372 // os << string(depth,' ');
2374 // parsing main loop
2375 for (pos_type i = 0; i < par->size(); ++i) {
2376 LyXFont font = par->getFont(params, i);
2378 // handle <emphasis> tag
2379 if (font_old.emph() != font.emph()) {
2380 if (font.emph() == LyXFont::ON) {
2381 if (style->latexparam() == "CDATA")
2384 if (style->latexparam() == "CDATA")
2388 if (style->latexparam() == "CDATA")
2390 os << "</emphasis>";
2391 if (style->latexparam() == "CDATA")
2398 if (par->isInset(i)) {
2399 Inset * inset = par->getInset(i);
2400 // don't print the inset in position 0 if desc_on == 3 (label)
2401 if (i || desc_on != 3) {
2402 if (style->latexparam() == "CDATA")
2404 inset->docbook(this, os, false);
2405 if (style->latexparam() == "CDATA")
2409 char c = par->getChar(i);
2412 boost::tie(ws, str) = sgml::escapeChar(c);
2414 if (style->pass_thru) {
2416 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
2418 } else if (desc_on ==1) {
2420 os << "\n</term><listitem><para>";
2430 if (style->latexparam() == "CDATA")
2432 os << "</emphasis>";
2433 if (style->latexparam() == "CDATA")
2437 // resets description flag correctly
2439 // <term> not closed...
2440 os << "</term>\n<listitem><para> </para>";
2442 if (style->free_spacing)
2447 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2448 // Other flags: -wall -v0 -x
2449 int Buffer::runChktex()
2451 if (!users->text) return 0;
2453 users->owner()->busy(true);
2455 // get LaTeX-Filename
2456 string const name = getLatexName();
2457 string path = filePath();
2459 string const org_path = path;
2460 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2464 Path p(path); // path to LaTeX file
2465 users->owner()->message(_("Running chktex..."));
2467 // Remove all error insets
2468 bool const removedErrorInsets = users->removeAutoInsets();
2470 // Generate the LaTeX file if neccessary
2471 makeLaTeXFile(name, org_path, false);
2474 Chktex chktex(lyxrc.chktex_command, name, filePath());
2475 int res = chktex.run(terr); // run chktex
2478 Alert::alert(_("chktex did not work!"),
2479 _("Could not run with file:"), name);
2480 } else if (res > 0) {
2481 // Insert all errors as errors boxes
2482 users->insertErrors(terr);
2485 // if we removed error insets before we ran chktex or if we inserted
2486 // error insets after we ran chktex, this must be run:
2487 if (removedErrorInsets || res) {
2488 #warning repaint needed here, or do you mean update() ?
2492 users->owner()->busy(false);
2498 void Buffer::validate(LaTeXFeatures & features) const
2500 LyXTextClass const & tclass = params.getLyXTextClass();
2502 if (params.tracking_changes) {
2503 features.require("dvipost");
2504 features.require("color");
2507 // AMS Style is at document level
2508 if (params.use_amsmath == BufferParams::AMS_ON
2509 || tclass.provides(LyXTextClass::amsmath))
2510 features.require("amsmath");
2512 for_each(paragraphs.begin(), paragraphs.end(),
2513 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2515 // the bullet shapes are buffer level not paragraph level
2516 // so they are tested here
2517 for (int i = 0; i < 4; ++i) {
2518 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2519 int const font = params.user_defined_bullets[i].getFont();
2521 int const c = params
2522 .user_defined_bullets[i]
2529 features.require("latexsym");
2531 } else if (font == 1) {
2532 features.require("amssymb");
2533 } else if ((font >= 2 && font <= 5)) {
2534 features.require("pifont");
2539 if (lyxerr.debugging(Debug::LATEX)) {
2540 features.showStruct();
2545 vector<string> const Buffer::getLabelList() const
2547 /// if this is a child document and the parent is already loaded
2548 /// Use the parent's list instead [ale990407]
2549 if (!params.parentname.empty()
2550 && bufferlist.exists(params.parentname)) {
2551 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2553 return tmp->getLabelList();
2556 vector<string> label_list;
2557 for (inset_iterator it = inset_const_iterator_begin();
2558 it != inset_const_iterator_end(); ++it) {
2559 vector<string> const l = it->getLabelList();
2560 label_list.insert(label_list.end(), l.begin(), l.end());
2566 // This is also a buffer property (ale)
2567 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2569 /// if this is a child document and the parent is already loaded
2570 /// use the parent's list instead [ale990412]
2571 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2572 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2574 tmp->fillWithBibKeys(keys);
2579 for (inset_iterator it = inset_const_iterator_begin();
2580 it != inset_const_iterator_end(); ++it) {
2581 if (it->lyxCode() == Inset::BIBTEX_CODE)
2582 static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2583 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2584 static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2585 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2586 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2587 string const key = bib.getContents();
2588 string const opt = bib.getOptions();
2589 string const ref; // = pit->asString(this, false);
2590 string const info = opt + "TheBibliographyRef" + ref;
2591 keys.push_back(pair<string, string>(key, info));
2597 bool Buffer::isDepClean(string const & name) const
2599 DepClean::const_iterator it = dep_clean_.find(name);
2600 if (it == dep_clean_.end())
2606 void Buffer::markDepClean(string const & name)
2608 dep_clean_[name] = true;
2612 bool Buffer::dispatch(string const & command, bool * result)
2614 // Split command string into command and argument
2616 string line = ltrim(command);
2617 string const arg = trim(split(line, cmd, ' '));
2619 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2623 bool Buffer::dispatch(int action, string const & argument, bool * result)
2625 bool dispatched = true;
2629 bool const tmp = Exporter::Export(this, argument, false);
2642 void Buffer::resizeInsets(BufferView * bv)
2644 /// then remove all LyXText in text-insets
2645 for_each(paragraphs.begin(), paragraphs.end(),
2646 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2650 void Buffer::redraw()
2652 #warning repaint needed here, or do you mean update() ?
2658 void Buffer::changeLanguage(Language const * from, Language const * to)
2661 ParIterator end = par_iterator_end();
2662 for (ParIterator it = par_iterator_begin(); it != end; ++it)
2663 (*it)->changeLanguage(params, from, to);
2667 bool Buffer::isMultiLingual()
2669 ParIterator end = par_iterator_end();
2670 for (ParIterator it = par_iterator_begin(); it != end; ++it)
2671 if ((*it)->isMultiLingual(params))
2678 void Buffer::inset_iterator::setParagraph()
2680 while (pit != pend) {
2681 it = pit->insetlist.begin();
2682 if (it != pit->insetlist.end())
2689 Inset * Buffer::getInsetFromID(int id_arg) const
2691 for (inset_iterator it = inset_const_iterator_begin();
2692 it != inset_const_iterator_end(); ++it)
2694 if (it->id() == id_arg)
2696 Inset * in = it->getInsetFromID(id_arg);
2704 Paragraph * Buffer::getParFromID(int id) const
2709 // why should we allow < 0 ??
2710 //lyx::Assert(id >= 0);
2712 ParConstIterator it(par_iterator_begin());
2713 ParConstIterator end(par_iterator_end());
2715 for (; it != end; ++it) {
2716 // go on then, show me how to remove
2718 if ((*it)->id() == id) {
2719 return const_cast<Paragraph*>(*it);
2727 ParIterator Buffer::par_iterator_begin()
2729 return ParIterator(&*(paragraphs.begin()));
2733 ParIterator Buffer::par_iterator_end()
2735 return ParIterator();
2738 ParConstIterator Buffer::par_iterator_begin() const
2740 return ParConstIterator(&*(paragraphs.begin()));
2744 ParConstIterator Buffer::par_iterator_end() const
2746 return ParConstIterator();
2751 void Buffer::addUser(BufferView * u)
2757 void Buffer::delUser(BufferView *)
2763 Language const * Buffer::getLanguage() const
2765 return params.language;
2769 bool Buffer::isClean() const
2775 bool Buffer::isBakClean() const
2781 void Buffer::markClean() const
2787 // if the .lyx file has been saved, we don't need an
2793 void Buffer::markBakClean()
2799 void Buffer::setUnnamed(bool flag)
2805 bool Buffer::isUnnamed()
2811 void Buffer::markDirty()
2819 DepClean::iterator it = dep_clean_.begin();
2820 DepClean::const_iterator const end = dep_clean_.end();
2822 for (; it != end; ++it) {
2828 string const & Buffer::fileName() const
2834 string const & Buffer::filePath() const
2840 bool Buffer::isReadonly() const
2846 BufferView * Buffer::getUser() const
2852 void Buffer::setParentName(string const & name)
2854 params.parentname = name;
2858 Buffer::inset_iterator::inset_iterator()
2863 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2870 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2874 if (it == pit->insetlist.end()) {
2883 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2885 inset_iterator tmp = *this;
2891 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2893 return *it.getInset();
2897 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2899 return it.getInset();
2903 Paragraph * Buffer::inset_iterator::getPar()
2909 lyx::pos_type Buffer::inset_iterator::getPos() const
2915 bool operator==(Buffer::inset_iterator const & iter1,
2916 Buffer::inset_iterator const & iter2)
2918 return iter1.pit == iter2.pit
2919 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2923 bool operator!=(Buffer::inset_iterator const & iter1,
2924 Buffer::inset_iterator const & iter2)
2926 return !(iter1 == iter2);