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>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 int const LYX_FORMAT = 308; // Uwe: Serbian-Latin
124 typedef map<string, bool> DepClean;
129 Impl(Buffer & parent, FileName const & file, bool readonly);
142 mutable TexRow texrow;
143 Buffer const * parent_buffer;
145 /// need to regenerate .tex?
149 mutable bool lyx_clean;
151 /// is autosave needed?
152 mutable bool bak_clean;
154 /// is this a unnamed file (New...)?
160 /// name of the file the buffer is associated with.
163 /** Set to true only when the file is fully loaded.
164 * Used to prevent the premature generation of previews
165 * and by the citation inset.
167 bool file_fully_loaded;
169 /// our Text that should be wrapped in an InsetText
173 mutable TocBackend toc_backend;
176 typedef map<unsigned int, MacroData, greater<int> > PositionToMacroMap;
177 typedef map<docstring, PositionToMacroMap> NameToPositionMacroMap;
178 NameToPositionMacroMap macros;
180 /// Container for all sort of Buffer dependant errors.
181 map<string, ErrorList> errorLists;
183 /// all embedded files of this buffer
184 EmbeddedFiles embedded_files;
186 /// timestamp and checksum used to test if the file has been externally
187 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
189 unsigned long checksum_;
192 frontend::WorkAreaManager * wa_;
197 /// A cache for the bibfiles (including bibfiles of loaded child
198 /// documents), needed for appropriate update of natbib labels.
199 mutable FileNameList bibfilesCache_;
203 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
204 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
205 read_only(readonly_), filename(file), file_fully_loaded(false),
206 inset(params), toc_backend(&parent), embedded_files(&parent),
207 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
209 inset.setAutoBreakRows(true);
210 lyxvc.setBuffer(&parent);
211 temppath = createBufferTmpDir();
213 // FIXME: And now do something if temppath == string(), because we
214 // assume from now on that temppath points to a valid temp dir.
215 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
218 wa_ = new frontend::WorkAreaManager;
222 Buffer::Buffer(string const & file, bool readonly)
223 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
225 LYXERR(Debug::INFO, "Buffer::Buffer()");
231 LYXERR(Debug::INFO, "Buffer::~Buffer()");
232 // here the buffer should take care that it is
233 // saved properly, before it goes into the void.
235 // GuiView already destroyed
238 Buffer const * master = masterBuffer();
239 if (master != this && use_gui)
240 // We are closing buf which was a child document so we
241 // must update the labels and section numbering of its master
243 updateLabels(*master);
245 resetChildDocuments(false);
247 if (!temppath().empty() && !FileName(temppath()).destroyDirectory()) {
248 Alert::warning(_("Could not remove temporary directory"),
249 bformat(_("Could not remove the temporary directory %1$s"),
250 from_utf8(temppath())));
253 // Remove any previewed LaTeX snippets associated with this buffer.
254 graphics::Previews::get().removeLoader(*this);
260 void Buffer::changed() const
267 frontend::WorkAreaManager & Buffer::workAreaManager() const
269 BOOST_ASSERT(d->wa_);
274 Text & Buffer::text() const
276 return const_cast<Text &>(d->inset.text_);
280 Inset & Buffer::inset() const
282 return const_cast<InsetText &>(d->inset);
286 BufferParams & Buffer::params()
292 BufferParams const & Buffer::params() const
298 ParagraphList & Buffer::paragraphs()
300 return text().paragraphs();
304 ParagraphList const & Buffer::paragraphs() const
306 return text().paragraphs();
310 LyXVC & Buffer::lyxvc()
316 LyXVC const & Buffer::lyxvc() const
322 string const & Buffer::temppath() const
328 TexRow const & Buffer::texrow() const
334 TocBackend & Buffer::tocBackend() const
336 return d->toc_backend;
340 EmbeddedFiles & Buffer::embeddedFiles()
342 return d->embedded_files;
346 EmbeddedFiles const & Buffer::embeddedFiles() const
348 return d->embedded_files;
352 Undo & Buffer::undo()
358 string Buffer::latexName(bool const no_path) const
360 FileName latex_name = makeLatexName(d->filename);
361 return no_path ? latex_name.onlyFileName()
362 : latex_name.absFilename();
366 string Buffer::logName(LogType * type) const
368 string const filename = latexName(false);
370 if (filename.empty()) {
376 string const path = temppath();
378 FileName const fname(addName(temppath(),
379 onlyFilename(changeExtension(filename,
381 FileName const bname(
382 addName(path, onlyFilename(
383 changeExtension(filename,
384 formats.extension("literate") + ".out"))));
386 // If no Latex log or Build log is newer, show Build log
388 if (bname.exists() &&
389 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
390 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
393 return bname.absFilename();
395 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
398 return fname.absFilename();
402 void Buffer::setReadonly(bool const flag)
404 if (d->read_only != flag) {
411 void Buffer::setFileName(string const & newfile)
413 d->filename = makeAbsPath(newfile);
414 setReadonly(d->filename.isReadOnly());
419 int Buffer::readHeader(Lexer & lex)
421 int unknown_tokens = 0;
423 int begin_header_line = -1;
425 // Initialize parameters that may be/go lacking in header:
426 params().branchlist().clear();
427 params().preamble.erase();
428 params().options.erase();
429 params().float_placement.erase();
430 params().paperwidth.erase();
431 params().paperheight.erase();
432 params().leftmargin.erase();
433 params().rightmargin.erase();
434 params().topmargin.erase();
435 params().bottommargin.erase();
436 params().headheight.erase();
437 params().headsep.erase();
438 params().footskip.erase();
439 params().listings_params.clear();
440 params().clearLayoutModules();
441 params().pdfoptions().clear();
443 for (int i = 0; i < 4; ++i) {
444 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
445 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
448 ErrorList & errorList = d->errorLists["Parse"];
452 string const token = lex.getString();
457 if (token == "\\end_header")
461 if (token == "\\begin_header") {
462 begin_header_line = line;
466 LYXERR(Debug::PARSER, "Handling document header token: `"
469 string unknown = params().readToken(lex, token, d->filename.onlyPath());
470 if (!unknown.empty()) {
471 if (unknown[0] != '\\' && token == "\\textclass") {
472 Alert::warning(_("Unknown document class"),
473 bformat(_("Using the default document class, because the "
474 "class %1$s is unknown."), from_utf8(unknown)));
477 docstring const s = bformat(_("Unknown token: "
481 errorList.push_back(ErrorItem(_("Document header error"),
486 if (begin_header_line) {
487 docstring const s = _("\\begin_header is missing");
488 errorList.push_back(ErrorItem(_("Document header error"),
492 return unknown_tokens;
497 // changed to be public and have one parameter
498 // Returns false if "\end_document" is not read (Asger)
499 bool Buffer::readDocument(Lexer & lex)
501 ErrorList & errorList = d->errorLists["Parse"];
505 string const token = lex.getString();
506 if (token != "\\begin_document") {
507 docstring const s = _("\\begin_document is missing");
508 errorList.push_back(ErrorItem(_("Document header error"),
512 // we are reading in a brand new document
513 BOOST_ASSERT(paragraphs().empty());
516 TextClass const & baseClass = textclasslist[params().getBaseClass()];
517 if (!baseClass.load(filePath())) {
518 string theclass = baseClass.name();
519 Alert::error(_("Can't load document class"), bformat(
520 _("Using the default document class, because the "
521 "class %1$s could not be loaded."), from_utf8(theclass)));
522 params().setBaseClass(defaultTextclass());
525 if (params().outputChanges) {
526 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
527 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
528 LaTeXFeatures::isAvailable("xcolor");
530 if (!dvipost && !xcolorsoul) {
531 Alert::warning(_("Changes not shown in LaTeX output"),
532 _("Changes will not be highlighted in LaTeX output, "
533 "because neither dvipost nor xcolor/soul are installed.\n"
534 "Please install these packages or redefine "
535 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
536 } else if (!xcolorsoul) {
537 Alert::warning(_("Changes not shown in LaTeX output"),
538 _("Changes will not be highlighted in LaTeX output "
539 "when using pdflatex, because xcolor and soul are not installed.\n"
540 "Please install both packages or redefine "
541 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
546 bool const res = text().read(*this, lex, errorList);
547 for_each(text().paragraphs().begin(),
548 text().paragraphs().end(),
549 bind(&Paragraph::setInsetOwner, _1, &inset()));
555 // needed to insert the selection
556 void Buffer::insertStringAsLines(ParagraphList & pars,
557 pit_type & pit, pos_type & pos,
558 Font const & fn, docstring const & str, bool autobreakrows)
562 // insert the string, don't insert doublespace
563 bool space_inserted = true;
564 for (docstring::const_iterator cit = str.begin();
565 cit != str.end(); ++cit) {
566 Paragraph & par = pars[pit];
568 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
569 breakParagraph(params(), pars, pit, pos,
570 par.layout()->isEnvironment());
573 space_inserted = true;
577 // do not insert consecutive spaces if !free_spacing
578 } else if ((*cit == ' ' || *cit == '\t') &&
579 space_inserted && !par.isFreeSpacing()) {
581 } else if (*cit == '\t') {
582 if (!par.isFreeSpacing()) {
583 // tabs are like spaces here
584 par.insertChar(pos, ' ', font, params().trackChanges);
586 space_inserted = true;
588 const pos_type n = 8 - pos % 8;
589 for (pos_type i = 0; i < n; ++i) {
590 par.insertChar(pos, ' ', font, params().trackChanges);
593 space_inserted = true;
595 } else if (!isPrintable(*cit)) {
596 // Ignore unprintables
599 // just insert the character
600 par.insertChar(pos, *cit, font, params().trackChanges);
602 space_inserted = (*cit == ' ');
609 bool Buffer::readString(string const & s)
611 params().compressed = false;
613 // remove dummy empty par
614 paragraphs().clear();
618 FileName const name = FileName::tempName();
619 switch (readFile(lex, name, true)) {
623 // We need to call lyx2lyx, so write the input to a file
624 ofstream os(name.toFilesystemEncoding().c_str());
627 return readFile(name);
637 bool Buffer::readFile(FileName const & filename)
639 FileName fname(filename);
640 // Check if the file is compressed.
641 string format = filename.guessFormatFromContents();
642 if (format == "zip") {
643 // decompress to a temp directory
644 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
645 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
647 FileName lyxfile(addName(temppath(), "content.lyx"));
648 // if both manifest.txt and file.lyx exist, this is am embedded file
649 if (lyxfile.exists()) {
650 params().embedded = true;
654 // The embedded lyx file can also be compressed, for backward compatibility
655 format = fname.guessFormatFromContents();
656 if (format == "gzip" || format == "zip" || format == "compress")
657 params().compressed = true;
659 // remove dummy empty par
660 paragraphs().clear();
663 if (readFile(lex, fname) != success)
670 bool Buffer::isFullyLoaded() const
672 return d->file_fully_loaded;
676 void Buffer::setFullyLoaded(bool value)
678 d->file_fully_loaded = value;
682 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
685 BOOST_ASSERT(!filename.empty());
688 Alert::error(_("Document could not be read"),
689 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
694 string const token = lex.getString();
697 Alert::error(_("Document could not be read"),
698 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
702 // the first token _must_ be...
703 if (token != "\\lyxformat") {
704 lyxerr << "Token: " << token << endl;
706 Alert::error(_("Document format failure"),
707 bformat(_("%1$s is not a LyX document."),
708 from_utf8(filename.absFilename())));
713 string tmp_format = lex.getString();
714 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
715 // if present remove ".," from string.
716 string::size_type dot = tmp_format.find_first_of(".,");
717 //lyxerr << " dot found at " << dot << endl;
718 if (dot != string::npos)
719 tmp_format.erase(dot, 1);
720 int const file_format = convert<int>(tmp_format);
721 //lyxerr << "format: " << file_format << endl;
723 // save timestamp and checksum of the original disk file, making sure
724 // to not overwrite them with those of the file created in the tempdir
725 // when it has to be converted to the current format.
727 // Save the timestamp and checksum of disk file. If filename is an
728 // emergency file, save the timestamp and checksum of the original lyx file
729 // because isExternallyModified will check for this file. (BUG4193)
730 string diskfile = filename.absFilename();
731 if (suffixIs(diskfile, ".emergency"))
732 diskfile = diskfile.substr(0, diskfile.size() - 10);
733 saveCheckSum(FileName(diskfile));
736 if (file_format != LYX_FORMAT) {
739 // lyx2lyx would fail
742 FileName const tmpfile = FileName::tempName();
743 if (tmpfile.empty()) {
744 Alert::error(_("Conversion failed"),
745 bformat(_("%1$s is from a different"
746 " version of LyX, but a temporary"
747 " file for converting it could"
749 from_utf8(filename.absFilename())));
752 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
753 if (lyx2lyx.empty()) {
754 Alert::error(_("Conversion script not found"),
755 bformat(_("%1$s is from a different"
756 " version of LyX, but the"
757 " conversion script lyx2lyx"
758 " could not be found."),
759 from_utf8(filename.absFilename())));
762 ostringstream command;
763 command << os::python()
764 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
765 << " -t " << convert<string>(LYX_FORMAT)
766 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
767 << ' ' << quoteName(filename.toFilesystemEncoding());
768 string const command_str = command.str();
770 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
772 cmd_ret const ret = runCommand(command_str);
773 if (ret.first != 0) {
774 Alert::error(_("Conversion script failed"),
775 bformat(_("%1$s is from a different version"
776 " of LyX, but the lyx2lyx script"
777 " failed to convert it."),
778 from_utf8(filename.absFilename())));
781 bool const ret = readFile(tmpfile);
782 // Do stuff with tmpfile name and buffer name here.
783 return ret ? success : failure;
788 if (readDocument(lex)) {
789 Alert::error(_("Document format failure"),
790 bformat(_("%1$s ended unexpectedly, which means"
791 " that it is probably corrupted."),
792 from_utf8(filename.absFilename())));
795 d->file_fully_loaded = true;
800 // Should probably be moved to somewhere else: BufferView? LyXView?
801 bool Buffer::save() const
803 // We don't need autosaves in the immediate future. (Asger)
804 resetAutosaveTimers();
806 string const encodedFilename = d->filename.toFilesystemEncoding();
809 bool madeBackup = false;
811 // make a backup if the file already exists
812 if (lyxrc.make_backup && fileName().exists()) {
813 backupName = FileName(absFileName() + '~');
814 if (!lyxrc.backupdir_path.empty()) {
815 string const mangledName =
816 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
817 backupName = FileName(addName(lyxrc.backupdir_path,
820 if (fileName().copyTo(backupName)) {
823 Alert::error(_("Backup failure"),
824 bformat(_("Cannot create backup file %1$s.\n"
825 "Please check whether the directory exists and is writeable."),
826 from_utf8(backupName.absFilename())));
827 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
831 // ask if the disk file has been externally modified (use checksum method)
832 if (fileName().exists() && isExternallyModified(checksum_method)) {
833 docstring const file = makeDisplayPath(absFileName(), 20);
834 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
835 "you want to overwrite this file?"), file);
836 int const ret = Alert::prompt(_("Overwrite modified file?"),
837 text, 1, 1, _("&Overwrite"), _("&Cancel"));
842 if (writeFile(d->filename)) {
846 // Saving failed, so backup is not backup
848 backupName.moveTo(d->filename);
854 bool Buffer::writeFile(FileName const & fname) const
856 if (d->read_only && fname == d->filename)
862 if (params().embedded)
863 // first write the .lyx file to the temporary directory
864 content = FileName(addName(temppath(), "content.lyx"));
868 docstring const str = bformat(_("Saving document %1$s..."),
869 makeDisplayPath(content.absFilename()));
872 if (params().compressed) {
873 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
874 retval = ofs && write(ofs);
876 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
877 retval = ofs && write(ofs);
881 message(str + _(" could not write file!."));
885 removeAutosaveFile(d->filename.absFilename());
886 saveCheckSum(d->filename);
887 message(str + _(" done."));
889 if (!params().embedded)
892 message(str + _(" writing embedded files!."));
893 // if embedding is enabled, write file.lyx and all the embedded files
894 // to the zip file fname.
895 if (!d->embedded_files.writeFile(fname)) {
896 message(str + _(" could not write embedded files!."));
899 message(str + _(" error while writing embedded files."));
904 bool Buffer::write(ostream & ofs) const
907 // Use the standard "C" locale for file output.
908 ofs.imbue(locale::classic());
911 // The top of the file should not be written by params().
913 // write out a comment in the top of the file
914 ofs << "#LyX " << lyx_version
915 << " created this file. For more info see http://www.lyx.org/\n"
916 << "\\lyxformat " << LYX_FORMAT << "\n"
917 << "\\begin_document\n";
920 /// For each author, set 'used' to true if there is a change
921 /// by this author in the document; otherwise set it to 'false'.
922 AuthorList::Authors::const_iterator a_it = params().authors().begin();
923 AuthorList::Authors::const_iterator a_end = params().authors().end();
924 for (; a_it != a_end; ++a_it)
925 a_it->second.setUsed(false);
927 ParIterator const end = par_iterator_end();
928 ParIterator it = par_iterator_begin();
929 for ( ; it != end; ++it)
930 it->checkAuthors(params().authors());
932 // now write out the buffer parameters.
933 ofs << "\\begin_header\n";
934 params().writeFile(ofs);
935 ofs << "\\end_header\n";
938 ofs << "\n\\begin_body\n";
939 text().write(*this, ofs);
940 ofs << "\n\\end_body\n";
942 // Write marker that shows file is complete
943 ofs << "\\end_document" << endl;
945 // Shouldn't really be needed....
948 // how to check if close went ok?
949 // Following is an attempt... (BE 20001011)
951 // good() returns false if any error occured, including some
953 // bad() returns true if something bad happened in the buffer,
954 // which should include file system full errors.
959 lyxerr << "File was not closed properly." << endl;
966 bool Buffer::makeLaTeXFile(FileName const & fname,
967 string const & original_path,
968 OutputParams const & runparams,
969 bool output_preamble, bool output_body) const
971 string const encoding = runparams.encoding->iconvName();
972 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
975 try { ofs.reset(encoding); }
976 catch (iconv_codecvt_facet_exception & e) {
977 lyxerr << "Caught iconv exception: " << e.what() << endl;
978 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
979 "verify that the support software for your encoding (%1$s) is "
980 "properly installed"), from_ascii(encoding)));
983 if (!openFileWrite(ofs, fname))
986 //TexStream ts(ofs.rdbuf(), &texrow());
988 bool failed_export = false;
991 writeLaTeXSource(ofs, original_path,
992 runparams, output_preamble, output_body);
994 catch (iconv_codecvt_facet_exception & e) {
995 lyxerr << "Caught iconv exception: " << e.what() << endl;
996 failed_export = true;
998 catch (exception const & e) {
999 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1000 failed_export = true;
1003 lyxerr << "Caught some really weird exception..." << endl;
1004 LyX::cref().exit(1);
1009 failed_export = true;
1010 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1013 if (failed_export) {
1014 Alert::error(_("Encoding error"),
1015 _("Some characters of your document are probably not "
1016 "representable in the chosen encoding.\n"
1017 "Changing the document encoding to utf8 could help."));
1024 void Buffer::writeLaTeXSource(odocstream & os,
1025 string const & original_path,
1026 OutputParams const & runparams_in,
1027 bool const output_preamble, bool const output_body) const
1029 OutputParams runparams = runparams_in;
1031 // validate the buffer.
1032 LYXERR(Debug::LATEX, " Validating buffer...");
1033 LaTeXFeatures features(*this, params(), runparams);
1035 LYXERR(Debug::LATEX, " Buffer validation done.");
1037 // The starting paragraph of the coming rows is the
1038 // first paragraph of the document. (Asger)
1039 if (output_preamble && runparams.nice) {
1040 os << "%% LyX " << lyx_version << " created this file. "
1041 "For more info, see http://www.lyx.org/.\n"
1042 "%% Do not edit unless you really know what "
1044 d->texrow.newline();
1045 d->texrow.newline();
1047 LYXERR(Debug::INFO, "lyx document header finished");
1048 // There are a few differences between nice LaTeX and usual files:
1049 // usual is \batchmode and has a
1050 // special input@path to allow the including of figures
1051 // with either \input or \includegraphics (what figinsets do).
1052 // input@path is set when the actual parameter
1053 // original_path is set. This is done for usual tex-file, but not
1054 // for nice-latex-file. (Matthias 250696)
1055 // Note that input@path is only needed for something the user does
1056 // in the preamble, included .tex files or ERT, files included by
1057 // LyX work without it.
1058 if (output_preamble) {
1059 if (!runparams.nice) {
1060 // code for usual, NOT nice-latex-file
1061 os << "\\batchmode\n"; // changed
1062 // from \nonstopmode
1063 d->texrow.newline();
1065 if (!original_path.empty()) {
1067 // We don't know the encoding of inputpath
1068 docstring const inputpath = from_utf8(latex_path(original_path));
1069 os << "\\makeatletter\n"
1070 << "\\def\\input@path{{"
1071 << inputpath << "/}}\n"
1072 << "\\makeatother\n";
1073 d->texrow.newline();
1074 d->texrow.newline();
1075 d->texrow.newline();
1078 // Write the preamble
1079 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1085 os << "\\begin{document}\n";
1086 d->texrow.newline();
1087 } // output_preamble
1089 d->texrow.start(paragraphs().begin()->id(), 0);
1091 LYXERR(Debug::INFO, "preamble finished, now the body.");
1093 // if we are doing a real file with body, even if this is the
1094 // child of some other buffer, let's cut the link here.
1095 // This happens for example if only a child document is printed.
1096 Buffer const * save_parent = 0;
1097 if (output_preamble) {
1098 save_parent = d->parent_buffer;
1099 d->parent_buffer = 0;
1102 loadChildDocuments();
1105 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1107 // Restore the parenthood if needed
1108 if (output_preamble)
1109 d->parent_buffer = save_parent;
1111 // add this just in case after all the paragraphs
1113 d->texrow.newline();
1115 if (output_preamble) {
1116 os << "\\end{document}\n";
1117 d->texrow.newline();
1118 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1120 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1122 runparams_in.encoding = runparams.encoding;
1124 // Just to be sure. (Asger)
1125 d->texrow.newline();
1127 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1128 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1132 bool Buffer::isLatex() const
1134 return params().getTextClass().outputType() == LATEX;
1138 bool Buffer::isLiterate() const
1140 return params().getTextClass().outputType() == LITERATE;
1144 bool Buffer::isDocBook() const
1146 return params().getTextClass().outputType() == DOCBOOK;
1150 void Buffer::makeDocBookFile(FileName const & fname,
1151 OutputParams const & runparams,
1152 bool const body_only) const
1154 LYXERR(Debug::LATEX, "makeDocBookFile...");
1158 if (!openFileWrite(ofs, fname))
1161 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1165 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1169 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1170 OutputParams const & runparams,
1171 bool const only_body) const
1173 LaTeXFeatures features(*this, params(), runparams);
1178 TextClass const & tclass = params().getTextClass();
1179 string const top_element = tclass.latexname();
1182 if (runparams.flavor == OutputParams::XML)
1183 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1186 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1189 if (! tclass.class_header().empty())
1190 os << from_ascii(tclass.class_header());
1191 else if (runparams.flavor == OutputParams::XML)
1192 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1193 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1195 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1197 docstring preamble = from_utf8(params().preamble);
1198 if (runparams.flavor != OutputParams::XML ) {
1199 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1200 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1201 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1202 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1205 string const name = runparams.nice
1206 ? changeExtension(absFileName(), ".sgml") : fname;
1207 preamble += features.getIncludedFiles(name);
1208 preamble += features.getLyXSGMLEntities();
1210 if (!preamble.empty()) {
1211 os << "\n [ " << preamble << " ]";
1216 string top = top_element;
1218 if (runparams.flavor == OutputParams::XML)
1219 top += params().language->code();
1221 top += params().language->code().substr(0,2);
1224 if (!params().options.empty()) {
1226 top += params().options;
1229 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1230 << " file was created by LyX " << lyx_version
1231 << "\n See http://www.lyx.org/ for more information -->\n";
1233 params().getTextClass().counters().reset();
1235 loadChildDocuments();
1237 sgml::openTag(os, top);
1239 docbookParagraphs(paragraphs(), *this, os, runparams);
1240 sgml::closeTag(os, top_element);
1244 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1245 // Other flags: -wall -v0 -x
1246 int Buffer::runChktex()
1250 // get LaTeX-Filename
1251 FileName const path(temppath());
1252 string const name = addName(path.absFilename(), latexName());
1253 string const org_path = filePath();
1255 PathChanger p(path); // path to LaTeX file
1256 message(_("Running chktex..."));
1258 // Generate the LaTeX file if neccessary
1259 OutputParams runparams(¶ms().encoding());
1260 runparams.flavor = OutputParams::LATEX;
1261 runparams.nice = false;
1262 makeLaTeXFile(FileName(name), org_path, runparams);
1265 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1266 int const res = chktex.run(terr); // run chktex
1269 Alert::error(_("chktex failure"),
1270 _("Could not run chktex successfully."));
1271 } else if (res > 0) {
1272 ErrorList & errlist = d->errorLists["ChkTeX"];
1274 bufferErrors(terr, errlist);
1285 void Buffer::validate(LaTeXFeatures & features) const
1287 params().validate(features);
1289 loadChildDocuments();
1291 for_each(paragraphs().begin(), paragraphs().end(),
1292 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1294 if (lyxerr.debugging(Debug::LATEX)) {
1295 features.showStruct();
1300 void Buffer::getLabelList(vector<docstring> & list) const
1302 /// if this is a child document and the parent is already loaded
1303 /// Use the parent's list instead [ale990407]
1304 Buffer const * tmp = masterBuffer();
1306 lyxerr << "masterBuffer() failed!" << endl;
1310 tmp->getLabelList(list);
1314 loadChildDocuments();
1316 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1317 it.nextInset()->getLabelList(*this, list);
1321 void Buffer::updateBibfilesCache() const
1323 // if this is a child document and the parent is already loaded
1324 // update the parent's cache instead
1325 Buffer const * tmp = masterBuffer();
1328 tmp->updateBibfilesCache();
1332 d->bibfilesCache_.clear();
1333 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1334 if (it->lyxCode() == BIBTEX_CODE) {
1335 InsetBibtex const & inset =
1336 static_cast<InsetBibtex const &>(*it);
1337 FileNameList const bibfiles = inset.getFiles(*this);
1338 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1341 } else if (it->lyxCode() == INCLUDE_CODE) {
1342 InsetInclude & inset =
1343 static_cast<InsetInclude &>(*it);
1344 inset.updateBibfilesCache(*this);
1345 FileNameList const & bibfiles =
1346 inset.getBibfilesCache(*this);
1347 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1355 FileNameList const & Buffer::getBibfilesCache() const
1357 // if this is a child document and the parent is already loaded
1358 // use the parent's cache instead
1359 Buffer const * tmp = masterBuffer();
1362 return tmp->getBibfilesCache();
1364 // We update the cache when first used instead of at loading time.
1365 if (d->bibfilesCache_.empty())
1366 const_cast<Buffer *>(this)->updateBibfilesCache();
1368 return d->bibfilesCache_;
1372 bool Buffer::isDepClean(string const & name) const
1374 DepClean::const_iterator const it = d->dep_clean.find(name);
1375 if (it == d->dep_clean.end())
1381 void Buffer::markDepClean(string const & name)
1383 d->dep_clean[name] = true;
1387 bool Buffer::dispatch(string const & command, bool * result)
1389 return dispatch(lyxaction.lookupFunc(command), result);
1393 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1395 bool dispatched = true;
1397 switch (func.action) {
1398 case LFUN_BUFFER_EXPORT: {
1399 bool const tmp = doExport(to_utf8(func.argument()), false);
1412 void Buffer::changeLanguage(Language const * from, Language const * to)
1417 for_each(par_iterator_begin(),
1419 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1423 bool Buffer::isMultiLingual() const
1425 ParConstIterator end = par_iterator_end();
1426 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1427 if (it->isMultiLingual(params()))
1434 ParIterator Buffer::getParFromID(int const id) const
1436 ParConstIterator it = par_iterator_begin();
1437 ParConstIterator const end = par_iterator_end();
1440 // John says this is called with id == -1 from undo
1441 lyxerr << "getParFromID(), id: " << id << endl;
1445 for (; it != end; ++it)
1453 bool Buffer::hasParWithID(int const id) const
1455 ParConstIterator const it = getParFromID(id);
1456 return it != par_iterator_end();
1460 ParIterator Buffer::par_iterator_begin()
1462 return lyx::par_iterator_begin(inset());
1466 ParIterator Buffer::par_iterator_end()
1468 return lyx::par_iterator_end(inset());
1472 ParConstIterator Buffer::par_iterator_begin() const
1474 return lyx::par_const_iterator_begin(inset());
1478 ParConstIterator Buffer::par_iterator_end() const
1480 return lyx::par_const_iterator_end(inset());
1484 Language const * Buffer::language() const
1486 return params().language;
1490 docstring const Buffer::B_(string const & l10n) const
1492 return params().B_(l10n);
1496 bool Buffer::isClean() const
1498 return d->lyx_clean;
1502 bool Buffer::isBakClean() const
1504 return d->bak_clean;
1508 bool Buffer::isExternallyModified(CheckMethod method) const
1510 BOOST_ASSERT(d->filename.exists());
1511 // if method == timestamp, check timestamp before checksum
1512 return (method == checksum_method
1513 || d->timestamp_ != d->filename.lastModified())
1514 && d->checksum_ != d->filename.checksum();
1518 void Buffer::saveCheckSum(FileName const & file) const
1520 if (file.exists()) {
1521 d->timestamp_ = file.lastModified();
1522 d->checksum_ = file.checksum();
1524 // in the case of save to a new file.
1531 void Buffer::markClean() const
1533 if (!d->lyx_clean) {
1534 d->lyx_clean = true;
1537 // if the .lyx file has been saved, we don't need an
1539 d->bak_clean = true;
1543 void Buffer::markBakClean() const
1545 d->bak_clean = true;
1549 void Buffer::setUnnamed(bool flag)
1555 bool Buffer::isUnnamed() const
1561 // FIXME: this function should be moved to buffer_pimpl.C
1562 void Buffer::markDirty()
1565 d->lyx_clean = false;
1568 d->bak_clean = false;
1570 DepClean::iterator it = d->dep_clean.begin();
1571 DepClean::const_iterator const end = d->dep_clean.end();
1573 for (; it != end; ++it)
1578 FileName Buffer::fileName() const
1584 string Buffer::absFileName() const
1586 return d->filename.absFilename();
1590 string Buffer::filePath() const
1592 return d->filename.onlyPath().absFilename();
1596 bool Buffer::isReadonly() const
1598 return d->read_only;
1602 void Buffer::setParent(Buffer const * buffer)
1604 // Avoids recursive include.
1605 d->parent_buffer = buffer == this ? 0 : buffer;
1609 Buffer const * Buffer::parent()
1611 return d->parent_buffer;
1615 Buffer const * Buffer::masterBuffer() const
1617 if (!d->parent_buffer)
1620 return d->parent_buffer->masterBuffer();
1624 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1626 Impl::PositionToMacroMap::iterator it;
1627 it = d->macros[name].upper_bound(par.macrocontextPosition());
1628 if (it != d->macros[name].end())
1631 // If there is a master buffer, query that
1632 Buffer const * master = masterBuffer();
1633 if (master && master != this)
1634 return master->hasMacro(name);
1636 return MacroTable::globalMacros().has(name);
1640 bool Buffer::hasMacro(docstring const & name) const
1642 if( !d->macros[name].empty() )
1645 // If there is a master buffer, query that
1646 Buffer const * master = masterBuffer();
1647 if (master && master != this)
1648 return master->hasMacro(name);
1650 return MacroTable::globalMacros().has(name);
1654 MacroData const & Buffer::getMacro(docstring const & name,
1655 Paragraph const & par) const
1657 Impl::PositionToMacroMap::iterator it;
1658 it = d->macros[name].upper_bound(par.macrocontextPosition());
1659 if( it != d->macros[name].end() )
1662 // If there is a master buffer, query that
1663 Buffer const * master = masterBuffer();
1664 if (master && master != this)
1665 return master->getMacro(name);
1667 return MacroTable::globalMacros().get(name);
1671 MacroData const & Buffer::getMacro(docstring const & name) const
1673 Impl::PositionToMacroMap::iterator it;
1674 it = d->macros[name].begin();
1675 if( it != d->macros[name].end() )
1678 // If there is a master buffer, query that
1679 Buffer const * master = masterBuffer();
1680 if (master && master != this)
1681 return master->getMacro(name);
1683 return MacroTable::globalMacros().get(name);
1687 void Buffer::updateMacros()
1689 // start with empty table
1690 d->macros = Impl::NameToPositionMacroMap();
1692 // Iterate over buffer
1693 ParagraphList & pars = text().paragraphs();
1694 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1695 // set position again
1696 pars[i].setMacrocontextPosition(i);
1698 //lyxerr << "searching main par " << i
1699 // << " for macro definitions" << endl;
1700 InsetList const & insets = pars[i].insetList();
1701 InsetList::const_iterator it = insets.begin();
1702 InsetList::const_iterator end = insets.end();
1703 for ( ; it != end; ++it) {
1704 if (it->inset->lyxCode() != MATHMACRO_CODE)
1708 MathMacroTemplate const & macroTemplate
1709 = static_cast<MathMacroTemplate const &>(*it->inset);
1712 if (macroTemplate.validMacro()) {
1713 MacroData macro = macroTemplate.asMacroData();
1716 // call hasMacro here instead of directly querying mc to
1717 // also take the master document into consideration
1718 macro.setRedefinition(hasMacro(macroTemplate.name()));
1720 // register macro (possibly overwrite the previous one of this paragraph)
1721 d->macros[macroTemplate.name()][i] = macro;
1728 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1731 //FIXME: This does not work for child documents yet.
1732 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1733 // Check if the label 'from' appears more than once
1734 vector<docstring> labels;
1737 if (code == CITE_CODE) {
1739 keys.fillWithBibKeys(this);
1740 BiblioInfo::const_iterator bit = keys.begin();
1741 BiblioInfo::const_iterator bend = keys.end();
1743 for (; bit != bend; ++bit)
1745 labels.push_back(bit->first);
1748 getLabelList(labels);
1749 paramName = "reference";
1752 if (count(labels.begin(), labels.end(), from) > 1)
1755 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1756 if (it->lyxCode() == code) {
1757 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1758 docstring const oldValue = inset.getParam(paramName);
1759 if (oldValue == from)
1760 inset.setParam(paramName, to);
1766 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1767 pit_type par_end, bool full_source)
1769 OutputParams runparams(¶ms().encoding());
1770 runparams.nice = true;
1771 runparams.flavor = OutputParams::LATEX;
1772 runparams.linelen = lyxrc.plaintext_linelen;
1773 // No side effect of file copying and image conversion
1774 runparams.dryrun = true;
1778 os << "% " << _("Preview source code") << "\n\n";
1779 d->texrow.newline();
1780 d->texrow.newline();
1782 writeLaTeXSource(os, filePath(), runparams, true, true);
1784 writeDocBookSource(os, absFileName(), runparams, false);
1787 runparams.par_begin = par_begin;
1788 runparams.par_end = par_end;
1789 if (par_begin + 1 == par_end)
1791 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1795 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1796 convert<docstring>(par_begin),
1797 convert<docstring>(par_end - 1))
1799 d->texrow.newline();
1800 d->texrow.newline();
1801 // output paragraphs
1803 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1806 docbookParagraphs(paragraphs(), *this, os, runparams);
1812 ErrorList & Buffer::errorList(string const & type) const
1814 static ErrorList emptyErrorList;
1815 map<string, ErrorList>::iterator I = d->errorLists.find(type);
1816 if (I == d->errorLists.end())
1817 return emptyErrorList;
1823 void Buffer::structureChanged() const
1826 gui_->structureChanged();
1830 void Buffer::errors(string const & err) const
1837 void Buffer::message(docstring const & msg) const
1844 void Buffer::setBusy(bool on) const
1851 void Buffer::setReadOnly(bool on) const
1854 d->wa_->setReadOnly(on);
1858 void Buffer::updateTitles() const
1861 d->wa_->updateTitles();
1865 void Buffer::resetAutosaveTimers() const
1868 gui_->resetAutosaveTimers();
1872 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1881 class AutoSaveBuffer : public ForkedProcess {
1884 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1885 : buffer_(buffer), fname_(fname) {}
1887 virtual boost::shared_ptr<ForkedProcess> clone() const
1889 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1894 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
1895 from_utf8(fname_.absFilename())));
1896 return run(DontWait);
1900 virtual int generateChild();
1902 Buffer const & buffer_;
1907 #if !defined (HAVE_FORK)
1911 int AutoSaveBuffer::generateChild()
1913 // tmp_ret will be located (usually) in /tmp
1914 // will that be a problem?
1915 pid_t const pid = fork();
1916 // If you want to debug the autosave
1917 // you should set pid to -1, and comment out the fork.
1918 if (pid == 0 || pid == -1) {
1919 // pid = -1 signifies that lyx was unable
1920 // to fork. But we will do the save
1922 bool failed = false;
1924 FileName const tmp_ret = FileName::tempName("lyxauto");
1925 if (!tmp_ret.empty()) {
1926 buffer_.writeFile(tmp_ret);
1927 // assume successful write of tmp_ret
1928 if (!tmp_ret.moveTo(fname_)) {
1930 // most likely couldn't move between
1931 // filesystems unless write of tmp_ret
1932 // failed so remove tmp file (if it
1934 tmp_ret.removeFile();
1941 // failed to write/rename tmp_ret so try writing direct
1942 if (!buffer_.writeFile(fname_)) {
1943 // It is dangerous to do this in the child,
1944 // but safe in the parent, so...
1945 if (pid == -1) // emit message signal.
1946 buffer_.message(_("Autosave failed!"));
1949 if (pid == 0) { // we are the child so...
1959 // Perfect target for a thread...
1960 void Buffer::autoSave() const
1962 if (isBakClean() || isReadonly()) {
1963 // We don't save now, but we'll try again later
1964 resetAutosaveTimers();
1968 // emit message signal.
1969 message(_("Autosaving current document..."));
1971 // create autosave filename
1972 string fname = filePath();
1974 fname += d->filename.onlyFileName();
1977 AutoSaveBuffer autosave(*this, FileName(fname));
1981 resetAutosaveTimers();
1985 void Buffer::resetChildDocuments(bool close_them) const
1987 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1988 if (it->lyxCode() != INCLUDE_CODE)
1990 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
1991 InsetCommandParams const & ip = inset.params();
1993 resetParentBuffer(this, ip, close_them);
1996 if (use_gui && masterBuffer() == this)
1997 updateLabels(*this);
2001 void Buffer::loadChildDocuments() const
2003 bool parse_error = false;
2005 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2006 if (it->lyxCode() != INCLUDE_CODE)
2008 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2009 InsetCommandParams const & ip = inset.params();
2010 Buffer * child = loadIfNeeded(*this, ip);
2013 parse_error |= !child->errorList("Parse").empty();
2014 child->loadChildDocuments();
2017 if (use_gui && masterBuffer() == this)
2018 updateLabels(*this);
2022 string Buffer::bufferFormat() const
2032 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2033 string & result_file) const
2035 string backend_format;
2036 OutputParams runparams(¶ms().encoding());
2037 runparams.flavor = OutputParams::LATEX;
2038 runparams.linelen = lyxrc.plaintext_linelen;
2039 vector<string> backs = backends();
2040 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2041 // Get shortest path to format
2042 Graph::EdgePath path;
2043 for (vector<string>::const_iterator it = backs.begin();
2044 it != backs.end(); ++it) {
2045 Graph::EdgePath p = theConverters().getPath(*it, format);
2046 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2047 backend_format = *it;
2052 runparams.flavor = theConverters().getFlavor(path);
2054 Alert::error(_("Couldn't export file"),
2055 bformat(_("No information for exporting the format %1$s."),
2056 formats.prettyName(format)));
2060 backend_format = format;
2061 // FIXME: Don't hardcode format names here, but use a flag
2062 if (backend_format == "pdflatex")
2063 runparams.flavor = OutputParams::PDFLATEX;
2066 string filename = latexName(false);
2067 filename = addName(temppath(), filename);
2068 filename = changeExtension(filename,
2069 formats.extension(backend_format));
2071 // Plain text backend
2072 if (backend_format == "text")
2073 writePlaintextFile(*this, FileName(filename), runparams);
2075 else if (backend_format == "lyx")
2076 writeFile(FileName(filename));
2078 else if (isDocBook()) {
2079 runparams.nice = !put_in_tempdir;
2080 makeDocBookFile(FileName(filename), runparams);
2083 else if (backend_format == format) {
2084 runparams.nice = true;
2085 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2087 } else if (!lyxrc.tex_allows_spaces
2088 && contains(filePath(), ' ')) {
2089 Alert::error(_("File name error"),
2090 _("The directory path to the document cannot contain spaces."));
2093 runparams.nice = false;
2094 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2098 string const error_type = (format == "program")
2099 ? "Build" : bufferFormat();
2100 string const ext = formats.extension(format);
2101 FileName const tmp_result_file(changeExtension(filename, ext));
2102 bool const success = theConverters().convert(this, FileName(filename),
2103 tmp_result_file, FileName(absFileName()), backend_format, format,
2104 errorList(error_type));
2105 // Emit the signal to show the error list.
2106 if (format != backend_format)
2112 result_file = tmp_result_file.absFilename();
2114 result_file = changeExtension(absFileName(), ext);
2115 // We need to copy referenced files (e. g. included graphics
2116 // if format == "dvi") to the result dir.
2117 vector<ExportedFile> const files =
2118 runparams.exportdata->externalFiles(format);
2119 string const dest = onlyPath(result_file);
2120 CopyStatus status = SUCCESS;
2121 for (vector<ExportedFile>::const_iterator it = files.begin();
2122 it != files.end() && status != CANCEL; ++it) {
2124 formats.getFormatFromFile(it->sourceName);
2125 status = copyFile(fmt, it->sourceName,
2126 makeAbsPath(it->exportName, dest),
2127 it->exportName, status == FORCE);
2129 if (status == CANCEL) {
2130 message(_("Document export cancelled."));
2131 } else if (tmp_result_file.exists()) {
2132 // Finally copy the main file
2133 status = copyFile(format, tmp_result_file,
2134 FileName(result_file), result_file,
2136 message(bformat(_("Document exported as %1$s "
2138 formats.prettyName(format),
2139 makeDisplayPath(result_file)));
2141 // This must be a dummy converter like fax (bug 1888)
2142 message(bformat(_("Document exported as %1$s"),
2143 formats.prettyName(format)));
2151 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2154 return doExport(format, put_in_tempdir, result_file);
2158 bool Buffer::preview(string const & format) const
2161 if (!doExport(format, true, result_file))
2163 return formats.view(*this, FileName(result_file), format);
2167 bool Buffer::isExportable(string const & format) const
2169 vector<string> backs = backends();
2170 for (vector<string>::const_iterator it = backs.begin();
2171 it != backs.end(); ++it)
2172 if (theConverters().isReachable(*it, format))
2178 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2180 vector<string> backs = backends();
2181 vector<Format const *> result =
2182 theConverters().getReachable(backs[0], only_viewable, true);
2183 for (vector<string>::const_iterator it = backs.begin() + 1;
2184 it != backs.end(); ++it) {
2185 vector<Format const *> r =
2186 theConverters().getReachable(*it, only_viewable, false);
2187 result.insert(result.end(), r.begin(), r.end());
2193 vector<string> Buffer::backends() const
2196 if (params().getTextClass().isTeXClassAvailable()) {
2197 v.push_back(bufferFormat());
2198 // FIXME: Don't hardcode format names here, but use a flag
2199 if (v.back() == "latex")
2200 v.push_back("pdflatex");
2202 v.push_back("text");
2208 bool Buffer::readFileHelper(FileName const & s)
2210 // File information about normal file
2212 docstring const file = makeDisplayPath(s.absFilename(), 50);
2213 docstring text = bformat(_("The specified document\n%1$s"
2214 "\ncould not be read."), file);
2215 Alert::error(_("Could not read document"), text);
2219 // Check if emergency save file exists and is newer.
2220 FileName const e(s.absFilename() + ".emergency");
2222 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2223 docstring const file = makeDisplayPath(s.absFilename(), 20);
2224 docstring const text =
2225 bformat(_("An emergency save of the document "
2227 "Recover emergency save?"), file);
2228 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2229 _("&Recover"), _("&Load Original"),
2233 // the file is not saved if we load the emergency file.
2243 // Now check if autosave file is newer.
2244 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2246 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2247 docstring const file = makeDisplayPath(s.absFilename(), 20);
2248 docstring const text =
2249 bformat(_("The backup of the document "
2250 "%1$s is newer.\n\nLoad the "
2251 "backup instead?"), file);
2252 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2253 _("&Load backup"), _("Load &original"),
2257 // the file is not saved if we load the autosave file.
2261 // Here we delete the autosave
2272 bool Buffer::loadLyXFile(FileName const & s)
2274 if (s.isReadableFile()) {
2275 if (readFileHelper(s)) {
2276 lyxvc().file_found_hook(s);
2277 if (!s.isWritable())
2282 docstring const file = makeDisplayPath(s.absFilename(), 20);
2283 // Here we probably should run
2284 if (LyXVC::file_not_found_hook(s)) {
2285 docstring const text =
2286 bformat(_("Do you want to retrieve the document"
2287 " %1$s from version control?"), file);
2288 int const ret = Alert::prompt(_("Retrieve from version control?"),
2289 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2292 // How can we know _how_ to do the checkout?
2293 // With the current VC support it has to be,
2294 // a RCS file since CVS do not have special ,v files.
2296 return loadLyXFile(s);
2304 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2306 TeXErrors::Errors::const_iterator cit = terr.begin();
2307 TeXErrors::Errors::const_iterator end = terr.end();
2309 for (; cit != end; ++cit) {
2312 int errorRow = cit->error_in_line;
2313 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2319 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2320 } while (found && id_start == id_end && pos_start == pos_end);
2322 errorList.push_back(ErrorItem(cit->error_desc,
2323 cit->error_text, id_start, pos_start, pos_end));