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 #include "support/gzstream.h"
69 #include "support/lyxlib.h"
70 #include "support/os.h"
71 #include "support/path.h"
72 #include "support/textutils.h"
73 #include "support/convert.h"
75 #include <boost/bind.hpp>
88 using lyx::support::AddName;
89 using lyx::support::bformat;
90 using lyx::support::ChangeExtension;
91 using lyx::support::cmd_ret;
92 using lyx::support::createBufferTmpDir;
93 using lyx::support::destroyDir;
94 using lyx::support::FileInfo;
95 using lyx::support::FileInfo;
96 using lyx::support::getFormatFromContents;
97 using lyx::support::IsDirWriteable;
98 using lyx::support::IsFileWriteable;
99 using lyx::support::LibFileSearch;
100 using lyx::support::ltrim;
101 using lyx::support::MakeAbsPath;
102 using lyx::support::MakeDisplayPath;
103 using lyx::support::MakeLatexName;
104 using lyx::support::OnlyFilename;
105 using lyx::support::OnlyPath;
106 using lyx::support::Path;
107 using lyx::support::QuoteName;
108 using lyx::support::removeAutosaveFile;
109 using lyx::support::rename;
110 using lyx::support::RunCommand;
111 using lyx::support::split;
112 using lyx::support::strToInt;
113 using lyx::support::subst;
114 using lyx::support::tempName;
115 using lyx::support::trim;
117 namespace os = lyx::support::os;
121 using std::make_pair;
127 using std::ostringstream;
135 // all these externs should eventually be removed.
136 extern BufferList bufferlist;
140 int const LYX_FORMAT = 239;
145 typedef std::map<string, bool> DepClean;
150 Impl(Buffer & parent, string const & file, bool readonly);
152 limited_stack<Undo> undostack;
153 limited_stack<Undo> redostack;
159 /// need to regenerate .tex?
163 mutable bool lyx_clean;
165 /// is autosave needed?
166 mutable bool bak_clean;
168 /// is this a unnamed file (New...)?
174 /// name of the file the buffer is associated with.
177 /// The path to the document file.
180 boost::scoped_ptr<Messages> messages;
182 /** Set to true only when the file is fully loaded.
183 * Used to prevent the premature generation of previews
184 * and by the citation inset.
186 bool file_fully_loaded;
188 /// our LyXText that should be wrapped in an InsetText
196 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
197 : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
198 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
201 lyxvc.buffer(&parent);
202 temppath = createBufferTmpDir();
203 // FIXME: And now do something if temppath == string(), because we
204 // assume from now on that temppath points to a valid temp dir.
205 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
209 Buffer::Buffer(string const & file, bool ronly)
210 : pimpl_(new Impl(*this, file, ronly))
212 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
218 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
219 // here the buffer should take care that it is
220 // saved properly, before it goes into the void.
224 if (!temppath().empty() && destroyDir(temppath()) != 0) {
225 Alert::warning(_("Could not remove temporary directory"),
226 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
229 // Remove any previewed LaTeX snippets associated with this buffer.
230 lyx::graphics::Previews::get().removeLoader(*this);
234 LyXText & Buffer::text() const
236 return const_cast<LyXText &>(pimpl_->inset.text_);
240 InsetBase & Buffer::inset() const
242 return const_cast<InsetText &>(pimpl_->inset);
246 limited_stack<Undo> & Buffer::undostack()
248 return pimpl_->undostack;
252 limited_stack<Undo> const & Buffer::undostack() const
254 return pimpl_->undostack;
258 limited_stack<Undo> & Buffer::redostack()
260 return pimpl_->redostack;
264 limited_stack<Undo> const & Buffer::redostack() const
266 return pimpl_->redostack;
270 BufferParams & Buffer::params()
272 return pimpl_->params;
276 BufferParams const & Buffer::params() const
278 return pimpl_->params;
282 ParagraphList & Buffer::paragraphs()
284 return text().paragraphs();
288 ParagraphList const & Buffer::paragraphs() const
290 return text().paragraphs();
294 LyXVC & Buffer::lyxvc()
296 return pimpl_->lyxvc;
300 LyXVC const & Buffer::lyxvc() const
302 return pimpl_->lyxvc;
306 string const & Buffer::temppath() const
308 return pimpl_->temppath;
312 TexRow & Buffer::texrow()
314 return pimpl_->texrow;
318 TexRow const & Buffer::texrow() const
320 return pimpl_->texrow;
324 string const Buffer::getLatexName(bool const no_path) const
326 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
327 return no_path ? OnlyFilename(name) : name;
331 pair<Buffer::LogType, string> const Buffer::getLogName() const
333 string const filename = getLatexName(false);
335 if (filename.empty())
336 return make_pair(Buffer::latexlog, string());
338 string const path = temppath();
340 string const fname = AddName(path,
341 OnlyFilename(ChangeExtension(filename,
344 AddName(path, OnlyFilename(
345 ChangeExtension(filename,
346 formats.extension("literate") + ".out")));
348 // If no Latex log or Build log is newer, show Build log
350 FileInfo const f_fi(fname);
351 FileInfo const b_fi(bname);
354 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
355 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
356 return make_pair(Buffer::buildlog, bname);
358 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
359 return make_pair(Buffer::latexlog, fname);
363 void Buffer::setReadonly(bool const flag)
365 if (pimpl_->read_only != flag) {
366 pimpl_->read_only = flag;
372 void Buffer::setFileName(string const & newfile)
374 pimpl_->filename = MakeAbsPath(newfile);
375 pimpl_->filepath = OnlyPath(pimpl_->filename);
376 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
381 // We'll remove this later. (Lgb)
384 void unknownClass(string const & unknown)
386 Alert::warning(_("Unknown document class"),
387 bformat(_("Using the default document class, because the "
388 "class %1$s is unknown."), unknown));
394 int Buffer::readHeader(LyXLex & lex)
396 int unknown_tokens = 0;
398 int begin_header_line = -1;
402 string const token = lex.getString();
407 if (token == "\\end_header")
411 if (token == "\\begin_header") {
412 begin_header_line = line;
416 lyxerr[Debug::PARSER] << "Handling header token: `"
417 << token << '\'' << endl;
419 string unknown = params().readToken(lex, token);
420 if (!unknown.empty()) {
421 if (unknown[0] != '\\' && token == "\\textclass") {
422 unknownClass(unknown);
425 string const s = bformat(_("Unknown token: "
429 error(ErrorItem(_("Header error"), s,
434 if (begin_header_line) {
435 string const s = _("\\begin_header is missing");
436 error(ErrorItem(_("Header error"), s, -1, 0, 0));
438 return unknown_tokens;
443 // changed to be public and have one parameter
444 // Returns false if "\end_document" is not read (Asger)
445 bool Buffer::readDocument(LyXLex & lex)
448 string const token = lex.getString();
449 if (token != "\\begin_document") {
450 string const s = _("\\begin_document is missing");
451 error(ErrorItem(_("Header error"), s, -1, 0, 0));
454 if (paragraphs().empty()) {
456 if (!params().getLyXTextClass().load()) {
457 string theclass = params().getLyXTextClass().name();
458 Alert::error(_("Can't load document class"), bformat(
459 "Using the default document class, because the "
460 " class %1$s could not be loaded.", theclass));
461 params().textclass = 0;
464 // We don't want to adopt the parameters from the
465 // document we insert, so read them into a temporary buffer
466 // and then discard it
468 Buffer tmpbuf("", false);
469 tmpbuf.readHeader(lex);
472 return text().read(*this, lex);
476 // needed to insert the selection
477 void Buffer::insertStringAsLines(ParagraphList & pars,
478 pit_type & par, pos_type & pos,
479 LyXFont const & fn, string const & str, bool autobreakrows)
481 LyXLayout_ptr const & layout = pars[par].layout();
485 pars[par].checkInsertChar(font);
486 // insert the string, don't insert doublespace
487 bool space_inserted = true;
488 for (string::const_iterator cit = str.begin();
489 cit != str.end(); ++cit) {
491 if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
492 breakParagraph(params(), paragraphs(), par, pos,
493 layout->isEnvironment());
496 space_inserted = true;
500 // do not insert consecutive spaces if !free_spacing
501 } else if ((*cit == ' ' || *cit == '\t') &&
502 space_inserted && !pars[par].isFreeSpacing()) {
504 } else if (*cit == '\t') {
505 if (!pars[par].isFreeSpacing()) {
506 // tabs are like spaces here
507 pars[par].insertChar(pos, ' ', font);
509 space_inserted = true;
511 const pos_type n = 8 - pos % 8;
512 for (pos_type i = 0; i < n; ++i) {
513 pars[par].insertChar(pos, ' ', font);
516 space_inserted = true;
518 } else if (!IsPrintable(*cit)) {
519 // Ignore unprintables
522 // just insert the character
523 pars[par].insertChar(pos, *cit, font);
525 space_inserted = (*cit == ' ');
532 bool Buffer::readFile(string const & filename)
534 // Check if the file is compressed.
535 string const format = getFormatFromContents(filename);
536 if (format == "gzip" || format == "zip" || format == "compress") {
537 params().compressed = true;
540 // remove dummy empty par
541 paragraphs().clear();
542 bool ret = readFile(filename, paragraphs().size());
544 // After we have read a file, we must ensure that the buffer
545 // language is set and used in the gui.
546 // If you know of a better place to put this, please tell me. (Lgb)
547 updateDocLang(params().language);
553 bool Buffer::readFile(string const & filename, pit_type const pit)
556 lex.setFile(filename);
557 return readFile(lex, filename, pit);
561 bool Buffer::fully_loaded() const
563 return pimpl_->file_fully_loaded;
567 void Buffer::fully_loaded(bool const value)
569 pimpl_->file_fully_loaded = value;
573 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
575 BOOST_ASSERT(!filename.empty());
578 Alert::error(_("Document could not be read"),
579 bformat(_("%1$s could not be read."), filename));
584 string const token(lex.getString());
587 Alert::error(_("Document could not be read"),
588 bformat(_("%1$s could not be read."), filename));
592 // the first token _must_ be...
593 if (token != "\\lyxformat") {
594 lyxerr << "Token: " << token << endl;
596 Alert::error(_("Document format failure"),
597 bformat(_("%1$s is not a LyX document."),
603 string tmp_format = lex.getString();
604 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
605 // if present remove ".," from string.
606 string::size_type dot = tmp_format.find_first_of(".,");
607 //lyxerr << " dot found at " << dot << endl;
608 if (dot != string::npos)
609 tmp_format.erase(dot, 1);
610 int file_format = strToInt(tmp_format);
611 //lyxerr << "format: " << file_format << endl;
613 if (file_format != LYX_FORMAT) {
614 string const tmpfile = tempName();
615 if (tmpfile.empty()) {
616 Alert::error(_("Conversion failed"),
617 bformat(_("%1$s is from an earlier"
618 " version of LyX, but a temporary"
619 " file for converting it could"
625 "python " + LibFileSearch("lyx2lyx", "lyx2lyx");
626 if (command.empty()) {
627 Alert::error(_("Conversion script not found"),
628 bformat(_("%1$s is from an earlier"
629 " version of LyX, but the"
630 " conversion script lyx2lyx"
631 " could not be found."),
636 + convert<string>(LYX_FORMAT)
637 + " -o " + tmpfile + ' '
638 + QuoteName(filename);
639 lyxerr[Debug::INFO] << "Running '"
642 cmd_ret const ret = RunCommand(command);
643 if (ret.first != 0) {
644 Alert::error(_("Conversion script failed"),
645 bformat(_("%1$s is from an earlier version"
646 " of LyX, but the lyx2lyx script"
647 " failed to convert it."),
651 bool ret = readFile(tmpfile, pit);
652 // Do stuff with tmpfile name and buffer name here.
658 if (readDocument(lex)) {
659 Alert::error(_("Document format failure"),
660 bformat(_("%1$s ended unexpectedly, which means"
661 " that it is probably corrupted."),
665 //lyxerr << "removing " << MacroTable::localMacros().size()
666 // << " temporary macro entries" << endl;
667 //MacroTable::localMacros().clear();
668 params().setPaperStuff();
670 pimpl_->file_fully_loaded = true;
675 // Should probably be moved to somewhere else: BufferView? LyXView?
676 bool Buffer::save() const
678 // We don't need autosaves in the immediate future. (Asger)
679 resetAutosaveTimers();
683 if (lyxrc.make_backup) {
684 s = fileName() + '~';
685 if (!lyxrc.backupdir_path.empty())
686 s = AddName(lyxrc.backupdir_path,
687 subst(os::internal_path(s),'/','!'));
689 // Rename is the wrong way of making a backup,
690 // this is the correct way.
691 /* truss cp fil fil2:
692 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
693 stat("LyXVC.lyx", 0xEFFFF688) = 0
694 open("LyXVC.lyx", O_RDONLY) = 3
695 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
696 fstat(4, 0xEFFFF508) = 0
697 fstat(3, 0xEFFFF508) = 0
698 read(3, " # T h i s f i l e w".., 8192) = 5579
699 write(4, " # T h i s f i l e w".., 5579) = 5579
700 read(3, 0xEFFFD4A0, 8192) = 0
703 chmod("LyXVC3.lyx", 0100644) = 0
704 lseek(0, 0, SEEK_CUR) = 46440
708 // Should probably have some more error checking here.
709 // Doing it this way, also makes the inodes stay the same.
710 // This is still not a very good solution, in particular we
711 // might loose the owner of the backup.
712 FileInfo finfo(fileName());
714 mode_t fmode = finfo.getMode();
715 struct utimbuf times = {
716 finfo.getAccessTime(),
717 finfo.getModificationTime() };
719 ifstream ifs(fileName().c_str());
720 ofstream ofs(s.c_str(), ios::out|ios::trunc);
725 ::chmod(s.c_str(), fmode);
727 if (::utime(s.c_str(), ×)) {
728 lyxerr << "utime error." << endl;
731 lyxerr << "LyX was not able to make "
732 "backup copy. Beware." << endl;
737 if (writeFile(fileName())) {
739 removeAutosaveFile(fileName());
741 // Saving failed, so backup is not backup
742 if (lyxrc.make_backup)
743 rename(s, fileName());
750 bool Buffer::writeFile(string const & fname) const
752 if (pimpl_->read_only && fname == fileName())
755 FileInfo finfo(fname);
756 if (finfo.exist() && !finfo.writable())
761 if (params().compressed) {
762 gz::ogzstream ofs(fname.c_str());
766 retval = do_writeFile(ofs);
769 ofstream ofs(fname.c_str());
773 retval = do_writeFile(ofs);
780 bool Buffer::do_writeFile(ostream & ofs) const
783 // Use the standard "C" locale for file output.
784 ofs.imbue(std::locale::classic());
787 // The top of the file should not be written by params().
789 // write out a comment in the top of the file
790 ofs << "#LyX " << lyx_version
791 << " created this file. For more info see http://www.lyx.org/\n"
792 << "\\lyxformat " << LYX_FORMAT << "\n"
793 << "\\begin_document\n";
795 // now write out the buffer parameters.
796 ofs << "\\begin_header\n";
797 params().writeFile(ofs);
798 ofs << "\\end_header\n";
801 ofs << "\n\\begin_body\n";
802 text().write(*this, ofs);
803 ofs << "\n\\end_body\n";
805 // Write marker that shows file is complete
806 ofs << "\\end_document" << endl;
808 // Shouldn't really be needed....
811 // how to check if close went ok?
812 // Following is an attempt... (BE 20001011)
814 // good() returns false if any error occured, including some
816 // bad() returns true if something bad happened in the buffer,
817 // which should include file system full errors.
822 lyxerr << "File was not closed properly." << endl;
829 void Buffer::makeLaTeXFile(string const & fname,
830 string const & original_path,
831 OutputParams const & runparams,
832 bool output_preamble, bool output_body)
834 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
837 if (!openFileWrite(ofs, fname))
840 makeLaTeXFile(ofs, original_path,
841 runparams, output_preamble, output_body);
845 lyxerr << "File '" << fname << "' was not closed properly." << endl;
849 void Buffer::makeLaTeXFile(ostream & os,
850 string const & original_path,
851 OutputParams const & runparams_in,
852 bool const output_preamble, bool const output_body)
854 OutputParams runparams = runparams_in;
856 // validate the buffer.
857 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
858 LaTeXFeatures features(*this, params(), runparams.nice);
860 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
864 // The starting paragraph of the coming rows is the
865 // first paragraph of the document. (Asger)
866 texrow().start(paragraphs().begin()->id(), 0);
868 if (output_preamble && runparams.nice) {
869 os << "%% LyX " << lyx_version << " created this file. "
870 "For more info, see http://www.lyx.org/.\n"
871 "%% Do not edit unless you really know what "
876 lyxerr[Debug::INFO] << "lyx header finished" << endl;
877 // There are a few differences between nice LaTeX and usual files:
878 // usual is \batchmode and has a
879 // special input@path to allow the including of figures
880 // with either \input or \includegraphics (what figinsets do).
881 // input@path is set when the actual parameter
882 // original_path is set. This is done for usual tex-file, but not
883 // for nice-latex-file. (Matthias 250696)
884 // Note that input@path is only needed for something the user does
885 // in the preamble, included .tex files or ERT, files included by
886 // LyX work without it.
887 if (output_preamble) {
888 if (!runparams.nice) {
889 // code for usual, NOT nice-latex-file
890 os << "\\batchmode\n"; // changed
894 if (!original_path.empty()) {
895 string inputpath = os::external_path(original_path);
896 subst(inputpath, "~", "\\string~");
897 os << "\\makeatletter\n"
898 << "\\def\\input@path{{"
899 << inputpath << "/}}\n"
900 << "\\makeatother\n";
906 // Write the preamble
907 runparams.use_babel = params().writeLaTeX(os, features, texrow());
913 os << "\\begin{document}\n";
916 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
918 if (!lyxrc.language_auto_begin) {
919 os << subst(lyxrc.language_command_begin, "$$lang",
920 params().language->babel())
925 // if we are doing a real file with body, even if this is the
926 // child of some other buffer, let's cut the link here.
927 // This happens for example if only a child document is printed.
928 string save_parentname;
929 if (output_preamble) {
930 save_parentname = params().parentname;
931 params().parentname.erase();
935 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
937 // Restore the parenthood if needed
939 params().parentname = save_parentname;
941 // add this just in case after all the paragraphs
945 if (!lyxrc.language_auto_end) {
946 os << subst(lyxrc.language_command_end, "$$lang",
947 params().language->babel())
952 if (output_preamble) {
953 os << "\\end{document}\n";
956 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
958 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
962 // Just to be sure. (Asger)
965 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
966 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
971 bool Buffer::isLatex() const
973 return params().getLyXTextClass().outputType() == LATEX;
977 bool Buffer::isLinuxDoc() const
979 return params().getLyXTextClass().outputType() == LINUXDOC;
983 bool Buffer::isLiterate() const
985 return params().getLyXTextClass().outputType() == LITERATE;
989 bool Buffer::isDocBook() const
991 return params().getLyXTextClass().outputType() == DOCBOOK;
995 bool Buffer::isSGML() const
997 LyXTextClass const & tclass = params().getLyXTextClass();
999 return tclass.outputType() == LINUXDOC ||
1000 tclass.outputType() == DOCBOOK;
1004 void Buffer::makeLinuxDocFile(string const & fname,
1005 OutputParams const & runparams,
1006 bool const body_only)
1009 if (!openFileWrite(ofs, fname))
1012 LaTeXFeatures features(*this, params(), runparams.nice);
1017 LyXTextClass const & tclass = params().getLyXTextClass();
1019 string const & top_element = tclass.latexname();
1022 ofs << tclass.class_header();
1024 string preamble = params().preamble;
1025 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1027 preamble += features.getIncludedFiles(name);
1028 preamble += features.getLyXSGMLEntities();
1030 if (!preamble.empty()) {
1031 ofs << " [ " << preamble << " ]";
1035 if (params().options.empty())
1036 sgml::openTag(ofs, top_element);
1038 string top = top_element;
1040 top += params().options;
1041 sgml::openTag(ofs, top);
1045 ofs << "<!-- LyX " << lyx_version
1046 << " created this file. For more info see http://www.lyx.org/"
1049 linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1053 sgml::closeTag(ofs, top_element);
1058 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1062 void Buffer::makeDocBookFile(string const & fname,
1063 OutputParams const & runparams,
1064 bool const only_body)
1067 if (!openFileWrite(ofs, fname))
1070 LaTeXFeatures features(*this, params(), runparams.nice);
1075 LyXTextClass const & tclass = params().getLyXTextClass();
1076 string const & top_element = tclass.latexname();
1079 if (runparams.flavor == OutputParams::XML)
1080 ofs << "<?xml version=\"1.0\" encoding=\""
1081 << params().language->encoding()->Name() << "\"?>\n";
1083 ofs << "<!DOCTYPE " << top_element << " ";
1085 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1086 else if (runparams.flavor == OutputParams::XML)
1087 ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1088 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1090 ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1092 string preamble = params().preamble;
1093 if (runparams.flavor != OutputParams::XML ) {
1094 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1095 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1096 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1097 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1100 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1102 preamble += features.getIncludedFiles(name);
1103 preamble += features.getLyXSGMLEntities();
1105 if (!preamble.empty()) {
1106 ofs << "\n [ " << preamble << " ]";
1111 string top = top_element;
1113 if (runparams.flavor == OutputParams::XML)
1114 top += params().language->code();
1116 top += params().language->code().substr(0,2);
1119 if (!params().options.empty()) {
1121 top += params().options;
1124 ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1125 << " file was created by LyX " << lyx_version
1126 << "\n See http://www.lyx.org/ for more information -->\n";
1128 params().getLyXTextClass().counters().reset();
1130 sgml::openTag(ofs, top);
1132 docbookParagraphs(paragraphs(), *this, ofs, runparams);
1133 sgml::closeTag(ofs, top_element);
1137 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1141 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1142 // Other flags: -wall -v0 -x
1143 int Buffer::runChktex()
1147 // get LaTeX-Filename
1148 string const name = getLatexName();
1149 string const path = temppath();
1150 string const org_path = filePath();
1152 Path p(path); // path to LaTeX file
1153 message(_("Running chktex..."));
1155 // Generate the LaTeX file if neccessary
1156 OutputParams runparams;
1157 runparams.flavor = OutputParams::LATEX;
1158 runparams.nice = false;
1159 makeLaTeXFile(name, org_path, runparams);
1162 Chktex chktex(lyxrc.chktex_command, name, filePath());
1163 int const res = chktex.run(terr); // run chktex
1166 Alert::error(_("chktex failure"),
1167 _("Could not run chktex successfully."));
1168 } else if (res > 0) {
1169 // Insert all errors as errors boxes
1170 bufferErrors(*this, terr);
1179 void Buffer::validate(LaTeXFeatures & features) const
1181 LyXTextClass const & tclass = params().getLyXTextClass();
1183 if (params().tracking_changes) {
1184 features.require("dvipost");
1185 features.require("color");
1188 // AMS Style is at document level
1189 if (params().use_amsmath == BufferParams::AMS_ON
1190 || tclass.provides(LyXTextClass::amsmath))
1191 features.require("amsmath");
1193 for_each(paragraphs().begin(), paragraphs().end(),
1194 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1196 // the bullet shapes are buffer level not paragraph level
1197 // so they are tested here
1198 for (int i = 0; i < 4; ++i) {
1199 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1200 int const font = params().user_defined_bullet(i).getFont();
1202 int const c = params()
1203 .user_defined_bullet(i)
1210 features.require("latexsym");
1212 } else if (font == 1) {
1213 features.require("amssymb");
1214 } else if ((font >= 2 && font <= 5)) {
1215 features.require("pifont");
1220 if (lyxerr.debugging(Debug::LATEX)) {
1221 features.showStruct();
1226 void Buffer::getLabelList(vector<string> & list) const
1228 /// if this is a child document and the parent is already loaded
1229 /// Use the parent's list instead [ale990407]
1230 Buffer const * tmp = getMasterBuffer();
1232 lyxerr << "getMasterBuffer() failed!" << endl;
1236 tmp->getLabelList(list);
1240 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1241 it.nextInset()->getLabelList(*this, list);
1245 // This is also a buffer property (ale)
1246 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1249 /// if this is a child document and the parent is already loaded
1250 /// use the parent's list instead [ale990412]
1251 Buffer const * tmp = getMasterBuffer();
1254 tmp->fillWithBibKeys(keys);
1258 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1259 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1260 InsetBibtex const & inset =
1261 dynamic_cast<InsetBibtex const &>(*it);
1262 inset.fillWithBibKeys(*this, keys);
1263 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1264 InsetInclude const & inset =
1265 dynamic_cast<InsetInclude const &>(*it);
1266 inset.fillWithBibKeys(*this, keys);
1267 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1268 InsetBibitem const & inset =
1269 dynamic_cast<InsetBibitem const &>(*it);
1270 string const key = inset.getContents();
1271 string const opt = inset.getOptions();
1272 string const ref; // = pit->asString(this, false);
1273 string const info = opt + "TheBibliographyRef" + ref;
1274 keys.push_back(pair<string, string>(key, info));
1280 bool Buffer::isDepClean(string const & name) const
1282 DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1283 if (it == pimpl_->dep_clean.end())
1289 void Buffer::markDepClean(string const & name)
1291 pimpl_->dep_clean[name] = true;
1295 bool Buffer::dispatch(string const & command, bool * result)
1297 return dispatch(lyxaction.lookupFunc(command), result);
1301 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1303 bool dispatched = true;
1305 switch (func.action) {
1307 bool const tmp = Exporter::Export(this, func.argument, false);
1320 void Buffer::changeLanguage(Language const * from, Language const * to)
1325 lyxerr << "Changing Language!" << endl;
1327 // Take care of l10n/i18n
1330 for_each(par_iterator_begin(),
1332 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1336 void Buffer::updateDocLang(Language const * nlang)
1338 BOOST_ASSERT(nlang);
1340 pimpl_->messages.reset(new Messages(nlang->code()));
1344 bool Buffer::isMultiLingual() const
1346 ParConstIterator end = par_iterator_end();
1347 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1348 if (it->isMultiLingual(params()))
1355 ParIterator Buffer::getParFromID(int const id) const
1357 ParConstIterator it = par_iterator_begin();
1358 ParConstIterator const end = par_iterator_end();
1361 // John says this is called with id == -1 from undo
1362 lyxerr << "getParFromID(), id: " << id << endl;
1366 for (; it != end; ++it)
1374 bool Buffer::hasParWithID(int const id) const
1376 ParConstIterator const it = getParFromID(id);
1377 return it != par_iterator_end();
1381 ParIterator Buffer::par_iterator_begin()
1383 return ::par_iterator_begin(inset());
1387 ParIterator Buffer::par_iterator_end()
1389 return ::par_iterator_end(inset());
1393 ParConstIterator Buffer::par_iterator_begin() const
1395 return ::par_const_iterator_begin(inset());
1399 ParConstIterator Buffer::par_iterator_end() const
1401 return ::par_const_iterator_end(inset());
1405 Language const * Buffer::getLanguage() const
1407 return params().language;
1411 string const Buffer::B_(string const & l10n) const
1413 if (pimpl_->messages.get()) {
1414 return pimpl_->messages->get(l10n);
1421 bool Buffer::isClean() const
1423 return pimpl_->lyx_clean;
1427 bool Buffer::isBakClean() const
1429 return pimpl_->bak_clean;
1433 void Buffer::markClean() const
1435 if (!pimpl_->lyx_clean) {
1436 pimpl_->lyx_clean = true;
1439 // if the .lyx file has been saved, we don't need an
1441 pimpl_->bak_clean = true;
1445 void Buffer::markBakClean()
1447 pimpl_->bak_clean = true;
1451 void Buffer::setUnnamed(bool flag)
1453 pimpl_->unnamed = flag;
1457 bool Buffer::isUnnamed() const
1459 return pimpl_->unnamed;
1463 #ifdef WITH_WARNINGS
1464 #warning this function should be moved to buffer_pimpl.C
1466 void Buffer::markDirty()
1468 if (pimpl_->lyx_clean) {
1469 pimpl_->lyx_clean = false;
1472 pimpl_->bak_clean = false;
1474 DepClean::iterator it = pimpl_->dep_clean.begin();
1475 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1477 for (; it != end; ++it) {
1483 string const & Buffer::fileName() const
1485 return pimpl_->filename;
1489 string const & Buffer::filePath() const
1491 return pimpl_->filepath;
1495 bool Buffer::isReadonly() const
1497 return pimpl_->read_only;
1501 void Buffer::setParentName(string const & name)
1503 params().parentname = name;
1507 Buffer const * Buffer::getMasterBuffer() const
1509 if (!params().parentname.empty()
1510 && bufferlist.exists(params().parentname)) {
1511 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1513 return buf->getMasterBuffer();
1520 MacroData const & Buffer::getMacro(std::string const & name) const
1522 return pimpl_->macros.get(name);
1526 bool Buffer::hasMacro(string const & name) const
1528 return pimpl_->macros.has(name);
1532 void Buffer::insertMacro(string const & name, MacroData const & data)
1534 MacroTable::globalMacros().insert(name, data);
1535 pimpl_->macros.insert(name, data);
1539 void Buffer::buildMacros()
1541 // Start with global table.
1542 pimpl_->macros = MacroTable::globalMacros();
1545 ParagraphList & pars = text().paragraphs();
1546 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1547 //lyxerr << "searching main par " << i
1548 // << " for macro definitions" << std::endl;
1549 InsetList::iterator it = pars[i].insetlist.begin();
1550 InsetList::iterator end = pars[i].insetlist.end();
1551 for ( ; it != end; ++it) {
1552 //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1553 if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1554 MathMacroTemplate & mac
1555 = static_cast<MathMacroTemplate &>(*it->inset);
1556 insertMacro(mac.name(), mac.asMacroData());