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>
111 using std::make_pair;
116 using std::ostringstream;
127 using support::addName;
128 using support::bformat;
129 using support::changeExtension;
130 using support::cmd_ret;
131 using support::createBufferTmpDir;
132 using support::FileName;
133 using support::FileNameList;
134 using support::libFileSearch;
135 using support::latex_path;
136 using support::ltrim;
137 using support::makeAbsPath;
138 using support::makeDisplayPath;
139 using support::makeLatexName;
140 using support::onlyFilename;
141 using support::onlyPath;
142 using support::quoteName;
143 using support::removeAutosaveFile;
144 using support::rename;
145 using support::runCommand;
146 using support::split;
147 using support::subst;
148 using support::tempName;
150 using support::suffixIs;
152 namespace Alert = frontend::Alert;
153 namespace os = support::os;
157 int const LYX_FORMAT = 306; // Uwe: support for Interlingua
162 typedef std::map<string, bool> DepClean;
167 Impl(Buffer & parent, FileName const & file, bool readonly);
180 mutable TexRow texrow;
181 Buffer const * parent_buffer;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this a unnamed file (New...)?
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
207 /// our Text that should be wrapped in an InsetText
211 mutable TocBackend toc_backend;
214 typedef std::map<unsigned int, MacroData, std::greater<int> > PositionToMacroMap;
215 typedef std::map<docstring, PositionToMacroMap> NameToPositionMacroMap;
216 NameToPositionMacroMap macros;
218 /// Container for all sort of Buffer dependant errors.
219 map<string, ErrorList> errorLists;
221 /// all embedded files of this buffer
222 EmbeddedFiles embedded_files;
224 /// timestamp and checksum used to test if the file has been externally
225 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
227 unsigned long checksum_;
230 frontend::WorkAreaManager * wa_;
235 /// A cache for the bibfiles (including bibfiles of loaded child
236 /// documents), needed for appropriate update of natbib labels.
237 mutable FileNameList bibfilesCache_;
241 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
242 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
243 read_only(readonly_), filename(file), file_fully_loaded(false),
244 inset(params), toc_backend(&parent), embedded_files(&parent),
245 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
247 inset.setAutoBreakRows(true);
248 lyxvc.setBuffer(&parent);
249 temppath = createBufferTmpDir();
251 // FIXME: And now do something if temppath == string(), because we
252 // assume from now on that temppath points to a valid temp dir.
253 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
256 wa_ = new frontend::WorkAreaManager;
260 Buffer::Buffer(string const & file, bool readonly)
261 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
263 LYXERR(Debug::INFO, "Buffer::Buffer()");
269 LYXERR(Debug::INFO, "Buffer::~Buffer()");
270 // here the buffer should take care that it is
271 // saved properly, before it goes into the void.
273 // GuiView already destroyed
276 Buffer const * master = masterBuffer();
277 if (master != this && use_gui)
278 // We are closing buf which was a child document so we
279 // must update the labels and section numbering of its master
281 updateLabels(*master);
283 resetChildDocuments(false);
285 if (!temppath().empty() && !FileName(temppath()).destroyDirectory()) {
286 Alert::warning(_("Could not remove temporary directory"),
287 bformat(_("Could not remove the temporary directory %1$s"),
288 from_utf8(temppath())));
291 // Remove any previewed LaTeX snippets associated with this buffer.
292 graphics::Previews::get().removeLoader(*this);
298 void Buffer::changed() const
305 frontend::WorkAreaManager & Buffer::workAreaManager() const
307 BOOST_ASSERT(d->wa_);
312 Text & Buffer::text() const
314 return const_cast<Text &>(d->inset.text_);
318 Inset & Buffer::inset() const
320 return const_cast<InsetText &>(d->inset);
324 BufferParams & Buffer::params()
330 BufferParams const & Buffer::params() const
336 ParagraphList & Buffer::paragraphs()
338 return text().paragraphs();
342 ParagraphList const & Buffer::paragraphs() const
344 return text().paragraphs();
348 LyXVC & Buffer::lyxvc()
354 LyXVC const & Buffer::lyxvc() const
360 string const & Buffer::temppath() const
366 TexRow const & Buffer::texrow() const
372 TocBackend & Buffer::tocBackend() const
374 return d->toc_backend;
378 EmbeddedFiles & Buffer::embeddedFiles()
380 return d->embedded_files;
384 EmbeddedFiles const & Buffer::embeddedFiles() const
386 return d->embedded_files;
390 Undo & Buffer::undo()
396 string Buffer::latexName(bool const no_path) const
398 FileName latex_name = makeLatexName(d->filename);
399 return no_path ? latex_name.onlyFileName()
400 : latex_name.absFilename();
404 string Buffer::logName(LogType * type) const
406 string const filename = latexName(false);
408 if (filename.empty()) {
414 string const path = temppath();
416 FileName const fname(addName(temppath(),
417 onlyFilename(changeExtension(filename,
419 FileName const bname(
420 addName(path, onlyFilename(
421 changeExtension(filename,
422 formats.extension("literate") + ".out"))));
424 // If no Latex log or Build log is newer, show Build log
426 if (bname.exists() &&
427 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
428 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
431 return bname.absFilename();
433 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
436 return fname.absFilename();
440 void Buffer::setReadonly(bool const flag)
442 if (d->read_only != flag) {
449 void Buffer::setFileName(string const & newfile)
451 d->filename = makeAbsPath(newfile);
452 setReadonly(d->filename.isReadOnly());
457 int Buffer::readHeader(Lexer & lex)
459 int unknown_tokens = 0;
461 int begin_header_line = -1;
463 // Initialize parameters that may be/go lacking in header:
464 params().branchlist().clear();
465 params().preamble.erase();
466 params().options.erase();
467 params().float_placement.erase();
468 params().paperwidth.erase();
469 params().paperheight.erase();
470 params().leftmargin.erase();
471 params().rightmargin.erase();
472 params().topmargin.erase();
473 params().bottommargin.erase();
474 params().headheight.erase();
475 params().headsep.erase();
476 params().footskip.erase();
477 params().listings_params.clear();
478 params().clearLayoutModules();
479 params().pdfoptions().clear();
481 for (int i = 0; i < 4; ++i) {
482 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
483 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
486 ErrorList & errorList = d->errorLists["Parse"];
490 string const token = lex.getString();
495 if (token == "\\end_header")
499 if (token == "\\begin_header") {
500 begin_header_line = line;
504 LYXERR(Debug::PARSER, "Handling document header token: `"
507 string unknown = params().readToken(lex, token, d->filename.onlyPath());
508 if (!unknown.empty()) {
509 if (unknown[0] != '\\' && token == "\\textclass") {
510 Alert::warning(_("Unknown document class"),
511 bformat(_("Using the default document class, because the "
512 "class %1$s is unknown."), from_utf8(unknown)));
515 docstring const s = bformat(_("Unknown token: "
519 errorList.push_back(ErrorItem(_("Document header error"),
524 if (begin_header_line) {
525 docstring const s = _("\\begin_header is missing");
526 errorList.push_back(ErrorItem(_("Document header error"),
530 return unknown_tokens;
535 // changed to be public and have one parameter
536 // Returns false if "\end_document" is not read (Asger)
537 bool Buffer::readDocument(Lexer & lex)
539 ErrorList & errorList = d->errorLists["Parse"];
543 string const token = lex.getString();
544 if (token != "\\begin_document") {
545 docstring const s = _("\\begin_document is missing");
546 errorList.push_back(ErrorItem(_("Document header error"),
550 // we are reading in a brand new document
551 BOOST_ASSERT(paragraphs().empty());
554 TextClass const & baseClass = textclasslist[params().getBaseClass()];
555 if (!baseClass.load(filePath())) {
556 string theclass = baseClass.name();
557 Alert::error(_("Can't load document class"), bformat(
558 _("Using the default document class, because the "
559 "class %1$s could not be loaded."), from_utf8(theclass)));
560 params().setBaseClass(defaultTextclass());
563 if (params().outputChanges) {
564 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
565 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
566 LaTeXFeatures::isAvailable("xcolor");
568 if (!dvipost && !xcolorsoul) {
569 Alert::warning(_("Changes not shown in LaTeX output"),
570 _("Changes will not be highlighted in LaTeX output, "
571 "because neither dvipost nor xcolor/soul are installed.\n"
572 "Please install these packages or redefine "
573 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
574 } else if (!xcolorsoul) {
575 Alert::warning(_("Changes not shown in LaTeX output"),
576 _("Changes will not be highlighted in LaTeX output "
577 "when using pdflatex, because xcolor and soul are not installed.\n"
578 "Please install both packages or redefine "
579 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
584 bool const res = text().read(*this, lex, errorList);
585 for_each(text().paragraphs().begin(),
586 text().paragraphs().end(),
587 bind(&Paragraph::setInsetOwner, _1, &inset()));
593 // needed to insert the selection
594 void Buffer::insertStringAsLines(ParagraphList & pars,
595 pit_type & pit, pos_type & pos,
596 Font const & fn, docstring const & str, bool autobreakrows)
600 // insert the string, don't insert doublespace
601 bool space_inserted = true;
602 for (docstring::const_iterator cit = str.begin();
603 cit != str.end(); ++cit) {
604 Paragraph & par = pars[pit];
606 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
607 breakParagraph(params(), pars, pit, pos,
608 par.layout()->isEnvironment());
611 space_inserted = true;
615 // do not insert consecutive spaces if !free_spacing
616 } else if ((*cit == ' ' || *cit == '\t') &&
617 space_inserted && !par.isFreeSpacing()) {
619 } else if (*cit == '\t') {
620 if (!par.isFreeSpacing()) {
621 // tabs are like spaces here
622 par.insertChar(pos, ' ', font, params().trackChanges);
624 space_inserted = true;
626 const pos_type n = 8 - pos % 8;
627 for (pos_type i = 0; i < n; ++i) {
628 par.insertChar(pos, ' ', font, params().trackChanges);
631 space_inserted = true;
633 } else if (!isPrintable(*cit)) {
634 // Ignore unprintables
637 // just insert the character
638 par.insertChar(pos, *cit, font, params().trackChanges);
640 space_inserted = (*cit == ' ');
647 bool Buffer::readString(std::string const & s)
649 params().compressed = false;
651 // remove dummy empty par
652 paragraphs().clear();
654 std::istringstream is(s);
656 FileName const name(tempName());
657 switch (readFile(lex, name, true)) {
661 // We need to call lyx2lyx, so write the input to a file
662 std::ofstream os(name.toFilesystemEncoding().c_str());
665 return readFile(name);
675 bool Buffer::readFile(FileName const & filename)
677 FileName fname(filename);
678 // Check if the file is compressed.
679 string format = filename.guessFormatFromContents();
680 if (format == "zip") {
681 // decompress to a temp directory
682 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
683 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
685 FileName lyxfile(addName(temppath(), "content.lyx"));
686 // if both manifest.txt and file.lyx exist, this is am embedded file
687 if (lyxfile.exists()) {
688 params().embedded = true;
692 // The embedded lyx file can also be compressed, for backward compatibility
693 format = fname.guessFormatFromContents();
694 if (format == "gzip" || format == "zip" || format == "compress")
695 params().compressed = true;
697 // remove dummy empty par
698 paragraphs().clear();
701 if (readFile(lex, fname) != success)
708 bool Buffer::isFullyLoaded() const
710 return d->file_fully_loaded;
714 void Buffer::setFullyLoaded(bool value)
716 d->file_fully_loaded = value;
720 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
723 BOOST_ASSERT(!filename.empty());
726 Alert::error(_("Document could not be read"),
727 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
732 string const token = lex.getString();
735 Alert::error(_("Document could not be read"),
736 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
740 // the first token _must_ be...
741 if (token != "\\lyxformat") {
742 lyxerr << "Token: " << token << endl;
744 Alert::error(_("Document format failure"),
745 bformat(_("%1$s is not a LyX document."),
746 from_utf8(filename.absFilename())));
751 string tmp_format = lex.getString();
752 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
753 // if present remove ".," from string.
754 string::size_type dot = tmp_format.find_first_of(".,");
755 //lyxerr << " dot found at " << dot << endl;
756 if (dot != string::npos)
757 tmp_format.erase(dot, 1);
758 int const file_format = convert<int>(tmp_format);
759 //lyxerr << "format: " << file_format << endl;
761 // save timestamp and checksum of the original disk file, making sure
762 // to not overwrite them with those of the file created in the tempdir
763 // when it has to be converted to the current format.
765 // Save the timestamp and checksum of disk file. If filename is an
766 // emergency file, save the timestamp and checksum of the original lyx file
767 // because isExternallyModified will check for this file. (BUG4193)
768 string diskfile = filename.absFilename();
769 if (suffixIs(diskfile, ".emergency"))
770 diskfile = diskfile.substr(0, diskfile.size() - 10);
771 saveCheckSum(FileName(diskfile));
774 if (file_format != LYX_FORMAT) {
777 // lyx2lyx would fail
780 FileName const tmpfile(tempName());
781 if (tmpfile.empty()) {
782 Alert::error(_("Conversion failed"),
783 bformat(_("%1$s is from a different"
784 " version of LyX, but a temporary"
785 " file for converting it could"
787 from_utf8(filename.absFilename())));
790 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
791 if (lyx2lyx.empty()) {
792 Alert::error(_("Conversion script not found"),
793 bformat(_("%1$s is from a different"
794 " version of LyX, but the"
795 " conversion script lyx2lyx"
796 " could not be found."),
797 from_utf8(filename.absFilename())));
800 ostringstream command;
801 command << os::python()
802 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
803 << " -t " << convert<string>(LYX_FORMAT)
804 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
805 << ' ' << quoteName(filename.toFilesystemEncoding());
806 string const command_str = command.str();
808 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
810 cmd_ret const ret = runCommand(command_str);
811 if (ret.first != 0) {
812 Alert::error(_("Conversion script failed"),
813 bformat(_("%1$s is from a different version"
814 " of LyX, but the lyx2lyx script"
815 " failed to convert it."),
816 from_utf8(filename.absFilename())));
819 bool const ret = readFile(tmpfile);
820 // Do stuff with tmpfile name and buffer name here.
821 return ret ? success : failure;
826 if (readDocument(lex)) {
827 Alert::error(_("Document format failure"),
828 bformat(_("%1$s ended unexpectedly, which means"
829 " that it is probably corrupted."),
830 from_utf8(filename.absFilename())));
833 d->file_fully_loaded = true;
838 // Should probably be moved to somewhere else: BufferView? LyXView?
839 bool Buffer::save() const
841 // We don't need autosaves in the immediate future. (Asger)
842 resetAutosaveTimers();
844 string const encodedFilename = d->filename.toFilesystemEncoding();
847 bool madeBackup = false;
849 // make a backup if the file already exists
850 if (lyxrc.make_backup && fileName().exists()) {
851 backupName = FileName(absFileName() + '~');
852 if (!lyxrc.backupdir_path.empty()) {
853 string const mangledName =
854 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
855 backupName = FileName(addName(lyxrc.backupdir_path,
858 if (fileName().copyTo(backupName, true)) {
861 Alert::error(_("Backup failure"),
862 bformat(_("Cannot create backup file %1$s.\n"
863 "Please check whether the directory exists and is writeable."),
864 from_utf8(backupName.absFilename())));
865 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
869 // ask if the disk file has been externally modified (use checksum method)
870 if (fileName().exists() && isExternallyModified(checksum_method)) {
871 docstring const file = makeDisplayPath(absFileName(), 20);
872 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
873 "you want to overwrite this file?"), file);
874 int const ret = Alert::prompt(_("Overwrite modified file?"),
875 text, 1, 1, _("&Overwrite"), _("&Cancel"));
880 if (writeFile(d->filename)) {
884 // Saving failed, so backup is not backup
886 rename(backupName, d->filename);
892 bool Buffer::writeFile(FileName const & fname) const
894 if (d->read_only && fname == d->filename)
900 if (params().embedded)
901 // first write the .lyx file to the temporary directory
902 content = FileName(addName(temppath(), "content.lyx"));
906 docstring const str = bformat(_("Saving document %1$s..."),
907 makeDisplayPath(content.absFilename()));
910 if (params().compressed) {
911 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
912 retval = ofs && write(ofs);
914 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
915 retval = ofs && write(ofs);
919 message(str + _(" could not write file!."));
923 removeAutosaveFile(d->filename.absFilename());
924 saveCheckSum(d->filename);
925 message(str + _(" done."));
927 if (!params().embedded)
930 message(str + _(" writing embedded files!."));
931 // if embedding is enabled, write file.lyx and all the embedded files
932 // to the zip file fname.
933 if (!d->embedded_files.writeFile(fname)) {
934 message(str + _(" could not write embedded files!."));
937 message(str + _(" error while writing embedded files."));
942 bool Buffer::write(ostream & ofs) const
945 // Use the standard "C" locale for file output.
946 ofs.imbue(std::locale::classic());
949 // The top of the file should not be written by params().
951 // write out a comment in the top of the file
952 ofs << "#LyX " << lyx_version
953 << " created this file. For more info see http://www.lyx.org/\n"
954 << "\\lyxformat " << LYX_FORMAT << "\n"
955 << "\\begin_document\n";
958 /// For each author, set 'used' to true if there is a change
959 /// by this author in the document; otherwise set it to 'false'.
960 AuthorList::Authors::const_iterator a_it = params().authors().begin();
961 AuthorList::Authors::const_iterator a_end = params().authors().end();
962 for (; a_it != a_end; ++a_it)
963 a_it->second.setUsed(false);
965 ParIterator const end = par_iterator_end();
966 ParIterator it = par_iterator_begin();
967 for ( ; it != end; ++it)
968 it->checkAuthors(params().authors());
970 // now write out the buffer parameters.
971 ofs << "\\begin_header\n";
972 params().writeFile(ofs);
973 ofs << "\\end_header\n";
976 ofs << "\n\\begin_body\n";
977 text().write(*this, ofs);
978 ofs << "\n\\end_body\n";
980 // Write marker that shows file is complete
981 ofs << "\\end_document" << endl;
983 // Shouldn't really be needed....
986 // how to check if close went ok?
987 // Following is an attempt... (BE 20001011)
989 // good() returns false if any error occured, including some
991 // bad() returns true if something bad happened in the buffer,
992 // which should include file system full errors.
997 lyxerr << "File was not closed properly." << endl;
1004 bool Buffer::makeLaTeXFile(FileName const & fname,
1005 string const & original_path,
1006 OutputParams const & runparams,
1007 bool output_preamble, bool output_body) const
1009 string const encoding = runparams.encoding->iconvName();
1010 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1013 try { ofs.reset(encoding); }
1014 catch (iconv_codecvt_facet_exception & e) {
1015 lyxerr << "Caught iconv exception: " << e.what() << endl;
1016 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1017 "verify that the support software for your encoding (%1$s) is "
1018 "properly installed"), from_ascii(encoding)));
1021 if (!openFileWrite(ofs, fname))
1024 //TexStream ts(ofs.rdbuf(), &texrow());
1026 bool failed_export = false;
1029 writeLaTeXSource(ofs, original_path,
1030 runparams, output_preamble, output_body);
1032 catch (iconv_codecvt_facet_exception & e) {
1033 lyxerr << "Caught iconv exception: " << e.what() << endl;
1034 failed_export = true;
1036 catch (std::exception const & e) {
1037 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1038 failed_export = true;
1041 lyxerr << "Caught some really weird exception..." << endl;
1042 LyX::cref().emergencyCleanup();
1048 failed_export = true;
1049 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1052 if (failed_export) {
1053 Alert::error(_("Encoding error"),
1054 _("Some characters of your document are probably not "
1055 "representable in the chosen encoding.\n"
1056 "Changing the document encoding to utf8 could help."));
1063 void Buffer::writeLaTeXSource(odocstream & os,
1064 string const & original_path,
1065 OutputParams const & runparams_in,
1066 bool const output_preamble, bool const output_body) const
1068 OutputParams runparams = runparams_in;
1070 // validate the buffer.
1071 LYXERR(Debug::LATEX, " Validating buffer...");
1072 LaTeXFeatures features(*this, params(), runparams);
1074 LYXERR(Debug::LATEX, " Buffer validation done.");
1076 // The starting paragraph of the coming rows is the
1077 // first paragraph of the document. (Asger)
1078 if (output_preamble && runparams.nice) {
1079 os << "%% LyX " << lyx_version << " created this file. "
1080 "For more info, see http://www.lyx.org/.\n"
1081 "%% Do not edit unless you really know what "
1083 d->texrow.newline();
1084 d->texrow.newline();
1086 LYXERR(Debug::INFO, "lyx document header finished");
1087 // There are a few differences between nice LaTeX and usual files:
1088 // usual is \batchmode and has a
1089 // special input@path to allow the including of figures
1090 // with either \input or \includegraphics (what figinsets do).
1091 // input@path is set when the actual parameter
1092 // original_path is set. This is done for usual tex-file, but not
1093 // for nice-latex-file. (Matthias 250696)
1094 // Note that input@path is only needed for something the user does
1095 // in the preamble, included .tex files or ERT, files included by
1096 // LyX work without it.
1097 if (output_preamble) {
1098 if (!runparams.nice) {
1099 // code for usual, NOT nice-latex-file
1100 os << "\\batchmode\n"; // changed
1101 // from \nonstopmode
1102 d->texrow.newline();
1104 if (!original_path.empty()) {
1106 // We don't know the encoding of inputpath
1107 docstring const inputpath = from_utf8(latex_path(original_path));
1108 os << "\\makeatletter\n"
1109 << "\\def\\input@path{{"
1110 << inputpath << "/}}\n"
1111 << "\\makeatother\n";
1112 d->texrow.newline();
1113 d->texrow.newline();
1114 d->texrow.newline();
1117 // Write the preamble
1118 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1124 os << "\\begin{document}\n";
1125 d->texrow.newline();
1126 } // output_preamble
1128 d->texrow.start(paragraphs().begin()->id(), 0);
1130 LYXERR(Debug::INFO, "preamble finished, now the body.");
1132 if (!lyxrc.language_auto_begin &&
1133 !params().language->babel().empty()) {
1135 os << from_utf8(subst(lyxrc.language_command_begin,
1137 params().language->babel()))
1139 d->texrow.newline();
1142 Encoding const & encoding = params().encoding();
1143 if (encoding.package() == Encoding::CJK) {
1144 // Open a CJK environment, since in contrast to the encodings
1145 // handled by inputenc the document encoding is not set in
1146 // the preamble if it is handled by CJK.sty.
1147 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1149 d->texrow.newline();
1152 // if we are doing a real file with body, even if this is the
1153 // child of some other buffer, let's cut the link here.
1154 // This happens for example if only a child document is printed.
1155 Buffer const * save_parent = 0;
1156 if (output_preamble) {
1157 save_parent = d->parent_buffer;
1158 d->parent_buffer = 0;
1161 loadChildDocuments();
1164 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1166 // Restore the parenthood if needed
1167 if (output_preamble)
1168 d->parent_buffer = save_parent;
1170 // add this just in case after all the paragraphs
1172 d->texrow.newline();
1174 if (encoding.package() == Encoding::CJK) {
1175 // Close the open CJK environment.
1176 // latexParagraphs will have opened one even if the last text
1178 os << "\\end{CJK}\n";
1179 d->texrow.newline();
1182 if (!lyxrc.language_auto_end &&
1183 !params().language->babel().empty()) {
1184 os << from_utf8(subst(lyxrc.language_command_end,
1186 params().language->babel()))
1188 d->texrow.newline();
1191 if (output_preamble) {
1192 os << "\\end{document}\n";
1193 d->texrow.newline();
1194 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1196 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1198 runparams_in.encoding = runparams.encoding;
1200 // Just to be sure. (Asger)
1201 d->texrow.newline();
1203 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1204 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1208 bool Buffer::isLatex() const
1210 return params().getTextClass().outputType() == LATEX;
1214 bool Buffer::isLiterate() const
1216 return params().getTextClass().outputType() == LITERATE;
1220 bool Buffer::isDocBook() const
1222 return params().getTextClass().outputType() == DOCBOOK;
1226 void Buffer::makeDocBookFile(FileName const & fname,
1227 OutputParams const & runparams,
1228 bool const body_only) const
1230 LYXERR(Debug::LATEX, "makeDocBookFile...");
1234 if (!openFileWrite(ofs, fname))
1237 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1241 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1245 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1246 OutputParams const & runparams,
1247 bool const only_body) const
1249 LaTeXFeatures features(*this, params(), runparams);
1254 TextClass const & tclass = params().getTextClass();
1255 string const top_element = tclass.latexname();
1258 if (runparams.flavor == OutputParams::XML)
1259 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1262 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1265 if (! tclass.class_header().empty())
1266 os << from_ascii(tclass.class_header());
1267 else if (runparams.flavor == OutputParams::XML)
1268 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1269 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1271 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1273 docstring preamble = from_utf8(params().preamble);
1274 if (runparams.flavor != OutputParams::XML ) {
1275 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1276 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1277 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1278 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1281 string const name = runparams.nice
1282 ? changeExtension(absFileName(), ".sgml") : fname;
1283 preamble += features.getIncludedFiles(name);
1284 preamble += features.getLyXSGMLEntities();
1286 if (!preamble.empty()) {
1287 os << "\n [ " << preamble << " ]";
1292 string top = top_element;
1294 if (runparams.flavor == OutputParams::XML)
1295 top += params().language->code();
1297 top += params().language->code().substr(0,2);
1300 if (!params().options.empty()) {
1302 top += params().options;
1305 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1306 << " file was created by LyX " << lyx_version
1307 << "\n See http://www.lyx.org/ for more information -->\n";
1309 params().getTextClass().counters().reset();
1311 loadChildDocuments();
1313 sgml::openTag(os, top);
1315 docbookParagraphs(paragraphs(), *this, os, runparams);
1316 sgml::closeTag(os, top_element);
1320 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1321 // Other flags: -wall -v0 -x
1322 int Buffer::runChktex()
1326 // get LaTeX-Filename
1327 FileName const path(temppath());
1328 string const name = addName(path.absFilename(), latexName());
1329 string const org_path = filePath();
1331 support::PathChanger p(path); // path to LaTeX file
1332 message(_("Running chktex..."));
1334 // Generate the LaTeX file if neccessary
1335 OutputParams runparams(¶ms().encoding());
1336 runparams.flavor = OutputParams::LATEX;
1337 runparams.nice = false;
1338 makeLaTeXFile(FileName(name), org_path, runparams);
1341 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1342 int const res = chktex.run(terr); // run chktex
1345 Alert::error(_("chktex failure"),
1346 _("Could not run chktex successfully."));
1347 } else if (res > 0) {
1348 ErrorList & errlist = d->errorLists["ChkTeX"];
1350 bufferErrors(terr, errlist);
1361 void Buffer::validate(LaTeXFeatures & features) const
1363 TextClass const & tclass = params().getTextClass();
1365 if (params().outputChanges) {
1366 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1367 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1368 LaTeXFeatures::isAvailable("xcolor");
1370 if (features.runparams().flavor == OutputParams::LATEX) {
1372 features.require("ct-dvipost");
1373 features.require("dvipost");
1374 } else if (xcolorsoul) {
1375 features.require("ct-xcolor-soul");
1376 features.require("soul");
1377 features.require("xcolor");
1379 features.require("ct-none");
1381 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1383 features.require("ct-xcolor-soul");
1384 features.require("soul");
1385 features.require("xcolor");
1386 features.require("pdfcolmk"); // improves color handling in PDF output
1388 features.require("ct-none");
1393 // AMS Style is at document level
1394 if (params().use_amsmath == BufferParams::package_on
1395 || tclass.provides("amsmath"))
1396 features.require("amsmath");
1397 if (params().use_esint == BufferParams::package_on)
1398 features.require("esint");
1400 loadChildDocuments();
1402 for_each(paragraphs().begin(), paragraphs().end(),
1403 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1405 // the bullet shapes are buffer level not paragraph level
1406 // so they are tested here
1407 for (int i = 0; i < 4; ++i) {
1408 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1409 int const font = params().user_defined_bullet(i).getFont();
1411 int const c = params()
1412 .user_defined_bullet(i)
1419 features.require("latexsym");
1421 } else if (font == 1) {
1422 features.require("amssymb");
1423 } else if ((font >= 2 && font <= 5)) {
1424 features.require("pifont");
1429 if (lyxerr.debugging(Debug::LATEX)) {
1430 features.showStruct();
1435 void Buffer::getLabelList(vector<docstring> & list) const
1437 /// if this is a child document and the parent is already loaded
1438 /// Use the parent's list instead [ale990407]
1439 Buffer const * tmp = masterBuffer();
1441 lyxerr << "masterBuffer() failed!" << endl;
1445 tmp->getLabelList(list);
1449 loadChildDocuments();
1451 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1452 it.nextInset()->getLabelList(*this, list);
1456 void Buffer::updateBibfilesCache() const
1458 // if this is a child document and the parent is already loaded
1459 // update the parent's cache instead
1460 Buffer const * tmp = masterBuffer();
1463 tmp->updateBibfilesCache();
1467 d->bibfilesCache_.clear();
1468 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1469 if (it->lyxCode() == BIBTEX_CODE) {
1470 InsetBibtex const & inset =
1471 static_cast<InsetBibtex const &>(*it);
1472 FileNameList const bibfiles = inset.getFiles(*this);
1473 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1476 } else if (it->lyxCode() == INCLUDE_CODE) {
1477 InsetInclude & inset =
1478 static_cast<InsetInclude &>(*it);
1479 inset.updateBibfilesCache(*this);
1480 FileNameList const & bibfiles =
1481 inset.getBibfilesCache(*this);
1482 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1490 FileNameList const & Buffer::getBibfilesCache() const
1492 // if this is a child document and the parent is already loaded
1493 // use the parent's cache instead
1494 Buffer const * tmp = masterBuffer();
1497 return tmp->getBibfilesCache();
1499 // We update the cache when first used instead of at loading time.
1500 if (d->bibfilesCache_.empty())
1501 const_cast<Buffer *>(this)->updateBibfilesCache();
1503 return d->bibfilesCache_;
1507 bool Buffer::isDepClean(string const & name) const
1509 DepClean::const_iterator const it = d->dep_clean.find(name);
1510 if (it == d->dep_clean.end())
1516 void Buffer::markDepClean(string const & name)
1518 d->dep_clean[name] = true;
1522 bool Buffer::dispatch(string const & command, bool * result)
1524 return dispatch(lyxaction.lookupFunc(command), result);
1528 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1530 bool dispatched = true;
1532 switch (func.action) {
1533 case LFUN_BUFFER_EXPORT: {
1534 bool const tmp = doExport(to_utf8(func.argument()), false);
1547 void Buffer::changeLanguage(Language const * from, Language const * to)
1552 for_each(par_iterator_begin(),
1554 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1558 bool Buffer::isMultiLingual() const
1560 ParConstIterator end = par_iterator_end();
1561 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1562 if (it->isMultiLingual(params()))
1569 ParIterator Buffer::getParFromID(int const id) const
1571 ParConstIterator it = par_iterator_begin();
1572 ParConstIterator const end = par_iterator_end();
1575 // John says this is called with id == -1 from undo
1576 lyxerr << "getParFromID(), id: " << id << endl;
1580 for (; it != end; ++it)
1588 bool Buffer::hasParWithID(int const id) const
1590 ParConstIterator const it = getParFromID(id);
1591 return it != par_iterator_end();
1595 ParIterator Buffer::par_iterator_begin()
1597 return lyx::par_iterator_begin(inset());
1601 ParIterator Buffer::par_iterator_end()
1603 return lyx::par_iterator_end(inset());
1607 ParConstIterator Buffer::par_iterator_begin() const
1609 return lyx::par_const_iterator_begin(inset());
1613 ParConstIterator Buffer::par_iterator_end() const
1615 return lyx::par_const_iterator_end(inset());
1619 Language const * Buffer::language() const
1621 return params().language;
1625 docstring const Buffer::B_(string const & l10n) const
1627 return params().B_(l10n);
1631 bool Buffer::isClean() const
1633 return d->lyx_clean;
1637 bool Buffer::isBakClean() const
1639 return d->bak_clean;
1643 bool Buffer::isExternallyModified(CheckMethod method) const
1645 BOOST_ASSERT(d->filename.exists());
1646 // if method == timestamp, check timestamp before checksum
1647 return (method == checksum_method
1648 || d->timestamp_ != d->filename.lastModified())
1649 && d->checksum_ != d->filename.checksum();
1653 void Buffer::saveCheckSum(FileName const & file) const
1655 if (file.exists()) {
1656 d->timestamp_ = file.lastModified();
1657 d->checksum_ = file.checksum();
1659 // in the case of save to a new file.
1666 void Buffer::markClean() const
1668 if (!d->lyx_clean) {
1669 d->lyx_clean = true;
1672 // if the .lyx file has been saved, we don't need an
1674 d->bak_clean = true;
1678 void Buffer::markBakClean() const
1680 d->bak_clean = true;
1684 void Buffer::setUnnamed(bool flag)
1690 bool Buffer::isUnnamed() const
1696 // FIXME: this function should be moved to buffer_pimpl.C
1697 void Buffer::markDirty()
1700 d->lyx_clean = false;
1703 d->bak_clean = false;
1705 DepClean::iterator it = d->dep_clean.begin();
1706 DepClean::const_iterator const end = d->dep_clean.end();
1708 for (; it != end; ++it)
1713 FileName Buffer::fileName() const
1719 string Buffer::absFileName() const
1721 return d->filename.absFilename();
1725 string Buffer::filePath() const
1727 return d->filename.onlyPath().absFilename();
1731 bool Buffer::isReadonly() const
1733 return d->read_only;
1737 void Buffer::setParent(Buffer const * buffer)
1739 // Avoids recursive include.
1740 d->parent_buffer = buffer == this ? 0 : buffer;
1744 Buffer const * Buffer::parent()
1746 return d->parent_buffer;
1750 Buffer const * Buffer::masterBuffer() const
1752 if (!d->parent_buffer)
1755 return d->parent_buffer->masterBuffer();
1759 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1761 Impl::PositionToMacroMap::iterator it;
1762 it = d->macros[name].upper_bound(par.macrocontextPosition());
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->hasMacro(name);
1771 return MacroTable::globalMacros().has(name);
1775 bool Buffer::hasMacro(docstring const & name) const
1777 if( !d->macros[name].empty() )
1780 // If there is a master buffer, query that
1781 Buffer const * master = masterBuffer();
1782 if (master && master != this)
1783 return master->hasMacro(name);
1785 return MacroTable::globalMacros().has(name);
1789 MacroData const & Buffer::getMacro(docstring const & name,
1790 Paragraph const & par) const
1792 Impl::PositionToMacroMap::iterator it;
1793 it = d->macros[name].upper_bound(par.macrocontextPosition());
1794 if( it != d->macros[name].end() )
1797 // If there is a master buffer, query that
1798 Buffer const * master = masterBuffer();
1799 if (master && master != this)
1800 return master->getMacro(name);
1802 return MacroTable::globalMacros().get(name);
1806 MacroData const & Buffer::getMacro(docstring const & name) const
1808 Impl::PositionToMacroMap::iterator it;
1809 it = d->macros[name].begin();
1810 if( it != d->macros[name].end() )
1813 // If there is a master buffer, query that
1814 Buffer const * master = masterBuffer();
1815 if (master && master != this)
1816 return master->getMacro(name);
1818 return MacroTable::globalMacros().get(name);
1822 void Buffer::updateMacros()
1824 // start with empty table
1825 d->macros = Impl::NameToPositionMacroMap();
1827 // Iterate over buffer
1828 ParagraphList & pars = text().paragraphs();
1829 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1830 // set position again
1831 pars[i].setMacrocontextPosition(i);
1833 //lyxerr << "searching main par " << i
1834 // << " for macro definitions" << std::endl;
1835 InsetList const & insets = pars[i].insetList();
1836 InsetList::const_iterator it = insets.begin();
1837 InsetList::const_iterator end = insets.end();
1838 for ( ; it != end; ++it) {
1839 if (it->inset->lyxCode() != MATHMACRO_CODE)
1843 MathMacroTemplate const & macroTemplate
1844 = static_cast<MathMacroTemplate const &>(*it->inset);
1847 if (macroTemplate.validMacro()) {
1848 MacroData macro = macroTemplate.asMacroData();
1851 // call hasMacro here instead of directly querying mc to
1852 // also take the master document into consideration
1853 macro.setRedefinition(hasMacro(macroTemplate.name()));
1855 // register macro (possibly overwrite the previous one of this paragraph)
1856 d->macros[macroTemplate.name()][i] = macro;
1863 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1866 //FIXME: This does not work for child documents yet.
1867 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1868 // Check if the label 'from' appears more than once
1869 vector<docstring> labels;
1872 if (code == CITE_CODE) {
1874 keys.fillWithBibKeys(this);
1875 BiblioInfo::const_iterator bit = keys.begin();
1876 BiblioInfo::const_iterator bend = keys.end();
1878 for (; bit != bend; ++bit)
1880 labels.push_back(bit->first);
1883 getLabelList(labels);
1884 paramName = "reference";
1887 if (std::count(labels.begin(), labels.end(), from) > 1)
1890 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1891 if (it->lyxCode() == code) {
1892 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1893 docstring const oldValue = inset.getParam(paramName);
1894 if (oldValue == from)
1895 inset.setParam(paramName, to);
1901 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1902 pit_type par_end, bool full_source)
1904 OutputParams runparams(¶ms().encoding());
1905 runparams.nice = true;
1906 runparams.flavor = OutputParams::LATEX;
1907 runparams.linelen = lyxrc.plaintext_linelen;
1908 // No side effect of file copying and image conversion
1909 runparams.dryrun = true;
1913 os << "% " << _("Preview source code") << "\n\n";
1914 d->texrow.newline();
1915 d->texrow.newline();
1917 writeLaTeXSource(os, filePath(), runparams, true, true);
1919 writeDocBookSource(os, absFileName(), runparams, false);
1922 runparams.par_begin = par_begin;
1923 runparams.par_end = par_end;
1924 if (par_begin + 1 == par_end)
1926 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1930 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1931 convert<docstring>(par_begin),
1932 convert<docstring>(par_end - 1))
1934 d->texrow.newline();
1935 d->texrow.newline();
1936 // output paragraphs
1938 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1941 docbookParagraphs(paragraphs(), *this, os, runparams);
1947 ErrorList & Buffer::errorList(string const & type) const
1949 static ErrorList emptyErrorList;
1950 std::map<string, ErrorList>::iterator I = d->errorLists.find(type);
1951 if (I == d->errorLists.end())
1952 return emptyErrorList;
1958 void Buffer::structureChanged() const
1961 gui_->structureChanged();
1965 void Buffer::errors(std::string const & err) const
1972 void Buffer::message(docstring const & msg) const
1979 void Buffer::setBusy(bool on) const
1986 void Buffer::setReadOnly(bool on) const
1989 d->wa_->setReadOnly(on);
1993 void Buffer::updateTitles() const
1996 d->wa_->updateTitles();
2000 void Buffer::resetAutosaveTimers() const
2003 gui_->resetAutosaveTimers();
2007 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2016 class AutoSaveBuffer : public support::ForkedProcess {
2019 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2020 : buffer_(buffer), fname_(fname) {}
2022 virtual boost::shared_ptr<ForkedProcess> clone() const
2024 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2029 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2030 from_utf8(fname_.absFilename())));
2031 return run(DontWait);
2035 virtual int generateChild();
2037 Buffer const & buffer_;
2042 #if !defined (HAVE_FORK)
2046 int AutoSaveBuffer::generateChild()
2048 // tmp_ret will be located (usually) in /tmp
2049 // will that be a problem?
2050 pid_t const pid = fork();
2051 // If you want to debug the autosave
2052 // you should set pid to -1, and comment out the fork.
2053 if (pid == 0 || pid == -1) {
2054 // pid = -1 signifies that lyx was unable
2055 // to fork. But we will do the save
2057 bool failed = false;
2059 FileName const tmp_ret(tempName(FileName(), "lyxauto"));
2060 if (!tmp_ret.empty()) {
2061 buffer_.writeFile(tmp_ret);
2062 // assume successful write of tmp_ret
2063 if (!rename(tmp_ret, fname_)) {
2065 // most likely couldn't move between
2066 // filesystems unless write of tmp_ret
2067 // failed so remove tmp file (if it
2069 tmp_ret.removeFile();
2076 // failed to write/rename tmp_ret so try writing direct
2077 if (!buffer_.writeFile(fname_)) {
2078 // It is dangerous to do this in the child,
2079 // but safe in the parent, so...
2080 if (pid == -1) // emit message signal.
2081 buffer_.message(_("Autosave failed!"));
2084 if (pid == 0) { // we are the child so...
2094 // Perfect target for a thread...
2095 void Buffer::autoSave() const
2097 if (isBakClean() || isReadonly()) {
2098 // We don't save now, but we'll try again later
2099 resetAutosaveTimers();
2103 // emit message signal.
2104 message(_("Autosaving current document..."));
2106 // create autosave filename
2107 string fname = filePath();
2109 fname += d->filename.onlyFileName();
2112 AutoSaveBuffer autosave(*this, FileName(fname));
2116 resetAutosaveTimers();
2120 void Buffer::resetChildDocuments(bool close_them) const
2122 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2123 if (it->lyxCode() != INCLUDE_CODE)
2125 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2126 InsetCommandParams const & ip = inset.params();
2128 resetParentBuffer(this, ip, close_them);
2131 if (use_gui && masterBuffer() == this)
2132 updateLabels(*this);
2136 void Buffer::loadChildDocuments() const
2138 bool parse_error = false;
2140 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2141 if (it->lyxCode() != INCLUDE_CODE)
2143 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2144 InsetCommandParams const & ip = inset.params();
2145 Buffer * child = loadIfNeeded(*this, ip);
2148 parse_error |= !child->errorList("Parse").empty();
2149 child->loadChildDocuments();
2152 if (use_gui && masterBuffer() == this)
2153 updateLabels(*this);
2157 string Buffer::bufferFormat() const
2167 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2168 string & result_file) const
2170 string backend_format;
2171 OutputParams runparams(¶ms().encoding());
2172 runparams.flavor = OutputParams::LATEX;
2173 runparams.linelen = lyxrc.plaintext_linelen;
2174 vector<string> backs = backends();
2175 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2176 // Get shortest path to format
2177 Graph::EdgePath path;
2178 for (vector<string>::const_iterator it = backs.begin();
2179 it != backs.end(); ++it) {
2180 Graph::EdgePath p = theConverters().getPath(*it, format);
2181 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2182 backend_format = *it;
2187 runparams.flavor = theConverters().getFlavor(path);
2189 Alert::error(_("Couldn't export file"),
2190 bformat(_("No information for exporting the format %1$s."),
2191 formats.prettyName(format)));
2195 backend_format = format;
2196 // FIXME: Don't hardcode format names here, but use a flag
2197 if (backend_format == "pdflatex")
2198 runparams.flavor = OutputParams::PDFLATEX;
2201 string filename = latexName(false);
2202 filename = addName(temppath(), filename);
2203 filename = changeExtension(filename,
2204 formats.extension(backend_format));
2206 // Plain text backend
2207 if (backend_format == "text")
2208 writePlaintextFile(*this, FileName(filename), runparams);
2210 else if (backend_format == "lyx")
2211 writeFile(FileName(filename));
2213 else if (isDocBook()) {
2214 runparams.nice = !put_in_tempdir;
2215 makeDocBookFile(FileName(filename), runparams);
2218 else if (backend_format == format) {
2219 runparams.nice = true;
2220 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2222 } else if (!lyxrc.tex_allows_spaces
2223 && support::contains(filePath(), ' ')) {
2224 Alert::error(_("File name error"),
2225 _("The directory path to the document cannot contain spaces."));
2228 runparams.nice = false;
2229 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2233 string const error_type = (format == "program")
2234 ? "Build" : bufferFormat();
2235 string const ext = formats.extension(format);
2236 FileName const tmp_result_file(changeExtension(filename, ext));
2237 bool const success = theConverters().convert(this, FileName(filename),
2238 tmp_result_file, FileName(absFileName()), backend_format, format,
2239 errorList(error_type));
2240 // Emit the signal to show the error list.
2241 if (format != backend_format)
2247 result_file = tmp_result_file.absFilename();
2249 result_file = changeExtension(absFileName(), ext);
2250 // We need to copy referenced files (e. g. included graphics
2251 // if format == "dvi") to the result dir.
2252 vector<ExportedFile> const files =
2253 runparams.exportdata->externalFiles(format);
2254 string const dest = onlyPath(result_file);
2255 CopyStatus status = SUCCESS;
2256 for (vector<ExportedFile>::const_iterator it = files.begin();
2257 it != files.end() && status != CANCEL; ++it) {
2259 formats.getFormatFromFile(it->sourceName);
2260 status = copyFile(fmt, it->sourceName,
2261 makeAbsPath(it->exportName, dest),
2262 it->exportName, status == FORCE);
2264 if (status == CANCEL) {
2265 message(_("Document export cancelled."));
2266 } else if (tmp_result_file.exists()) {
2267 // Finally copy the main file
2268 status = copyFile(format, tmp_result_file,
2269 FileName(result_file), result_file,
2271 message(bformat(_("Document exported as %1$s "
2273 formats.prettyName(format),
2274 makeDisplayPath(result_file)));
2276 // This must be a dummy converter like fax (bug 1888)
2277 message(bformat(_("Document exported as %1$s"),
2278 formats.prettyName(format)));
2286 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2289 return doExport(format, put_in_tempdir, result_file);
2293 bool Buffer::preview(string const & format) const
2296 if (!doExport(format, true, result_file))
2298 return formats.view(*this, FileName(result_file), format);
2302 bool Buffer::isExportable(string const & format) const
2304 vector<string> backs = backends();
2305 for (vector<string>::const_iterator it = backs.begin();
2306 it != backs.end(); ++it)
2307 if (theConverters().isReachable(*it, format))
2313 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2315 vector<string> backs = backends();
2316 vector<Format const *> result =
2317 theConverters().getReachable(backs[0], only_viewable, true);
2318 for (vector<string>::const_iterator it = backs.begin() + 1;
2319 it != backs.end(); ++it) {
2320 vector<Format const *> r =
2321 theConverters().getReachable(*it, only_viewable, false);
2322 result.insert(result.end(), r.begin(), r.end());
2328 vector<string> Buffer::backends() const
2331 if (params().getTextClass().isTeXClassAvailable()) {
2332 v.push_back(bufferFormat());
2333 // FIXME: Don't hardcode format names here, but use a flag
2334 if (v.back() == "latex")
2335 v.push_back("pdflatex");
2337 v.push_back("text");
2343 bool Buffer::readFileHelper(FileName const & s)
2345 // File information about normal file
2347 docstring const file = makeDisplayPath(s.absFilename(), 50);
2348 docstring text = bformat(_("The specified document\n%1$s"
2349 "\ncould not be read."), file);
2350 Alert::error(_("Could not read document"), text);
2354 // Check if emergency save file exists and is newer.
2355 FileName const e(s.absFilename() + ".emergency");
2357 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2358 docstring const file = makeDisplayPath(s.absFilename(), 20);
2359 docstring const text =
2360 bformat(_("An emergency save of the document "
2362 "Recover emergency save?"), file);
2363 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2364 _("&Recover"), _("&Load Original"),
2368 // the file is not saved if we load the emergency file.
2378 // Now check if autosave file is newer.
2379 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2381 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2382 docstring const file = makeDisplayPath(s.absFilename(), 20);
2383 docstring const text =
2384 bformat(_("The backup of the document "
2385 "%1$s is newer.\n\nLoad the "
2386 "backup instead?"), file);
2387 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2388 _("&Load backup"), _("Load &original"),
2392 // the file is not saved if we load the autosave file.
2396 // Here we delete the autosave
2407 bool Buffer::loadLyXFile(FileName const & s)
2409 if (s.isReadableFile()) {
2410 if (readFileHelper(s)) {
2411 lyxvc().file_found_hook(s);
2412 if (!s.isWritable())
2417 docstring const file = makeDisplayPath(s.absFilename(), 20);
2418 // Here we probably should run
2419 if (LyXVC::file_not_found_hook(s)) {
2420 docstring const text =
2421 bformat(_("Do you want to retrieve the document"
2422 " %1$s from version control?"), file);
2423 int const ret = Alert::prompt(_("Retrieve from version control?"),
2424 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2427 // How can we know _how_ to do the checkout?
2428 // With the current VC support it has to be,
2429 // a RCS file since CVS do not have special ,v files.
2431 return loadLyXFile(s);
2439 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2441 TeXErrors::Errors::const_iterator cit = terr.begin();
2442 TeXErrors::Errors::const_iterator end = terr.end();
2444 for (; cit != end; ++cit) {
2447 int errorRow = cit->error_in_line;
2448 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2454 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2455 } while (found && id_start == id_end && pos_start == pos_end);
2457 errorList.push_back(ErrorItem(cit->error_desc,
2458 cit->error_text, id_start, pos_start, pos_end));