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::strToInt;
115 using lyx::support::subst;
116 using lyx::support::tempName;
117 using lyx::support::trim;
119 namespace os = lyx::support::os;
123 using std::make_pair;
129 using std::ostringstream;
137 // all these externs should eventually be removed.
138 extern BufferList bufferlist;
142 int const LYX_FORMAT = 239;
147 typedef std::map<string, bool> DepClean;
152 Impl(Buffer & parent, string const & file, bool readonly);
154 limited_stack<Undo> undostack;
155 limited_stack<Undo> redostack;
161 /// need to regenerate .tex?
165 mutable bool lyx_clean;
167 /// is autosave needed?
168 mutable bool bak_clean;
170 /// is this a unnamed file (New...)?
176 /// name of the file the buffer is associated with.
179 /// The path to the document file.
182 boost::scoped_ptr<Messages> messages;
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
190 /// our LyXText that should be wrapped in an InsetText
198 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
199 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
200 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
203 lyxvc.buffer(&parent);
204 temppath = createBufferTmpDir();
205 // FIXME: And now do something if temppath == string(), because we
206 // assume from now on that temppath points to a valid temp dir.
207 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
211 Buffer::Buffer(string const & file, bool ronly)
212 : pimpl_(new Impl(*this, file, ronly))
214 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
220 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
221 // here the buffer should take care that it is
222 // saved properly, before it goes into the void.
226 if (!temppath().empty() && destroyDir(temppath()) != 0) {
227 Alert::warning(_("Could not remove temporary directory"),
228 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
231 // Remove any previewed LaTeX snippets associated with this buffer.
232 lyx::graphics::Previews::get().removeLoader(*this);
236 LyXText & Buffer::text() const
238 return const_cast<LyXText &>(pimpl_->inset.text_);
242 InsetBase & Buffer::inset() const
244 return const_cast<InsetText &>(pimpl_->inset);
248 limited_stack<Undo> & Buffer::undostack()
250 return pimpl_->undostack;
254 limited_stack<Undo> const & Buffer::undostack() const
256 return pimpl_->undostack;
260 limited_stack<Undo> & Buffer::redostack()
262 return pimpl_->redostack;
266 limited_stack<Undo> const & Buffer::redostack() const
268 return pimpl_->redostack;
272 BufferParams & Buffer::params()
274 return pimpl_->params;
278 BufferParams const & Buffer::params() const
280 return pimpl_->params;
284 ParagraphList & Buffer::paragraphs()
286 return text().paragraphs();
290 ParagraphList const & Buffer::paragraphs() const
292 return text().paragraphs();
296 LyXVC & Buffer::lyxvc()
298 return pimpl_->lyxvc;
302 LyXVC const & Buffer::lyxvc() const
304 return pimpl_->lyxvc;
308 string const & Buffer::temppath() const
310 return pimpl_->temppath;
314 TexRow & Buffer::texrow()
316 return pimpl_->texrow;
320 TexRow const & Buffer::texrow() const
322 return pimpl_->texrow;
326 string const Buffer::getLatexName(bool const no_path) const
328 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
329 return no_path ? OnlyFilename(name) : name;
333 pair<Buffer::LogType, string> const Buffer::getLogName() const
335 string const filename = getLatexName(false);
337 if (filename.empty())
338 return make_pair(Buffer::latexlog, string());
340 string const path = temppath();
342 string const fname = AddName(path,
343 OnlyFilename(ChangeExtension(filename,
346 AddName(path, OnlyFilename(
347 ChangeExtension(filename,
348 formats.extension("literate") + ".out")));
350 // If no Latex log or Build log is newer, show Build log
352 FileInfo const f_fi(fname);
353 FileInfo const b_fi(bname);
356 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
357 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
358 return make_pair(Buffer::buildlog, bname);
360 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
361 return make_pair(Buffer::latexlog, fname);
365 void Buffer::setReadonly(bool const flag)
367 if (pimpl_->read_only != flag) {
368 pimpl_->read_only = flag;
374 void Buffer::setFileName(string const & newfile)
376 pimpl_->filename = MakeAbsPath(newfile);
377 pimpl_->filepath = OnlyPath(pimpl_->filename);
378 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
383 // We'll remove this later. (Lgb)
386 void unknownClass(string const & unknown)
388 Alert::warning(_("Unknown document class"),
389 bformat(_("Using the default document class, because the "
390 "class %1$s is unknown."), unknown));
396 int Buffer::readHeader(LyXLex & lex)
398 int unknown_tokens = 0;
400 int begin_header_line = -1;
404 string const token = lex.getString();
409 if (token == "\\end_header")
413 if (token == "\\begin_header") {
414 begin_header_line = line;
418 lyxerr[Debug::PARSER] << "Handling header token: `"
419 << token << '\'' << endl;
421 string unknown = params().readToken(lex, token);
422 if (!unknown.empty()) {
423 if (unknown[0] != '\\' && token == "\\textclass") {
424 unknownClass(unknown);
427 string const s = bformat(_("Unknown token: "
431 error(ErrorItem(_("Header error"), s,
436 if (begin_header_line) {
437 string const s = _("\\begin_header is missing");
438 error(ErrorItem(_("Header error"), s, -1, 0, 0));
440 return unknown_tokens;
445 // changed to be public and have one parameter
446 // Returns false if "\end_document" is not read (Asger)
447 bool Buffer::readDocument(LyXLex & lex)
450 string const token = lex.getString();
451 if (token != "\\begin_document") {
452 string const s = _("\\begin_document is missing");
453 error(ErrorItem(_("Header error"), s, -1, 0, 0));
456 if (paragraphs().empty()) {
458 if (!params().getLyXTextClass().load()) {
459 string theclass = params().getLyXTextClass().name();
460 Alert::error(_("Can't load document class"), bformat(
461 "Using the default document class, because the "
462 " class %1$s could not be loaded.", theclass));
463 params().textclass = 0;
466 // We don't want to adopt the parameters from the
467 // document we insert, so read them into a temporary buffer
468 // and then discard it
470 Buffer tmpbuf("", false);
471 tmpbuf.readHeader(lex);
474 return text().read(*this, lex);
478 // needed to insert the selection
479 void Buffer::insertStringAsLines(ParagraphList & pars,
480 pit_type & par, pos_type & pos,
481 LyXFont const & fn, string const & str, bool autobreakrows)
483 LyXLayout_ptr const & layout = pars[par].layout();
487 pars[par].checkInsertChar(font);
488 // insert the string, don't insert doublespace
489 bool space_inserted = true;
490 for (string::const_iterator cit = str.begin();
491 cit != str.end(); ++cit) {
493 if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
494 breakParagraph(params(), paragraphs(), par, pos,
495 layout->isEnvironment());
498 space_inserted = true;
502 // do not insert consecutive spaces if !free_spacing
503 } else if ((*cit == ' ' || *cit == '\t') &&
504 space_inserted && !pars[par].isFreeSpacing()) {
506 } else if (*cit == '\t') {
507 if (!pars[par].isFreeSpacing()) {
508 // tabs are like spaces here
509 pars[par].insertChar(pos, ' ', font);
511 space_inserted = true;
513 const pos_type n = 8 - pos % 8;
514 for (pos_type i = 0; i < n; ++i) {
515 pars[par].insertChar(pos, ' ', font);
518 space_inserted = true;
520 } else if (!IsPrintable(*cit)) {
521 // Ignore unprintables
524 // just insert the character
525 pars[par].insertChar(pos, *cit, font);
527 space_inserted = (*cit == ' ');
534 bool Buffer::readFile(string const & filename)
536 // Check if the file is compressed.
537 string const format = getFormatFromContents(filename);
538 if (format == "gzip" || format == "zip" || format == "compress") {
539 params().compressed = true;
542 // remove dummy empty par
543 paragraphs().clear();
544 bool ret = readFile(filename, paragraphs().size());
546 // After we have read a file, we must ensure that the buffer
547 // language is set and used in the gui.
548 // If you know of a better place to put this, please tell me. (Lgb)
549 updateDocLang(params().language);
555 bool Buffer::readFile(string const & filename, pit_type const pit)
558 lex.setFile(filename);
559 return readFile(lex, filename, pit);
563 bool Buffer::fully_loaded() const
565 return pimpl_->file_fully_loaded;
569 void Buffer::fully_loaded(bool const value)
571 pimpl_->file_fully_loaded = value;
575 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
577 BOOST_ASSERT(!filename.empty());
580 Alert::error(_("Document could not be read"),
581 bformat(_("%1$s could not be read."), filename));
586 string const token(lex.getString());
589 Alert::error(_("Document could not be read"),
590 bformat(_("%1$s could not be read."), filename));
594 // the first token _must_ be...
595 if (token != "\\lyxformat") {
596 lyxerr << "Token: " << token << endl;
598 Alert::error(_("Document format failure"),
599 bformat(_("%1$s is not a LyX document."),
605 string tmp_format = lex.getString();
606 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
607 // if present remove ".," from string.
608 string::size_type dot = tmp_format.find_first_of(".,");
609 //lyxerr << " dot found at " << dot << endl;
610 if (dot != string::npos)
611 tmp_format.erase(dot, 1);
612 int file_format = strToInt(tmp_format);
613 //lyxerr << "format: " << file_format << endl;
615 if (file_format != LYX_FORMAT) {
616 string const tmpfile = tempName();
617 if (tmpfile.empty()) {
618 Alert::error(_("Conversion failed"),
619 bformat(_("%1$s is from an earlier"
620 " version of LyX, but a temporary"
621 " file for converting it could"
627 "python " + LibFileSearch("lyx2lyx", "lyx2lyx");
628 if (command.empty()) {
629 Alert::error(_("Conversion script not found"),
630 bformat(_("%1$s is from an earlier"
631 " version of LyX, but the"
632 " conversion script lyx2lyx"
633 " could not be found."),
638 + convert<string>(LYX_FORMAT)
639 + " -o " + tmpfile + ' '
640 + QuoteName(filename);
641 lyxerr[Debug::INFO] << "Running '"
644 cmd_ret const ret = RunCommand(command);
645 if (ret.first != 0) {
646 Alert::error(_("Conversion script failed"),
647 bformat(_("%1$s is from an earlier version"
648 " of LyX, but the lyx2lyx script"
649 " failed to convert it."),
653 bool ret = readFile(tmpfile, pit);
654 // Do stuff with tmpfile name and buffer name here.
660 if (readDocument(lex)) {
661 Alert::error(_("Document format failure"),
662 bformat(_("%1$s ended unexpectedly, which means"
663 " that it is probably corrupted."),
667 //lyxerr << "removing " << MacroTable::localMacros().size()
668 // << " temporary macro entries" << endl;
669 //MacroTable::localMacros().clear();
670 params().setPaperStuff();
672 pimpl_->file_fully_loaded = true;
677 // Should probably be moved to somewhere else: BufferView? LyXView?
678 bool Buffer::save() const
680 // We don't need autosaves in the immediate future. (Asger)
681 resetAutosaveTimers();
685 if (lyxrc.make_backup) {
686 s = fileName() + '~';
687 if (!lyxrc.backupdir_path.empty())
688 s = AddName(lyxrc.backupdir_path,
689 subst(os::internal_path(s),'/','!'));
691 // Rename is the wrong way of making a backup,
692 // this is the correct way.
693 /* truss cp fil fil2:
694 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
695 stat("LyXVC.lyx", 0xEFFFF688) = 0
696 open("LyXVC.lyx", O_RDONLY) = 3
697 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
698 fstat(4, 0xEFFFF508) = 0
699 fstat(3, 0xEFFFF508) = 0
700 read(3, " # T h i s f i l e w".., 8192) = 5579
701 write(4, " # T h i s f i l e w".., 5579) = 5579
702 read(3, 0xEFFFD4A0, 8192) = 0
705 chmod("LyXVC3.lyx", 0100644) = 0
706 lseek(0, 0, SEEK_CUR) = 46440
710 // Should probably have some more error checking here.
711 // Doing it this way, also makes the inodes stay the same.
712 // This is still not a very good solution, in particular we
713 // might loose the owner of the backup.
714 FileInfo finfo(fileName());
716 mode_t fmode = finfo.getMode();
717 struct utimbuf times = {
718 finfo.getAccessTime(),
719 finfo.getModificationTime() };
721 ifstream ifs(fileName().c_str());
722 ofstream ofs(s.c_str(), ios::out|ios::trunc);
727 ::chmod(s.c_str(), fmode);
729 if (::utime(s.c_str(), ×)) {
730 lyxerr << "utime error." << endl;
733 lyxerr << "LyX was not able to make "
734 "backup copy. Beware." << endl;
739 if (writeFile(fileName())) {
741 removeAutosaveFile(fileName());
743 // Saving failed, so backup is not backup
744 if (lyxrc.make_backup)
745 rename(s, fileName());
752 bool Buffer::writeFile(string const & fname) const
754 if (pimpl_->read_only && fname == fileName())
757 FileInfo finfo(fname);
758 if (finfo.exist() && !finfo.writable())
763 if (params().compressed) {
764 #ifdef USE_COMPRESSION
765 gz::ogzstream ofs(fname.c_str());
769 retval = do_writeFile(ofs);
774 ofstream ofs(fname.c_str());
778 retval = do_writeFile(ofs);
785 bool Buffer::do_writeFile(ostream & ofs) const
788 // Use the standard "C" locale for file output.
789 ofs.imbue(std::locale::classic());
792 // The top of the file should not be written by params().
794 // write out a comment in the top of the file
795 ofs << "#LyX " << lyx_version
796 << " created this file. For more info see http://www.lyx.org/\n"
797 << "\\lyxformat " << LYX_FORMAT << "\n"
798 << "\\begin_document\n";
800 // now write out the buffer parameters.
801 ofs << "\\begin_header\n";
802 params().writeFile(ofs);
803 ofs << "\\end_header\n";
806 ofs << "\n\\begin_body\n";
807 text().write(*this, ofs);
808 ofs << "\n\\end_body\n";
810 // Write marker that shows file is complete
811 ofs << "\\end_document" << endl;
813 // Shouldn't really be needed....
816 // how to check if close went ok?
817 // Following is an attempt... (BE 20001011)
819 // good() returns false if any error occured, including some
821 // bad() returns true if something bad happened in the buffer,
822 // which should include file system full errors.
827 lyxerr << "File was not closed properly." << endl;
834 void Buffer::makeLaTeXFile(string const & fname,
835 string const & original_path,
836 OutputParams const & runparams,
837 bool output_preamble, bool output_body)
839 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
842 if (!openFileWrite(ofs, fname))
845 makeLaTeXFile(ofs, original_path,
846 runparams, output_preamble, output_body);
850 lyxerr << "File '" << fname << "' was not closed properly." << endl;
854 void Buffer::makeLaTeXFile(ostream & os,
855 string const & original_path,
856 OutputParams const & runparams_in,
857 bool const output_preamble, bool const output_body)
859 OutputParams runparams = runparams_in;
861 // validate the buffer.
862 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
863 LaTeXFeatures features(*this, params(), runparams.nice);
865 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
869 // The starting paragraph of the coming rows is the
870 // first paragraph of the document. (Asger)
871 texrow().start(paragraphs().begin()->id(), 0);
873 if (output_preamble && runparams.nice) {
874 os << "%% LyX " << lyx_version << " created this file. "
875 "For more info, see http://www.lyx.org/.\n"
876 "%% Do not edit unless you really know what "
881 lyxerr[Debug::INFO] << "lyx header finished" << endl;
882 // There are a few differences between nice LaTeX and usual files:
883 // usual is \batchmode and has a
884 // special input@path to allow the including of figures
885 // with either \input or \includegraphics (what figinsets do).
886 // input@path is set when the actual parameter
887 // original_path is set. This is done for usual tex-file, but not
888 // for nice-latex-file. (Matthias 250696)
889 // Note that input@path is only needed for something the user does
890 // in the preamble, included .tex files or ERT, files included by
891 // LyX work without it.
892 if (output_preamble) {
893 if (!runparams.nice) {
894 // code for usual, NOT nice-latex-file
895 os << "\\batchmode\n"; // changed
899 if (!original_path.empty()) {
900 string inputpath = os::external_path(original_path);
901 subst(inputpath, "~", "\\string~");
902 os << "\\makeatletter\n"
903 << "\\def\\input@path{{"
904 << inputpath << "/}}\n"
905 << "\\makeatother\n";
911 // Write the preamble
912 runparams.use_babel = params().writeLaTeX(os, features, texrow());
918 os << "\\begin{document}\n";
921 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
923 if (!lyxrc.language_auto_begin) {
924 os << subst(lyxrc.language_command_begin, "$$lang",
925 params().language->babel())
930 // if we are doing a real file with body, even if this is the
931 // child of some other buffer, let's cut the link here.
932 // This happens for example if only a child document is printed.
933 string save_parentname;
934 if (output_preamble) {
935 save_parentname = params().parentname;
936 params().parentname.erase();
940 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
942 // Restore the parenthood if needed
944 params().parentname = save_parentname;
946 // add this just in case after all the paragraphs
950 if (!lyxrc.language_auto_end) {
951 os << subst(lyxrc.language_command_end, "$$lang",
952 params().language->babel())
957 if (output_preamble) {
958 os << "\\end{document}\n";
961 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
963 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
967 // Just to be sure. (Asger)
970 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
971 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
976 bool Buffer::isLatex() const
978 return params().getLyXTextClass().outputType() == LATEX;
982 bool Buffer::isLinuxDoc() const
984 return params().getLyXTextClass().outputType() == LINUXDOC;
988 bool Buffer::isLiterate() const
990 return params().getLyXTextClass().outputType() == LITERATE;
994 bool Buffer::isDocBook() const
996 return params().getLyXTextClass().outputType() == DOCBOOK;
1000 bool Buffer::isSGML() const
1002 LyXTextClass const & tclass = params().getLyXTextClass();
1004 return tclass.outputType() == LINUXDOC ||
1005 tclass.outputType() == DOCBOOK;
1009 void Buffer::makeLinuxDocFile(string const & fname,
1010 OutputParams const & runparams,
1011 bool const body_only)
1014 if (!openFileWrite(ofs, fname))
1017 LaTeXFeatures features(*this, params(), runparams.nice);
1022 LyXTextClass const & tclass = params().getLyXTextClass();
1024 string const & top_element = tclass.latexname();
1027 ofs << tclass.class_header();
1029 string preamble = params().preamble;
1030 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1032 preamble += features.getIncludedFiles(name);
1033 preamble += features.getLyXSGMLEntities();
1035 if (!preamble.empty()) {
1036 ofs << " [ " << preamble << " ]";
1040 if (params().options.empty())
1041 sgml::openTag(ofs, top_element);
1043 string top = top_element;
1045 top += params().options;
1046 sgml::openTag(ofs, top);
1050 ofs << "<!-- LyX " << lyx_version
1051 << " created this file. For more info see http://www.lyx.org/"
1054 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1058 sgml::closeTag(ofs, top_element);
1063 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1067 void Buffer::makeDocBookFile(string const & fname,
1068 OutputParams const & runparams,
1069 bool const only_body)
1072 if (!openFileWrite(ofs, fname))
1075 LaTeXFeatures features(*this, params(), runparams.nice);
1080 LyXTextClass const & tclass = params().getLyXTextClass();
1081 string const & top_element = tclass.latexname();
1084 if (runparams.flavor == OutputParams::XML)
1085 ofs << "<?xml version=\"1.0\" encoding=\""
1086 << params().language->encoding()->Name() << "\"?>\n";
1088 ofs << "<!DOCTYPE " << top_element << " ";
1090 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1091 else if (runparams.flavor == OutputParams::XML)
1092 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1093 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1095 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1097 string preamble = params().preamble;
1098 if (runparams.flavor != OutputParams::XML ) {
1099 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1100 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1101 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1102 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1105 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1107 preamble += features.getIncludedFiles(name);
1108 preamble += features.getLyXSGMLEntities();
1110 if (!preamble.empty()) {
1111 ofs << "\n [ " << preamble << " ]";
1116 string top = top_element;
1118 if (runparams.flavor == OutputParams::XML)
1119 top += params().language->code();
1121 top += params().language->code().substr(0,2);
1124 if (!params().options.empty()) {
1126 top += params().options;
1129 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1130 << " file was created by LyX " << lyx_version
1131 << "\n See http://www.lyx.org/ for more information -->\n";
1133 params().getLyXTextClass().counters().reset();
1135 sgml::openTag(ofs, top);
1137 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1138 sgml::closeTag(ofs, top_element);
1142 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1146 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1147 // Other flags: -wall -v0 -x
1148 int Buffer::runChktex()
1152 // get LaTeX-Filename
1153 string const name = getLatexName();
1154 string const path = temppath();
1155 string const org_path = filePath();
1157 Path p(path); // path to LaTeX file
1158 message(_("Running chktex..."));
1160 // Generate the LaTeX file if neccessary
1161 OutputParams runparams;
1162 runparams.flavor = OutputParams::LATEX;
1163 runparams.nice = false;
1164 makeLaTeXFile(name, org_path, runparams);
1167 Chktex chktex(lyxrc.chktex_command, name, filePath());
1168 int const res = chktex.run(terr); // run chktex
1171 Alert::error(_("chktex failure"),
1172 _("Could not run chktex successfully."));
1173 } else if (res > 0) {
1174 // Insert all errors as errors boxes
1175 bufferErrors(*this, terr);
1184 void Buffer::validate(LaTeXFeatures & features) const
1186 LyXTextClass const & tclass = params().getLyXTextClass();
1188 if (params().tracking_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());