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/filetools.h"
83 #include "support/ForkedCalls.h"
84 #include "support/gettext.h"
85 #include "support/gzstream.h"
86 #include "support/lstrings.h"
87 #include "support/lyxalgo.h"
88 #include "support/lyxlib.h"
89 #include "support/os.h"
90 #include "support/Path.h"
91 #include "support/textutils.h"
92 #include "support/types.h"
93 #include "support/FileZipListDir.h"
95 #if !defined (HAVE_FORK)
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
110 using std::make_pair;
115 using std::ostringstream;
126 using support::addName;
127 using support::bformat;
128 using support::changeExtension;
129 using support::cmd_ret;
130 using support::createBufferTmpDir;
131 using support::FileName;
132 using support::libFileSearch;
133 using support::latex_path;
134 using support::ltrim;
135 using support::makeAbsPath;
136 using support::makeDisplayPath;
137 using support::makeLatexName;
138 using support::onlyFilename;
139 using support::onlyPath;
140 using support::quoteName;
141 using support::removeAutosaveFile;
142 using support::rename;
143 using support::runCommand;
144 using support::split;
145 using support::subst;
146 using support::tempName;
148 using support::suffixIs;
150 namespace Alert = frontend::Alert;
151 namespace os = support::os;
155 int const LYX_FORMAT = 304; // JSpitzm: framed.sty goes InsetBox
160 typedef std::map<string, bool> DepClean;
165 Impl(Buffer & parent, FileName const & file, bool readonly);
178 mutable TexRow texrow;
179 Buffer const * parent_buffer;
181 /// need to regenerate .tex?
185 mutable bool lyx_clean;
187 /// is autosave needed?
188 mutable bool bak_clean;
190 /// is this a unnamed file (New...)?
196 /// name of the file the buffer is associated with.
199 /** Set to true only when the file is fully loaded.
200 * Used to prevent the premature generation of previews
201 * and by the citation inset.
203 bool file_fully_loaded;
205 /// our Text that should be wrapped in an InsetText
209 mutable TocBackend toc_backend;
212 typedef std::map<unsigned int, MacroData, std::greater<int> > PositionToMacroMap;
213 typedef std::map<docstring, PositionToMacroMap> NameToPositionMacroMap;
214 NameToPositionMacroMap macros;
216 /// Container for all sort of Buffer dependant errors.
217 map<string, ErrorList> errorLists;
219 /// all embedded files of this buffer
220 EmbeddedFiles embedded_files;
222 /// timestamp and checksum used to test if the file has been externally
223 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
225 unsigned long checksum_;
228 frontend::WorkAreaManager * wa_;
235 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
236 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
237 read_only(readonly_), filename(file), file_fully_loaded(false),
238 inset(params), toc_backend(&parent), embedded_files(&parent),
239 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
241 inset.setAutoBreakRows(true);
242 lyxvc.setBuffer(&parent);
243 temppath = createBufferTmpDir();
245 // FIXME: And now do something if temppath == string(), because we
246 // assume from now on that temppath points to a valid temp dir.
247 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
250 wa_ = new frontend::WorkAreaManager;
254 Buffer::Buffer(string const & file, bool readonly)
255 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
257 LYXERR(Debug::INFO, "Buffer::Buffer()");
263 LYXERR(Debug::INFO, "Buffer::~Buffer()");
264 // here the buffer should take care that it is
265 // saved properly, before it goes into the void.
267 // GuiView already destroyed
270 Buffer const * master = masterBuffer();
271 if (master != this && use_gui)
272 // We are closing buf which was a child document so we
273 // must update the labels and section numbering of its master
275 updateLabels(*master);
277 resetChildDocuments(false);
279 if (!temppath().empty() && !FileName(temppath()).destroyDirectory()) {
280 Alert::warning(_("Could not remove temporary directory"),
281 bformat(_("Could not remove the temporary directory %1$s"),
282 from_utf8(temppath())));
285 // Remove any previewed LaTeX snippets associated with this buffer.
286 graphics::Previews::get().removeLoader(*this);
292 void Buffer::changed() const
299 frontend::WorkAreaManager & Buffer::workAreaManager() const
301 BOOST_ASSERT(d->wa_);
306 Text & Buffer::text() const
308 return const_cast<Text &>(d->inset.text_);
312 Inset & Buffer::inset() const
314 return const_cast<InsetText &>(d->inset);
318 BufferParams & Buffer::params()
324 BufferParams const & Buffer::params() const
330 ParagraphList & Buffer::paragraphs()
332 return text().paragraphs();
336 ParagraphList const & Buffer::paragraphs() const
338 return text().paragraphs();
342 LyXVC & Buffer::lyxvc()
348 LyXVC const & Buffer::lyxvc() const
354 string const & Buffer::temppath() const
360 TexRow const & Buffer::texrow() const
366 TocBackend & Buffer::tocBackend() const
368 return d->toc_backend;
372 EmbeddedFiles & Buffer::embeddedFiles()
374 return d->embedded_files;
378 EmbeddedFiles const & Buffer::embeddedFiles() const
380 return d->embedded_files;
384 Undo & Buffer::undo()
390 string Buffer::latexName(bool const no_path) const
392 FileName latex_name = makeLatexName(d->filename);
393 return no_path ? latex_name.onlyFileName()
394 : latex_name.absFilename();
398 string Buffer::logName(LogType * type) const
400 string const filename = latexName(false);
402 if (filename.empty()) {
408 string const path = temppath();
410 FileName const fname(addName(temppath(),
411 onlyFilename(changeExtension(filename,
413 FileName const bname(
414 addName(path, onlyFilename(
415 changeExtension(filename,
416 formats.extension("literate") + ".out"))));
418 // If no Latex log or Build log is newer, show Build log
420 if (bname.exists() &&
421 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
422 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
425 return bname.absFilename();
427 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
430 return fname.absFilename();
434 void Buffer::setReadonly(bool const flag)
436 if (d->read_only != flag) {
443 void Buffer::setFileName(string const & newfile)
445 d->filename = makeAbsPath(newfile);
446 setReadonly(d->filename.isReadOnly());
451 int Buffer::readHeader(Lexer & lex)
453 int unknown_tokens = 0;
455 int begin_header_line = -1;
457 // Initialize parameters that may be/go lacking in header:
458 params().branchlist().clear();
459 params().preamble.erase();
460 params().options.erase();
461 params().float_placement.erase();
462 params().paperwidth.erase();
463 params().paperheight.erase();
464 params().leftmargin.erase();
465 params().rightmargin.erase();
466 params().topmargin.erase();
467 params().bottommargin.erase();
468 params().headheight.erase();
469 params().headsep.erase();
470 params().footskip.erase();
471 params().listings_params.clear();
472 params().clearLayoutModules();
473 params().pdfoptions().clear();
475 for (int i = 0; i < 4; ++i) {
476 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
477 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
480 ErrorList & errorList = d->errorLists["Parse"];
484 string const token = lex.getString();
489 if (token == "\\end_header")
493 if (token == "\\begin_header") {
494 begin_header_line = line;
498 LYXERR(Debug::PARSER, "Handling document header token: `"
501 string unknown = params().readToken(lex, token, d->filename.onlyPath());
502 if (!unknown.empty()) {
503 if (unknown[0] != '\\' && token == "\\textclass") {
504 Alert::warning(_("Unknown document class"),
505 bformat(_("Using the default document class, because the "
506 "class %1$s is unknown."), from_utf8(unknown)));
509 docstring const s = bformat(_("Unknown token: "
513 errorList.push_back(ErrorItem(_("Document header error"),
518 if (begin_header_line) {
519 docstring const s = _("\\begin_header is missing");
520 errorList.push_back(ErrorItem(_("Document header error"),
524 return unknown_tokens;
529 // changed to be public and have one parameter
530 // Returns false if "\end_document" is not read (Asger)
531 bool Buffer::readDocument(Lexer & lex)
533 ErrorList & errorList = d->errorLists["Parse"];
537 string const token = lex.getString();
538 if (token != "\\begin_document") {
539 docstring const s = _("\\begin_document is missing");
540 errorList.push_back(ErrorItem(_("Document header error"),
544 // we are reading in a brand new document
545 BOOST_ASSERT(paragraphs().empty());
548 TextClass const & baseClass = textclasslist[params().getBaseClass()];
549 if (!baseClass.load(filePath())) {
550 string theclass = baseClass.name();
551 Alert::error(_("Can't load document class"), bformat(
552 _("Using the default document class, because the "
553 "class %1$s could not be loaded."), from_utf8(theclass)));
554 params().setBaseClass(defaultTextclass());
557 if (params().outputChanges) {
558 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
559 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
560 LaTeXFeatures::isAvailable("xcolor");
562 if (!dvipost && !xcolorsoul) {
563 Alert::warning(_("Changes not shown in LaTeX output"),
564 _("Changes will not be highlighted in LaTeX output, "
565 "because neither dvipost nor xcolor/soul are installed.\n"
566 "Please install these packages or redefine "
567 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
568 } else if (!xcolorsoul) {
569 Alert::warning(_("Changes not shown in LaTeX output"),
570 _("Changes will not be highlighted in LaTeX output "
571 "when using pdflatex, because xcolor and soul are not installed.\n"
572 "Please install both packages or redefine "
573 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578 bool const res = text().read(*this, lex, errorList);
579 for_each(text().paragraphs().begin(),
580 text().paragraphs().end(),
581 bind(&Paragraph::setInsetOwner, _1, &inset()));
587 // needed to insert the selection
588 void Buffer::insertStringAsLines(ParagraphList & pars,
589 pit_type & pit, pos_type & pos,
590 Font const & fn, docstring const & str, bool autobreakrows)
594 // insert the string, don't insert doublespace
595 bool space_inserted = true;
596 for (docstring::const_iterator cit = str.begin();
597 cit != str.end(); ++cit) {
598 Paragraph & par = pars[pit];
600 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
601 breakParagraph(params(), pars, pit, pos,
602 par.layout()->isEnvironment());
605 space_inserted = true;
609 // do not insert consecutive spaces if !free_spacing
610 } else if ((*cit == ' ' || *cit == '\t') &&
611 space_inserted && !par.isFreeSpacing()) {
613 } else if (*cit == '\t') {
614 if (!par.isFreeSpacing()) {
615 // tabs are like spaces here
616 par.insertChar(pos, ' ', font, params().trackChanges);
618 space_inserted = true;
620 const pos_type n = 8 - pos % 8;
621 for (pos_type i = 0; i < n; ++i) {
622 par.insertChar(pos, ' ', font, params().trackChanges);
625 space_inserted = true;
627 } else if (!isPrintable(*cit)) {
628 // Ignore unprintables
631 // just insert the character
632 par.insertChar(pos, *cit, font, params().trackChanges);
634 space_inserted = (*cit == ' ');
641 bool Buffer::readString(std::string const & s)
643 params().compressed = false;
645 // remove dummy empty par
646 paragraphs().clear();
648 std::istringstream is(s);
650 FileName const name(tempName());
651 switch (readFile(lex, name, true)) {
655 // We need to call lyx2lyx, so write the input to a file
656 std::ofstream os(name.toFilesystemEncoding().c_str());
659 return readFile(name);
669 bool Buffer::readFile(FileName const & filename)
671 FileName fname(filename);
672 // Check if the file is compressed.
673 string format = filename.guessFormatFromContents();
674 if (format == "zip") {
675 // decompress to a temp directory
676 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
677 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
679 FileName lyxfile(addName(temppath(), "content.lyx"));
680 // if both manifest.txt and file.lyx exist, this is am embedded file
681 if (lyxfile.exists()) {
682 params().embedded = true;
686 // The embedded lyx file can also be compressed, for backward compatibility
687 format = fname.guessFormatFromContents();
688 if (format == "gzip" || format == "zip" || format == "compress")
689 params().compressed = true;
691 // remove dummy empty par
692 paragraphs().clear();
695 if (readFile(lex, fname) != success)
702 bool Buffer::isFullyLoaded() const
704 return d->file_fully_loaded;
708 void Buffer::setFullyLoaded(bool value)
710 d->file_fully_loaded = value;
714 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
717 BOOST_ASSERT(!filename.empty());
720 Alert::error(_("Document could not be read"),
721 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
726 string const token = lex.getString();
729 Alert::error(_("Document could not be read"),
730 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
734 // the first token _must_ be...
735 if (token != "\\lyxformat") {
736 lyxerr << "Token: " << token << endl;
738 Alert::error(_("Document format failure"),
739 bformat(_("%1$s is not a LyX document."),
740 from_utf8(filename.absFilename())));
745 string tmp_format = lex.getString();
746 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
747 // if present remove ".," from string.
748 string::size_type dot = tmp_format.find_first_of(".,");
749 //lyxerr << " dot found at " << dot << endl;
750 if (dot != string::npos)
751 tmp_format.erase(dot, 1);
752 int const file_format = convert<int>(tmp_format);
753 //lyxerr << "format: " << file_format << endl;
755 // save timestamp and checksum of the original disk file, making sure
756 // to not overwrite them with those of the file created in the tempdir
757 // when it has to be converted to the current format.
759 // Save the timestamp and checksum of disk file. If filename is an
760 // emergency file, save the timestamp and checksum of the original lyx file
761 // because isExternallyModified will check for this file. (BUG4193)
762 string diskfile = filename.absFilename();
763 if (suffixIs(diskfile, ".emergency"))
764 diskfile = diskfile.substr(0, diskfile.size() - 10);
765 saveCheckSum(FileName(diskfile));
768 if (file_format != LYX_FORMAT) {
771 // lyx2lyx would fail
774 FileName const tmpfile(tempName());
775 if (tmpfile.empty()) {
776 Alert::error(_("Conversion failed"),
777 bformat(_("%1$s is from a different"
778 " version of LyX, but a temporary"
779 " file for converting it could"
781 from_utf8(filename.absFilename())));
784 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
785 if (lyx2lyx.empty()) {
786 Alert::error(_("Conversion script not found"),
787 bformat(_("%1$s is from a different"
788 " version of LyX, but the"
789 " conversion script lyx2lyx"
790 " could not be found."),
791 from_utf8(filename.absFilename())));
794 ostringstream command;
795 command << os::python()
796 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
797 << " -t " << convert<string>(LYX_FORMAT)
798 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
799 << ' ' << quoteName(filename.toFilesystemEncoding());
800 string const command_str = command.str();
802 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
804 cmd_ret const ret = runCommand(command_str);
805 if (ret.first != 0) {
806 Alert::error(_("Conversion script failed"),
807 bformat(_("%1$s is from a different version"
808 " of LyX, but the lyx2lyx script"
809 " failed to convert it."),
810 from_utf8(filename.absFilename())));
813 bool const ret = readFile(tmpfile);
814 // Do stuff with tmpfile name and buffer name here.
815 return ret ? success : failure;
820 if (readDocument(lex)) {
821 Alert::error(_("Document format failure"),
822 bformat(_("%1$s ended unexpectedly, which means"
823 " that it is probably corrupted."),
824 from_utf8(filename.absFilename())));
827 d->file_fully_loaded = true;
832 // Should probably be moved to somewhere else: BufferView? LyXView?
833 bool Buffer::save() const
835 // We don't need autosaves in the immediate future. (Asger)
836 resetAutosaveTimers();
838 string const encodedFilename = d->filename.toFilesystemEncoding();
841 bool madeBackup = false;
843 // make a backup if the file already exists
844 if (lyxrc.make_backup && fileName().exists()) {
845 backupName = FileName(absFileName() + '~');
846 if (!lyxrc.backupdir_path.empty()) {
847 string const mangledName =
848 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
849 backupName = FileName(addName(lyxrc.backupdir_path,
852 if (fileName().copyTo(backupName, true)) {
855 Alert::error(_("Backup failure"),
856 bformat(_("Cannot create backup file %1$s.\n"
857 "Please check whether the directory exists and is writeable."),
858 from_utf8(backupName.absFilename())));
859 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
863 // ask if the disk file has been externally modified (use checksum method)
864 if (fileName().exists() && isExternallyModified(checksum_method)) {
865 docstring const file = makeDisplayPath(absFileName(), 20);
866 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
867 "you want to overwrite this file?"), file);
868 int const ret = Alert::prompt(_("Overwrite modified file?"),
869 text, 1, 1, _("&Overwrite"), _("&Cancel"));
874 if (writeFile(d->filename)) {
878 // Saving failed, so backup is not backup
880 rename(backupName, d->filename);
886 bool Buffer::writeFile(FileName const & fname) const
888 if (d->read_only && fname == d->filename)
894 if (params().embedded)
895 // first write the .lyx file to the temporary directory
896 content = FileName(addName(temppath(), "content.lyx"));
900 docstring const str = bformat(_("Saving document %1$s..."),
901 makeDisplayPath(content.absFilename()));
904 if (params().compressed) {
905 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
906 retval = ofs && write(ofs);
908 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
909 retval = ofs && write(ofs);
913 message(str + _(" could not write file!."));
917 removeAutosaveFile(d->filename.absFilename());
918 saveCheckSum(d->filename);
919 message(str + _(" done."));
921 if (!params().embedded)
924 message(str + _(" writing embedded files!."));
925 // if embedding is enabled, write file.lyx and all the embedded files
926 // to the zip file fname.
927 if (!d->embedded_files.writeFile(fname)) {
928 message(str + _(" could not write embedded files!."));
931 message(str + _(" error while writing embedded files."));
936 bool Buffer::write(ostream & ofs) const
939 // Use the standard "C" locale for file output.
940 ofs.imbue(std::locale::classic());
943 // The top of the file should not be written by params().
945 // write out a comment in the top of the file
946 ofs << "#LyX " << lyx_version
947 << " created this file. For more info see http://www.lyx.org/\n"
948 << "\\lyxformat " << LYX_FORMAT << "\n"
949 << "\\begin_document\n";
952 /// For each author, set 'used' to true if there is a change
953 /// by this author in the document; otherwise set it to 'false'.
954 AuthorList::Authors::const_iterator a_it = params().authors().begin();
955 AuthorList::Authors::const_iterator a_end = params().authors().end();
956 for (; a_it != a_end; ++a_it)
957 a_it->second.setUsed(false);
959 ParIterator const end = par_iterator_end();
960 ParIterator it = par_iterator_begin();
961 for ( ; it != end; ++it)
962 it->checkAuthors(params().authors());
964 // now write out the buffer parameters.
965 ofs << "\\begin_header\n";
966 params().writeFile(ofs);
967 ofs << "\\end_header\n";
970 ofs << "\n\\begin_body\n";
971 text().write(*this, ofs);
972 ofs << "\n\\end_body\n";
974 // Write marker that shows file is complete
975 ofs << "\\end_document" << endl;
977 // Shouldn't really be needed....
980 // how to check if close went ok?
981 // Following is an attempt... (BE 20001011)
983 // good() returns false if any error occured, including some
985 // bad() returns true if something bad happened in the buffer,
986 // which should include file system full errors.
991 lyxerr << "File was not closed properly." << endl;
998 bool Buffer::makeLaTeXFile(FileName const & fname,
999 string const & original_path,
1000 OutputParams const & runparams,
1001 bool output_preamble, bool output_body) const
1003 string const encoding = runparams.encoding->iconvName();
1004 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1006 odocfstream ofs(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 (!lyxrc.language_auto_begin &&
1119 !params().language->babel().empty()) {
1121 os << from_utf8(subst(lyxrc.language_command_begin,
1123 params().language->babel()))
1125 d->texrow.newline();
1128 Encoding const & encoding = params().encoding();
1129 if (encoding.package() == Encoding::CJK) {
1130 // Open a CJK environment, since in contrast to the encodings
1131 // handled by inputenc the document encoding is not set in
1132 // the preamble if it is handled by CJK.sty.
1133 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1135 d->texrow.newline();
1138 // if we are doing a real file with body, even if this is the
1139 // child of some other buffer, let's cut the link here.
1140 // This happens for example if only a child document is printed.
1141 Buffer const * save_parent = 0;
1142 if (output_preamble) {
1143 save_parent = d->parent_buffer;
1144 d->parent_buffer = 0;
1147 loadChildDocuments();
1150 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1152 // Restore the parenthood if needed
1153 if (output_preamble)
1154 d->parent_buffer = save_parent;
1156 // add this just in case after all the paragraphs
1158 d->texrow.newline();
1160 if (encoding.package() == Encoding::CJK) {
1161 // Close the open CJK environment.
1162 // latexParagraphs will have opened one even if the last text
1164 os << "\\end{CJK}\n";
1165 d->texrow.newline();
1168 if (!lyxrc.language_auto_end &&
1169 !params().language->babel().empty()) {
1170 os << from_utf8(subst(lyxrc.language_command_end,
1172 params().language->babel()))
1174 d->texrow.newline();
1177 if (output_preamble) {
1178 os << "\\end{document}\n";
1179 d->texrow.newline();
1180 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1182 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1184 runparams_in.encoding = runparams.encoding;
1186 // Just to be sure. (Asger)
1187 d->texrow.newline();
1189 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1190 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1194 bool Buffer::isLatex() const
1196 return params().getTextClass().outputType() == LATEX;
1200 bool Buffer::isLiterate() const
1202 return params().getTextClass().outputType() == LITERATE;
1206 bool Buffer::isDocBook() const
1208 return params().getTextClass().outputType() == DOCBOOK;
1212 void Buffer::makeDocBookFile(FileName const & fname,
1213 OutputParams const & runparams,
1214 bool const body_only) const
1216 LYXERR(Debug::LATEX, "makeDocBookFile...");
1220 if (!openFileWrite(ofs, fname))
1223 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1227 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1231 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1232 OutputParams const & runparams,
1233 bool const only_body) const
1235 LaTeXFeatures features(*this, params(), runparams);
1240 TextClass const & tclass = params().getTextClass();
1241 string const top_element = tclass.latexname();
1244 if (runparams.flavor == OutputParams::XML)
1245 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1248 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1251 if (! tclass.class_header().empty())
1252 os << from_ascii(tclass.class_header());
1253 else if (runparams.flavor == OutputParams::XML)
1254 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1255 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1257 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1259 docstring preamble = from_utf8(params().preamble);
1260 if (runparams.flavor != OutputParams::XML ) {
1261 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1262 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1263 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1264 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1267 string const name = runparams.nice
1268 ? changeExtension(absFileName(), ".sgml") : fname;
1269 preamble += features.getIncludedFiles(name);
1270 preamble += features.getLyXSGMLEntities();
1272 if (!preamble.empty()) {
1273 os << "\n [ " << preamble << " ]";
1278 string top = top_element;
1280 if (runparams.flavor == OutputParams::XML)
1281 top += params().language->code();
1283 top += params().language->code().substr(0,2);
1286 if (!params().options.empty()) {
1288 top += params().options;
1291 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1292 << " file was created by LyX " << lyx_version
1293 << "\n See http://www.lyx.org/ for more information -->\n";
1295 params().getTextClass().counters().reset();
1297 loadChildDocuments();
1299 sgml::openTag(os, top);
1301 docbookParagraphs(paragraphs(), *this, os, runparams);
1302 sgml::closeTag(os, top_element);
1306 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1307 // Other flags: -wall -v0 -x
1308 int Buffer::runChktex()
1312 // get LaTeX-Filename
1313 FileName const path(temppath());
1314 string const name = addName(path.absFilename(), latexName());
1315 string const org_path = filePath();
1317 support::PathChanger p(path); // path to LaTeX file
1318 message(_("Running chktex..."));
1320 // Generate the LaTeX file if neccessary
1321 OutputParams runparams(¶ms().encoding());
1322 runparams.flavor = OutputParams::LATEX;
1323 runparams.nice = false;
1324 makeLaTeXFile(FileName(name), org_path, runparams);
1327 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1328 int const res = chktex.run(terr); // run chktex
1331 Alert::error(_("chktex failure"),
1332 _("Could not run chktex successfully."));
1333 } else if (res > 0) {
1334 ErrorList & errlist = d->errorLists["ChkTeX"];
1336 bufferErrors(terr, errlist);
1347 void Buffer::validate(LaTeXFeatures & features) const
1349 TextClass const & tclass = params().getTextClass();
1351 if (params().outputChanges) {
1352 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1353 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1354 LaTeXFeatures::isAvailable("xcolor");
1356 if (features.runparams().flavor == OutputParams::LATEX) {
1358 features.require("ct-dvipost");
1359 features.require("dvipost");
1360 } else if (xcolorsoul) {
1361 features.require("ct-xcolor-soul");
1362 features.require("soul");
1363 features.require("xcolor");
1365 features.require("ct-none");
1367 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1369 features.require("ct-xcolor-soul");
1370 features.require("soul");
1371 features.require("xcolor");
1372 features.require("pdfcolmk"); // improves color handling in PDF output
1374 features.require("ct-none");
1379 // AMS Style is at document level
1380 if (params().use_amsmath == BufferParams::package_on
1381 || tclass.provides("amsmath"))
1382 features.require("amsmath");
1383 if (params().use_esint == BufferParams::package_on)
1384 features.require("esint");
1386 loadChildDocuments();
1388 for_each(paragraphs().begin(), paragraphs().end(),
1389 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1391 // the bullet shapes are buffer level not paragraph level
1392 // so they are tested here
1393 for (int i = 0; i < 4; ++i) {
1394 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1395 int const font = params().user_defined_bullet(i).getFont();
1397 int const c = params()
1398 .user_defined_bullet(i)
1405 features.require("latexsym");
1407 } else if (font == 1) {
1408 features.require("amssymb");
1409 } else if ((font >= 2 && font <= 5)) {
1410 features.require("pifont");
1415 if (lyxerr.debugging(Debug::LATEX)) {
1416 features.showStruct();
1421 void Buffer::getLabelList(vector<docstring> & list) const
1423 /// if this is a child document and the parent is already loaded
1424 /// Use the parent's list instead [ale990407]
1425 Buffer const * tmp = masterBuffer();
1427 lyxerr << "masterBuffer() failed!" << endl;
1431 tmp->getLabelList(list);
1435 loadChildDocuments();
1437 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1438 it.nextInset()->getLabelList(*this, list);
1442 void Buffer::updateBibfilesCache() const
1444 // if this is a child document and the parent is already loaded
1445 // update the parent's cache instead
1446 Buffer const * tmp = masterBuffer();
1449 tmp->updateBibfilesCache();
1453 bibfilesCache_.clear();
1454 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1455 if (it->lyxCode() == BIBTEX_CODE) {
1456 InsetBibtex const & inset =
1457 static_cast<InsetBibtex const &>(*it);
1458 vector<FileName> const bibfiles = inset.getFiles(*this);
1459 bibfilesCache_.insert(bibfilesCache_.end(),
1462 } else if (it->lyxCode() == INCLUDE_CODE) {
1463 InsetInclude & inset =
1464 static_cast<InsetInclude &>(*it);
1465 inset.updateBibfilesCache(*this);
1466 vector<FileName> const & bibfiles =
1467 inset.getBibfilesCache(*this);
1468 bibfilesCache_.insert(bibfilesCache_.end(),
1476 vector<FileName> const & Buffer::getBibfilesCache() const
1478 // if this is a child document and the parent is already loaded
1479 // use the parent's cache instead
1480 Buffer const * tmp = masterBuffer();
1483 return tmp->getBibfilesCache();
1485 // We update the cache when first used instead of at loading time.
1486 if (bibfilesCache_.empty())
1487 const_cast<Buffer *>(this)->updateBibfilesCache();
1489 return bibfilesCache_;
1493 bool Buffer::isDepClean(string const & name) const
1495 DepClean::const_iterator const it = d->dep_clean.find(name);
1496 if (it == d->dep_clean.end())
1502 void Buffer::markDepClean(string const & name)
1504 d->dep_clean[name] = true;
1508 bool Buffer::dispatch(string const & command, bool * result)
1510 return dispatch(lyxaction.lookupFunc(command), result);
1514 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1516 bool dispatched = true;
1518 switch (func.action) {
1519 case LFUN_BUFFER_EXPORT: {
1520 bool const tmp = doExport(to_utf8(func.argument()), false);
1533 void Buffer::changeLanguage(Language const * from, Language const * to)
1538 for_each(par_iterator_begin(),
1540 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1544 bool Buffer::isMultiLingual() const
1546 ParConstIterator end = par_iterator_end();
1547 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1548 if (it->isMultiLingual(params()))
1555 ParIterator Buffer::getParFromID(int const id) const
1557 ParConstIterator it = par_iterator_begin();
1558 ParConstIterator const end = par_iterator_end();
1561 // John says this is called with id == -1 from undo
1562 lyxerr << "getParFromID(), id: " << id << endl;
1566 for (; it != end; ++it)
1574 bool Buffer::hasParWithID(int const id) const
1576 ParConstIterator const it = getParFromID(id);
1577 return it != par_iterator_end();
1581 ParIterator Buffer::par_iterator_begin()
1583 return lyx::par_iterator_begin(inset());
1587 ParIterator Buffer::par_iterator_end()
1589 return lyx::par_iterator_end(inset());
1593 ParConstIterator Buffer::par_iterator_begin() const
1595 return lyx::par_const_iterator_begin(inset());
1599 ParConstIterator Buffer::par_iterator_end() const
1601 return lyx::par_const_iterator_end(inset());
1605 Language const * Buffer::language() const
1607 return params().language;
1611 docstring const Buffer::B_(string const & l10n) const
1613 return params().B_(l10n);
1617 bool Buffer::isClean() const
1619 return d->lyx_clean;
1623 bool Buffer::isBakClean() const
1625 return d->bak_clean;
1629 bool Buffer::isExternallyModified(CheckMethod method) const
1631 BOOST_ASSERT(d->filename.exists());
1632 // if method == timestamp, check timestamp before checksum
1633 return (method == checksum_method
1634 || d->timestamp_ != d->filename.lastModified())
1635 && d->checksum_ != d->filename.checksum();
1639 void Buffer::saveCheckSum(FileName const & file) const
1641 if (file.exists()) {
1642 d->timestamp_ = file.lastModified();
1643 d->checksum_ = file.checksum();
1645 // in the case of save to a new file.
1652 void Buffer::markClean() const
1654 if (!d->lyx_clean) {
1655 d->lyx_clean = true;
1658 // if the .lyx file has been saved, we don't need an
1660 d->bak_clean = true;
1664 void Buffer::markBakClean() const
1666 d->bak_clean = true;
1670 void Buffer::setUnnamed(bool flag)
1676 bool Buffer::isUnnamed() const
1682 // FIXME: this function should be moved to buffer_pimpl.C
1683 void Buffer::markDirty()
1686 d->lyx_clean = false;
1689 d->bak_clean = false;
1691 DepClean::iterator it = d->dep_clean.begin();
1692 DepClean::const_iterator const end = d->dep_clean.end();
1694 for (; it != end; ++it)
1699 FileName Buffer::fileName() const
1705 string Buffer::absFileName() const
1707 return d->filename.absFilename();
1711 string Buffer::filePath() const
1713 return d->filename.onlyPath().absFilename();
1717 bool Buffer::isReadonly() const
1719 return d->read_only;
1723 void Buffer::setParent(Buffer const * buffer)
1725 // Avoids recursive include.
1726 d->parent_buffer = buffer == this ? 0 : buffer;
1730 Buffer const * Buffer::parent()
1732 return d->parent_buffer;
1736 Buffer const * Buffer::masterBuffer() const
1738 if (!d->parent_buffer)
1741 return d->parent_buffer->masterBuffer();
1745 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1747 Impl::PositionToMacroMap::iterator it;
1748 it = d->macros[name].upper_bound(par.macrocontextPosition());
1749 if (it != d->macros[name].end())
1752 // If there is a master buffer, query that
1753 Buffer const * master = masterBuffer();
1754 if (master && master != this)
1755 return master->hasMacro(name);
1757 return MacroTable::globalMacros().has(name);
1761 bool Buffer::hasMacro(docstring const & name) const
1763 if( !d->macros[name].empty() )
1766 // If there is a master buffer, query that
1767 Buffer const * master = masterBuffer();
1768 if (master && master != this)
1769 return master->hasMacro(name);
1771 return MacroTable::globalMacros().has(name);
1775 MacroData const & Buffer::getMacro(docstring const & name,
1776 Paragraph const & par) const
1778 Impl::PositionToMacroMap::iterator it;
1779 it = d->macros[name].upper_bound(par.macrocontextPosition());
1780 if( it != d->macros[name].end() )
1783 // If there is a master buffer, query that
1784 Buffer const * master = masterBuffer();
1785 if (master && master != this)
1786 return master->getMacro(name);
1788 return MacroTable::globalMacros().get(name);
1792 MacroData const & Buffer::getMacro(docstring const & name) const
1794 Impl::PositionToMacroMap::iterator it;
1795 it = d->macros[name].begin();
1796 if( it != d->macros[name].end() )
1799 // If there is a master buffer, query that
1800 Buffer const * master = masterBuffer();
1801 if (master && master != this)
1802 return master->getMacro(name);
1804 return MacroTable::globalMacros().get(name);
1808 void Buffer::updateMacros()
1810 // start with empty table
1811 d->macros = Impl::NameToPositionMacroMap();
1813 // Iterate over buffer
1814 ParagraphList & pars = text().paragraphs();
1815 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1816 // set position again
1817 pars[i].setMacrocontextPosition(i);
1819 //lyxerr << "searching main par " << i
1820 // << " for macro definitions" << std::endl;
1821 InsetList const & insets = pars[i].insetList();
1822 InsetList::const_iterator it = insets.begin();
1823 InsetList::const_iterator end = insets.end();
1824 for ( ; it != end; ++it) {
1825 if (it->inset->lyxCode() != MATHMACRO_CODE)
1829 MathMacroTemplate const & macroTemplate
1830 = static_cast<MathMacroTemplate const &>(*it->inset);
1833 if (macroTemplate.validMacro()) {
1834 MacroData macro = macroTemplate.asMacroData();
1837 // call hasMacro here instead of directly querying mc to
1838 // also take the master document into consideration
1839 macro.setRedefinition(hasMacro(macroTemplate.name()));
1841 // register macro (possibly overwrite the previous one of this paragraph)
1842 d->macros[macroTemplate.name()][i] = macro;
1849 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1852 //FIXME: This does not work for child documents yet.
1853 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1854 // Check if the label 'from' appears more than once
1855 vector<docstring> labels;
1858 if (code == CITE_CODE) {
1860 keys.fillWithBibKeys(this);
1861 BiblioInfo::const_iterator bit = keys.begin();
1862 BiblioInfo::const_iterator bend = keys.end();
1864 for (; bit != bend; ++bit)
1866 labels.push_back(bit->first);
1869 getLabelList(labels);
1870 paramName = "reference";
1873 if (std::count(labels.begin(), labels.end(), from) > 1)
1876 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1877 if (it->lyxCode() == code) {
1878 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1879 docstring const oldValue = inset.getParam(paramName);
1880 if (oldValue == from)
1881 inset.setParam(paramName, to);
1887 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1888 pit_type par_end, bool full_source)
1890 OutputParams runparams(¶ms().encoding());
1891 runparams.nice = true;
1892 runparams.flavor = OutputParams::LATEX;
1893 runparams.linelen = lyxrc.plaintext_linelen;
1894 // No side effect of file copying and image conversion
1895 runparams.dryrun = true;
1899 os << "% " << _("Preview source code") << "\n\n";
1900 d->texrow.newline();
1901 d->texrow.newline();
1903 writeLaTeXSource(os, filePath(), runparams, true, true);
1905 writeDocBookSource(os, absFileName(), runparams, false);
1908 runparams.par_begin = par_begin;
1909 runparams.par_end = par_end;
1910 if (par_begin + 1 == par_end)
1912 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1916 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1917 convert<docstring>(par_begin),
1918 convert<docstring>(par_end - 1))
1920 d->texrow.newline();
1921 d->texrow.newline();
1922 // output paragraphs
1924 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1927 docbookParagraphs(paragraphs(), *this, os, runparams);
1933 ErrorList & Buffer::errorList(string const & type) const
1935 static ErrorList emptyErrorList;
1936 std::map<string, ErrorList>::iterator I = d->errorLists.find(type);
1937 if (I == d->errorLists.end())
1938 return emptyErrorList;
1944 void Buffer::structureChanged() const
1947 gui_->structureChanged();
1951 void Buffer::errors(std::string const & err) const
1958 void Buffer::message(docstring const & msg) const
1965 void Buffer::setBusy(bool on) const
1972 void Buffer::setReadOnly(bool on) const
1975 d->wa_->setReadOnly(on);
1979 void Buffer::updateTitles() const
1982 d->wa_->updateTitles();
1986 void Buffer::resetAutosaveTimers() const
1989 gui_->resetAutosaveTimers();
1993 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2002 class AutoSaveBuffer : public support::ForkedProcess {
2005 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2006 : buffer_(buffer), fname_(fname) {}
2008 virtual boost::shared_ptr<ForkedProcess> clone() const
2010 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2015 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2016 from_utf8(fname_.absFilename())));
2017 return run(DontWait);
2021 virtual int generateChild();
2023 Buffer const & buffer_;
2028 #if !defined (HAVE_FORK)
2032 int AutoSaveBuffer::generateChild()
2034 // tmp_ret will be located (usually) in /tmp
2035 // will that be a problem?
2036 pid_t const pid = fork();
2037 // If you want to debug the autosave
2038 // you should set pid to -1, and comment out the fork.
2039 if (pid == 0 || pid == -1) {
2040 // pid = -1 signifies that lyx was unable
2041 // to fork. But we will do the save
2043 bool failed = false;
2045 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
2046 if (!tmp_ret.empty()) {
2047 buffer_.writeFile(tmp_ret);
2048 // assume successful write of tmp_ret
2049 if (!rename(tmp_ret, fname_)) {
2051 // most likely couldn't move between
2052 // filesystems unless write of tmp_ret
2053 // failed so remove tmp file (if it
2055 tmp_ret.removeFile();
2062 // failed to write/rename tmp_ret so try writing direct
2063 if (!buffer_.writeFile(fname_)) {
2064 // It is dangerous to do this in the child,
2065 // but safe in the parent, so...
2066 if (pid == -1) // emit message signal.
2067 buffer_.message(_("Autosave failed!"));
2070 if (pid == 0) { // we are the child so...
2080 // Perfect target for a thread...
2081 void Buffer::autoSave() const
2083 if (isBakClean() || isReadonly()) {
2084 // We don't save now, but we'll try again later
2085 resetAutosaveTimers();
2089 // emit message signal.
2090 message(_("Autosaving current document..."));
2092 // create autosave filename
2093 string fname = filePath();
2095 fname += d->filename.onlyFileName();
2098 AutoSaveBuffer autosave(*this, FileName(fname));
2102 resetAutosaveTimers();
2106 void Buffer::resetChildDocuments(bool close_them) const
2108 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2109 if (it->lyxCode() != INCLUDE_CODE)
2111 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2112 InsetCommandParams const & ip = inset.params();
2114 resetParentBuffer(this, ip, close_them);
2117 if (use_gui && masterBuffer() == this)
2118 updateLabels(*this);
2122 void Buffer::loadChildDocuments() const
2124 bool parse_error = false;
2126 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2127 if (it->lyxCode() != INCLUDE_CODE)
2129 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2130 InsetCommandParams const & ip = inset.params();
2131 Buffer * child = loadIfNeeded(*this, ip);
2134 parse_error |= !child->errorList("Parse").empty();
2135 child->loadChildDocuments();
2138 if (use_gui && masterBuffer() == this)
2139 updateLabels(*this);
2143 string Buffer::bufferFormat() const
2153 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2154 string & result_file) const
2156 string backend_format;
2157 OutputParams runparams(¶ms().encoding());
2158 runparams.flavor = OutputParams::LATEX;
2159 runparams.linelen = lyxrc.plaintext_linelen;
2160 vector<string> backs = backends();
2161 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2162 // Get shortest path to format
2163 Graph::EdgePath path;
2164 for (vector<string>::const_iterator it = backs.begin();
2165 it != backs.end(); ++it) {
2166 Graph::EdgePath p = theConverters().getPath(*it, format);
2167 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2168 backend_format = *it;
2173 runparams.flavor = theConverters().getFlavor(path);
2175 Alert::error(_("Couldn't export file"),
2176 bformat(_("No information for exporting the format %1$s."),
2177 formats.prettyName(format)));
2181 backend_format = format;
2182 // FIXME: Don't hardcode format names here, but use a flag
2183 if (backend_format == "pdflatex")
2184 runparams.flavor = OutputParams::PDFLATEX;
2187 string filename = latexName(false);
2188 filename = addName(temppath(), filename);
2189 filename = changeExtension(filename,
2190 formats.extension(backend_format));
2192 // Plain text backend
2193 if (backend_format == "text")
2194 writePlaintextFile(*this, FileName(filename), runparams);
2196 else if (backend_format == "lyx")
2197 writeFile(FileName(filename));
2199 else if (isDocBook()) {
2200 runparams.nice = !put_in_tempdir;
2201 makeDocBookFile(FileName(filename), runparams);
2204 else if (backend_format == format) {
2205 runparams.nice = true;
2206 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2208 } else if (!lyxrc.tex_allows_spaces
2209 && support::contains(filePath(), ' ')) {
2210 Alert::error(_("File name error"),
2211 _("The directory path to the document cannot contain spaces."));
2214 runparams.nice = false;
2215 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2219 string const error_type = (format == "program")
2220 ? "Build" : bufferFormat();
2221 string const ext = formats.extension(format);
2222 FileName const tmp_result_file(changeExtension(filename, ext));
2223 bool const success = theConverters().convert(this, FileName(filename),
2224 tmp_result_file, FileName(absFileName()), backend_format, format,
2225 errorList(error_type));
2226 // Emit the signal to show the error list.
2227 if (format != backend_format)
2233 result_file = tmp_result_file.absFilename();
2235 result_file = changeExtension(absFileName(), ext);
2236 // We need to copy referenced files (e. g. included graphics
2237 // if format == "dvi") to the result dir.
2238 vector<ExportedFile> const files =
2239 runparams.exportdata->externalFiles(format);
2240 string const dest = onlyPath(result_file);
2241 CopyStatus status = SUCCESS;
2242 for (vector<ExportedFile>::const_iterator it = files.begin();
2243 it != files.end() && status != CANCEL; ++it) {
2245 formats.getFormatFromFile(it->sourceName);
2246 status = copyFile(fmt, it->sourceName,
2247 makeAbsPath(it->exportName, dest),
2248 it->exportName, status == FORCE);
2250 if (status == CANCEL) {
2251 message(_("Document export cancelled."));
2252 } else if (tmp_result_file.exists()) {
2253 // Finally copy the main file
2254 status = copyFile(format, tmp_result_file,
2255 FileName(result_file), result_file,
2257 message(bformat(_("Document exported as %1$s "
2259 formats.prettyName(format),
2260 makeDisplayPath(result_file)));
2262 // This must be a dummy converter like fax (bug 1888)
2263 message(bformat(_("Document exported as %1$s"),
2264 formats.prettyName(format)));
2272 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2275 return doExport(format, put_in_tempdir, result_file);
2279 bool Buffer::preview(string const & format) const
2282 if (!doExport(format, true, result_file))
2284 return formats.view(*this, FileName(result_file), format);
2288 bool Buffer::isExportable(string const & format) const
2290 vector<string> backs = backends();
2291 for (vector<string>::const_iterator it = backs.begin();
2292 it != backs.end(); ++it)
2293 if (theConverters().isReachable(*it, format))
2299 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2301 vector<string> backs = backends();
2302 vector<Format const *> result =
2303 theConverters().getReachable(backs[0], only_viewable, true);
2304 for (vector<string>::const_iterator it = backs.begin() + 1;
2305 it != backs.end(); ++it) {
2306 vector<Format const *> r =
2307 theConverters().getReachable(*it, only_viewable, false);
2308 result.insert(result.end(), r.begin(), r.end());
2314 vector<string> Buffer::backends() const
2317 if (params().getTextClass().isTeXClassAvailable()) {
2318 v.push_back(bufferFormat());
2319 // FIXME: Don't hardcode format names here, but use a flag
2320 if (v.back() == "latex")
2321 v.push_back("pdflatex");
2323 v.push_back("text");
2329 bool Buffer::readFileHelper(FileName const & s)
2331 // File information about normal file
2333 docstring const file = makeDisplayPath(s.absFilename(), 50);
2334 docstring text = bformat(_("The specified document\n%1$s"
2335 "\ncould not be read."), file);
2336 Alert::error(_("Could not read document"), text);
2340 // Check if emergency save file exists and is newer.
2341 FileName const e(s.absFilename() + ".emergency");
2343 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2344 docstring const file = makeDisplayPath(s.absFilename(), 20);
2345 docstring const text =
2346 bformat(_("An emergency save of the document "
2348 "Recover emergency save?"), file);
2349 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2350 _("&Recover"), _("&Load Original"),
2354 // the file is not saved if we load the emergency file.
2364 // Now check if autosave file is newer.
2365 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2367 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2368 docstring const file = makeDisplayPath(s.absFilename(), 20);
2369 docstring const text =
2370 bformat(_("The backup of the document "
2371 "%1$s is newer.\n\nLoad the "
2372 "backup instead?"), file);
2373 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2374 _("&Load backup"), _("Load &original"),
2378 // the file is not saved if we load the autosave file.
2382 // Here we delete the autosave
2393 bool Buffer::loadLyXFile(FileName const & s)
2395 if (s.isReadableFile()) {
2396 if (readFileHelper(s)) {
2397 lyxvc().file_found_hook(s);
2398 if (!s.isWritable())
2403 docstring const file = makeDisplayPath(s.absFilename(), 20);
2404 // Here we probably should run
2405 if (LyXVC::file_not_found_hook(s)) {
2406 docstring const text =
2407 bformat(_("Do you want to retrieve the document"
2408 " %1$s from version control?"), file);
2409 int const ret = Alert::prompt(_("Retrieve from version control?"),
2410 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2413 // How can we know _how_ to do the checkout?
2414 // With the current VC support it has to be,
2415 // a RCS file since CVS do not have special ,v files.
2417 return loadLyXFile(s);
2425 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2427 TeXErrors::Errors::const_iterator cit = terr.begin();
2428 TeXErrors::Errors::const_iterator end = terr.end();
2430 for (; cit != end; ++cit) {
2433 int errorRow = cit->error_in_line;
2434 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2440 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2441 } while (found && id_start == id_end && pos_start == pos_end);
2443 errorList.push_back(ErrorItem(cit->error_desc,
2444 cit->error_text, id_start, pos_start, pos_end));