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
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
24 #include "Converter.h"
26 #include "DocIterator.h"
27 #include "EmbeddedFiles.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
56 #include "TexStream.h"
57 #include "TextClassList.h"
59 #include "TocBackend.h"
61 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/convert.h"
80 #include "support/debug.h"
81 #include "support/FileFilterList.h"
82 #include "support/FileNameList.h"
83 #include "support/filetools.h"
84 #include "support/ForkedCalls.h"
85 #include "support/gettext.h"
86 #include "support/gzstream.h"
87 #include "support/lstrings.h"
88 #include "support/lyxalgo.h"
89 #include "support/lyxlib.h"
90 #include "support/os.h"
91 #include "support/Path.h"
92 #include "support/textutils.h"
93 #include "support/types.h"
94 #include "support/FileZipListDir.h"
96 #if !defined (HAVE_FORK)
100 #include <boost/bind.hpp>
101 #include <boost/shared_ptr.hpp>
113 using support::addName;
114 using support::bformat;
115 using support::changeExtension;
116 using support::cmd_ret;
117 using support::createBufferTmpDir;
118 using support::FileName;
119 using support::FileNameList;
120 using support::libFileSearch;
121 using support::latex_path;
122 using support::ltrim;
123 using support::makeAbsPath;
124 using support::makeDisplayPath;
125 using support::makeLatexName;
126 using support::onlyFilename;
127 using support::onlyPath;
128 using support::quoteName;
129 using support::removeAutosaveFile;
130 using support::rename;
131 using support::runCommand;
132 using support::split;
133 using support::subst;
134 using support::tempName;
136 using support::suffixIs;
138 namespace Alert = frontend::Alert;
139 namespace os = support::os;
143 int const LYX_FORMAT = 307; // JSpitzm: support for \slash
148 typedef std::map<string, bool> DepClean;
153 Impl(Buffer & parent, FileName const & file, bool readonly);
166 mutable TexRow texrow;
167 Buffer const * parent_buffer;
169 /// need to regenerate .tex?
173 mutable bool lyx_clean;
175 /// is autosave needed?
176 mutable bool bak_clean;
178 /// is this a unnamed file (New...)?
184 /// name of the file the buffer is associated with.
187 /** Set to true only when the file is fully loaded.
188 * Used to prevent the premature generation of previews
189 * and by the citation inset.
191 bool file_fully_loaded;
193 /// our Text that should be wrapped in an InsetText
197 mutable TocBackend toc_backend;
200 typedef std::map<unsigned int, MacroData, std::greater<int> > PositionToMacroMap;
201 typedef std::map<docstring, PositionToMacroMap> NameToPositionMacroMap;
202 NameToPositionMacroMap macros;
204 /// Container for all sort of Buffer dependant errors.
205 map<string, ErrorList> errorLists;
207 /// all embedded files of this buffer
208 EmbeddedFiles embedded_files;
210 /// timestamp and checksum used to test if the file has been externally
211 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
213 unsigned long checksum_;
216 frontend::WorkAreaManager * wa_;
221 /// A cache for the bibfiles (including bibfiles of loaded child
222 /// documents), needed for appropriate update of natbib labels.
223 mutable FileNameList bibfilesCache_;
227 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
228 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
229 read_only(readonly_), filename(file), file_fully_loaded(false),
230 inset(params), toc_backend(&parent), embedded_files(&parent),
231 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
233 inset.setAutoBreakRows(true);
234 lyxvc.setBuffer(&parent);
235 temppath = createBufferTmpDir();
237 // FIXME: And now do something if temppath == string(), because we
238 // assume from now on that temppath points to a valid temp dir.
239 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
242 wa_ = new frontend::WorkAreaManager;
246 Buffer::Buffer(string const & file, bool readonly)
247 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
249 LYXERR(Debug::INFO, "Buffer::Buffer()");
255 LYXERR(Debug::INFO, "Buffer::~Buffer()");
256 // here the buffer should take care that it is
257 // saved properly, before it goes into the void.
259 // GuiView already destroyed
262 Buffer const * master = masterBuffer();
263 if (master != this && use_gui)
264 // We are closing buf which was a child document so we
265 // must update the labels and section numbering of its master
267 updateLabels(*master);
269 resetChildDocuments(false);
271 if (!temppath().empty() && !FileName(temppath()).destroyDirectory()) {
272 Alert::warning(_("Could not remove temporary directory"),
273 bformat(_("Could not remove the temporary directory %1$s"),
274 from_utf8(temppath())));
277 // Remove any previewed LaTeX snippets associated with this buffer.
278 graphics::Previews::get().removeLoader(*this);
284 void Buffer::changed() const
291 frontend::WorkAreaManager & Buffer::workAreaManager() const
293 BOOST_ASSERT(d->wa_);
298 Text & Buffer::text() const
300 return const_cast<Text &>(d->inset.text_);
304 Inset & Buffer::inset() const
306 return const_cast<InsetText &>(d->inset);
310 BufferParams & Buffer::params()
316 BufferParams const & Buffer::params() const
322 ParagraphList & Buffer::paragraphs()
324 return text().paragraphs();
328 ParagraphList const & Buffer::paragraphs() const
330 return text().paragraphs();
334 LyXVC & Buffer::lyxvc()
340 LyXVC const & Buffer::lyxvc() const
346 string const & Buffer::temppath() const
352 TexRow const & Buffer::texrow() const
358 TocBackend & Buffer::tocBackend() const
360 return d->toc_backend;
364 EmbeddedFiles & Buffer::embeddedFiles()
366 return d->embedded_files;
370 EmbeddedFiles const & Buffer::embeddedFiles() const
372 return d->embedded_files;
376 Undo & Buffer::undo()
382 string Buffer::latexName(bool const no_path) const
384 FileName latex_name = makeLatexName(d->filename);
385 return no_path ? latex_name.onlyFileName()
386 : latex_name.absFilename();
390 string Buffer::logName(LogType * type) const
392 string const filename = latexName(false);
394 if (filename.empty()) {
400 string const path = temppath();
402 FileName const fname(addName(temppath(),
403 onlyFilename(changeExtension(filename,
405 FileName const bname(
406 addName(path, onlyFilename(
407 changeExtension(filename,
408 formats.extension("literate") + ".out"))));
410 // If no Latex log or Build log is newer, show Build log
412 if (bname.exists() &&
413 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
414 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
417 return bname.absFilename();
419 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
422 return fname.absFilename();
426 void Buffer::setReadonly(bool const flag)
428 if (d->read_only != flag) {
435 void Buffer::setFileName(string const & newfile)
437 d->filename = makeAbsPath(newfile);
438 setReadonly(d->filename.isReadOnly());
443 int Buffer::readHeader(Lexer & lex)
445 int unknown_tokens = 0;
447 int begin_header_line = -1;
449 // Initialize parameters that may be/go lacking in header:
450 params().branchlist().clear();
451 params().preamble.erase();
452 params().options.erase();
453 params().float_placement.erase();
454 params().paperwidth.erase();
455 params().paperheight.erase();
456 params().leftmargin.erase();
457 params().rightmargin.erase();
458 params().topmargin.erase();
459 params().bottommargin.erase();
460 params().headheight.erase();
461 params().headsep.erase();
462 params().footskip.erase();
463 params().listings_params.clear();
464 params().clearLayoutModules();
465 params().pdfoptions().clear();
467 for (int i = 0; i < 4; ++i) {
468 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
469 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
472 ErrorList & errorList = d->errorLists["Parse"];
476 string const token = lex.getString();
481 if (token == "\\end_header")
485 if (token == "\\begin_header") {
486 begin_header_line = line;
490 LYXERR(Debug::PARSER, "Handling document header token: `"
493 string unknown = params().readToken(lex, token, d->filename.onlyPath());
494 if (!unknown.empty()) {
495 if (unknown[0] != '\\' && token == "\\textclass") {
496 Alert::warning(_("Unknown document class"),
497 bformat(_("Using the default document class, because the "
498 "class %1$s is unknown."), from_utf8(unknown)));
501 docstring const s = bformat(_("Unknown token: "
505 errorList.push_back(ErrorItem(_("Document header error"),
510 if (begin_header_line) {
511 docstring const s = _("\\begin_header is missing");
512 errorList.push_back(ErrorItem(_("Document header error"),
516 return unknown_tokens;
521 // changed to be public and have one parameter
522 // Returns false if "\end_document" is not read (Asger)
523 bool Buffer::readDocument(Lexer & lex)
525 ErrorList & errorList = d->errorLists["Parse"];
529 string const token = lex.getString();
530 if (token != "\\begin_document") {
531 docstring const s = _("\\begin_document is missing");
532 errorList.push_back(ErrorItem(_("Document header error"),
536 // we are reading in a brand new document
537 BOOST_ASSERT(paragraphs().empty());
540 TextClass const & baseClass = textclasslist[params().getBaseClass()];
541 if (!baseClass.load(filePath())) {
542 string theclass = baseClass.name();
543 Alert::error(_("Can't load document class"), bformat(
544 _("Using the default document class, because the "
545 "class %1$s could not be loaded."), from_utf8(theclass)));
546 params().setBaseClass(defaultTextclass());
549 if (params().outputChanges) {
550 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
551 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
552 LaTeXFeatures::isAvailable("xcolor");
554 if (!dvipost && !xcolorsoul) {
555 Alert::warning(_("Changes not shown in LaTeX output"),
556 _("Changes will not be highlighted in LaTeX output, "
557 "because neither dvipost nor xcolor/soul are installed.\n"
558 "Please install these packages or redefine "
559 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
560 } else if (!xcolorsoul) {
561 Alert::warning(_("Changes not shown in LaTeX output"),
562 _("Changes will not be highlighted in LaTeX output "
563 "when using pdflatex, because xcolor and soul are not installed.\n"
564 "Please install both packages or redefine "
565 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
570 bool const res = text().read(*this, lex, errorList);
571 for_each(text().paragraphs().begin(),
572 text().paragraphs().end(),
573 bind(&Paragraph::setInsetOwner, _1, &inset()));
579 // needed to insert the selection
580 void Buffer::insertStringAsLines(ParagraphList & pars,
581 pit_type & pit, pos_type & pos,
582 Font const & fn, docstring const & str, bool autobreakrows)
586 // insert the string, don't insert doublespace
587 bool space_inserted = true;
588 for (docstring::const_iterator cit = str.begin();
589 cit != str.end(); ++cit) {
590 Paragraph & par = pars[pit];
592 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
593 breakParagraph(params(), pars, pit, pos,
594 par.layout()->isEnvironment());
597 space_inserted = true;
601 // do not insert consecutive spaces if !free_spacing
602 } else if ((*cit == ' ' || *cit == '\t') &&
603 space_inserted && !par.isFreeSpacing()) {
605 } else if (*cit == '\t') {
606 if (!par.isFreeSpacing()) {
607 // tabs are like spaces here
608 par.insertChar(pos, ' ', font, params().trackChanges);
610 space_inserted = true;
612 const pos_type n = 8 - pos % 8;
613 for (pos_type i = 0; i < n; ++i) {
614 par.insertChar(pos, ' ', font, params().trackChanges);
617 space_inserted = true;
619 } else if (!isPrintable(*cit)) {
620 // Ignore unprintables
623 // just insert the character
624 par.insertChar(pos, *cit, font, params().trackChanges);
626 space_inserted = (*cit == ' ');
633 bool Buffer::readString(std::string const & s)
635 params().compressed = false;
637 // remove dummy empty par
638 paragraphs().clear();
640 std::istringstream is(s);
642 FileName const name(tempName());
643 switch (readFile(lex, name, true)) {
647 // We need to call lyx2lyx, so write the input to a file
648 std::ofstream os(name.toFilesystemEncoding().c_str());
651 return readFile(name);
661 bool Buffer::readFile(FileName const & filename)
663 FileName fname(filename);
664 // Check if the file is compressed.
665 string format = filename.guessFormatFromContents();
666 if (format == "zip") {
667 // decompress to a temp directory
668 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
669 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
671 FileName lyxfile(addName(temppath(), "content.lyx"));
672 // if both manifest.txt and file.lyx exist, this is am embedded file
673 if (lyxfile.exists()) {
674 params().embedded = true;
678 // The embedded lyx file can also be compressed, for backward compatibility
679 format = fname.guessFormatFromContents();
680 if (format == "gzip" || format == "zip" || format == "compress")
681 params().compressed = true;
683 // remove dummy empty par
684 paragraphs().clear();
687 if (readFile(lex, fname) != success)
694 bool Buffer::isFullyLoaded() const
696 return d->file_fully_loaded;
700 void Buffer::setFullyLoaded(bool value)
702 d->file_fully_loaded = value;
706 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
709 BOOST_ASSERT(!filename.empty());
712 Alert::error(_("Document could not be read"),
713 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
718 string const token = lex.getString();
721 Alert::error(_("Document could not be read"),
722 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
726 // the first token _must_ be...
727 if (token != "\\lyxformat") {
728 lyxerr << "Token: " << token << endl;
730 Alert::error(_("Document format failure"),
731 bformat(_("%1$s is not a LyX document."),
732 from_utf8(filename.absFilename())));
737 string tmp_format = lex.getString();
738 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
739 // if present remove ".," from string.
740 string::size_type dot = tmp_format.find_first_of(".,");
741 //lyxerr << " dot found at " << dot << endl;
742 if (dot != string::npos)
743 tmp_format.erase(dot, 1);
744 int const file_format = convert<int>(tmp_format);
745 //lyxerr << "format: " << file_format << endl;
747 // save timestamp and checksum of the original disk file, making sure
748 // to not overwrite them with those of the file created in the tempdir
749 // when it has to be converted to the current format.
751 // Save the timestamp and checksum of disk file. If filename is an
752 // emergency file, save the timestamp and checksum of the original lyx file
753 // because isExternallyModified will check for this file. (BUG4193)
754 string diskfile = filename.absFilename();
755 if (suffixIs(diskfile, ".emergency"))
756 diskfile = diskfile.substr(0, diskfile.size() - 10);
757 saveCheckSum(FileName(diskfile));
760 if (file_format != LYX_FORMAT) {
763 // lyx2lyx would fail
766 FileName const tmpfile(tempName());
767 if (tmpfile.empty()) {
768 Alert::error(_("Conversion failed"),
769 bformat(_("%1$s is from a different"
770 " version of LyX, but a temporary"
771 " file for converting it could"
773 from_utf8(filename.absFilename())));
776 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
777 if (lyx2lyx.empty()) {
778 Alert::error(_("Conversion script not found"),
779 bformat(_("%1$s is from a different"
780 " version of LyX, but the"
781 " conversion script lyx2lyx"
782 " could not be found."),
783 from_utf8(filename.absFilename())));
786 ostringstream command;
787 command << os::python()
788 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
789 << " -t " << convert<string>(LYX_FORMAT)
790 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
791 << ' ' << quoteName(filename.toFilesystemEncoding());
792 string const command_str = command.str();
794 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
796 cmd_ret const ret = runCommand(command_str);
797 if (ret.first != 0) {
798 Alert::error(_("Conversion script failed"),
799 bformat(_("%1$s is from a different version"
800 " of LyX, but the lyx2lyx script"
801 " failed to convert it."),
802 from_utf8(filename.absFilename())));
805 bool const ret = readFile(tmpfile);
806 // Do stuff with tmpfile name and buffer name here.
807 return ret ? success : failure;
812 if (readDocument(lex)) {
813 Alert::error(_("Document format failure"),
814 bformat(_("%1$s ended unexpectedly, which means"
815 " that it is probably corrupted."),
816 from_utf8(filename.absFilename())));
819 d->file_fully_loaded = true;
824 // Should probably be moved to somewhere else: BufferView? LyXView?
825 bool Buffer::save() const
827 // We don't need autosaves in the immediate future. (Asger)
828 resetAutosaveTimers();
830 string const encodedFilename = d->filename.toFilesystemEncoding();
833 bool madeBackup = false;
835 // make a backup if the file already exists
836 if (lyxrc.make_backup && fileName().exists()) {
837 backupName = FileName(absFileName() + '~');
838 if (!lyxrc.backupdir_path.empty()) {
839 string const mangledName =
840 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
841 backupName = FileName(addName(lyxrc.backupdir_path,
844 if (fileName().copyTo(backupName, true)) {
847 Alert::error(_("Backup failure"),
848 bformat(_("Cannot create backup file %1$s.\n"
849 "Please check whether the directory exists and is writeable."),
850 from_utf8(backupName.absFilename())));
851 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
855 // ask if the disk file has been externally modified (use checksum method)
856 if (fileName().exists() && isExternallyModified(checksum_method)) {
857 docstring const file = makeDisplayPath(absFileName(), 20);
858 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
859 "you want to overwrite this file?"), file);
860 int const ret = Alert::prompt(_("Overwrite modified file?"),
861 text, 1, 1, _("&Overwrite"), _("&Cancel"));
866 if (writeFile(d->filename)) {
870 // Saving failed, so backup is not backup
872 rename(backupName, d->filename);
878 bool Buffer::writeFile(FileName const & fname) const
880 if (d->read_only && fname == d->filename)
886 if (params().embedded)
887 // first write the .lyx file to the temporary directory
888 content = FileName(addName(temppath(), "content.lyx"));
892 docstring const str = bformat(_("Saving document %1$s..."),
893 makeDisplayPath(content.absFilename()));
896 if (params().compressed) {
897 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
898 retval = ofs && write(ofs);
900 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
901 retval = ofs && write(ofs);
905 message(str + _(" could not write file!."));
909 removeAutosaveFile(d->filename.absFilename());
910 saveCheckSum(d->filename);
911 message(str + _(" done."));
913 if (!params().embedded)
916 message(str + _(" writing embedded files!."));
917 // if embedding is enabled, write file.lyx and all the embedded files
918 // to the zip file fname.
919 if (!d->embedded_files.writeFile(fname)) {
920 message(str + _(" could not write embedded files!."));
923 message(str + _(" error while writing embedded files."));
928 bool Buffer::write(ostream & ofs) const
931 // Use the standard "C" locale for file output.
932 ofs.imbue(std::locale::classic());
935 // The top of the file should not be written by params().
937 // write out a comment in the top of the file
938 ofs << "#LyX " << lyx_version
939 << " created this file. For more info see http://www.lyx.org/\n"
940 << "\\lyxformat " << LYX_FORMAT << "\n"
941 << "\\begin_document\n";
944 /// For each author, set 'used' to true if there is a change
945 /// by this author in the document; otherwise set it to 'false'.
946 AuthorList::Authors::const_iterator a_it = params().authors().begin();
947 AuthorList::Authors::const_iterator a_end = params().authors().end();
948 for (; a_it != a_end; ++a_it)
949 a_it->second.setUsed(false);
951 ParIterator const end = par_iterator_end();
952 ParIterator it = par_iterator_begin();
953 for ( ; it != end; ++it)
954 it->checkAuthors(params().authors());
956 // now write out the buffer parameters.
957 ofs << "\\begin_header\n";
958 params().writeFile(ofs);
959 ofs << "\\end_header\n";
962 ofs << "\n\\begin_body\n";
963 text().write(*this, ofs);
964 ofs << "\n\\end_body\n";
966 // Write marker that shows file is complete
967 ofs << "\\end_document" << endl;
969 // Shouldn't really be needed....
972 // how to check if close went ok?
973 // Following is an attempt... (BE 20001011)
975 // good() returns false if any error occured, including some
977 // bad() returns true if something bad happened in the buffer,
978 // which should include file system full errors.
983 lyxerr << "File was not closed properly." << endl;
990 bool Buffer::makeLaTeXFile(FileName const & fname,
991 string const & original_path,
992 OutputParams const & runparams,
993 bool output_preamble, bool output_body) const
995 string const encoding = runparams.encoding->iconvName();
996 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
999 try { ofs.reset(encoding); }
1000 catch (iconv_codecvt_facet_exception & e) {
1001 lyxerr << "Caught iconv exception: " << e.what() << endl;
1002 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1003 "verify that the support software for your encoding (%1$s) is "
1004 "properly installed"), from_ascii(encoding)));
1007 if (!openFileWrite(ofs, fname))
1010 //TexStream ts(ofs.rdbuf(), &texrow());
1012 bool failed_export = false;
1015 writeLaTeXSource(ofs, original_path,
1016 runparams, output_preamble, output_body);
1018 catch (iconv_codecvt_facet_exception & e) {
1019 lyxerr << "Caught iconv exception: " << e.what() << endl;
1020 failed_export = true;
1022 catch (std::exception const & e) {
1023 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1024 failed_export = true;
1027 lyxerr << "Caught some really weird exception..." << endl;
1028 LyX::cref().emergencyCleanup();
1034 failed_export = true;
1035 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1038 if (failed_export) {
1039 Alert::error(_("Encoding error"),
1040 _("Some characters of your document are probably not "
1041 "representable in the chosen encoding.\n"
1042 "Changing the document encoding to utf8 could help."));
1049 void Buffer::writeLaTeXSource(odocstream & os,
1050 string const & original_path,
1051 OutputParams const & runparams_in,
1052 bool const output_preamble, bool const output_body) const
1054 OutputParams runparams = runparams_in;
1056 // validate the buffer.
1057 LYXERR(Debug::LATEX, " Validating buffer...");
1058 LaTeXFeatures features(*this, params(), runparams);
1060 LYXERR(Debug::LATEX, " Buffer validation done.");
1062 // The starting paragraph of the coming rows is the
1063 // first paragraph of the document. (Asger)
1064 if (output_preamble && runparams.nice) {
1065 os << "%% LyX " << lyx_version << " created this file. "
1066 "For more info, see http://www.lyx.org/.\n"
1067 "%% Do not edit unless you really know what "
1069 d->texrow.newline();
1070 d->texrow.newline();
1072 LYXERR(Debug::INFO, "lyx document header finished");
1073 // There are a few differences between nice LaTeX and usual files:
1074 // usual is \batchmode and has a
1075 // special input@path to allow the including of figures
1076 // with either \input or \includegraphics (what figinsets do).
1077 // input@path is set when the actual parameter
1078 // original_path is set. This is done for usual tex-file, but not
1079 // for nice-latex-file. (Matthias 250696)
1080 // Note that input@path is only needed for something the user does
1081 // in the preamble, included .tex files or ERT, files included by
1082 // LyX work without it.
1083 if (output_preamble) {
1084 if (!runparams.nice) {
1085 // code for usual, NOT nice-latex-file
1086 os << "\\nonstopmode\n";
1087 d->texrow.newline();
1089 if (!original_path.empty()) {
1091 // We don't know the encoding of inputpath
1092 docstring const inputpath = from_utf8(latex_path(original_path));
1093 os << "\\makeatletter\n"
1094 << "\\def\\input@path{{"
1095 << inputpath << "/}}\n"
1096 << "\\makeatother\n";
1097 d->texrow.newline();
1098 d->texrow.newline();
1099 d->texrow.newline();
1102 // Write the preamble
1103 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1109 os << "\\begin{document}\n";
1110 d->texrow.newline();
1111 } // output_preamble
1113 d->texrow.start(paragraphs().begin()->id(), 0);
1115 LYXERR(Debug::INFO, "preamble finished, now the body.");
1117 // if we are doing a real file with body, even if this is the
1118 // child of some other buffer, let's cut the link here.
1119 // This happens for example if only a child document is printed.
1120 Buffer const * save_parent = 0;
1121 if (output_preamble) {
1122 save_parent = d->parent_buffer;
1123 d->parent_buffer = 0;
1126 loadChildDocuments();
1129 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1131 // Restore the parenthood if needed
1132 if (output_preamble)
1133 d->parent_buffer = save_parent;
1135 // add this just in case after all the paragraphs
1137 d->texrow.newline();
1139 if (output_preamble) {
1140 os << "\\end{document}\n";
1141 d->texrow.newline();
1142 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1144 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1146 runparams_in.encoding = runparams.encoding;
1148 // Just to be sure. (Asger)
1149 d->texrow.newline();
1151 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1152 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1156 bool Buffer::isLatex() const
1158 return params().getTextClass().outputType() == LATEX;
1162 bool Buffer::isLiterate() const
1164 return params().getTextClass().outputType() == LITERATE;
1168 bool Buffer::isDocBook() const
1170 return params().getTextClass().outputType() == DOCBOOK;
1174 void Buffer::makeDocBookFile(FileName const & fname,
1175 OutputParams const & runparams,
1176 bool const body_only) const
1178 LYXERR(Debug::LATEX, "makeDocBookFile...");
1182 if (!openFileWrite(ofs, fname))
1185 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1189 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1193 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1194 OutputParams const & runparams,
1195 bool const only_body) const
1197 LaTeXFeatures features(*this, params(), runparams);
1202 TextClass const & tclass = params().getTextClass();
1203 string const top_element = tclass.latexname();
1206 if (runparams.flavor == OutputParams::XML)
1207 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1210 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1213 if (! tclass.class_header().empty())
1214 os << from_ascii(tclass.class_header());
1215 else if (runparams.flavor == OutputParams::XML)
1216 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1217 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1219 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1221 docstring preamble = from_utf8(params().preamble);
1222 if (runparams.flavor != OutputParams::XML ) {
1223 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1224 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1225 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1226 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1229 string const name = runparams.nice
1230 ? changeExtension(absFileName(), ".sgml") : fname;
1231 preamble += features.getIncludedFiles(name);
1232 preamble += features.getLyXSGMLEntities();
1234 if (!preamble.empty()) {
1235 os << "\n [ " << preamble << " ]";
1240 string top = top_element;
1242 if (runparams.flavor == OutputParams::XML)
1243 top += params().language->code();
1245 top += params().language->code().substr(0,2);
1248 if (!params().options.empty()) {
1250 top += params().options;
1253 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1254 << " file was created by LyX " << lyx_version
1255 << "\n See http://www.lyx.org/ for more information -->\n";
1257 params().getTextClass().counters().reset();
1259 loadChildDocuments();
1261 sgml::openTag(os, top);
1263 docbookParagraphs(paragraphs(), *this, os, runparams);
1264 sgml::closeTag(os, top_element);
1268 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1269 // Other flags: -wall -v0 -x
1270 int Buffer::runChktex()
1274 // get LaTeX-Filename
1275 FileName const path(temppath());
1276 string const name = addName(path.absFilename(), latexName());
1277 string const org_path = filePath();
1279 support::PathChanger p(path); // path to LaTeX file
1280 message(_("Running chktex..."));
1282 // Generate the LaTeX file if neccessary
1283 OutputParams runparams(¶ms().encoding());
1284 runparams.flavor = OutputParams::LATEX;
1285 runparams.nice = false;
1286 makeLaTeXFile(FileName(name), org_path, runparams);
1289 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1290 int const res = chktex.run(terr); // run chktex
1293 Alert::error(_("chktex failure"),
1294 _("Could not run chktex successfully."));
1295 } else if (res > 0) {
1296 ErrorList & errlist = d->errorLists["ChkTeX"];
1298 bufferErrors(terr, errlist);
1309 void Buffer::validate(LaTeXFeatures & features) const
1311 TextClass const & tclass = params().getTextClass();
1313 if (params().outputChanges) {
1314 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1315 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1316 LaTeXFeatures::isAvailable("xcolor");
1318 if (features.runparams().flavor == OutputParams::LATEX) {
1320 features.require("ct-dvipost");
1321 features.require("dvipost");
1322 } else if (xcolorsoul) {
1323 features.require("ct-xcolor-soul");
1324 features.require("soul");
1325 features.require("xcolor");
1327 features.require("ct-none");
1329 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1331 features.require("ct-xcolor-soul");
1332 features.require("soul");
1333 features.require("xcolor");
1334 features.require("pdfcolmk"); // improves color handling in PDF output
1336 features.require("ct-none");
1341 // Floats with 'Here definitely' as default setting.
1342 if (params().float_placement.find('H') != string::npos)
1343 features.require("float");
1345 // AMS Style is at document level
1346 if (params().use_amsmath == BufferParams::package_on
1347 || tclass.provides("amsmath"))
1348 features.require("amsmath");
1349 if (params().use_esint == BufferParams::package_on)
1350 features.require("esint");
1352 loadChildDocuments();
1354 for_each(paragraphs().begin(), paragraphs().end(),
1355 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1357 // the bullet shapes are buffer level not paragraph level
1358 // so they are tested here
1359 for (int i = 0; i < 4; ++i) {
1360 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1361 int const font = params().user_defined_bullet(i).getFont();
1363 int const c = params()
1364 .user_defined_bullet(i)
1371 features.require("latexsym");
1373 } else if (font == 1) {
1374 features.require("amssymb");
1375 } else if ((font >= 2 && font <= 5)) {
1376 features.require("pifont");
1381 if (lyxerr.debugging(Debug::LATEX)) {
1382 features.showStruct();
1387 void Buffer::getLabelList(vector<docstring> & list) const
1389 /// if this is a child document and the parent is already loaded
1390 /// Use the parent's list instead [ale990407]
1391 Buffer const * tmp = masterBuffer();
1393 lyxerr << "masterBuffer() failed!" << endl;
1397 tmp->getLabelList(list);
1401 loadChildDocuments();
1403 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1404 it.nextInset()->getLabelList(*this, list);
1408 void Buffer::updateBibfilesCache() const
1410 // if this is a child document and the parent is already loaded
1411 // update the parent's cache instead
1412 Buffer const * tmp = masterBuffer();
1415 tmp->updateBibfilesCache();
1419 d->bibfilesCache_.clear();
1420 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1421 if (it->lyxCode() == BIBTEX_CODE) {
1422 InsetBibtex const & inset =
1423 static_cast<InsetBibtex const &>(*it);
1424 FileNameList const bibfiles = inset.getFiles(*this);
1425 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1428 } else if (it->lyxCode() == INCLUDE_CODE) {
1429 InsetInclude & inset =
1430 static_cast<InsetInclude &>(*it);
1431 inset.updateBibfilesCache(*this);
1432 FileNameList const & bibfiles =
1433 inset.getBibfilesCache(*this);
1434 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1442 FileNameList const & Buffer::getBibfilesCache() const
1444 // if this is a child document and the parent is already loaded
1445 // use the parent's cache instead
1446 Buffer const * tmp = masterBuffer();
1449 return tmp->getBibfilesCache();
1451 // We update the cache when first used instead of at loading time.
1452 if (d->bibfilesCache_.empty())
1453 const_cast<Buffer *>(this)->updateBibfilesCache();
1455 return d->bibfilesCache_;
1459 bool Buffer::isDepClean(string const & name) const
1461 DepClean::const_iterator const it = d->dep_clean.find(name);
1462 if (it == d->dep_clean.end())
1468 void Buffer::markDepClean(string const & name)
1470 d->dep_clean[name] = true;
1474 bool Buffer::dispatch(string const & command, bool * result)
1476 return dispatch(lyxaction.lookupFunc(command), result);
1480 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1482 bool dispatched = true;
1484 switch (func.action) {
1485 case LFUN_BUFFER_EXPORT: {
1486 bool const tmp = doExport(to_utf8(func.argument()), false);
1499 void Buffer::changeLanguage(Language const * from, Language const * to)
1504 for_each(par_iterator_begin(),
1506 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1510 bool Buffer::isMultiLingual() const
1512 ParConstIterator end = par_iterator_end();
1513 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1514 if (it->isMultiLingual(params()))
1521 ParIterator Buffer::getParFromID(int const id) const
1523 ParConstIterator it = par_iterator_begin();
1524 ParConstIterator const end = par_iterator_end();
1527 // John says this is called with id == -1 from undo
1528 lyxerr << "getParFromID(), id: " << id << endl;
1532 for (; it != end; ++it)
1540 bool Buffer::hasParWithID(int const id) const
1542 ParConstIterator const it = getParFromID(id);
1543 return it != par_iterator_end();
1547 ParIterator Buffer::par_iterator_begin()
1549 return lyx::par_iterator_begin(inset());
1553 ParIterator Buffer::par_iterator_end()
1555 return lyx::par_iterator_end(inset());
1559 ParConstIterator Buffer::par_iterator_begin() const
1561 return lyx::par_const_iterator_begin(inset());
1565 ParConstIterator Buffer::par_iterator_end() const
1567 return lyx::par_const_iterator_end(inset());
1571 Language const * Buffer::language() const
1573 return params().language;
1577 docstring const Buffer::B_(string const & l10n) const
1579 return params().B_(l10n);
1583 bool Buffer::isClean() const
1585 return d->lyx_clean;
1589 bool Buffer::isBakClean() const
1591 return d->bak_clean;
1595 bool Buffer::isExternallyModified(CheckMethod method) const
1597 BOOST_ASSERT(d->filename.exists());
1598 // if method == timestamp, check timestamp before checksum
1599 return (method == checksum_method
1600 || d->timestamp_ != d->filename.lastModified())
1601 && d->checksum_ != d->filename.checksum();
1605 void Buffer::saveCheckSum(FileName const & file) const
1607 if (file.exists()) {
1608 d->timestamp_ = file.lastModified();
1609 d->checksum_ = file.checksum();
1611 // in the case of save to a new file.
1618 void Buffer::markClean() const
1620 if (!d->lyx_clean) {
1621 d->lyx_clean = true;
1624 // if the .lyx file has been saved, we don't need an
1626 d->bak_clean = true;
1630 void Buffer::markBakClean() const
1632 d->bak_clean = true;
1636 void Buffer::setUnnamed(bool flag)
1642 bool Buffer::isUnnamed() const
1648 // FIXME: this function should be moved to buffer_pimpl.C
1649 void Buffer::markDirty()
1652 d->lyx_clean = false;
1655 d->bak_clean = false;
1657 DepClean::iterator it = d->dep_clean.begin();
1658 DepClean::const_iterator const end = d->dep_clean.end();
1660 for (; it != end; ++it)
1665 FileName Buffer::fileName() const
1671 string Buffer::absFileName() const
1673 return d->filename.absFilename();
1677 string Buffer::filePath() const
1679 return d->filename.onlyPath().absFilename();
1683 bool Buffer::isReadonly() const
1685 return d->read_only;
1689 void Buffer::setParent(Buffer const * buffer)
1691 // Avoids recursive include.
1692 d->parent_buffer = buffer == this ? 0 : buffer;
1696 Buffer const * Buffer::parent()
1698 return d->parent_buffer;
1702 Buffer const * Buffer::masterBuffer() const
1704 if (!d->parent_buffer)
1707 return d->parent_buffer->masterBuffer();
1711 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1713 Impl::PositionToMacroMap::iterator it;
1714 it = d->macros[name].upper_bound(par.macrocontextPosition());
1715 if (it != d->macros[name].end())
1718 // If there is a master buffer, query that
1719 Buffer const * master = masterBuffer();
1720 if (master && master != this)
1721 return master->hasMacro(name);
1723 return MacroTable::globalMacros().has(name);
1727 bool Buffer::hasMacro(docstring const & name) const
1729 if( !d->macros[name].empty() )
1732 // If there is a master buffer, query that
1733 Buffer const * master = masterBuffer();
1734 if (master && master != this)
1735 return master->hasMacro(name);
1737 return MacroTable::globalMacros().has(name);
1741 MacroData const & Buffer::getMacro(docstring const & name,
1742 Paragraph const & par) const
1744 Impl::PositionToMacroMap::iterator it;
1745 it = d->macros[name].upper_bound(par.macrocontextPosition());
1746 if( it != d->macros[name].end() )
1749 // If there is a master buffer, query that
1750 Buffer const * master = masterBuffer();
1751 if (master && master != this)
1752 return master->getMacro(name);
1754 return MacroTable::globalMacros().get(name);
1758 MacroData const & Buffer::getMacro(docstring const & name) const
1760 Impl::PositionToMacroMap::iterator it;
1761 it = d->macros[name].begin();
1762 if( it != d->macros[name].end() )
1765 // If there is a master buffer, query that
1766 Buffer const * master = masterBuffer();
1767 if (master && master != this)
1768 return master->getMacro(name);
1770 return MacroTable::globalMacros().get(name);
1774 void Buffer::updateMacros()
1776 // start with empty table
1777 d->macros = Impl::NameToPositionMacroMap();
1779 // Iterate over buffer
1780 ParagraphList & pars = text().paragraphs();
1781 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1782 // set position again
1783 pars[i].setMacrocontextPosition(i);
1785 //lyxerr << "searching main par " << i
1786 // << " for macro definitions" << std::endl;
1787 InsetList const & insets = pars[i].insetList();
1788 InsetList::const_iterator it = insets.begin();
1789 InsetList::const_iterator end = insets.end();
1790 for ( ; it != end; ++it) {
1791 if (it->inset->lyxCode() != MATHMACRO_CODE)
1795 MathMacroTemplate const & macroTemplate
1796 = static_cast<MathMacroTemplate const &>(*it->inset);
1799 if (macroTemplate.validMacro()) {
1800 MacroData macro = macroTemplate.asMacroData();
1803 // call hasMacro here instead of directly querying mc to
1804 // also take the master document into consideration
1805 macro.setRedefinition(hasMacro(macroTemplate.name()));
1807 // register macro (possibly overwrite the previous one of this paragraph)
1808 d->macros[macroTemplate.name()][i] = macro;
1815 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1818 //FIXME: This does not work for child documents yet.
1819 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1820 // Check if the label 'from' appears more than once
1821 vector<docstring> labels;
1824 if (code == CITE_CODE) {
1826 keys.fillWithBibKeys(this);
1827 BiblioInfo::const_iterator bit = keys.begin();
1828 BiblioInfo::const_iterator bend = keys.end();
1830 for (; bit != bend; ++bit)
1832 labels.push_back(bit->first);
1835 getLabelList(labels);
1836 paramName = "reference";
1839 if (std::count(labels.begin(), labels.end(), from) > 1)
1842 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1843 if (it->lyxCode() == code) {
1844 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1845 docstring const oldValue = inset.getParam(paramName);
1846 if (oldValue == from)
1847 inset.setParam(paramName, to);
1853 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1854 pit_type par_end, bool full_source)
1856 OutputParams runparams(¶ms().encoding());
1857 runparams.nice = true;
1858 runparams.flavor = OutputParams::LATEX;
1859 runparams.linelen = lyxrc.plaintext_linelen;
1860 // No side effect of file copying and image conversion
1861 runparams.dryrun = true;
1865 os << "% " << _("Preview source code") << "\n\n";
1866 d->texrow.newline();
1867 d->texrow.newline();
1869 writeLaTeXSource(os, filePath(), runparams, true, true);
1871 writeDocBookSource(os, absFileName(), runparams, false);
1874 runparams.par_begin = par_begin;
1875 runparams.par_end = par_end;
1876 if (par_begin + 1 == par_end)
1878 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1882 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1883 convert<docstring>(par_begin),
1884 convert<docstring>(par_end - 1))
1886 d->texrow.newline();
1887 d->texrow.newline();
1888 // output paragraphs
1890 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1893 docbookParagraphs(paragraphs(), *this, os, runparams);
1899 ErrorList & Buffer::errorList(string const & type) const
1901 static ErrorList emptyErrorList;
1902 std::map<string, ErrorList>::iterator I = d->errorLists.find(type);
1903 if (I == d->errorLists.end())
1904 return emptyErrorList;
1910 void Buffer::structureChanged() const
1913 gui_->structureChanged();
1917 void Buffer::errors(std::string const & err) const
1924 void Buffer::message(docstring const & msg) const
1931 void Buffer::setBusy(bool on) const
1938 void Buffer::setReadOnly(bool on) const
1941 d->wa_->setReadOnly(on);
1945 void Buffer::updateTitles() const
1948 d->wa_->updateTitles();
1952 void Buffer::resetAutosaveTimers() const
1955 gui_->resetAutosaveTimers();
1959 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1968 class AutoSaveBuffer : public support::ForkedProcess {
1971 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1972 : buffer_(buffer), fname_(fname) {}
1974 virtual boost::shared_ptr<ForkedProcess> clone() const
1976 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1981 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
1982 from_utf8(fname_.absFilename())));
1983 return run(DontWait);
1987 virtual int generateChild();
1989 Buffer const & buffer_;
1994 #if !defined (HAVE_FORK)
1998 int AutoSaveBuffer::generateChild()
2000 // tmp_ret will be located (usually) in /tmp
2001 // will that be a problem?
2002 pid_t const pid = fork();
2003 // If you want to debug the autosave
2004 // you should set pid to -1, and comment out the fork.
2005 if (pid == 0 || pid == -1) {
2006 // pid = -1 signifies that lyx was unable
2007 // to fork. But we will do the save
2009 bool failed = false;
2011 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
2012 if (!tmp_ret.empty()) {
2013 buffer_.writeFile(tmp_ret);
2014 // assume successful write of tmp_ret
2015 if (!rename(tmp_ret, fname_)) {
2017 // most likely couldn't move between
2018 // filesystems unless write of tmp_ret
2019 // failed so remove tmp file (if it
2021 tmp_ret.removeFile();
2028 // failed to write/rename tmp_ret so try writing direct
2029 if (!buffer_.writeFile(fname_)) {
2030 // It is dangerous to do this in the child,
2031 // but safe in the parent, so...
2032 if (pid == -1) // emit message signal.
2033 buffer_.message(_("Autosave failed!"));
2036 if (pid == 0) { // we are the child so...
2046 // Perfect target for a thread...
2047 void Buffer::autoSave() const
2049 if (isBakClean() || isReadonly()) {
2050 // We don't save now, but we'll try again later
2051 resetAutosaveTimers();
2055 // emit message signal.
2056 message(_("Autosaving current document..."));
2058 // create autosave filename
2059 string fname = filePath();
2061 fname += d->filename.onlyFileName();
2064 AutoSaveBuffer autosave(*this, FileName(fname));
2068 resetAutosaveTimers();
2072 void Buffer::resetChildDocuments(bool close_them) const
2074 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2075 if (it->lyxCode() != INCLUDE_CODE)
2077 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2078 InsetCommandParams const & ip = inset.params();
2080 resetParentBuffer(this, ip, close_them);
2083 if (use_gui && masterBuffer() == this)
2084 updateLabels(*this);
2088 void Buffer::loadChildDocuments() const
2090 bool parse_error = false;
2092 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2093 if (it->lyxCode() != INCLUDE_CODE)
2095 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2096 InsetCommandParams const & ip = inset.params();
2097 Buffer * child = loadIfNeeded(*this, ip);
2100 parse_error |= !child->errorList("Parse").empty();
2101 child->loadChildDocuments();
2104 if (use_gui && masterBuffer() == this)
2105 updateLabels(*this);
2109 string Buffer::bufferFormat() const
2119 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2120 string & result_file) const
2122 string backend_format;
2123 OutputParams runparams(¶ms().encoding());
2124 runparams.flavor = OutputParams::LATEX;
2125 runparams.linelen = lyxrc.plaintext_linelen;
2126 vector<string> backs = backends();
2127 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2128 // Get shortest path to format
2129 Graph::EdgePath path;
2130 for (vector<string>::const_iterator it = backs.begin();
2131 it != backs.end(); ++it) {
2132 Graph::EdgePath p = theConverters().getPath(*it, format);
2133 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2134 backend_format = *it;
2139 runparams.flavor = theConverters().getFlavor(path);
2141 Alert::error(_("Couldn't export file"),
2142 bformat(_("No information for exporting the format %1$s."),
2143 formats.prettyName(format)));
2147 backend_format = format;
2148 // FIXME: Don't hardcode format names here, but use a flag
2149 if (backend_format == "pdflatex")
2150 runparams.flavor = OutputParams::PDFLATEX;
2153 string filename = latexName(false);
2154 filename = addName(temppath(), filename);
2155 filename = changeExtension(filename,
2156 formats.extension(backend_format));
2158 // Plain text backend
2159 if (backend_format == "text")
2160 writePlaintextFile(*this, FileName(filename), runparams);
2162 else if (backend_format == "lyx")
2163 writeFile(FileName(filename));
2165 else if (isDocBook()) {
2166 runparams.nice = !put_in_tempdir;
2167 makeDocBookFile(FileName(filename), runparams);
2170 else if (backend_format == format) {
2171 runparams.nice = true;
2172 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2174 } else if (!lyxrc.tex_allows_spaces
2175 && support::contains(filePath(), ' ')) {
2176 Alert::error(_("File name error"),
2177 _("The directory path to the document cannot contain spaces."));
2180 runparams.nice = false;
2181 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2185 string const error_type = (format == "program")
2186 ? "Build" : bufferFormat();
2187 string const ext = formats.extension(format);
2188 FileName const tmp_result_file(changeExtension(filename, ext));
2189 bool const success = theConverters().convert(this, FileName(filename),
2190 tmp_result_file, FileName(absFileName()), backend_format, format,
2191 errorList(error_type));
2192 // Emit the signal to show the error list.
2193 if (format != backend_format)
2199 result_file = tmp_result_file.absFilename();
2201 result_file = changeExtension(absFileName(), ext);
2202 // We need to copy referenced files (e. g. included graphics
2203 // if format == "dvi") to the result dir.
2204 vector<ExportedFile> const files =
2205 runparams.exportdata->externalFiles(format);
2206 string const dest = onlyPath(result_file);
2207 CopyStatus status = SUCCESS;
2208 for (vector<ExportedFile>::const_iterator it = files.begin();
2209 it != files.end() && status != CANCEL; ++it) {
2211 formats.getFormatFromFile(it->sourceName);
2212 status = copyFile(fmt, it->sourceName,
2213 makeAbsPath(it->exportName, dest),
2214 it->exportName, status == FORCE);
2216 if (status == CANCEL) {
2217 message(_("Document export cancelled."));
2218 } else if (tmp_result_file.exists()) {
2219 // Finally copy the main file
2220 status = copyFile(format, tmp_result_file,
2221 FileName(result_file), result_file,
2223 message(bformat(_("Document exported as %1$s "
2225 formats.prettyName(format),
2226 makeDisplayPath(result_file)));
2228 // This must be a dummy converter like fax (bug 1888)
2229 message(bformat(_("Document exported as %1$s"),
2230 formats.prettyName(format)));
2238 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2241 return doExport(format, put_in_tempdir, result_file);
2245 bool Buffer::preview(string const & format) const
2248 if (!doExport(format, true, result_file))
2250 return formats.view(*this, FileName(result_file), format);
2254 bool Buffer::isExportable(string const & format) const
2256 vector<string> backs = backends();
2257 for (vector<string>::const_iterator it = backs.begin();
2258 it != backs.end(); ++it)
2259 if (theConverters().isReachable(*it, format))
2265 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2267 vector<string> backs = backends();
2268 vector<Format const *> result =
2269 theConverters().getReachable(backs[0], only_viewable, true);
2270 for (vector<string>::const_iterator it = backs.begin() + 1;
2271 it != backs.end(); ++it) {
2272 vector<Format const *> r =
2273 theConverters().getReachable(*it, only_viewable, false);
2274 result.insert(result.end(), r.begin(), r.end());
2280 vector<string> Buffer::backends() const
2283 if (params().getTextClass().isTeXClassAvailable()) {
2284 v.push_back(bufferFormat());
2285 // FIXME: Don't hardcode format names here, but use a flag
2286 if (v.back() == "latex")
2287 v.push_back("pdflatex");
2289 v.push_back("text");
2295 bool Buffer::readFileHelper(FileName const & s)
2297 // File information about normal file
2299 docstring const file = makeDisplayPath(s.absFilename(), 50);
2300 docstring text = bformat(_("The specified document\n%1$s"
2301 "\ncould not be read."), file);
2302 Alert::error(_("Could not read document"), text);
2306 // Check if emergency save file exists and is newer.
2307 FileName const e(s.absFilename() + ".emergency");
2309 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2310 docstring const file = makeDisplayPath(s.absFilename(), 20);
2311 docstring const text =
2312 bformat(_("An emergency save of the document "
2314 "Recover emergency save?"), file);
2315 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2316 _("&Recover"), _("&Load Original"),
2320 // the file is not saved if we load the emergency file.
2330 // Now check if autosave file is newer.
2331 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2333 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2334 docstring const file = makeDisplayPath(s.absFilename(), 20);
2335 docstring const text =
2336 bformat(_("The backup of the document "
2337 "%1$s is newer.\n\nLoad the "
2338 "backup instead?"), file);
2339 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2340 _("&Load backup"), _("Load &original"),
2344 // the file is not saved if we load the autosave file.
2348 // Here we delete the autosave
2359 bool Buffer::loadLyXFile(FileName const & s)
2361 if (s.isReadableFile()) {
2362 if (readFileHelper(s)) {
2363 lyxvc().file_found_hook(s);
2364 if (!s.isWritable())
2369 docstring const file = makeDisplayPath(s.absFilename(), 20);
2370 // Here we probably should run
2371 if (LyXVC::file_not_found_hook(s)) {
2372 docstring const text =
2373 bformat(_("Do you want to retrieve the document"
2374 " %1$s from version control?"), file);
2375 int const ret = Alert::prompt(_("Retrieve from version control?"),
2376 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2379 // How can we know _how_ to do the checkout?
2380 // With the current VC support it has to be,
2381 // a RCS file since CVS do not have special ,v files.
2383 return loadLyXFile(s);
2391 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2393 TeXErrors::Errors::const_iterator cit = terr.begin();
2394 TeXErrors::Errors::const_iterator end = terr.end();
2396 for (; cit != end; ++cit) {
2399 int errorRow = cit->error_in_line;
2400 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2406 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2407 } while (found && id_start == id_end && pos_start == pos_end);
2409 errorList.push_back(ErrorItem(cit->error_desc,
2410 cit->error_text, id_start, pos_start, pos_end));