3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
24 #include "errorlist.h"
27 #include "funcrequest.h"
29 #include "insetiterator.h"
32 #include "LaTeXFeatures.h"
33 #include "LyXAction.h"
41 #include "output_docbook.h"
42 #include "output_latex.h"
43 #include "output_linuxdoc.h"
44 #include "paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "pariterator.h"
53 #include "insets/insetbibitem.h"
54 #include "insets/insetbibtex.h"
55 #include "insets/insetinclude.h"
56 #include "insets/insettext.h"
58 #include "mathed/math_macrotemplate.h"
59 #include "mathed/math_macrotable.h"
60 #include "mathed/math_support.h"
62 #include "frontends/Alert.h"
64 #include "graphics/Previews.h"
66 #include "support/FileInfo.h"
67 #include "support/filetools.h"
68 #ifdef USE_COMPRESSION
69 # include "support/gzstream.h"
71 #include "support/lyxlib.h"
72 #include "support/os.h"
73 #include "support/path.h"
74 #include "support/textutils.h"
75 #include "support/convert.h"
77 #include <boost/bind.hpp>
90 using lyx::support::AddName;
91 using lyx::support::bformat;
92 using lyx::support::ChangeExtension;
93 using lyx::support::cmd_ret;
94 using lyx::support::createBufferTmpDir;
95 using lyx::support::destroyDir;
96 using lyx::support::FileInfo;
97 using lyx::support::FileInfo;
98 using lyx::support::getFormatFromContents;
99 using lyx::support::IsDirWriteable;
100 using lyx::support::IsFileWriteable;
101 using lyx::support::LibFileSearch;
102 using lyx::support::ltrim;
103 using lyx::support::MakeAbsPath;
104 using lyx::support::MakeDisplayPath;
105 using lyx::support::MakeLatexName;
106 using lyx::support::OnlyFilename;
107 using lyx::support::OnlyPath;
108 using lyx::support::Path;
109 using lyx::support::QuoteName;
110 using lyx::support::removeAutosaveFile;
111 using lyx::support::rename;
112 using lyx::support::RunCommand;
113 using lyx::support::split;
114 using lyx::support::subst;
115 using lyx::support::tempName;
116 using lyx::support::trim;
118 namespace os = lyx::support::os;
122 using std::make_pair;
128 using std::ostringstream;
136 // all these externs should eventually be removed.
137 extern BufferList bufferlist;
141 int const LYX_FORMAT = 240;
146 typedef std::map<string, bool> DepClean;
151 Impl(Buffer & parent, string const & file, bool readonly);
153 limited_stack<Undo> undostack;
154 limited_stack<Undo> redostack;
160 /// need to regenerate .tex?
164 mutable bool lyx_clean;
166 /// is autosave needed?
167 mutable bool bak_clean;
169 /// is this a unnamed file (New...)?
175 /// name of the file the buffer is associated with.
178 /// The path to the document file.
181 boost::scoped_ptr<Messages> messages;
183 /** Set to true only when the file is fully loaded.
184 * Used to prevent the premature generation of previews
185 * and by the citation inset.
187 bool file_fully_loaded;
189 /// our LyXText that should be wrapped in an InsetText
197 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
198 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
199 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
202 lyxvc.buffer(&parent);
203 temppath = createBufferTmpDir();
204 // FIXME: And now do something if temppath == string(), because we
205 // assume from now on that temppath points to a valid temp dir.
206 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
210 Buffer::Buffer(string const & file, bool ronly)
211 : pimpl_(new Impl(*this, file, ronly))
213 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
219 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
220 // here the buffer should take care that it is
221 // saved properly, before it goes into the void.
225 if (!temppath().empty() && destroyDir(temppath()) != 0) {
226 Alert::warning(_("Could not remove temporary directory"),
227 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
230 // Remove any previewed LaTeX snippets associated with this buffer.
231 lyx::graphics::Previews::get().removeLoader(*this);
235 LyXText & Buffer::text() const
237 return const_cast<LyXText &>(pimpl_->inset.text_);
241 InsetBase & Buffer::inset() const
243 return const_cast<InsetText &>(pimpl_->inset);
247 limited_stack<Undo> & Buffer::undostack()
249 return pimpl_->undostack;
253 limited_stack<Undo> const & Buffer::undostack() const
255 return pimpl_->undostack;
259 limited_stack<Undo> & Buffer::redostack()
261 return pimpl_->redostack;
265 limited_stack<Undo> const & Buffer::redostack() const
267 return pimpl_->redostack;
271 BufferParams & Buffer::params()
273 return pimpl_->params;
277 BufferParams const & Buffer::params() const
279 return pimpl_->params;
283 ParagraphList & Buffer::paragraphs()
285 return text().paragraphs();
289 ParagraphList const & Buffer::paragraphs() const
291 return text().paragraphs();
295 LyXVC & Buffer::lyxvc()
297 return pimpl_->lyxvc;
301 LyXVC const & Buffer::lyxvc() const
303 return pimpl_->lyxvc;
307 string const & Buffer::temppath() const
309 return pimpl_->temppath;
313 TexRow & Buffer::texrow()
315 return pimpl_->texrow;
319 TexRow const & Buffer::texrow() const
321 return pimpl_->texrow;
325 string const Buffer::getLatexName(bool const no_path) const
327 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
328 return no_path ? OnlyFilename(name) : name;
332 pair<Buffer::LogType, string> const Buffer::getLogName() const
334 string const filename = getLatexName(false);
336 if (filename.empty())
337 return make_pair(Buffer::latexlog, string());
339 string const path = temppath();
341 string const fname = AddName(path,
342 OnlyFilename(ChangeExtension(filename,
345 AddName(path, OnlyFilename(
346 ChangeExtension(filename,
347 formats.extension("literate") + ".out")));
349 // If no Latex log or Build log is newer, show Build log
351 FileInfo const f_fi(fname);
352 FileInfo const b_fi(bname);
355 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
356 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
357 return make_pair(Buffer::buildlog, bname);
359 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
360 return make_pair(Buffer::latexlog, fname);
364 void Buffer::setReadonly(bool const flag)
366 if (pimpl_->read_only != flag) {
367 pimpl_->read_only = flag;
373 void Buffer::setFileName(string const & newfile)
375 pimpl_->filename = MakeAbsPath(newfile);
376 pimpl_->filepath = OnlyPath(pimpl_->filename);
377 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
382 // We'll remove this later. (Lgb)
385 void unknownClass(string const & unknown)
387 Alert::warning(_("Unknown document class"),
388 bformat(_("Using the default document class, because the "
389 "class %1$s is unknown."), unknown));
395 int Buffer::readHeader(LyXLex & lex)
397 int unknown_tokens = 0;
399 int begin_header_line = -1;
403 string const token = lex.getString();
408 if (token == "\\end_header")
412 if (token == "\\begin_header") {
413 begin_header_line = line;
417 lyxerr[Debug::PARSER] << "Handling header token: `"
418 << token << '\'' << endl;
420 string unknown = params().readToken(lex, token);
421 if (!unknown.empty()) {
422 if (unknown[0] != '\\' && token == "\\textclass") {
423 unknownClass(unknown);
426 string const s = bformat(_("Unknown token: "
430 error(ErrorItem(_("Header error"), s,
435 if (begin_header_line) {
436 string const s = _("\\begin_header is missing");
437 error(ErrorItem(_("Header error"), s, -1, 0, 0));
439 return unknown_tokens;
444 // changed to be public and have one parameter
445 // Returns false if "\end_document" is not read (Asger)
446 bool Buffer::readDocument(LyXLex & lex)
449 string const token = lex.getString();
450 if (token != "\\begin_document") {
451 string const s = _("\\begin_document is missing");
452 error(ErrorItem(_("Header error"), s, -1, 0, 0));
455 if (paragraphs().empty()) {
457 if (!params().getLyXTextClass().load()) {
458 string theclass = params().getLyXTextClass().name();
459 Alert::error(_("Can't load document class"), bformat(
460 "Using the default document class, because the "
461 " class %1$s could not be loaded.", theclass));
462 params().textclass = 0;
465 // We don't want to adopt the parameters from the
466 // document we insert, so read them into a temporary buffer
467 // and then discard it
469 Buffer tmpbuf("", false);
470 tmpbuf.readHeader(lex);
473 return text().read(*this, lex);
477 // needed to insert the selection
478 void Buffer::insertStringAsLines(ParagraphList & pars,
479 pit_type & par, pos_type & pos,
480 LyXFont const & fn, string const & str, bool autobreakrows)
482 LyXLayout_ptr const & layout = pars[par].layout();
486 pars[par].checkInsertChar(font);
487 // insert the string, don't insert doublespace
488 bool space_inserted = true;
489 for (string::const_iterator cit = str.begin();
490 cit != str.end(); ++cit) {
492 if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
493 breakParagraph(params(), paragraphs(), par, pos,
494 layout->isEnvironment());
497 space_inserted = true;
501 // do not insert consecutive spaces if !free_spacing
502 } else if ((*cit == ' ' || *cit == '\t') &&
503 space_inserted && !pars[par].isFreeSpacing()) {
505 } else if (*cit == '\t') {
506 if (!pars[par].isFreeSpacing()) {
507 // tabs are like spaces here
508 pars[par].insertChar(pos, ' ', font);
510 space_inserted = true;
512 const pos_type n = 8 - pos % 8;
513 for (pos_type i = 0; i < n; ++i) {
514 pars[par].insertChar(pos, ' ', font);
517 space_inserted = true;
519 } else if (!IsPrintable(*cit)) {
520 // Ignore unprintables
523 // just insert the character
524 pars[par].insertChar(pos, *cit, font);
526 space_inserted = (*cit == ' ');
533 bool Buffer::readFile(string const & filename)
535 // Check if the file is compressed.
536 string const format = getFormatFromContents(filename);
537 if (format == "gzip" || format == "zip" || format == "compress") {
538 params().compressed = true;
541 // remove dummy empty par
542 paragraphs().clear();
543 bool ret = readFile(filename, paragraphs().size());
545 // After we have read a file, we must ensure that the buffer
546 // language is set and used in the gui.
547 // If you know of a better place to put this, please tell me. (Lgb)
548 updateDocLang(params().language);
554 bool Buffer::readFile(string const & filename, pit_type const pit)
557 lex.setFile(filename);
558 return readFile(lex, filename, pit);
562 bool Buffer::fully_loaded() const
564 return pimpl_->file_fully_loaded;
568 void Buffer::fully_loaded(bool const value)
570 pimpl_->file_fully_loaded = value;
574 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
576 BOOST_ASSERT(!filename.empty());
579 Alert::error(_("Document could not be read"),
580 bformat(_("%1$s could not be read."), filename));
585 string const token(lex.getString());
588 Alert::error(_("Document could not be read"),
589 bformat(_("%1$s could not be read."), filename));
593 // the first token _must_ be...
594 if (token != "\\lyxformat") {
595 lyxerr << "Token: " << token << endl;
597 Alert::error(_("Document format failure"),
598 bformat(_("%1$s is not a LyX document."),
604 string tmp_format = lex.getString();
605 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
606 // if present remove ".," from string.
607 string::size_type dot = tmp_format.find_first_of(".,");
608 //lyxerr << " dot found at " << dot << endl;
609 if (dot != string::npos)
610 tmp_format.erase(dot, 1);
611 int const file_format = convert<int>(tmp_format);
612 //lyxerr << "format: " << file_format << endl;
614 if (file_format != LYX_FORMAT) {
615 string const tmpfile = tempName();
616 if (tmpfile.empty()) {
617 Alert::error(_("Conversion failed"),
618 bformat(_("%1$s is from an earlier"
619 " version of LyX, but a temporary"
620 " file for converting it could"
626 "python " + LibFileSearch("lyx2lyx", "lyx2lyx");
627 if (command.empty()) {
628 Alert::error(_("Conversion script not found"),
629 bformat(_("%1$s is from an earlier"
630 " version of LyX, but the"
631 " conversion script lyx2lyx"
632 " could not be found."),
637 + convert<string>(LYX_FORMAT)
638 + " -o " + tmpfile + ' '
639 + QuoteName(filename);
640 lyxerr[Debug::INFO] << "Running '"
643 cmd_ret const ret = RunCommand(command);
644 if (ret.first != 0) {
645 Alert::error(_("Conversion script failed"),
646 bformat(_("%1$s is from an earlier version"
647 " of LyX, but the lyx2lyx script"
648 " failed to convert it."),
652 bool const ret = readFile(tmpfile, pit);
653 // Do stuff with tmpfile name and buffer name here.
659 if (readDocument(lex)) {
660 Alert::error(_("Document format failure"),
661 bformat(_("%1$s ended unexpectedly, which means"
662 " that it is probably corrupted."),
666 //lyxerr << "removing " << MacroTable::localMacros().size()
667 // << " temporary macro entries" << endl;
668 //MacroTable::localMacros().clear();
669 params().setPaperStuff();
671 pimpl_->file_fully_loaded = true;
676 // Should probably be moved to somewhere else: BufferView? LyXView?
677 bool Buffer::save() const
679 // We don't need autosaves in the immediate future. (Asger)
680 resetAutosaveTimers();
684 if (lyxrc.make_backup) {
685 s = fileName() + '~';
686 if (!lyxrc.backupdir_path.empty())
687 s = AddName(lyxrc.backupdir_path,
688 subst(os::internal_path(s),'/','!'));
690 // Rename is the wrong way of making a backup,
691 // this is the correct way.
692 /* truss cp fil fil2:
693 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
694 stat("LyXVC.lyx", 0xEFFFF688) = 0
695 open("LyXVC.lyx", O_RDONLY) = 3
696 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
697 fstat(4, 0xEFFFF508) = 0
698 fstat(3, 0xEFFFF508) = 0
699 read(3, " # T h i s f i l e w".., 8192) = 5579
700 write(4, " # T h i s f i l e w".., 5579) = 5579
701 read(3, 0xEFFFD4A0, 8192) = 0
704 chmod("LyXVC3.lyx", 0100644) = 0
705 lseek(0, 0, SEEK_CUR) = 46440
709 // Should probably have some more error checking here.
710 // Doing it this way, also makes the inodes stay the same.
711 // This is still not a very good solution, in particular we
712 // might loose the owner of the backup.
713 FileInfo finfo(fileName());
715 mode_t fmode = finfo.getMode();
716 struct utimbuf times = {
717 finfo.getAccessTime(),
718 finfo.getModificationTime() };
720 ifstream ifs(fileName().c_str());
721 ofstream ofs(s.c_str(), ios::out|ios::trunc);
726 ::chmod(s.c_str(), fmode);
728 if (::utime(s.c_str(), ×)) {
729 lyxerr << "utime error." << endl;
732 lyxerr << "LyX was not able to make "
733 "backup copy. Beware." << endl;
738 if (writeFile(fileName())) {
740 removeAutosaveFile(fileName());
742 // Saving failed, so backup is not backup
743 if (lyxrc.make_backup)
744 rename(s, fileName());
751 bool Buffer::writeFile(string const & fname) const
753 if (pimpl_->read_only && fname == fileName())
756 FileInfo finfo(fname);
757 if (finfo.exist() && !finfo.writable())
762 if (params().compressed) {
763 #ifdef USE_COMPRESSION
764 gz::ogzstream ofs(fname.c_str());
768 retval = do_writeFile(ofs);
773 ofstream ofs(fname.c_str());
777 retval = do_writeFile(ofs);
784 bool Buffer::do_writeFile(ostream & ofs) const
787 // Use the standard "C" locale for file output.
788 ofs.imbue(std::locale::classic());
791 // The top of the file should not be written by params().
793 // write out a comment in the top of the file
794 ofs << "#LyX " << lyx_version
795 << " created this file. For more info see http://www.lyx.org/\n"
796 << "\\lyxformat " << LYX_FORMAT << "\n"
797 << "\\begin_document\n";
799 // now write out the buffer parameters.
800 ofs << "\\begin_header\n";
801 params().writeFile(ofs);
802 ofs << "\\end_header\n";
805 ofs << "\n\\begin_body\n";
806 text().write(*this, ofs);
807 ofs << "\n\\end_body\n";
809 // Write marker that shows file is complete
810 ofs << "\\end_document" << endl;
812 // Shouldn't really be needed....
815 // how to check if close went ok?
816 // Following is an attempt... (BE 20001011)
818 // good() returns false if any error occured, including some
820 // bad() returns true if something bad happened in the buffer,
821 // which should include file system full errors.
826 lyxerr << "File was not closed properly." << endl;
833 void Buffer::makeLaTeXFile(string const & fname,
834 string const & original_path,
835 OutputParams const & runparams,
836 bool output_preamble, bool output_body)
838 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
841 if (!openFileWrite(ofs, fname))
844 makeLaTeXFile(ofs, original_path,
845 runparams, output_preamble, output_body);
849 lyxerr << "File '" << fname << "' was not closed properly." << endl;
853 void Buffer::makeLaTeXFile(ostream & os,
854 string const & original_path,
855 OutputParams const & runparams_in,
856 bool const output_preamble, bool const output_body)
858 OutputParams runparams = runparams_in;
860 // validate the buffer.
861 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
862 LaTeXFeatures features(*this, params(), runparams.nice);
864 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
868 // The starting paragraph of the coming rows is the
869 // first paragraph of the document. (Asger)
870 texrow().start(paragraphs().begin()->id(), 0);
872 if (output_preamble && runparams.nice) {
873 os << "%% LyX " << lyx_version << " created this file. "
874 "For more info, see http://www.lyx.org/.\n"
875 "%% Do not edit unless you really know what "
880 lyxerr[Debug::INFO] << "lyx header finished" << endl;
881 // There are a few differences between nice LaTeX and usual files:
882 // usual is \batchmode and has a
883 // special input@path to allow the including of figures
884 // with either \input or \includegraphics (what figinsets do).
885 // input@path is set when the actual parameter
886 // original_path is set. This is done for usual tex-file, but not
887 // for nice-latex-file. (Matthias 250696)
888 // Note that input@path is only needed for something the user does
889 // in the preamble, included .tex files or ERT, files included by
890 // LyX work without it.
891 if (output_preamble) {
892 if (!runparams.nice) {
893 // code for usual, NOT nice-latex-file
894 os << "\\batchmode\n"; // changed
898 if (!original_path.empty()) {
899 string inputpath = os::external_path(original_path);
900 subst(inputpath, "~", "\\string~");
901 os << "\\makeatletter\n"
902 << "\\def\\input@path{{"
903 << inputpath << "/}}\n"
904 << "\\makeatother\n";
910 // Write the preamble
911 runparams.use_babel = params().writeLaTeX(os, features, texrow());
917 os << "\\begin{document}\n";
920 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
922 if (!lyxrc.language_auto_begin) {
923 os << subst(lyxrc.language_command_begin, "$$lang",
924 params().language->babel())
929 // if we are doing a real file with body, even if this is the
930 // child of some other buffer, let's cut the link here.
931 // This happens for example if only a child document is printed.
932 string save_parentname;
933 if (output_preamble) {
934 save_parentname = params().parentname;
935 params().parentname.erase();
939 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
941 // Restore the parenthood if needed
943 params().parentname = save_parentname;
945 // add this just in case after all the paragraphs
949 if (!lyxrc.language_auto_end) {
950 os << subst(lyxrc.language_command_end, "$$lang",
951 params().language->babel())
956 if (output_preamble) {
957 os << "\\end{document}\n";
960 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
962 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
966 // Just to be sure. (Asger)
969 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
970 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
975 bool Buffer::isLatex() const
977 return params().getLyXTextClass().outputType() == LATEX;
981 bool Buffer::isLinuxDoc() const
983 return params().getLyXTextClass().outputType() == LINUXDOC;
987 bool Buffer::isLiterate() const
989 return params().getLyXTextClass().outputType() == LITERATE;
993 bool Buffer::isDocBook() const
995 return params().getLyXTextClass().outputType() == DOCBOOK;
999 bool Buffer::isSGML() const
1001 LyXTextClass const & tclass = params().getLyXTextClass();
1003 return tclass.outputType() == LINUXDOC ||
1004 tclass.outputType() == DOCBOOK;
1008 void Buffer::makeLinuxDocFile(string const & fname,
1009 OutputParams const & runparams,
1010 bool const body_only)
1013 if (!openFileWrite(ofs, fname))
1016 LaTeXFeatures features(*this, params(), runparams.nice);
1021 LyXTextClass const & tclass = params().getLyXTextClass();
1023 string const & top_element = tclass.latexname();
1026 ofs << tclass.class_header();
1028 string preamble = params().preamble;
1029 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1031 preamble += features.getIncludedFiles(name);
1032 preamble += features.getLyXSGMLEntities();
1034 if (!preamble.empty()) {
1035 ofs << " [ " << preamble << " ]";
1039 if (params().options.empty())
1040 sgml::openTag(ofs, top_element);
1042 string top = top_element;
1044 top += params().options;
1045 sgml::openTag(ofs, top);
1049 ofs << "<!-- LyX " << lyx_version
1050 << " created this file. For more info see http://www.lyx.org/"
1053 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1057 sgml::closeTag(ofs, top_element);
1062 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1066 void Buffer::makeDocBookFile(string const & fname,
1067 OutputParams const & runparams,
1068 bool const only_body)
1071 if (!openFileWrite(ofs, fname))
1074 LaTeXFeatures features(*this, params(), runparams.nice);
1079 LyXTextClass const & tclass = params().getLyXTextClass();
1080 string const & top_element = tclass.latexname();
1083 if (runparams.flavor == OutputParams::XML)
1084 ofs << "<?xml version=\"1.0\" encoding=\""
1085 << params().language->encoding()->Name() << "\"?>\n";
1087 ofs << "<!DOCTYPE " << top_element << " ";
1089 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1090 else if (runparams.flavor == OutputParams::XML)
1091 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1092 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1094 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1096 string preamble = params().preamble;
1097 if (runparams.flavor != OutputParams::XML ) {
1098 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1099 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1100 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1101 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1104 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1106 preamble += features.getIncludedFiles(name);
1107 preamble += features.getLyXSGMLEntities();
1109 if (!preamble.empty()) {
1110 ofs << "\n [ " << preamble << " ]";
1115 string top = top_element;
1117 if (runparams.flavor == OutputParams::XML)
1118 top += params().language->code();
1120 top += params().language->code().substr(0,2);
1123 if (!params().options.empty()) {
1125 top += params().options;
1128 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1129 << " file was created by LyX " << lyx_version
1130 << "\n See http://www.lyx.org/ for more information -->\n";
1132 params().getLyXTextClass().counters().reset();
1134 sgml::openTag(ofs, top);
1136 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1137 sgml::closeTag(ofs, top_element);
1141 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1145 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1146 // Other flags: -wall -v0 -x
1147 int Buffer::runChktex()
1151 // get LaTeX-Filename
1152 string const name = getLatexName();
1153 string const path = temppath();
1154 string const org_path = filePath();
1156 Path p(path); // path to LaTeX file
1157 message(_("Running chktex..."));
1159 // Generate the LaTeX file if neccessary
1160 OutputParams runparams;
1161 runparams.flavor = OutputParams::LATEX;
1162 runparams.nice = false;
1163 makeLaTeXFile(name, org_path, runparams);
1166 Chktex chktex(lyxrc.chktex_command, name, filePath());
1167 int const res = chktex.run(terr); // run chktex
1170 Alert::error(_("chktex failure"),
1171 _("Could not run chktex successfully."));
1172 } else if (res > 0) {
1173 // Insert all errors as errors boxes
1174 bufferErrors(*this, terr);
1183 void Buffer::validate(LaTeXFeatures & features) const
1185 LyXTextClass const & tclass = params().getLyXTextClass();
1187 if (features.isAvailable("dvipost") && params().tracking_changes
1188 && params().output_changes) {
1189 features.require("dvipost");
1190 features.require("color");
1193 // AMS Style is at document level
1194 if (params().use_amsmath == BufferParams::AMS_ON
1195 || tclass.provides(LyXTextClass::amsmath))
1196 features.require("amsmath");
1198 for_each(paragraphs().begin(), paragraphs().end(),
1199 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1201 // the bullet shapes are buffer level not paragraph level
1202 // so they are tested here
1203 for (int i = 0; i < 4; ++i) {
1204 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1205 int const font = params().user_defined_bullet(i).getFont();
1207 int const c = params()
1208 .user_defined_bullet(i)
1215 features.require("latexsym");
1217 } else if (font == 1) {
1218 features.require("amssymb");
1219 } else if ((font >= 2 && font <= 5)) {
1220 features.require("pifont");
1225 if (lyxerr.debugging(Debug::LATEX)) {
1226 features.showStruct();
1231 void Buffer::getLabelList(vector<string> & list) const
1233 /// if this is a child document and the parent is already loaded
1234 /// Use the parent's list instead [ale990407]
1235 Buffer const * tmp = getMasterBuffer();
1237 lyxerr << "getMasterBuffer() failed!" << endl;
1241 tmp->getLabelList(list);
1245 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1246 it.nextInset()->getLabelList(*this, list);
1250 // This is also a buffer property (ale)
1251 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1254 /// if this is a child document and the parent is already loaded
1255 /// use the parent's list instead [ale990412]
1256 Buffer const * tmp = getMasterBuffer();
1259 tmp->fillWithBibKeys(keys);
1263 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1264 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1265 InsetBibtex const & inset =
1266 dynamic_cast<InsetBibtex const &>(*it);
1267 inset.fillWithBibKeys(*this, keys);
1268 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1269 InsetInclude const & inset =
1270 dynamic_cast<InsetInclude const &>(*it);
1271 inset.fillWithBibKeys(*this, keys);
1272 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1273 InsetBibitem const & inset =
1274 dynamic_cast<InsetBibitem const &>(*it);
1275 string const key = inset.getContents();
1276 string const opt = inset.getOptions();
1277 string const ref; // = pit->asString(this, false);
1278 string const info = opt + "TheBibliographyRef" + ref;
1279 keys.push_back(pair<string, string>(key, info));
1285 bool Buffer::isDepClean(string const & name) const
1287 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1288 if (it == pimpl_->dep_clean.end())
1294 void Buffer::markDepClean(string const & name)
1296 pimpl_->dep_clean[name] = true;
1300 bool Buffer::dispatch(string const & command, bool * result)
1302 return dispatch(lyxaction.lookupFunc(command), result);
1306 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1308 bool dispatched = true;
1310 switch (func.action) {
1312 bool const tmp = Exporter::Export(this, func.argument, false);
1325 void Buffer::changeLanguage(Language const * from, Language const * to)
1330 lyxerr << "Changing Language!" << endl;
1332 // Take care of l10n/i18n
1335 for_each(par_iterator_begin(),
1337 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1341 void Buffer::updateDocLang(Language const * nlang)
1343 BOOST_ASSERT(nlang);
1345 pimpl_->messages.reset(new Messages(nlang->code()));
1349 bool Buffer::isMultiLingual() const
1351 ParConstIterator end = par_iterator_end();
1352 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1353 if (it->isMultiLingual(params()))
1360 ParIterator Buffer::getParFromID(int const id) const
1362 ParConstIterator it = par_iterator_begin();
1363 ParConstIterator const end = par_iterator_end();
1366 // John says this is called with id == -1 from undo
1367 lyxerr << "getParFromID(), id: " << id << endl;
1371 for (; it != end; ++it)
1379 bool Buffer::hasParWithID(int const id) const
1381 ParConstIterator const it = getParFromID(id);
1382 return it != par_iterator_end();
1386 ParIterator Buffer::par_iterator_begin()
1388 return ::par_iterator_begin(inset());
1392 ParIterator Buffer::par_iterator_end()
1394 return ::par_iterator_end(inset());
1398 ParConstIterator Buffer::par_iterator_begin() const
1400 return ::par_const_iterator_begin(inset());
1404 ParConstIterator Buffer::par_iterator_end() const
1406 return ::par_const_iterator_end(inset());
1410 Language const * Buffer::getLanguage() const
1412 return params().language;
1416 string const Buffer::B_(string const & l10n) const
1418 if (pimpl_->messages.get()) {
1419 return pimpl_->messages->get(l10n);
1426 bool Buffer::isClean() const
1428 return pimpl_->lyx_clean;
1432 bool Buffer::isBakClean() const
1434 return pimpl_->bak_clean;
1438 void Buffer::markClean() const
1440 if (!pimpl_->lyx_clean) {
1441 pimpl_->lyx_clean = true;
1444 // if the .lyx file has been saved, we don't need an
1446 pimpl_->bak_clean = true;
1450 void Buffer::markBakClean()
1452 pimpl_->bak_clean = true;
1456 void Buffer::setUnnamed(bool flag)
1458 pimpl_->unnamed = flag;
1462 bool Buffer::isUnnamed() const
1464 return pimpl_->unnamed;
1468 #ifdef WITH_WARNINGS
1469 #warning this function should be moved to buffer_pimpl.C
1471 void Buffer::markDirty()
1473 if (pimpl_->lyx_clean) {
1474 pimpl_->lyx_clean = false;
1477 pimpl_->bak_clean = false;
1479 DepClean::iterator it = pimpl_->dep_clean.begin();
1480 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1482 for (; it != end; ++it) {
1488 string const & Buffer::fileName() const
1490 return pimpl_->filename;
1494 string const & Buffer::filePath() const
1496 return pimpl_->filepath;
1500 bool Buffer::isReadonly() const
1502 return pimpl_->read_only;
1506 void Buffer::setParentName(string const & name)
1508 params().parentname = name;
1512 Buffer const * Buffer::getMasterBuffer() const
1514 if (!params().parentname.empty()
1515 && bufferlist.exists(params().parentname)) {
1516 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1518 return buf->getMasterBuffer();
1525 MacroData const & Buffer::getMacro(std::string const & name) const
1527 return pimpl_->macros.get(name);
1531 bool Buffer::hasMacro(string const & name) const
1533 return pimpl_->macros.has(name);
1537 void Buffer::insertMacro(string const & name, MacroData const & data)
1539 MacroTable::globalMacros().insert(name, data);
1540 pimpl_->macros.insert(name, data);
1544 void Buffer::buildMacros()
1546 // Start with global table.
1547 pimpl_->macros = MacroTable::globalMacros();
1550 ParagraphList & pars = text().paragraphs();
1551 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1552 //lyxerr << "searching main par " << i
1553 // << " for macro definitions" << std::endl;
1554 InsetList::iterator it = pars[i].insetlist.begin();
1555 InsetList::iterator end = pars[i].insetlist.end();
1556 for ( ; it != end; ++it) {
1557 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1558 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1559 MathMacroTemplate & mac
1560 = static_cast<MathMacroTemplate &>(*it->inset);
1561 insertMacro(mac.name(), mac.asMacroData());