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, ParagraphList::iterator pit)
345 int unknown_tokens = 0;
348 Paragraph::depth_type depth = 0;
349 bool the_end_read = false;
351 LyXFont font(LyXFont::ALL_INHERIT, params.language);
353 if (paragraphs.empty()) {
354 unknown_tokens += readHeader(lex);
356 if (!params.getLyXTextClass().load()) {
358 Alert::alert(_("Textclass Loading Error!"),
359 boost::io::str(boost::format(_("Can't load textclass %1$s")) %
360 params.getLyXTextClass().name()),
361 _("-- substituting default."));
363 Alert::alert(_("Textclass Loading Error!"),
364 _("Can't load textclass ")
365 + params.getLyXTextClass().name(),
366 _("-- substituting default."));
368 params.textclass = 0;
371 // We are inserting into an existing document
372 users->text->breakParagraph(users, paragraphs);
376 // We don't want to adopt the parameters from the
377 // document we insert, so read them into a temporary buffer
378 // and then discard it
380 Buffer tmpbuf("", false);
381 tmpbuf.readHeader(lex);
386 string const token = lex.getString();
391 lyxerr[Debug::PARSER] << "Handling token: `"
392 << token << '\'' << endl;
394 if (token == "\\the_end") {
399 unknown_tokens += readToken(lex, paragraphs, pit, token, pos, depth, font);
402 if (unknown_layouts > 0) {
403 string s = _("Couldn't set the layout for ");
404 if (unknown_layouts == 1) {
405 s += _("one paragraph");
407 s += tostr(unknown_layouts);
408 s += _(" paragraphs");
411 Alert::alert(_("Textclass Loading Error!"), s,
412 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
414 Alert::alert(_("Textclass Loading Error!"), s,
415 _("When reading ") + fileName());
419 if (unknown_tokens > 0) {
420 string s = _("Encountered ");
421 if (unknown_tokens == 1) {
422 s += _("one unknown token");
424 s += tostr(unknown_tokens);
425 s += _(" unknown tokens");
428 Alert::alert(_("Textclass Loading Error!"), s,
429 boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
431 Alert::alert(_("Textclass Loading Error!"), s,
432 _("When reading ") + fileName());
441 Buffer::readToken(LyXLex & lex, ParagraphList & pars,
442 ParagraphList::iterator & pit,
443 string const & token, int & pos,
444 Paragraph::depth_type & depth,
447 static Change current_change;
450 // The order of the tags tested may seem unnatural, but this
451 // has been done in order to reduce the number of string
452 // comparisons needed to recognize a given token. This leads
453 // on large documents like UserGuide to a reduction of a
455 if (token[0] != '\\') {
456 for (string::const_iterator cit = token.begin();
457 cit != token.end(); ++cit) {
458 pit->insertChar(pos, (*cit), font, current_change);
461 } else if (token == "\\layout") {
462 // reset the font as we start a new layout and if the font is
463 // not ALL_INHERIT,document_language then it will be set to the
464 // right values after this tag (Jug 20020420)
465 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
468 string layoutname = lex.getString();
470 LyXTextClass const & tclass = params.getLyXTextClass();
472 if (layoutname.empty()) {
473 layoutname = tclass.defaultLayoutName();
475 bool hasLayout = tclass.hasLayout(layoutname);
477 lyxerr << "Layout '" << layoutname << "' does not"
478 << " exist in textclass '" << tclass.name()
480 lyxerr << "Trying to use default layout instead."
482 layoutname = tclass.defaultLayoutName();
486 // The is the compability reading of layout caption.
487 // It can be removed in LyX version 1.3.0. (Lgb)
488 if (compare_ascii_no_case(layoutname, "caption") == 0) {
489 // We expect that the par we are now working on is
490 // really inside a InsetText inside a InsetFloat.
491 // We also know that captions can only be
492 // one paragraph. (Lgb)
494 // We should now read until the next "\layout"
496 // This is probably not good enough, what if the
497 // caption is the last par in the document (Lgb)
498 istream & ist = lex.getStream();
504 if (prefixIs(line, "\\layout")) {
508 if (prefixIs(line, "\\begin_inset"))
510 if (prefixIs(line, "\\end_inset")) {
521 // Now we should have the whole layout in ss
522 // we should now be able to give this to the
524 ss << "\\end_inset\n";
526 // This seems like a bug in stringstream.
527 // We really should be able to use ss
529 istringstream is(ss.str());
531 tmplex.setStream(is);
532 Inset * inset = new InsetCaption;
533 inset->Read(this, tmplex);
534 pit->InsertInset(pos, inset, font);
538 Paragraph * par = new Paragraph();
539 par->layout(params.getLyXTextClass().defaultLayout());
540 if (params.tracking_changes)
543 par->layout(params.getLyXTextClass()[layoutname]);
544 // Test whether the layout is obsolete.
545 LyXLayout_ptr const & layout = par->layout();
546 if (!layout->obsoleted_by().empty())
547 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
548 par->params().depth(depth);
550 if (pit != pars.end())
552 pit = pars.insert(pit, par);
557 } else if (token == "\\end_inset") {
558 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
559 << "Missing \\begin_inset?.\n";
560 // Simply ignore this. The insets do not have
562 // But insets should read it, it is a part of
563 // the inset isn't it? Lgb.
564 } else if (token == "\\begin_inset") {
565 readInset(lex, pit, pos, font, current_change);
566 } else if (token == "\\family") {
568 font.setLyXFamily(lex.getString());
569 } else if (token == "\\series") {
571 font.setLyXSeries(lex.getString());
572 } else if (token == "\\shape") {
574 font.setLyXShape(lex.getString());
575 } else if (token == "\\size") {
577 font.setLyXSize(lex.getString());
578 } else if (token == "\\lang") {
580 string const tok = lex.getString();
581 Language const * lang = languages.getLanguage(tok);
583 font.setLanguage(lang);
585 font.setLanguage(params.language);
586 lex.printError("Unknown language `$$Token'");
588 } else if (token == "\\numeric") {
590 font.setNumber(font.setLyXMisc(lex.getString()));
591 } else if (token == "\\emph") {
593 font.setEmph(font.setLyXMisc(lex.getString()));
594 } else if (token == "\\bar") {
596 string const tok = lex.getString();
597 // This is dirty, but gone with LyX3. (Asger)
599 font.setUnderbar(LyXFont::ON);
600 else if (tok == "no")
601 font.setUnderbar(LyXFont::OFF);
602 else if (tok == "default")
603 font.setUnderbar(LyXFont::INHERIT);
605 lex.printError("Unknown bar font flag "
607 } else if (token == "\\noun") {
609 font.setNoun(font.setLyXMisc(lex.getString()));
610 } else if (token == "\\color") {
612 font.setLyXColor(lex.getString());
613 } else if (token == "\\SpecialChar") {
614 LyXLayout_ptr const & layout = pit->layout();
616 // Insets don't make sense in a free-spacing context! ---Kayvan
617 if (layout->free_spacing || pit->isFreeSpacing()) {
620 string const next_token = lex.getString();
621 if (next_token == "\\-") {
622 pit->insertChar(pos, '-', font, current_change);
623 } else if (next_token == "~") {
624 pit->insertChar(pos, ' ', font, current_change);
626 lex.printError("Token `$$Token' "
628 "paragraph layout!");
633 Inset * inset = new InsetSpecialChar;
634 inset->read(this, lex);
635 pit->insertInset(pos, inset, font, current_change);
638 } else if (token == "\\i") {
639 Inset * inset = new InsetLatexAccent;
640 inset->read(this, lex);
641 pit->insertInset(pos, inset, font, current_change);
643 } else if (token == "\\backslash") {
644 pit->insertChar(pos, '\\', font, current_change);
646 } else if (token == "\\begin_deeper") {
648 } else if (token == "\\end_deeper") {
650 lex.printError("\\end_deeper: "
651 "depth is already null");
655 } else if (token == "\\noindent") {
656 pit->params().noindent(true);
657 } else if (token == "\\leftindent") {
659 LyXLength value(lex.getString());
660 pit->params().leftIndent(value);
661 } else if (token == "\\fill_top") {
662 pit->params().spaceTop(VSpace(VSpace::VFILL));
663 } else if (token == "\\fill_bottom") {
664 pit->params().spaceBottom(VSpace(VSpace::VFILL));
665 } else if (token == "\\line_top") {
666 pit->params().lineTop(true);
667 } else if (token == "\\line_bottom") {
668 pit->params().lineBottom(true);
669 } else if (token == "\\pagebreak_top") {
670 pit->params().pagebreakTop(true);
671 } else if (token == "\\pagebreak_bottom") {
672 pit->params().pagebreakBottom(true);
673 } else if (token == "\\start_of_appendix") {
674 pit->params().startOfAppendix(true);
675 } else if (token == "\\paragraph_spacing") {
677 string const tmp = rtrim(lex.getString());
678 if (tmp == "single") {
679 pit->params().spacing(Spacing(Spacing::Single));
680 } else if (tmp == "onehalf") {
681 pit->params().spacing(Spacing(Spacing::Onehalf));
682 } else if (tmp == "double") {
683 pit->params().spacing(Spacing(Spacing::Double));
684 } else if (tmp == "other") {
686 pit->params().spacing(Spacing(Spacing::Other,
689 lex.printError("Unknown spacing token: '$$Token'");
691 } else if (token == "\\align") {
692 int tmpret = lex.findToken(string_align);
695 int const tmpret2 = int(pow(2.0, tmpret));
696 pit->params().align(LyXAlignment(tmpret2));
697 } else if (token == "\\added_space_top") {
699 VSpace value = VSpace(lex.getString());
700 // only add the length when value > 0 or
702 if ((value.length().len().value() != 0) ||
704 (value.kind() != VSpace::LENGTH))
705 pit->params().spaceTop(value);
706 } else if (token == "\\added_space_bottom") {
708 VSpace value = VSpace(lex.getString());
709 // only add the length when value > 0 or
711 if ((value.length().len().value() != 0) ||
713 (value.kind() != VSpace::LENGTH))
714 pit->params().spaceBottom(value);
715 } else if (token == "\\labelwidthstring") {
717 pit->params().labelWidthString(lex.getString());
718 // do not delete this token, it is still needed!
719 } else if (token == "\\newline") {
720 pit->insertChar(pos, Paragraph::META_NEWLINE, font, current_change);
722 } else if (token == "\\LyXTable") {
723 Inset * inset = new InsetTabular(*this);
724 inset->read(this, lex);
725 pit->insertInset(pos, inset, font, current_change);
727 } else if (token == "\\bibitem") { // ale970302
728 InsetCommandParams p("bibitem", "dummy");
729 InsetBibitem * inset = new InsetBibitem(p);
730 inset->read(this, lex);
731 pit->insertInset(pos, inset, font, current_change);
733 } else if (token == "\\hfill") {
734 pit->insertInset(pos, new InsetHFill(),
735 LyXFont(LyXFont::ALL_INHERIT, params.language));
737 } else if (token == "\\change_unchanged") {
738 // Hack ! Needed for empty paragraphs :/
741 current_change = Change(Change::UNCHANGED);
742 } else if (token == "\\change_inserted") {
744 istringstream istr(lex.getString());
749 current_change = Change(Change::INSERTED, params.author_ids[aid], ct);
750 } else if (token == "\\change_deleted") {
752 istringstream istr(lex.getString());
757 current_change = Change(Change::DELETED, params.author_ids[aid], ct);
759 // This should be insurance for the future: (Asger)
763 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
764 fmt % token % lex.text();
765 string const s = fmt.str();
767 string const s = _("Unknown token: ") + token
768 + ' ' + lex.text() + '\n';
770 // we can do this here this way because we're actually reading
771 // the buffer and don't care about LyXText right now.
772 InsetError * new_inset = new InsetError(s);
773 pit->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
782 // needed to insert the selection
783 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
784 LyXFont const & fn,string const & str)
786 LyXLayout_ptr const & layout = par->layout();
790 par->checkInsertChar(font);
791 // insert the string, don't insert doublespace
792 bool space_inserted = true;
793 bool autobreakrows = !par->inInset() ||
794 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
795 for(string::const_iterator cit = str.begin();
796 cit != str.end(); ++cit) {
798 if (autobreakrows && (!par->empty() || layout->keepempty)) {
799 breakParagraph(params, paragraphs, par, pos,
800 layout->isEnvironment());
803 space_inserted = true;
807 // do not insert consecutive spaces if !free_spacing
808 } else if ((*cit == ' ' || *cit == '\t') &&
809 space_inserted && !layout->free_spacing &&
810 !par->isFreeSpacing())
813 } else if (*cit == '\t') {
814 if (!layout->free_spacing && !par->isFreeSpacing()) {
815 // tabs are like spaces here
816 par->insertChar(pos, ' ', font);
818 space_inserted = true;
820 const pos_type nb = 8 - pos % 8;
821 for (pos_type a = 0; a < nb ; ++a) {
822 par->insertChar(pos, ' ', font);
825 space_inserted = true;
827 } else if (!IsPrintable(*cit)) {
828 // Ignore unprintables
831 // just insert the character
832 par->insertChar(pos, *cit, font);
834 space_inserted = (*cit == ' ');
841 void Buffer::readInset(LyXLex & lex, ParagraphList::iterator pit,
842 int & pos, LyXFont & font, Change current_change)
845 if (lex.getString() != "\\begin_inset") {
846 lyxerr << "Buffer::readInset: Consistency check failed."
853 string const tmptok = lex.getString();
855 // test the different insets
856 if (tmptok == "LatexCommand") {
857 InsetCommandParams inscmd;
860 string const cmdName = inscmd.getCmdName();
862 // This strange command allows LyX to recognize "natbib" style
863 // citations: citet, citep, Citet etc.
864 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
865 inset = new InsetCitation(inscmd);
866 } else if (cmdName == "bibitem") {
867 lex.printError("Wrong place for bibitem");
868 inset = new InsetBibitem(inscmd);
869 } else if (cmdName == "BibTeX") {
870 inset = new InsetBibtex(inscmd);
871 } else if (cmdName == "index") {
872 inset = new InsetIndex(inscmd);
873 } else if (cmdName == "include") {
874 inset = new InsetInclude(inscmd, *this);
875 } else if (cmdName == "label") {
876 inset = new InsetLabel(inscmd);
877 } else if (cmdName == "url"
878 || cmdName == "htmlurl") {
879 inset = new InsetUrl(inscmd);
880 } else if (cmdName == "ref"
881 || cmdName == "pageref"
883 || cmdName == "vpageref"
884 || cmdName == "prettyref") {
885 if (!inscmd.getOptions().empty()
886 || !inscmd.getContents().empty()) {
887 inset = new InsetRef(inscmd, *this);
889 } else if (cmdName == "tableofcontents") {
890 inset = new InsetTOC(inscmd);
891 } else if (cmdName == "listofalgorithms") {
892 inset = new InsetFloatList("algorithm");
893 } else if (cmdName == "listoffigures") {
894 inset = new InsetFloatList("figure");
895 } else if (cmdName == "listoftables") {
896 inset = new InsetFloatList("table");
897 } else if (cmdName == "printindex") {
898 inset = new InsetPrintIndex(inscmd);
899 } else if (cmdName == "lyxparent") {
900 inset = new InsetParent(inscmd, *this);
903 if (tmptok == "Quotes") {
904 inset = new InsetQuotes;
905 } else if (tmptok == "External") {
906 inset = new InsetExternal;
907 } else if (tmptok == "FormulaMacro") {
908 inset = new InsetFormulaMacro;
909 } else if (tmptok == "Formula") {
910 inset = new InsetFormula;
911 } else if (tmptok == "Graphics") {
912 inset = new InsetGraphics;
913 } else if (tmptok == "Note") {
914 inset = new InsetNote(params);
915 } else if (tmptok == "Include") {
916 InsetCommandParams p("Include");
917 inset = new InsetInclude(p, *this);
918 } else if (tmptok == "ERT") {
919 inset = new InsetERT(params);
920 } else if (tmptok == "Tabular") {
921 inset = new InsetTabular(*this);
922 } else if (tmptok == "Text") {
923 inset = new InsetText(params);
924 } else if (tmptok == "Foot") {
925 inset = new InsetFoot(params);
926 } else if (tmptok == "Marginal") {
927 inset = new InsetMarginal(params);
928 } else if (tmptok == "OptArg") {
929 inset = new InsetOptArg(params);
930 } else if (tmptok == "Minipage") {
931 inset = new InsetMinipage(params);
932 } else if (tmptok == "Float") {
934 string tmptok = lex.getString();
935 inset = new InsetFloat(params, tmptok);
936 } else if (tmptok == "Wrap") {
938 string tmptok = lex.getString();
939 inset = new InsetWrap(params, tmptok);
941 } else if (tmptok == "List") {
942 inset = new InsetList;
943 } else if (tmptok == "Theorem") {
944 inset = new InsetList;
946 } else if (tmptok == "Caption") {
947 inset = new InsetCaption(params);
948 } else if (tmptok == "FloatList") {
949 inset = new InsetFloatList;
953 inset->read(this, lex);
957 pit->insertInset(pos, inset, font, current_change);
963 bool Buffer::readFile(LyXLex & lex, string const & filename)
965 return readFile(lex, filename, paragraphs.begin());
969 bool Buffer::readFile(LyXLex & lex, string const & filename, ParagraphList::iterator pit)
973 string const token(lex.getString());
974 if (token == "\\lyxformat") { // the first token _must_ be...
976 string tmp_format = lex.getString();
977 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
978 // if present remove ".," from string.
979 string::size_type dot = tmp_format.find_first_of(".,");
980 //lyxerr << " dot found at " << dot << endl;
981 if (dot != string::npos)
982 tmp_format.erase(dot, 1);
983 file_format = strToInt(tmp_format);
984 //lyxerr << "format: " << file_format << endl;
985 if (file_format == LYX_FORMAT) {
987 } else if (file_format > LYX_FORMAT) {
989 Alert::alert(_("Warning!"),
990 _("The file was created with a newer version of "
991 "LyX. This is likely to cause problems."));
993 } else if (file_format < LYX_FORMAT) {
995 if (file_format < 200) {
996 Alert::alert(_("ERROR!"),
997 _("Old LyX file format found. "
998 "Use LyX 0.10.x to read this!"));
1000 } else if (!filename.empty()) {
1002 LibFileSearch("lyx2lyx", "lyx2lyx");
1003 if (command.empty()) {
1004 Alert::alert(_("ERROR!"),
1005 _("Can't find conversion script."));
1009 +tostr(LYX_FORMAT) + ' '
1010 + QuoteName(filename);
1011 lyxerr[Debug::INFO] << "Running '"
1014 cmd_ret const ret = RunCommand(command);
1016 Alert::alert(_("ERROR!"),
1017 _("An error occured while "
1018 "running the conversion script."));
1021 istringstream is(STRCONV(ret.second));
1022 LyXLex tmplex(0, 0);
1023 tmplex.setStream(is);
1024 return readFile(tmplex, string(), pit);
1026 // This code is reached if lyx2lyx failed (for
1027 // some reason) to change the file format of
1033 bool the_end = readBody(lex, pit);
1034 params.setPaperStuff();
1037 Alert::alert(_("Warning!"),
1038 _("Reading of document is not complete"),
1039 _("Maybe the document is truncated"));
1042 } else { // "\\lyxformat" not found
1043 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1046 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1051 // Should probably be moved to somewhere else: BufferView? LyXView?
1052 bool Buffer::save() const
1054 // We don't need autosaves in the immediate future. (Asger)
1055 resetAutosaveTimers();
1059 if (lyxrc.make_backup) {
1060 s = fileName() + '~';
1061 if (!lyxrc.backupdir_path.empty())
1062 s = AddName(lyxrc.backupdir_path,
1063 subst(os::slashify_path(s),'/','!'));
1065 // Rename is the wrong way of making a backup,
1066 // this is the correct way.
1067 /* truss cp fil fil2:
1068 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1069 stat("LyXVC.lyx", 0xEFFFF688) = 0
1070 open("LyXVC.lyx", O_RDONLY) = 3
1071 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1072 fstat(4, 0xEFFFF508) = 0
1073 fstat(3, 0xEFFFF508) = 0
1074 read(3, " # T h i s f i l e w".., 8192) = 5579
1075 write(4, " # T h i s f i l e w".., 5579) = 5579
1076 read(3, 0xEFFFD4A0, 8192) = 0
1079 chmod("LyXVC3.lyx", 0100644) = 0
1080 lseek(0, 0, SEEK_CUR) = 46440
1084 // Should probably have some more error checking here.
1085 // Doing it this way, also makes the inodes stay the same.
1086 // This is still not a very good solution, in particular we
1087 // might loose the owner of the backup.
1088 FileInfo finfo(fileName());
1089 if (finfo.exist()) {
1090 mode_t fmode = finfo.getMode();
1091 struct utimbuf times = {
1092 finfo.getAccessTime(),
1093 finfo.getModificationTime() };
1095 ifstream ifs(fileName().c_str());
1096 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1101 ::chmod(s.c_str(), fmode);
1103 if (::utime(s.c_str(), ×)) {
1104 lyxerr << "utime error." << endl;
1107 lyxerr << "LyX was not able to make "
1108 "backup copy. Beware." << endl;
1113 if (writeFile(fileName())) {
1115 removeAutosaveFile(fileName());
1117 // Saving failed, so backup is not backup
1118 if (lyxrc.make_backup) {
1119 lyx::rename(s, fileName());
1127 bool Buffer::writeFile(string const & fname) const
1129 if (read_only && (fname == fileName())) {
1133 FileInfo finfo(fname);
1134 if (finfo.exist() && !finfo.writable()) {
1138 ofstream ofs(fname.c_str());
1144 // Use the standard "C" locale for file output.
1145 ofs.imbue(std::locale::classic());
1148 // The top of the file should not be written by params.
1150 // write out a comment in the top of the file
1151 ofs << '#' << lyx_docversion
1152 << " created this file. For more info see http://www.lyx.org/\n"
1153 << "\\lyxformat " << LYX_FORMAT << "\n";
1155 // now write out the buffer paramters.
1156 params.writeFile(ofs);
1158 ofs << "\\end_header\n";
1160 Paragraph::depth_type depth = 0;
1162 // this will write out all the paragraphs
1163 // using recursive descent.
1164 ParagraphList::iterator pit = paragraphs.begin();
1165 ParagraphList::iterator pend = paragraphs.end();
1166 for (; pit != pend; ++pit)
1167 pit->write(this, ofs, params, depth);
1169 // Write marker that shows file is complete
1170 ofs << "\n\\the_end" << endl;
1174 // how to check if close went ok?
1175 // Following is an attempt... (BE 20001011)
1177 // good() returns false if any error occured, including some
1178 // formatting error.
1179 // bad() returns true if something bad happened in the buffer,
1180 // which should include file system full errors.
1187 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1189 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1201 pair<int, string> const addDepth(int depth, int ldepth)
1205 d += (ldepth - depth) * 2;
1206 return make_pair(d, string(d, ' '));
1212 string const Buffer::asciiParagraph(Paragraph const & par,
1213 unsigned int linelen,
1214 bool noparbreak) const
1216 ostringstream buffer;
1217 Paragraph::depth_type depth = 0;
1219 Paragraph::depth_type ltype_depth = 0;
1220 bool ref_printed = false;
1221 // if (!par->previous()) {
1223 // begins or ends a deeper area ?
1224 if (depth != par->params().depth()) {
1225 if (par->params().depth() > depth) {
1226 while (par->params().depth() > depth) {
1230 while (par->params().depth() < depth) {
1236 depth = par.params().depth();
1239 // First write the layout
1240 string const & tmp = par.layout()->name();
1241 if (compare_no_case(tmp, "itemize") == 0) {
1243 ltype_depth = depth + 1;
1244 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1246 ltype_depth = depth + 1;
1247 } else if (contains(ascii_lowercase(tmp), "ection")) {
1249 ltype_depth = depth + 1;
1250 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1252 ltype_depth = depth + 1;
1253 } else if (compare_ascii_no_case(tmp, "description") == 0) {
1255 ltype_depth = depth + 1;
1256 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1259 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1267 /* maybe some vertical spaces */
1269 /* the labelwidthstring used in lists */
1273 /* some pagebreaks? */
1277 /* what about the alignment */
1279 // lyxerr << "Should this ever happen?" << endl;
1282 // linelen <= 0 is special and means we don't have paragraph breaks
1284 string::size_type currlinelen = 0;
1290 buffer << string(depth * 2, ' ');
1291 currlinelen += depth * 2;
1294 // we should probably change to the paragraph language in the
1295 // gettext here (if possible) so that strings are outputted in
1296 // the correct language! (20012712 Jug)
1300 case 4: // (Sub)Paragraph
1301 case 5: // Description
1305 buffer << _("Abstract") << "\n\n";
1308 string const abst = _("Abstract: ");
1310 currlinelen += abst.length();
1313 case 7: // Bibliography
1316 buffer << _("References") << "\n\n";
1319 string const refs = _("References: ");
1321 currlinelen += refs.length();
1329 string const parlab = par.params().labelString();
1330 buffer << parlab << ' ';
1331 currlinelen += parlab.length() + 1;
1339 pair<int, string> p = addDepth(depth, ltype_depth);
1341 currlinelen += p.first;
1344 // this is to change the linebreak to do it by word a bit more
1345 // intelligent hopefully! (only in the case where we have a
1346 // max linelength!) (Jug)
1350 for (pos_type i = 0; i < par.size(); ++i) {
1351 char c = par.getUChar(params, i);
1353 case Paragraph::META_INSET:
1355 Inset const * inset = par.getInset(i);
1359 currlinelen += word.length();
1362 if (inset->ascii(this, buffer, linelen)) {
1363 // to be sure it breaks paragraph
1364 currlinelen += linelen;
1370 case Paragraph::META_NEWLINE:
1372 buffer << word << "\n";
1375 pair<int, string> p = addDepth(depth,
1378 currlinelen = p.first;
1385 currlinelen + word.length() > linelen - 10) {
1387 pair<int, string> p = addDepth(depth, ltype_depth);
1389 currlinelen = p.first;
1392 buffer << word << ' ';
1393 currlinelen += word.length() + 1;
1400 lyxerr[Debug::INFO] <<
1401 "writeAsciiFile: NULL char in structure." << endl;
1403 if ((linelen > 0) &&
1404 (currlinelen + word.length()) > linelen)
1408 pair<int, string> p =
1409 addDepth(depth, ltype_depth);
1411 currlinelen = p.first;
1418 return STRCONV(buffer.str());
1422 void Buffer::writeFileAscii(string const & fname, int linelen)
1424 ofstream ofs(fname.c_str());
1426 Alert::err_alert(_("Error: Cannot write file:"), fname);
1429 writeFileAscii(ofs, linelen);
1433 void Buffer::writeFileAscii(ostream & os, int linelen)
1435 ParagraphList::iterator beg = paragraphs.begin();
1436 ParagraphList::iterator end = paragraphs.end();
1437 ParagraphList::iterator it = beg;
1438 for (; it != end; ++it) {
1439 os << asciiParagraph(*it, linelen, it == beg);
1446 void Buffer::makeLaTeXFile(string const & fname,
1447 string const & original_path,
1448 bool nice, bool only_body, bool only_preamble)
1450 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1452 ofstream ofs(fname.c_str());
1454 Alert::err_alert(_("Error: Cannot open file: "), fname);
1458 makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1462 lyxerr << "File was not closed properly." << endl;
1467 void Buffer::makeLaTeXFile(ostream & os,
1468 string const & original_path,
1469 bool nice, bool only_body, bool only_preamble)
1471 niceFile = nice; // this will be used by Insetincludes.
1473 // validate the buffer.
1474 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1475 LaTeXFeatures features(params);
1477 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1480 // The starting paragraph of the coming rows is the
1481 // first paragraph of the document. (Asger)
1482 texrow.start(&*(paragraphs.begin()), 0);
1484 if (!only_body && nice) {
1485 os << "%% " << lyx_docversion << " created this file. "
1486 "For more info, see http://www.lyx.org/.\n"
1487 "%% Do not edit unless you really know what "
1492 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1493 // There are a few differences between nice LaTeX and usual files:
1494 // usual is \batchmode and has a
1495 // special input@path to allow the including of figures
1496 // with either \input or \includegraphics (what figinsets do).
1497 // input@path is set when the actual parameter
1498 // original_path is set. This is done for usual tex-file, but not
1499 // for nice-latex-file. (Matthias 250696)
1502 // code for usual, NOT nice-latex-file
1503 os << "\\batchmode\n"; // changed
1504 // from \nonstopmode
1507 if (!original_path.empty()) {
1508 string inputpath = os::external_path(original_path);
1509 subst(inputpath, "~", "\\string~");
1510 os << "\\makeatletter\n"
1511 << "\\def\\input@path{{"
1512 << inputpath << "/}}\n"
1513 << "\\makeatother\n";
1519 // Write the preamble
1520 params.writeLaTeX(os, features, texrow);
1526 os << "\\begin{document}\n";
1529 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1531 if (!lyxrc.language_auto_begin) {
1532 os << subst(lyxrc.language_command_begin, "$$lang",
1533 params.language->babel())
1538 latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1540 // add this just in case after all the paragraphs
1544 if (!lyxrc.language_auto_end) {
1545 os << subst(lyxrc.language_command_end, "$$lang",
1546 params.language->babel())
1552 os << "\\end{document}\n";
1555 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1557 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1561 // Just to be sure. (Asger)
1564 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1565 lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1568 // we want this to be true outside previews (for insetexternal)
1573 bool Buffer::isLatex() const
1575 return params.getLyXTextClass().outputType() == LATEX;
1579 bool Buffer::isLinuxDoc() const
1581 return params.getLyXTextClass().outputType() == LINUXDOC;
1585 bool Buffer::isLiterate() const
1587 return params.getLyXTextClass().outputType() == LITERATE;
1591 bool Buffer::isDocBook() const
1593 return params.getLyXTextClass().outputType() == DOCBOOK;
1597 bool Buffer::isSGML() const
1599 LyXTextClass const & tclass = params.getLyXTextClass();
1601 return tclass.outputType() == LINUXDOC ||
1602 tclass.outputType() == DOCBOOK;
1606 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1608 ofstream ofs(fname.c_str());
1611 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
1615 niceFile = nice; // this will be used by included files.
1617 LaTeXFeatures features(params);
1623 LyXTextClass const & tclass = params.getLyXTextClass();
1625 string top_element = tclass.latexname();
1628 ofs << "<!doctype linuxdoc system";
1630 string preamble = params.preamble;
1631 const string name = nice ? ChangeExtension(filename_, ".sgml")
1633 preamble += features.getIncludedFiles(name);
1634 preamble += features.getLyXSGMLEntities();
1636 if (!preamble.empty()) {
1637 ofs << " [ " << preamble << " ]";
1641 if (params.options.empty())
1642 sgml::openTag(ofs, 0, false, top_element);
1644 string top = top_element;
1646 top += params.options;
1647 sgml::openTag(ofs, 0, false, top);
1651 ofs << "<!-- " << lyx_docversion
1652 << " created this file. For more info see http://www.lyx.org/"
1655 Paragraph::depth_type depth = 0; // paragraph depth
1656 Paragraph * par = &*(paragraphs.begin());
1658 vector<string> environment_stack(5);
1661 LyXLayout_ptr const & style = par->layout();
1662 // treat <toc> as a special case for compatibility with old code
1663 if (par->isInset(0)) {
1664 Inset * inset = par->getInset(0);
1665 Inset::Code lyx_code = inset->lyxCode();
1666 if (lyx_code == Inset::TOC_CODE) {
1667 string const temp = "toc";
1668 sgml::openTag(ofs, depth, false, temp);
1675 // environment tag closing
1676 for (; depth > par->params().depth(); --depth) {
1677 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1678 environment_stack[depth].erase();
1681 // write opening SGML tags
1682 switch (style->latextype) {
1683 case LATEX_PARAGRAPH:
1684 if (depth == par->params().depth()
1685 && !environment_stack[depth].empty()) {
1686 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1687 environment_stack[depth].erase();
1693 sgml::openTag(ofs, depth, false, style->latexname());
1699 _("Error: Wrong depth for LatexType Command.\n"));
1701 if (!environment_stack[depth].empty()) {
1702 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1706 environment_stack[depth].erase();
1707 sgml::openTag(ofs, depth, false, style->latexname());
1710 case LATEX_ENVIRONMENT:
1711 case LATEX_ITEM_ENVIRONMENT:
1712 case LATEX_BIB_ENVIRONMENT:
1714 string const & latexname = style->latexname();
1716 if (depth == par->params().depth()
1717 && environment_stack[depth] != latexname) {
1718 sgml::closeTag(ofs, depth, false,
1719 environment_stack[depth]);
1720 environment_stack[depth].erase();
1722 if (depth < par->params().depth()) {
1723 depth = par->params().depth();
1724 environment_stack[depth].erase();
1726 if (environment_stack[depth] != latexname) {
1728 sgml::openTag(ofs, depth, false, "p");
1730 sgml::openTag(ofs, depth, false, latexname);
1732 if (environment_stack.size() == depth + 1)
1733 environment_stack.push_back("!-- --");
1734 environment_stack[depth] = latexname;
1737 if (style->latexparam() == "CDATA")
1740 if (style->latextype == LATEX_ENVIRONMENT) break;
1742 if (style->labeltype == LABEL_MANUAL)
1747 sgml::openTag(ofs, depth + 1, false, item_name);
1752 sgml::openTag(ofs, depth, false, style->latexname());
1756 simpleLinuxDocOnePar(ofs, par, depth);
1761 // write closing SGML tags
1762 switch (style->latextype) {
1765 case LATEX_ENVIRONMENT:
1766 case LATEX_ITEM_ENVIRONMENT:
1767 case LATEX_BIB_ENVIRONMENT:
1768 if (style->latexparam() == "CDATA")
1772 sgml::closeTag(ofs, depth, false, style->latexname());
1778 for (int i = depth; i >= 0; --i)
1779 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1783 sgml::closeTag(ofs, 0, false, top_element);
1787 // How to check for successful close
1789 // we want this to be true outside previews (for insetexternal)
1794 // checks, if newcol chars should be put into this line
1795 // writes newline, if necessary.
1798 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1799 string::size_type newcol)
1802 if (colcount > lyxrc.ascii_linelen) {
1804 colcount = newcol; // assume write after this call
1819 string tag_name(PAR_TAG const & pt) {
1821 case NONE: return "!-- --";
1822 case TT: return "tt";
1823 case SF: return "sf";
1824 case BF: return "bf";
1825 case IT: return "it";
1826 case SL: return "sl";
1827 case EM: return "em";
1834 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1836 p1 = static_cast<PAR_TAG>(p1 | p2);
1841 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1843 p1 = static_cast<PAR_TAG>(p1 & ~p2);
1849 // Handle internal paragraph parsing -- layout already processed.
1850 void Buffer::simpleLinuxDocOnePar(ostream & os,
1852 Paragraph::depth_type /*depth*/)
1854 LyXLayout_ptr const & style = par->layout();
1856 string::size_type char_line_count = 5; // Heuristic choice ;-)
1858 // gets paragraph main font
1861 if (style->labeltype == LABEL_MANUAL) {
1862 font_old = style->labelfont;
1865 font_old = style->font;
1869 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1870 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1871 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
1874 stack<PAR_TAG> tag_state;
1875 // parsing main loop
1876 for (pos_type i = 0; i < par->size(); ++i) {
1878 PAR_TAG tag_close = NONE;
1879 list < PAR_TAG > tag_open;
1881 LyXFont const font = par->getFont(params, i);
1883 if (font_old.family() != font.family()) {
1884 switch (family_type) {
1885 case LyXFont::SANS_FAMILY:
1888 case LyXFont::TYPEWRITER_FAMILY:
1895 family_type = font.family();
1897 switch (family_type) {
1898 case LyXFont::SANS_FAMILY:
1899 tag_open.push_back(SF);
1901 case LyXFont::TYPEWRITER_FAMILY:
1902 tag_open.push_back(TT);
1909 if (font_old.series() != font.series()) {
1910 switch (series_type) {
1911 case LyXFont::BOLD_SERIES:
1918 series_type = font.series();
1920 switch (series_type) {
1921 case LyXFont::BOLD_SERIES:
1922 tag_open.push_back(BF);
1930 if (font_old.shape() != font.shape()) {
1931 switch (shape_type) {
1932 case LyXFont::ITALIC_SHAPE:
1935 case LyXFont::SLANTED_SHAPE:
1942 shape_type = font.shape();
1944 switch (shape_type) {
1945 case LyXFont::ITALIC_SHAPE:
1946 tag_open.push_back(IT);
1948 case LyXFont::SLANTED_SHAPE:
1949 tag_open.push_back(SL);
1956 if (font_old.emph() != font.emph()) {
1957 if (font.emph() == LyXFont::ON) {
1958 tag_open.push_back(EM);
1967 list < PAR_TAG > temp;
1968 while (!tag_state.empty() && tag_close) {
1969 PAR_TAG k = tag_state.top();
1971 os << "</" << tag_name(k) << '>';
1978 for(list< PAR_TAG >::const_iterator j = temp.begin();
1979 j != temp.end(); ++j) {
1981 os << '<' << tag_name(*j) << '>';
1984 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1985 j != tag_open.end(); ++j) {
1987 os << '<' << tag_name(*j) << '>';
1990 char c = par->getChar(i);
1992 if (c == Paragraph::META_INSET) {
1993 Inset * inset = par->getInset(i);
1994 inset->linuxdoc(this, os);
1999 if (style->latexparam() == "CDATA") {
2000 // "TeX"-Mode on == > SGML-Mode on.
2007 boost::tie(ws, str) = sgml::escapeChar(c);
2008 if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2009 // in freespacing mode, spaces are
2010 // non-breaking characters
2011 if (desc_on) {// if char is ' ' then...
2014 sgmlLineBreak(os, char_line_count, 6);
2018 sgmlLineBreak(os, char_line_count, 1);
2023 char_line_count += str.length();
2029 while (!tag_state.empty()) {
2030 os << "</" << tag_name(tag_state.top()) << '>';
2034 // resets description flag correctly
2036 // <tag> not closed...
2037 sgmlLineBreak(os, char_line_count, 6);
2043 // Print an error message.
2044 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2045 string const & /*message*/) const
2047 #ifdef WITH_WARNINGS
2048 #warning This is wrong we cannot insert an inset like this!!!
2049 // I guess this was Jose' so I explain you more or less why this
2050 // is wrong. This way you insert something in the paragraph and
2051 // don't tell it to LyXText (row rebreaking and undo handling!!!)
2052 // I deactivate this code, have a look at BufferView::insertErrors
2053 // how you should do this correctly! (Jug 20020315)
2056 // insert an error marker in text
2057 InsetError * new_inset = new InsetError(message);
2058 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2064 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2066 ofstream ofs(fname.c_str());
2068 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2072 Paragraph * par = &*(paragraphs.begin());
2074 niceFile = nice; // this will be used by Insetincludes.
2076 LaTeXFeatures features(params);
2081 LyXTextClass const & tclass = params.getLyXTextClass();
2082 string top_element = tclass.latexname();
2085 ofs << "<!DOCTYPE " << top_element
2086 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2088 string preamble = params.preamble;
2089 const string name = nice ? ChangeExtension(filename_, ".sgml")
2091 preamble += features.getIncludedFiles(name);
2092 preamble += features.getLyXSGMLEntities();
2094 if (!preamble.empty()) {
2095 ofs << "\n [ " << preamble << " ]";
2100 string top = top_element;
2102 top += params.language->code();
2105 if (!params.options.empty()) {
2107 top += params.options;
2109 sgml::openTag(ofs, 0, false, top);
2111 ofs << "<!-- DocBook file was created by " << lyx_docversion
2112 << "\n See http://www.lyx.org/ for more information -->\n";
2114 vector<string> environment_stack(10);
2115 vector<string> environment_inner(10);
2116 vector<string> command_stack(10);
2118 bool command_flag = false;
2119 Paragraph::depth_type command_depth = 0;
2120 Paragraph::depth_type command_base = 0;
2121 Paragraph::depth_type cmd_depth = 0;
2122 Paragraph::depth_type depth = 0; // paragraph depth
2125 string command_name;
2131 int desc_on = 0; // description mode
2133 LyXLayout_ptr const & style = par->layout();
2135 // environment tag closing
2136 for (; depth > par->params().depth(); --depth) {
2137 if (environment_inner[depth] != "!-- --") {
2138 item_name = "listitem";
2139 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2140 if (environment_inner[depth] == "varlistentry")
2141 sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2143 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2144 environment_stack[depth].erase();
2145 environment_inner[depth].erase();
2148 if (depth == par->params().depth()
2149 && environment_stack[depth] != style->latexname()
2150 && !environment_stack[depth].empty()) {
2151 if (environment_inner[depth] != "!-- --") {
2152 item_name= "listitem";
2153 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2154 if (environment_inner[depth] == "varlistentry")
2155 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2158 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2160 environment_stack[depth].erase();
2161 environment_inner[depth].erase();
2164 // Write opening SGML tags.
2165 switch (style->latextype) {
2166 case LATEX_PARAGRAPH:
2167 sgml::openTag(ofs, depth + command_depth,
2168 false, style->latexname());
2174 _("Error: Wrong depth for LatexType Command.\n"));
2176 command_name = style->latexname();
2178 sgmlparam = style->latexparam();
2179 c_params = split(sgmlparam, c_depth,'|');
2181 cmd_depth = lyx::atoi(c_depth);
2184 if (cmd_depth < command_base) {
2185 for (Paragraph::depth_type j = command_depth;
2186 j >= command_base; --j) {
2187 sgml::closeTag(ofs, j, false, command_stack[j]);
2190 command_depth = command_base = cmd_depth;
2191 } else if (cmd_depth <= command_depth) {
2192 for (int j = command_depth;
2193 j >= int(cmd_depth); --j) {
2194 sgml::closeTag(ofs, j, false, command_stack[j]);
2197 command_depth = cmd_depth;
2199 command_depth = cmd_depth;
2201 command_depth = command_base = cmd_depth;
2202 command_flag = true;
2204 if (command_stack.size() == command_depth + 1)
2205 command_stack.push_back(string());
2206 command_stack[command_depth] = command_name;
2208 // treat label as a special case for
2209 // more WYSIWYM handling.
2210 // This is a hack while paragraphs can't have
2211 // attributes, like id in this case.
2212 if (par->isInset(0)) {
2213 Inset * inset = par->getInset(0);
2214 Inset::Code lyx_code = inset->lyxCode();
2215 if (lyx_code == Inset::LABEL_CODE) {
2216 command_name += " id=\"";
2217 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2218 command_name += '"';
2223 sgml::openTag(ofs, depth + command_depth, false, command_name);
2225 item_name = c_params.empty() ? "title" : c_params;
2226 sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2229 case LATEX_ENVIRONMENT:
2230 case LATEX_ITEM_ENVIRONMENT:
2231 if (depth < par->params().depth()) {
2232 depth = par->params().depth();
2233 environment_stack[depth].erase();
2236 if (environment_stack[depth] != style->latexname()) {
2237 if (environment_stack.size() == depth + 1) {
2238 environment_stack.push_back("!-- --");
2239 environment_inner.push_back("!-- --");
2241 environment_stack[depth] = style->latexname();
2242 environment_inner[depth] = "!-- --";
2243 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2245 if (environment_inner[depth] != "!-- --") {
2246 item_name= "listitem";
2247 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2248 if (environment_inner[depth] == "varlistentry")
2249 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2253 if (style->latextype == LATEX_ENVIRONMENT) {
2254 if (!style->latexparam().empty()) {
2255 if (style->latexparam() == "CDATA")
2258 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2263 desc_on = (style->labeltype == LABEL_MANUAL);
2265 environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2266 sgml::openTag(ofs, depth + 1 + command_depth,
2267 false, environment_inner[depth]);
2269 item_name = desc_on ? "term" : "para";
2270 sgml::openTag(ofs, depth + 1 + command_depth,
2274 sgml::openTag(ofs, depth + command_depth,
2275 false, style->latexname());
2279 simpleDocBookOnePar(ofs, par, desc_on,
2280 depth + 1 + command_depth);
2284 // write closing SGML tags
2285 switch (style->latextype) {
2287 end_tag = c_params.empty() ? "title" : c_params;
2288 sgml::closeTag(ofs, depth + command_depth,
2291 case LATEX_ENVIRONMENT:
2292 if (!style->latexparam().empty()) {
2293 if (style->latexparam() == "CDATA")
2296 sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2299 case LATEX_ITEM_ENVIRONMENT:
2300 if (desc_on == 1) break;
2302 sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2304 case LATEX_PARAGRAPH:
2305 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2308 sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2314 for (int d = depth; d >= 0; --d) {
2315 if (!environment_stack[depth].empty()) {
2316 if (environment_inner[depth] != "!-- --") {
2317 item_name = "listitem";
2318 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2319 if (environment_inner[depth] == "varlistentry")
2320 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2323 sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2327 for (int j = command_depth; j >= 0 ; --j)
2328 if (!command_stack[j].empty()) {
2329 sgml::closeTag(ofs, j, false, command_stack[j]);
2334 sgml::closeTag(ofs, 0, false, top_element);
2337 // How to check for successful close
2339 // we want this to be true outside previews (for insetexternal)
2344 void Buffer::simpleDocBookOnePar(ostream & os,
2345 Paragraph * par, int & desc_on,
2346 Paragraph::depth_type depth) const
2348 bool emph_flag = false;
2350 LyXLayout_ptr const & style = par->layout();
2352 LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2354 int char_line_count = depth;
2355 //if (!style.free_spacing)
2356 // os << string(depth,' ');
2358 // parsing main loop
2359 for (pos_type i = 0; i < par->size(); ++i) {
2360 LyXFont font = par->getFont(params, i);
2362 // handle <emphasis> tag
2363 if (font_old.emph() != font.emph()) {
2364 if (font.emph() == LyXFont::ON) {
2365 if (style->latexparam() == "CDATA")
2368 if (style->latexparam() == "CDATA")
2372 if (style->latexparam() == "CDATA")
2374 os << "</emphasis>";
2375 if (style->latexparam() == "CDATA")
2382 if (par->isInset(i)) {
2383 Inset * inset = par->getInset(i);
2384 // don't print the inset in position 0 if desc_on == 3 (label)
2385 if (i || desc_on != 3) {
2386 if (style->latexparam() == "CDATA")
2388 inset->docbook(this, os, false);
2389 if (style->latexparam() == "CDATA")
2393 char c = par->getChar(i);
2396 boost::tie(ws, str) = sgml::escapeChar(c);
2398 if (style->pass_thru) {
2400 } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
2402 } else if (desc_on ==1) {
2404 os << "\n</term><listitem><para>";
2414 if (style->latexparam() == "CDATA")
2416 os << "</emphasis>";
2417 if (style->latexparam() == "CDATA")
2421 // resets description flag correctly
2423 // <term> not closed...
2424 os << "</term>\n<listitem><para> </para>";
2426 if (style->free_spacing)
2431 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2432 // Other flags: -wall -v0 -x
2433 int Buffer::runChktex()
2435 if (!users->text) return 0;
2437 users->owner()->busy(true);
2439 // get LaTeX-Filename
2440 string const name = getLatexName();
2441 string path = filePath();
2443 string const org_path = path;
2444 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2448 Path p(path); // path to LaTeX file
2449 users->owner()->message(_("Running chktex..."));
2451 // Remove all error insets
2452 bool const removedErrorInsets = users->removeAutoInsets();
2454 // Generate the LaTeX file if neccessary
2455 makeLaTeXFile(name, org_path, false);
2458 Chktex chktex(lyxrc.chktex_command, name, filePath());
2459 int res = chktex.run(terr); // run chktex
2462 Alert::alert(_("chktex did not work!"),
2463 _("Could not run with file:"), name);
2464 } else if (res > 0) {
2465 // Insert all errors as errors boxes
2466 users->insertErrors(terr);
2469 // if we removed error insets before we ran chktex or if we inserted
2470 // error insets after we ran chktex, this must be run:
2471 if (removedErrorInsets || res) {
2472 #warning repaint needed here, or do you mean update() ?
2476 users->owner()->busy(false);
2482 void Buffer::validate(LaTeXFeatures & features) const
2484 LyXTextClass const & tclass = params.getLyXTextClass();
2486 if (params.tracking_changes) {
2487 features.require("dvipost");
2488 features.require("color");
2491 // AMS Style is at document level
2492 if (params.use_amsmath == BufferParams::AMS_ON
2493 || tclass.provides(LyXTextClass::amsmath))
2494 features.require("amsmath");
2496 for_each(paragraphs.begin(), paragraphs.end(),
2497 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2499 // the bullet shapes are buffer level not paragraph level
2500 // so they are tested here
2501 for (int i = 0; i < 4; ++i) {
2502 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2503 int const font = params.user_defined_bullets[i].getFont();
2505 int const c = params
2506 .user_defined_bullets[i]
2513 features.require("latexsym");
2515 } else if (font == 1) {
2516 features.require("amssymb");
2517 } else if ((font >= 2 && font <= 5)) {
2518 features.require("pifont");
2523 if (lyxerr.debugging(Debug::LATEX)) {
2524 features.showStruct();
2529 vector<string> const Buffer::getLabelList() const
2531 /// if this is a child document and the parent is already loaded
2532 /// Use the parent's list instead [ale990407]
2533 if (!params.parentname.empty()
2534 && bufferlist.exists(params.parentname)) {
2535 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2537 return tmp->getLabelList();
2540 vector<string> label_list;
2541 for (inset_iterator it = inset_const_iterator_begin();
2542 it != inset_const_iterator_end(); ++it) {
2543 vector<string> const l = it->getLabelList();
2544 label_list.insert(label_list.end(), l.begin(), l.end());
2550 // This is also a buffer property (ale)
2551 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2553 /// if this is a child document and the parent is already loaded
2554 /// use the parent's list instead [ale990412]
2555 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2556 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2558 tmp->fillWithBibKeys(keys);
2563 for (inset_iterator it = inset_const_iterator_begin();
2564 it != inset_const_iterator_end(); ++it) {
2565 if (it->lyxCode() == Inset::BIBTEX_CODE)
2566 static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2567 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2568 static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2569 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2570 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2571 string const key = bib.getContents();
2572 string const opt = bib.getOptions();
2573 string const ref; // = pit->asString(this, false);
2574 string const info = opt + "TheBibliographyRef" + ref;
2575 keys.push_back(pair<string, string>(key, info));
2581 bool Buffer::isDepClean(string const & name) const
2583 DepClean::const_iterator it = dep_clean_.find(name);
2584 if (it == dep_clean_.end())
2590 void Buffer::markDepClean(string const & name)
2592 dep_clean_[name] = true;
2596 bool Buffer::dispatch(string const & command, bool * result)
2598 // Split command string into command and argument
2600 string line = ltrim(command);
2601 string const arg = trim(split(line, cmd, ' '));
2603 return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2607 bool Buffer::dispatch(int action, string const & argument, bool * result)
2609 bool dispatched = true;
2613 bool const tmp = Exporter::Export(this, argument, false);
2626 void Buffer::resizeInsets(BufferView * bv)
2628 /// then remove all LyXText in text-insets
2629 for_each(paragraphs.begin(), paragraphs.end(),
2630 boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2634 void Buffer::redraw()
2636 #warning repaint needed here, or do you mean update() ?
2642 void Buffer::changeLanguage(Language const * from, Language const * to)
2645 ParIterator end = par_iterator_end();
2646 for (ParIterator it = par_iterator_begin(); it != end; ++it)
2647 (*it)->changeLanguage(params, from, to);
2651 bool Buffer::isMultiLingual()
2653 ParIterator end = par_iterator_end();
2654 for (ParIterator it = par_iterator_begin(); it != end; ++it)
2655 if ((*it)->isMultiLingual(params))
2662 void Buffer::inset_iterator::setParagraph()
2664 while (pit != pend) {
2665 it = pit->insetlist.begin();
2666 if (it != pit->insetlist.end())
2673 Inset * Buffer::getInsetFromID(int id_arg) const
2675 for (inset_iterator it = inset_const_iterator_begin();
2676 it != inset_const_iterator_end(); ++it)
2678 if (it->id() == id_arg)
2680 Inset * in = it->getInsetFromID(id_arg);
2688 Paragraph * Buffer::getParFromID(int id) const
2693 // why should we allow < 0 ??
2694 //lyx::Assert(id >= 0);
2696 ParConstIterator it(par_iterator_begin());
2697 ParConstIterator end(par_iterator_end());
2699 for (; it != end; ++it) {
2700 // go on then, show me how to remove
2702 if ((*it)->id() == id) {
2703 return const_cast<Paragraph*>(*it);
2711 ParIterator Buffer::par_iterator_begin()
2713 return ParIterator(&*(paragraphs.begin()));
2717 ParIterator Buffer::par_iterator_end()
2719 return ParIterator();
2722 ParConstIterator Buffer::par_iterator_begin() const
2724 return ParConstIterator(&*(paragraphs.begin()));
2728 ParConstIterator Buffer::par_iterator_end() const
2730 return ParConstIterator();
2735 void Buffer::addUser(BufferView * u)
2741 void Buffer::delUser(BufferView *)
2747 Language const * Buffer::getLanguage() const
2749 return params.language;
2753 bool Buffer::isClean() const
2759 bool Buffer::isBakClean() const
2765 void Buffer::markClean() const
2771 // if the .lyx file has been saved, we don't need an
2777 void Buffer::markBakClean()
2783 void Buffer::setUnnamed(bool flag)
2789 bool Buffer::isUnnamed()
2795 void Buffer::markDirty()
2803 DepClean::iterator it = dep_clean_.begin();
2804 DepClean::const_iterator const end = dep_clean_.end();
2806 for (; it != end; ++it) {
2812 string const & Buffer::fileName() const
2818 string const & Buffer::filePath() const
2824 bool Buffer::isReadonly() const
2830 BufferView * Buffer::getUser() const
2836 void Buffer::setParentName(string const & name)
2838 params.parentname = name;
2842 Buffer::inset_iterator::inset_iterator()
2847 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2854 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2858 if (it == pit->insetlist.end()) {
2867 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2869 inset_iterator tmp = *this;
2875 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2877 return *it.getInset();
2881 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2883 return it.getInset();
2887 Paragraph * Buffer::inset_iterator::getPar()
2893 lyx::pos_type Buffer::inset_iterator::getPos() const
2899 bool operator==(Buffer::inset_iterator const & iter1,
2900 Buffer::inset_iterator const & iter2)
2902 return iter1.pit == iter2.pit
2903 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2907 bool operator!=(Buffer::inset_iterator const & iter1,
2908 Buffer::inset_iterator const & iter2)
2910 return !(iter1 == iter2);