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 << "\\batchmode\n"; // changed
1087 // from \nonstopmode
1088 d->texrow.newline();
1090 if (!original_path.empty()) {
1092 // We don't know the encoding of inputpath
1093 docstring const inputpath = from_utf8(latex_path(original_path));
1094 os << "\\makeatletter\n"
1095 << "\\def\\input@path{{"
1096 << inputpath << "/}}\n"
1097 << "\\makeatother\n";
1098 d->texrow.newline();
1099 d->texrow.newline();
1100 d->texrow.newline();
1103 // Write the preamble
1104 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1110 os << "\\begin{document}\n";
1111 d->texrow.newline();
1112 } // output_preamble
1114 d->texrow.start(paragraphs().begin()->id(), 0);
1116 LYXERR(Debug::INFO, "preamble finished, now the body.");
1118 // if we are doing a real file with body, even if this is the
1119 // child of some other buffer, let's cut the link here.
1120 // This happens for example if only a child document is printed.
1121 Buffer const * save_parent = 0;
1122 if (output_preamble) {
1123 save_parent = d->parent_buffer;
1124 d->parent_buffer = 0;
1127 loadChildDocuments();
1130 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1132 // Restore the parenthood if needed
1133 if (output_preamble)
1134 d->parent_buffer = save_parent;
1136 // add this just in case after all the paragraphs
1138 d->texrow.newline();
1140 if (output_preamble) {
1141 os << "\\end{document}\n";
1142 d->texrow.newline();
1143 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1145 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1147 runparams_in.encoding = runparams.encoding;
1149 // Just to be sure. (Asger)
1150 d->texrow.newline();
1152 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1153 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1157 bool Buffer::isLatex() const
1159 return params().getTextClass().outputType() == LATEX;
1163 bool Buffer::isLiterate() const
1165 return params().getTextClass().outputType() == LITERATE;
1169 bool Buffer::isDocBook() const
1171 return params().getTextClass().outputType() == DOCBOOK;
1175 void Buffer::makeDocBookFile(FileName const & fname,
1176 OutputParams const & runparams,
1177 bool const body_only) const
1179 LYXERR(Debug::LATEX, "makeDocBookFile...");
1183 if (!openFileWrite(ofs, fname))
1186 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1190 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1194 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1195 OutputParams const & runparams,
1196 bool const only_body) const
1198 LaTeXFeatures features(*this, params(), runparams);
1203 TextClass const & tclass = params().getTextClass();
1204 string const top_element = tclass.latexname();
1207 if (runparams.flavor == OutputParams::XML)
1208 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1211 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1214 if (! tclass.class_header().empty())
1215 os << from_ascii(tclass.class_header());
1216 else if (runparams.flavor == OutputParams::XML)
1217 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1218 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1220 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1222 docstring preamble = from_utf8(params().preamble);
1223 if (runparams.flavor != OutputParams::XML ) {
1224 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1225 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1226 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1227 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1230 string const name = runparams.nice
1231 ? changeExtension(absFileName(), ".sgml") : fname;
1232 preamble += features.getIncludedFiles(name);
1233 preamble += features.getLyXSGMLEntities();
1235 if (!preamble.empty()) {
1236 os << "\n [ " << preamble << " ]";
1241 string top = top_element;
1243 if (runparams.flavor == OutputParams::XML)
1244 top += params().language->code();
1246 top += params().language->code().substr(0,2);
1249 if (!params().options.empty()) {
1251 top += params().options;
1254 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1255 << " file was created by LyX " << lyx_version
1256 << "\n See http://www.lyx.org/ for more information -->\n";
1258 params().getTextClass().counters().reset();
1260 loadChildDocuments();
1262 sgml::openTag(os, top);
1264 docbookParagraphs(paragraphs(), *this, os, runparams);
1265 sgml::closeTag(os, top_element);
1269 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1270 // Other flags: -wall -v0 -x
1271 int Buffer::runChktex()
1275 // get LaTeX-Filename
1276 FileName const path(temppath());
1277 string const name = addName(path.absFilename(), latexName());
1278 string const org_path = filePath();
1280 support::PathChanger p(path); // path to LaTeX file
1281 message(_("Running chktex..."));
1283 // Generate the LaTeX file if neccessary
1284 OutputParams runparams(¶ms().encoding());
1285 runparams.flavor = OutputParams::LATEX;
1286 runparams.nice = false;
1287 makeLaTeXFile(FileName(name), org_path, runparams);
1290 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1291 int const res = chktex.run(terr); // run chktex
1294 Alert::error(_("chktex failure"),
1295 _("Could not run chktex successfully."));
1296 } else if (res > 0) {
1297 ErrorList & errlist = d->errorLists["ChkTeX"];
1299 bufferErrors(terr, errlist);
1310 void Buffer::validate(LaTeXFeatures & features) const
1312 TextClass const & tclass = params().getTextClass();
1314 if (params().outputChanges) {
1315 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1316 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1317 LaTeXFeatures::isAvailable("xcolor");
1319 if (features.runparams().flavor == OutputParams::LATEX) {
1321 features.require("ct-dvipost");
1322 features.require("dvipost");
1323 } else if (xcolorsoul) {
1324 features.require("ct-xcolor-soul");
1325 features.require("soul");
1326 features.require("xcolor");
1328 features.require("ct-none");
1330 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1332 features.require("ct-xcolor-soul");
1333 features.require("soul");
1334 features.require("xcolor");
1335 features.require("pdfcolmk"); // improves color handling in PDF output
1337 features.require("ct-none");
1342 // Floats with 'Here definitely' as default setting.
1343 if (params().float_placement.find('H') != string::npos)
1344 features.require("float");
1346 // AMS Style is at document level
1347 if (params().use_amsmath == BufferParams::package_on
1348 || tclass.provides("amsmath"))
1349 features.require("amsmath");
1350 if (params().use_esint == BufferParams::package_on)
1351 features.require("esint");
1353 loadChildDocuments();
1355 for_each(paragraphs().begin(), paragraphs().end(),
1356 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1358 // the bullet shapes are buffer level not paragraph level
1359 // so they are tested here
1360 for (int i = 0; i < 4; ++i) {
1361 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1362 int const font = params().user_defined_bullet(i).getFont();
1364 int const c = params()
1365 .user_defined_bullet(i)
1372 features.require("latexsym");
1374 } else if (font == 1) {
1375 features.require("amssymb");
1376 } else if ((font >= 2 && font <= 5)) {
1377 features.require("pifont");
1382 if (lyxerr.debugging(Debug::LATEX)) {
1383 features.showStruct();
1388 void Buffer::getLabelList(vector<docstring> & list) const
1390 /// if this is a child document and the parent is already loaded
1391 /// Use the parent's list instead [ale990407]
1392 Buffer const * tmp = masterBuffer();
1394 lyxerr << "masterBuffer() failed!" << endl;
1398 tmp->getLabelList(list);
1402 loadChildDocuments();
1404 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1405 it.nextInset()->getLabelList(*this, list);
1409 void Buffer::updateBibfilesCache() const
1411 // if this is a child document and the parent is already loaded
1412 // update the parent's cache instead
1413 Buffer const * tmp = masterBuffer();
1416 tmp->updateBibfilesCache();
1420 d->bibfilesCache_.clear();
1421 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1422 if (it->lyxCode() == BIBTEX_CODE) {
1423 InsetBibtex const & inset =
1424 static_cast<InsetBibtex const &>(*it);
1425 FileNameList const bibfiles = inset.getFiles(*this);
1426 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1429 } else if (it->lyxCode() == INCLUDE_CODE) {
1430 InsetInclude & inset =
1431 static_cast<InsetInclude &>(*it);
1432 inset.updateBibfilesCache(*this);
1433 FileNameList const & bibfiles =
1434 inset.getBibfilesCache(*this);
1435 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1443 FileNameList const & Buffer::getBibfilesCache() const
1445 // if this is a child document and the parent is already loaded
1446 // use the parent's cache instead
1447 Buffer const * tmp = masterBuffer();
1450 return tmp->getBibfilesCache();
1452 // We update the cache when first used instead of at loading time.
1453 if (d->bibfilesCache_.empty())
1454 const_cast<Buffer *>(this)->updateBibfilesCache();
1456 return d->bibfilesCache_;
1460 bool Buffer::isDepClean(string const & name) const
1462 DepClean::const_iterator const it = d->dep_clean.find(name);
1463 if (it == d->dep_clean.end())
1469 void Buffer::markDepClean(string const & name)
1471 d->dep_clean[name] = true;
1475 bool Buffer::dispatch(string const & command, bool * result)
1477 return dispatch(lyxaction.lookupFunc(command), result);
1481 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1483 bool dispatched = true;
1485 switch (func.action) {
1486 case LFUN_BUFFER_EXPORT: {
1487 bool const tmp = doExport(to_utf8(func.argument()), false);
1500 void Buffer::changeLanguage(Language const * from, Language const * to)
1505 for_each(par_iterator_begin(),
1507 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1511 bool Buffer::isMultiLingual() const
1513 ParConstIterator end = par_iterator_end();
1514 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1515 if (it->isMultiLingual(params()))
1522 ParIterator Buffer::getParFromID(int const id) const
1524 ParConstIterator it = par_iterator_begin();
1525 ParConstIterator const end = par_iterator_end();
1528 // John says this is called with id == -1 from undo
1529 lyxerr << "getParFromID(), id: " << id << endl;
1533 for (; it != end; ++it)
1541 bool Buffer::hasParWithID(int const id) const
1543 ParConstIterator const it = getParFromID(id);
1544 return it != par_iterator_end();
1548 ParIterator Buffer::par_iterator_begin()
1550 return lyx::par_iterator_begin(inset());
1554 ParIterator Buffer::par_iterator_end()
1556 return lyx::par_iterator_end(inset());
1560 ParConstIterator Buffer::par_iterator_begin() const
1562 return lyx::par_const_iterator_begin(inset());
1566 ParConstIterator Buffer::par_iterator_end() const
1568 return lyx::par_const_iterator_end(inset());
1572 Language const * Buffer::language() const
1574 return params().language;
1578 docstring const Buffer::B_(string const & l10n) const
1580 return params().B_(l10n);
1584 bool Buffer::isClean() const
1586 return d->lyx_clean;
1590 bool Buffer::isBakClean() const
1592 return d->bak_clean;
1596 bool Buffer::isExternallyModified(CheckMethod method) const
1598 BOOST_ASSERT(d->filename.exists());
1599 // if method == timestamp, check timestamp before checksum
1600 return (method == checksum_method
1601 || d->timestamp_ != d->filename.lastModified())
1602 && d->checksum_ != d->filename.checksum();
1606 void Buffer::saveCheckSum(FileName const & file) const
1608 if (file.exists()) {
1609 d->timestamp_ = file.lastModified();
1610 d->checksum_ = file.checksum();
1612 // in the case of save to a new file.
1619 void Buffer::markClean() const
1621 if (!d->lyx_clean) {
1622 d->lyx_clean = true;
1625 // if the .lyx file has been saved, we don't need an
1627 d->bak_clean = true;
1631 void Buffer::markBakClean() const
1633 d->bak_clean = true;
1637 void Buffer::setUnnamed(bool flag)
1643 bool Buffer::isUnnamed() const
1649 // FIXME: this function should be moved to buffer_pimpl.C
1650 void Buffer::markDirty()
1653 d->lyx_clean = false;
1656 d->bak_clean = false;
1658 DepClean::iterator it = d->dep_clean.begin();
1659 DepClean::const_iterator const end = d->dep_clean.end();
1661 for (; it != end; ++it)
1666 FileName Buffer::fileName() const
1672 string Buffer::absFileName() const
1674 return d->filename.absFilename();
1678 string Buffer::filePath() const
1680 return d->filename.onlyPath().absFilename();
1684 bool Buffer::isReadonly() const
1686 return d->read_only;
1690 void Buffer::setParent(Buffer const * buffer)
1692 // Avoids recursive include.
1693 d->parent_buffer = buffer == this ? 0 : buffer;
1697 Buffer const * Buffer::parent()
1699 return d->parent_buffer;
1703 Buffer const * Buffer::masterBuffer() const
1705 if (!d->parent_buffer)
1708 return d->parent_buffer->masterBuffer();
1712 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1714 Impl::PositionToMacroMap::iterator it;
1715 it = d->macros[name].upper_bound(par.macrocontextPosition());
1716 if (it != d->macros[name].end())
1719 // If there is a master buffer, query that
1720 Buffer const * master = masterBuffer();
1721 if (master && master != this)
1722 return master->hasMacro(name);
1724 return MacroTable::globalMacros().has(name);
1728 bool Buffer::hasMacro(docstring const & name) const
1730 if( !d->macros[name].empty() )
1733 // If there is a master buffer, query that
1734 Buffer const * master = masterBuffer();
1735 if (master && master != this)
1736 return master->hasMacro(name);
1738 return MacroTable::globalMacros().has(name);
1742 MacroData const & Buffer::getMacro(docstring const & name,
1743 Paragraph const & par) const
1745 Impl::PositionToMacroMap::iterator it;
1746 it = d->macros[name].upper_bound(par.macrocontextPosition());
1747 if( it != d->macros[name].end() )
1750 // If there is a master buffer, query that
1751 Buffer const * master = masterBuffer();
1752 if (master && master != this)
1753 return master->getMacro(name);
1755 return MacroTable::globalMacros().get(name);
1759 MacroData const & Buffer::getMacro(docstring const & name) const
1761 Impl::PositionToMacroMap::iterator it;
1762 it = d->macros[name].begin();
1763 if( it != d->macros[name].end() )
1766 // If there is a master buffer, query that
1767 Buffer const * master = masterBuffer();
1768 if (master && master != this)
1769 return master->getMacro(name);
1771 return MacroTable::globalMacros().get(name);
1775 void Buffer::updateMacros()
1777 // start with empty table
1778 d->macros = Impl::NameToPositionMacroMap();
1780 // Iterate over buffer
1781 ParagraphList & pars = text().paragraphs();
1782 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1783 // set position again
1784 pars[i].setMacrocontextPosition(i);
1786 //lyxerr << "searching main par " << i
1787 // << " for macro definitions" << std::endl;
1788 InsetList const & insets = pars[i].insetList();
1789 InsetList::const_iterator it = insets.begin();
1790 InsetList::const_iterator end = insets.end();
1791 for ( ; it != end; ++it) {
1792 if (it->inset->lyxCode() != MATHMACRO_CODE)
1796 MathMacroTemplate const & macroTemplate
1797 = static_cast<MathMacroTemplate const &>(*it->inset);
1800 if (macroTemplate.validMacro()) {
1801 MacroData macro = macroTemplate.asMacroData();
1804 // call hasMacro here instead of directly querying mc to
1805 // also take the master document into consideration
1806 macro.setRedefinition(hasMacro(macroTemplate.name()));
1808 // register macro (possibly overwrite the previous one of this paragraph)
1809 d->macros[macroTemplate.name()][i] = macro;
1816 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1819 //FIXME: This does not work for child documents yet.
1820 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1821 // Check if the label 'from' appears more than once
1822 vector<docstring> labels;
1825 if (code == CITE_CODE) {
1827 keys.fillWithBibKeys(this);
1828 BiblioInfo::const_iterator bit = keys.begin();
1829 BiblioInfo::const_iterator bend = keys.end();
1831 for (; bit != bend; ++bit)
1833 labels.push_back(bit->first);
1836 getLabelList(labels);
1837 paramName = "reference";
1840 if (std::count(labels.begin(), labels.end(), from) > 1)
1843 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1844 if (it->lyxCode() == code) {
1845 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1846 docstring const oldValue = inset.getParam(paramName);
1847 if (oldValue == from)
1848 inset.setParam(paramName, to);
1854 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1855 pit_type par_end, bool full_source)
1857 OutputParams runparams(¶ms().encoding());
1858 runparams.nice = true;
1859 runparams.flavor = OutputParams::LATEX;
1860 runparams.linelen = lyxrc.plaintext_linelen;
1861 // No side effect of file copying and image conversion
1862 runparams.dryrun = true;
1866 os << "% " << _("Preview source code") << "\n\n";
1867 d->texrow.newline();
1868 d->texrow.newline();
1870 writeLaTeXSource(os, filePath(), runparams, true, true);
1872 writeDocBookSource(os, absFileName(), runparams, false);
1875 runparams.par_begin = par_begin;
1876 runparams.par_end = par_end;
1877 if (par_begin + 1 == par_end)
1879 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1883 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1884 convert<docstring>(par_begin),
1885 convert<docstring>(par_end - 1))
1887 d->texrow.newline();
1888 d->texrow.newline();
1889 // output paragraphs
1891 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1894 docbookParagraphs(paragraphs(), *this, os, runparams);
1900 ErrorList & Buffer::errorList(string const & type) const
1902 static ErrorList emptyErrorList;
1903 std::map<string, ErrorList>::iterator I = d->errorLists.find(type);
1904 if (I == d->errorLists.end())
1905 return emptyErrorList;
1911 void Buffer::structureChanged() const
1914 gui_->structureChanged();
1918 void Buffer::errors(std::string const & err) const
1925 void Buffer::message(docstring const & msg) const
1932 void Buffer::setBusy(bool on) const
1939 void Buffer::setReadOnly(bool on) const
1942 d->wa_->setReadOnly(on);
1946 void Buffer::updateTitles() const
1949 d->wa_->updateTitles();
1953 void Buffer::resetAutosaveTimers() const
1956 gui_->resetAutosaveTimers();
1960 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1969 class AutoSaveBuffer : public support::ForkedProcess {
1972 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1973 : buffer_(buffer), fname_(fname) {}
1975 virtual boost::shared_ptr<ForkedProcess> clone() const
1977 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1982 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
1983 from_utf8(fname_.absFilename())));
1984 return run(DontWait);
1988 virtual int generateChild();
1990 Buffer const & buffer_;
1995 #if !defined (HAVE_FORK)
1999 int AutoSaveBuffer::generateChild()
2001 // tmp_ret will be located (usually) in /tmp
2002 // will that be a problem?
2003 pid_t const pid = fork();
2004 // If you want to debug the autosave
2005 // you should set pid to -1, and comment out the fork.
2006 if (pid == 0 || pid == -1) {
2007 // pid = -1 signifies that lyx was unable
2008 // to fork. But we will do the save
2010 bool failed = false;
2012 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
2013 if (!tmp_ret.empty()) {
2014 buffer_.writeFile(tmp_ret);
2015 // assume successful write of tmp_ret
2016 if (!rename(tmp_ret, fname_)) {
2018 // most likely couldn't move between
2019 // filesystems unless write of tmp_ret
2020 // failed so remove tmp file (if it
2022 tmp_ret.removeFile();
2029 // failed to write/rename tmp_ret so try writing direct
2030 if (!buffer_.writeFile(fname_)) {
2031 // It is dangerous to do this in the child,
2032 // but safe in the parent, so...
2033 if (pid == -1) // emit message signal.
2034 buffer_.message(_("Autosave failed!"));
2037 if (pid == 0) { // we are the child so...
2047 // Perfect target for a thread...
2048 void Buffer::autoSave() const
2050 if (isBakClean() || isReadonly()) {
2051 // We don't save now, but we'll try again later
2052 resetAutosaveTimers();
2056 // emit message signal.
2057 message(_("Autosaving current document..."));
2059 // create autosave filename
2060 string fname = filePath();
2062 fname += d->filename.onlyFileName();
2065 AutoSaveBuffer autosave(*this, FileName(fname));
2069 resetAutosaveTimers();
2073 void Buffer::resetChildDocuments(bool close_them) const
2075 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2076 if (it->lyxCode() != INCLUDE_CODE)
2078 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2079 InsetCommandParams const & ip = inset.params();
2081 resetParentBuffer(this, ip, close_them);
2084 if (use_gui && masterBuffer() == this)
2085 updateLabels(*this);
2089 void Buffer::loadChildDocuments() const
2091 bool parse_error = false;
2093 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2094 if (it->lyxCode() != INCLUDE_CODE)
2096 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2097 InsetCommandParams const & ip = inset.params();
2098 Buffer * child = loadIfNeeded(*this, ip);
2101 parse_error |= !child->errorList("Parse").empty();
2102 child->loadChildDocuments();
2105 if (use_gui && masterBuffer() == this)
2106 updateLabels(*this);
2110 string Buffer::bufferFormat() const
2120 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2121 string & result_file) const
2123 string backend_format;
2124 OutputParams runparams(¶ms().encoding());
2125 runparams.flavor = OutputParams::LATEX;
2126 runparams.linelen = lyxrc.plaintext_linelen;
2127 vector<string> backs = backends();
2128 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2129 // Get shortest path to format
2130 Graph::EdgePath path;
2131 for (vector<string>::const_iterator it = backs.begin();
2132 it != backs.end(); ++it) {
2133 Graph::EdgePath p = theConverters().getPath(*it, format);
2134 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2135 backend_format = *it;
2140 runparams.flavor = theConverters().getFlavor(path);
2142 Alert::error(_("Couldn't export file"),
2143 bformat(_("No information for exporting the format %1$s."),
2144 formats.prettyName(format)));
2148 backend_format = format;
2149 // FIXME: Don't hardcode format names here, but use a flag
2150 if (backend_format == "pdflatex")
2151 runparams.flavor = OutputParams::PDFLATEX;
2154 string filename = latexName(false);
2155 filename = addName(temppath(), filename);
2156 filename = changeExtension(filename,
2157 formats.extension(backend_format));
2159 // Plain text backend
2160 if (backend_format == "text")
2161 writePlaintextFile(*this, FileName(filename), runparams);
2163 else if (backend_format == "lyx")
2164 writeFile(FileName(filename));
2166 else if (isDocBook()) {
2167 runparams.nice = !put_in_tempdir;
2168 makeDocBookFile(FileName(filename), runparams);
2171 else if (backend_format == format) {
2172 runparams.nice = true;
2173 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2175 } else if (!lyxrc.tex_allows_spaces
2176 && support::contains(filePath(), ' ')) {
2177 Alert::error(_("File name error"),
2178 _("The directory path to the document cannot contain spaces."));
2181 runparams.nice = false;
2182 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2186 string const error_type = (format == "program")
2187 ? "Build" : bufferFormat();
2188 string const ext = formats.extension(format);
2189 FileName const tmp_result_file(changeExtension(filename, ext));
2190 bool const success = theConverters().convert(this, FileName(filename),
2191 tmp_result_file, FileName(absFileName()), backend_format, format,
2192 errorList(error_type));
2193 // Emit the signal to show the error list.
2194 if (format != backend_format)
2200 result_file = tmp_result_file.absFilename();
2202 result_file = changeExtension(absFileName(), ext);
2203 // We need to copy referenced files (e. g. included graphics
2204 // if format == "dvi") to the result dir.
2205 vector<ExportedFile> const files =
2206 runparams.exportdata->externalFiles(format);
2207 string const dest = onlyPath(result_file);
2208 CopyStatus status = SUCCESS;
2209 for (vector<ExportedFile>::const_iterator it = files.begin();
2210 it != files.end() && status != CANCEL; ++it) {
2212 formats.getFormatFromFile(it->sourceName);
2213 status = copyFile(fmt, it->sourceName,
2214 makeAbsPath(it->exportName, dest),
2215 it->exportName, status == FORCE);
2217 if (status == CANCEL) {
2218 message(_("Document export cancelled."));
2219 } else if (tmp_result_file.exists()) {
2220 // Finally copy the main file
2221 status = copyFile(format, tmp_result_file,
2222 FileName(result_file), result_file,
2224 message(bformat(_("Document exported as %1$s "
2226 formats.prettyName(format),
2227 makeDisplayPath(result_file)));
2229 // This must be a dummy converter like fax (bug 1888)
2230 message(bformat(_("Document exported as %1$s"),
2231 formats.prettyName(format)));
2239 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2242 return doExport(format, put_in_tempdir, result_file);
2246 bool Buffer::preview(string const & format) const
2249 if (!doExport(format, true, result_file))
2251 return formats.view(*this, FileName(result_file), format);
2255 bool Buffer::isExportable(string const & format) const
2257 vector<string> backs = backends();
2258 for (vector<string>::const_iterator it = backs.begin();
2259 it != backs.end(); ++it)
2260 if (theConverters().isReachable(*it, format))
2266 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2268 vector<string> backs = backends();
2269 vector<Format const *> result =
2270 theConverters().getReachable(backs[0], only_viewable, true);
2271 for (vector<string>::const_iterator it = backs.begin() + 1;
2272 it != backs.end(); ++it) {
2273 vector<Format const *> r =
2274 theConverters().getReachable(*it, only_viewable, false);
2275 result.insert(result.end(), r.begin(), r.end());
2281 vector<string> Buffer::backends() const
2284 if (params().getTextClass().isTeXClassAvailable()) {
2285 v.push_back(bufferFormat());
2286 // FIXME: Don't hardcode format names here, but use a flag
2287 if (v.back() == "latex")
2288 v.push_back("pdflatex");
2290 v.push_back("text");
2296 bool Buffer::readFileHelper(FileName const & s)
2298 // File information about normal file
2300 docstring const file = makeDisplayPath(s.absFilename(), 50);
2301 docstring text = bformat(_("The specified document\n%1$s"
2302 "\ncould not be read."), file);
2303 Alert::error(_("Could not read document"), text);
2307 // Check if emergency save file exists and is newer.
2308 FileName const e(s.absFilename() + ".emergency");
2310 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2311 docstring const file = makeDisplayPath(s.absFilename(), 20);
2312 docstring const text =
2313 bformat(_("An emergency save of the document "
2315 "Recover emergency save?"), file);
2316 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2317 _("&Recover"), _("&Load Original"),
2321 // the file is not saved if we load the emergency file.
2331 // Now check if autosave file is newer.
2332 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2334 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2335 docstring const file = makeDisplayPath(s.absFilename(), 20);
2336 docstring const text =
2337 bformat(_("The backup of the document "
2338 "%1$s is newer.\n\nLoad the "
2339 "backup instead?"), file);
2340 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2341 _("&Load backup"), _("Load &original"),
2345 // the file is not saved if we load the autosave file.
2349 // Here we delete the autosave
2360 bool Buffer::loadLyXFile(FileName const & s)
2362 if (s.isReadableFile()) {
2363 if (readFileHelper(s)) {
2364 lyxvc().file_found_hook(s);
2365 if (!s.isWritable())
2370 docstring const file = makeDisplayPath(s.absFilename(), 20);
2371 // Here we probably should run
2372 if (LyXVC::file_not_found_hook(s)) {
2373 docstring const text =
2374 bformat(_("Do you want to retrieve the document"
2375 " %1$s from version control?"), file);
2376 int const ret = Alert::prompt(_("Retrieve from version control?"),
2377 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2380 // How can we know _how_ to do the checkout?
2381 // With the current VC support it has to be,
2382 // a RCS file since CVS do not have special ,v files.
2384 return loadLyXFile(s);
2392 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2394 TeXErrors::Errors::const_iterator cit = terr.begin();
2395 TeXErrors::Errors::const_iterator end = terr.end();
2397 for (; cit != end; ++cit) {
2400 int errorRow = cit->error_in_line;
2401 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2407 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2408 } while (found && id_start == id_end && pos_start == pos_end);
2410 errorList.push_back(ErrorItem(cit->error_desc,
2411 cit->error_text, id_start, pos_start, pos_end));