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/ExceptionMessage.h"
82 #include "support/FileFilterList.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96 #include "support/FileZipListDir.h"
98 #if !defined (HAVE_FORK)
102 #include <boost/bind.hpp>
103 #include <boost/shared_ptr.hpp>
112 using namespace lyx::support;
116 namespace Alert = frontend::Alert;
117 namespace os = support::os;
121 int const LYX_FORMAT = 308; // Uwe: Serbian-Latin
126 typedef map<string, bool> DepClean;
131 Impl(Buffer & parent, FileName const & file, bool readonly);
144 mutable TexRow texrow;
145 Buffer const * parent_buffer;
147 /// need to regenerate .tex?
151 mutable bool lyx_clean;
153 /// is autosave needed?
154 mutable bool bak_clean;
156 /// is this a unnamed file (New...)?
162 /// name of the file the buffer is associated with.
165 /** Set to true only when the file is fully loaded.
166 * Used to prevent the premature generation of previews
167 * and by the citation inset.
169 bool file_fully_loaded;
171 /// our Text that should be wrapped in an InsetText
175 mutable TocBackend toc_backend;
178 typedef map<unsigned int, MacroData, greater<int> > PositionToMacroMap;
179 typedef map<docstring, PositionToMacroMap> NameToPositionMacroMap;
180 NameToPositionMacroMap macros;
182 /// Container for all sort of Buffer dependant errors.
183 map<string, ErrorList> errorLists;
185 /// all embedded files of this buffer
186 EmbeddedFiles embedded_files;
188 /// timestamp and checksum used to test if the file has been externally
189 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
191 unsigned long checksum_;
194 frontend::WorkAreaManager * wa_;
199 /// A cache for the bibfiles (including bibfiles of loaded child
200 /// documents), needed for appropriate update of natbib labels.
201 mutable FileNameList bibfilesCache_;
204 /// Creates the per buffer temporary directory
205 static FileName createBufferTmpDir()
208 // We are in our own directory. Why bother to mangle name?
209 // In fact I wrote this code to circumvent a problematic behaviour
210 // (bug?) of EMX mkstemp().
211 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
212 convert<string>(count++));
214 if (!tmpfl.createDirectory(0777)) {
215 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
216 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
217 from_utf8(tmpfl.absFilename())));
223 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
224 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
225 read_only(readonly_), filename(file), file_fully_loaded(false),
226 inset(params), toc_backend(&parent), embedded_files(&parent),
227 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
229 temppath = createBufferTmpDir();
230 inset.setAutoBreakRows(true);
231 lyxvc.setBuffer(&parent);
233 wa_ = new frontend::WorkAreaManager;
237 Buffer::Buffer(string const & file, bool readonly)
238 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
240 LYXERR(Debug::INFO, "Buffer::Buffer()");
246 LYXERR(Debug::INFO, "Buffer::~Buffer()");
247 // here the buffer should take care that it is
248 // saved properly, before it goes into the void.
250 // GuiView already destroyed
253 Buffer const * master = masterBuffer();
254 if (master != this && use_gui)
255 // We are closing buf which was a child document so we
256 // must update the labels and section numbering of its master
258 updateLabels(*master);
260 resetChildDocuments(false);
262 if (!d->temppath.destroyDirectory()) {
263 Alert::warning(_("Could not remove temporary directory"),
264 bformat(_("Could not remove the temporary directory %1$s"),
265 from_utf8(d->temppath.absFilename())));
268 // Remove any previewed LaTeX snippets associated with this buffer.
269 graphics::Previews::get().removeLoader(*this);
275 void Buffer::changed() const
282 frontend::WorkAreaManager & Buffer::workAreaManager() const
284 BOOST_ASSERT(d->wa_);
289 Text & Buffer::text() const
291 return const_cast<Text &>(d->inset.text_);
295 Inset & Buffer::inset() const
297 return const_cast<InsetText &>(d->inset);
301 BufferParams & Buffer::params()
307 BufferParams const & Buffer::params() const
313 ParagraphList & Buffer::paragraphs()
315 return text().paragraphs();
319 ParagraphList const & Buffer::paragraphs() const
321 return text().paragraphs();
325 LyXVC & Buffer::lyxvc()
331 LyXVC const & Buffer::lyxvc() const
337 string const Buffer::temppath() const
339 return d->temppath.absFilename();
343 TexRow const & Buffer::texrow() const
349 TocBackend & Buffer::tocBackend() const
351 return d->toc_backend;
355 EmbeddedFiles & Buffer::embeddedFiles()
357 return d->embedded_files;
361 EmbeddedFiles const & Buffer::embeddedFiles() const
363 return d->embedded_files;
367 Undo & Buffer::undo()
373 string Buffer::latexName(bool const no_path) const
375 FileName latex_name = makeLatexName(d->filename);
376 return no_path ? latex_name.onlyFileName()
377 : latex_name.absFilename();
381 string Buffer::logName(LogType * type) const
383 string const filename = latexName(false);
385 if (filename.empty()) {
391 string const path = temppath();
393 FileName const fname(addName(temppath(),
394 onlyFilename(changeExtension(filename,
396 FileName const bname(
397 addName(path, onlyFilename(
398 changeExtension(filename,
399 formats.extension("literate") + ".out"))));
401 // If no Latex log or Build log is newer, show Build log
403 if (bname.exists() &&
404 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
405 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
408 return bname.absFilename();
410 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
413 return fname.absFilename();
417 void Buffer::setReadonly(bool const flag)
419 if (d->read_only != flag) {
426 void Buffer::setFileName(string const & newfile)
428 d->filename = makeAbsPath(newfile);
429 setReadonly(d->filename.isReadOnly());
434 int Buffer::readHeader(Lexer & lex)
436 int unknown_tokens = 0;
438 int begin_header_line = -1;
440 // Initialize parameters that may be/go lacking in header:
441 params().branchlist().clear();
442 params().preamble.erase();
443 params().options.erase();
444 params().float_placement.erase();
445 params().paperwidth.erase();
446 params().paperheight.erase();
447 params().leftmargin.erase();
448 params().rightmargin.erase();
449 params().topmargin.erase();
450 params().bottommargin.erase();
451 params().headheight.erase();
452 params().headsep.erase();
453 params().footskip.erase();
454 params().listings_params.clear();
455 params().clearLayoutModules();
456 params().pdfoptions().clear();
458 for (int i = 0; i < 4; ++i) {
459 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
460 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
463 ErrorList & errorList = d->errorLists["Parse"];
467 string const token = lex.getString();
472 if (token == "\\end_header")
476 if (token == "\\begin_header") {
477 begin_header_line = line;
481 LYXERR(Debug::PARSER, "Handling document header token: `"
484 string unknown = params().readToken(lex, token, d->filename.onlyPath());
485 if (!unknown.empty()) {
486 if (unknown[0] != '\\' && token == "\\textclass") {
487 Alert::warning(_("Unknown document class"),
488 bformat(_("Using the default document class, because the "
489 "class %1$s is unknown."), from_utf8(unknown)));
492 docstring const s = bformat(_("Unknown token: "
496 errorList.push_back(ErrorItem(_("Document header error"),
501 if (begin_header_line) {
502 docstring const s = _("\\begin_header is missing");
503 errorList.push_back(ErrorItem(_("Document header error"),
507 return unknown_tokens;
512 // changed to be public and have one parameter
513 // Returns false if "\end_document" is not read (Asger)
514 bool Buffer::readDocument(Lexer & lex)
516 ErrorList & errorList = d->errorLists["Parse"];
520 string const token = lex.getString();
521 if (token != "\\begin_document") {
522 docstring const s = _("\\begin_document is missing");
523 errorList.push_back(ErrorItem(_("Document header error"),
527 // we are reading in a brand new document
528 BOOST_ASSERT(paragraphs().empty());
531 TextClass const & baseClass = textclasslist[params().getBaseClass()];
532 if (!baseClass.load(filePath())) {
533 string theclass = baseClass.name();
534 Alert::error(_("Can't load document class"), bformat(
535 _("Using the default document class, because the "
536 "class %1$s could not be loaded."), from_utf8(theclass)));
537 params().setBaseClass(defaultTextclass());
540 if (params().outputChanges) {
541 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
542 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
543 LaTeXFeatures::isAvailable("xcolor");
545 if (!dvipost && !xcolorsoul) {
546 Alert::warning(_("Changes not shown in LaTeX output"),
547 _("Changes will not be highlighted in LaTeX output, "
548 "because neither dvipost nor xcolor/soul are installed.\n"
549 "Please install these packages or redefine "
550 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
551 } else if (!xcolorsoul) {
552 Alert::warning(_("Changes not shown in LaTeX output"),
553 _("Changes will not be highlighted in LaTeX output "
554 "when using pdflatex, because xcolor and soul are not installed.\n"
555 "Please install both packages or redefine "
556 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
561 bool const res = text().read(*this, lex, errorList);
562 for_each(text().paragraphs().begin(),
563 text().paragraphs().end(),
564 bind(&Paragraph::setInsetOwner, _1, &inset()));
570 // needed to insert the selection
571 void Buffer::insertStringAsLines(ParagraphList & pars,
572 pit_type & pit, pos_type & pos,
573 Font const & fn, docstring const & str, bool autobreakrows)
577 // insert the string, don't insert doublespace
578 bool space_inserted = true;
579 for (docstring::const_iterator cit = str.begin();
580 cit != str.end(); ++cit) {
581 Paragraph & par = pars[pit];
583 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
584 breakParagraph(params(), pars, pit, pos,
585 par.layout()->isEnvironment());
588 space_inserted = true;
592 // do not insert consecutive spaces if !free_spacing
593 } else if ((*cit == ' ' || *cit == '\t') &&
594 space_inserted && !par.isFreeSpacing()) {
596 } else if (*cit == '\t') {
597 if (!par.isFreeSpacing()) {
598 // tabs are like spaces here
599 par.insertChar(pos, ' ', font, params().trackChanges);
601 space_inserted = true;
603 const pos_type n = 8 - pos % 8;
604 for (pos_type i = 0; i < n; ++i) {
605 par.insertChar(pos, ' ', font, params().trackChanges);
608 space_inserted = true;
610 } else if (!isPrintable(*cit)) {
611 // Ignore unprintables
614 // just insert the character
615 par.insertChar(pos, *cit, font, params().trackChanges);
617 space_inserted = (*cit == ' ');
624 bool Buffer::readString(string const & s)
626 params().compressed = false;
628 // remove dummy empty par
629 paragraphs().clear();
633 FileName const name = FileName::tempName();
634 switch (readFile(lex, name, true)) {
638 // We need to call lyx2lyx, so write the input to a file
639 ofstream os(name.toFilesystemEncoding().c_str());
642 return readFile(name);
652 bool Buffer::readFile(FileName const & filename)
654 FileName fname(filename);
655 // Check if the file is compressed.
656 string format = filename.guessFormatFromContents();
657 if (format == "zip") {
658 // decompress to a temp directory
659 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
660 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
662 FileName lyxfile(addName(temppath(), "content.lyx"));
663 // if both manifest.txt and file.lyx exist, this is am embedded file
664 if (lyxfile.exists()) {
665 params().embedded = true;
669 // The embedded lyx file can also be compressed, for backward compatibility
670 format = fname.guessFormatFromContents();
671 if (format == "gzip" || format == "zip" || format == "compress")
672 params().compressed = true;
674 // remove dummy empty par
675 paragraphs().clear();
678 if (readFile(lex, fname) != success)
685 bool Buffer::isFullyLoaded() const
687 return d->file_fully_loaded;
691 void Buffer::setFullyLoaded(bool value)
693 d->file_fully_loaded = value;
697 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
700 BOOST_ASSERT(!filename.empty());
703 Alert::error(_("Document could not be read"),
704 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
709 string const token = lex.getString();
712 Alert::error(_("Document could not be read"),
713 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
717 // the first token _must_ be...
718 if (token != "\\lyxformat") {
719 lyxerr << "Token: " << token << endl;
721 Alert::error(_("Document format failure"),
722 bformat(_("%1$s is not a LyX document."),
723 from_utf8(filename.absFilename())));
728 string tmp_format = lex.getString();
729 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
730 // if present remove ".," from string.
731 string::size_type dot = tmp_format.find_first_of(".,");
732 //lyxerr << " dot found at " << dot << endl;
733 if (dot != string::npos)
734 tmp_format.erase(dot, 1);
735 int const file_format = convert<int>(tmp_format);
736 //lyxerr << "format: " << file_format << endl;
738 // save timestamp and checksum of the original disk file, making sure
739 // to not overwrite them with those of the file created in the tempdir
740 // when it has to be converted to the current format.
742 // Save the timestamp and checksum of disk file. If filename is an
743 // emergency file, save the timestamp and checksum of the original lyx file
744 // because isExternallyModified will check for this file. (BUG4193)
745 string diskfile = filename.absFilename();
746 if (suffixIs(diskfile, ".emergency"))
747 diskfile = diskfile.substr(0, diskfile.size() - 10);
748 saveCheckSum(FileName(diskfile));
751 if (file_format != LYX_FORMAT) {
754 // lyx2lyx would fail
757 FileName const tmpfile = FileName::tempName();
758 if (tmpfile.empty()) {
759 Alert::error(_("Conversion failed"),
760 bformat(_("%1$s is from a different"
761 " version of LyX, but a temporary"
762 " file for converting it could"
764 from_utf8(filename.absFilename())));
767 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
768 if (lyx2lyx.empty()) {
769 Alert::error(_("Conversion script not found"),
770 bformat(_("%1$s is from a different"
771 " version of LyX, but the"
772 " conversion script lyx2lyx"
773 " could not be found."),
774 from_utf8(filename.absFilename())));
777 ostringstream command;
778 command << os::python()
779 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
780 << " -t " << convert<string>(LYX_FORMAT)
781 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
782 << ' ' << quoteName(filename.toFilesystemEncoding());
783 string const command_str = command.str();
785 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
787 cmd_ret const ret = runCommand(command_str);
788 if (ret.first != 0) {
789 Alert::error(_("Conversion script failed"),
790 bformat(_("%1$s is from a different version"
791 " of LyX, but the lyx2lyx script"
792 " failed to convert it."),
793 from_utf8(filename.absFilename())));
796 bool const ret = readFile(tmpfile);
797 // Do stuff with tmpfile name and buffer name here.
798 return ret ? success : failure;
803 if (readDocument(lex)) {
804 Alert::error(_("Document format failure"),
805 bformat(_("%1$s ended unexpectedly, which means"
806 " that it is probably corrupted."),
807 from_utf8(filename.absFilename())));
810 d->file_fully_loaded = true;
815 // Should probably be moved to somewhere else: BufferView? LyXView?
816 bool Buffer::save() const
818 // We don't need autosaves in the immediate future. (Asger)
819 resetAutosaveTimers();
821 string const encodedFilename = d->filename.toFilesystemEncoding();
824 bool madeBackup = false;
826 // make a backup if the file already exists
827 if (lyxrc.make_backup && fileName().exists()) {
828 backupName = FileName(absFileName() + '~');
829 if (!lyxrc.backupdir_path.empty()) {
830 string const mangledName =
831 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
832 backupName = FileName(addName(lyxrc.backupdir_path,
835 if (fileName().copyTo(backupName)) {
838 Alert::error(_("Backup failure"),
839 bformat(_("Cannot create backup file %1$s.\n"
840 "Please check whether the directory exists and is writeable."),
841 from_utf8(backupName.absFilename())));
842 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
846 // ask if the disk file has been externally modified (use checksum method)
847 if (fileName().exists() && isExternallyModified(checksum_method)) {
848 docstring const file = makeDisplayPath(absFileName(), 20);
849 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
850 "you want to overwrite this file?"), file);
851 int const ret = Alert::prompt(_("Overwrite modified file?"),
852 text, 1, 1, _("&Overwrite"), _("&Cancel"));
857 if (writeFile(d->filename)) {
861 // Saving failed, so backup is not backup
863 backupName.moveTo(d->filename);
869 bool Buffer::writeFile(FileName const & fname) const
871 if (d->read_only && fname == d->filename)
877 if (params().embedded)
878 // first write the .lyx file to the temporary directory
879 content = FileName(addName(temppath(), "content.lyx"));
883 docstring const str = bformat(_("Saving document %1$s..."),
884 makeDisplayPath(content.absFilename()));
887 if (params().compressed) {
888 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
889 retval = ofs && write(ofs);
891 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
892 retval = ofs && write(ofs);
896 message(str + _(" could not write file!."));
900 removeAutosaveFile(d->filename.absFilename());
901 saveCheckSum(d->filename);
902 message(str + _(" done."));
904 if (!params().embedded)
907 message(str + _(" writing embedded files!."));
908 // if embedding is enabled, write file.lyx and all the embedded files
909 // to the zip file fname.
910 if (!d->embedded_files.writeFile(fname)) {
911 message(str + _(" could not write embedded files!."));
914 message(str + _(" error while writing embedded files."));
919 bool Buffer::write(ostream & ofs) const
922 // Use the standard "C" locale for file output.
923 ofs.imbue(locale::classic());
926 // The top of the file should not be written by params().
928 // write out a comment in the top of the file
929 ofs << "#LyX " << lyx_version
930 << " created this file. For more info see http://www.lyx.org/\n"
931 << "\\lyxformat " << LYX_FORMAT << "\n"
932 << "\\begin_document\n";
935 /// For each author, set 'used' to true if there is a change
936 /// by this author in the document; otherwise set it to 'false'.
937 AuthorList::Authors::const_iterator a_it = params().authors().begin();
938 AuthorList::Authors::const_iterator a_end = params().authors().end();
939 for (; a_it != a_end; ++a_it)
940 a_it->second.setUsed(false);
942 ParIterator const end = par_iterator_end();
943 ParIterator it = par_iterator_begin();
944 for ( ; it != end; ++it)
945 it->checkAuthors(params().authors());
947 // now write out the buffer parameters.
948 ofs << "\\begin_header\n";
949 params().writeFile(ofs);
950 ofs << "\\end_header\n";
953 ofs << "\n\\begin_body\n";
954 text().write(*this, ofs);
955 ofs << "\n\\end_body\n";
957 // Write marker that shows file is complete
958 ofs << "\\end_document" << endl;
960 // Shouldn't really be needed....
963 // how to check if close went ok?
964 // Following is an attempt... (BE 20001011)
966 // good() returns false if any error occured, including some
968 // bad() returns true if something bad happened in the buffer,
969 // which should include file system full errors.
974 lyxerr << "File was not closed properly." << endl;
981 bool Buffer::makeLaTeXFile(FileName const & fname,
982 string const & original_path,
983 OutputParams const & runparams,
984 bool output_preamble, bool output_body) const
986 string const encoding = runparams.encoding->iconvName();
987 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
990 try { ofs.reset(encoding); }
991 catch (iconv_codecvt_facet_exception & e) {
992 lyxerr << "Caught iconv exception: " << e.what() << endl;
993 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
994 "verify that the support software for your encoding (%1$s) is "
995 "properly installed"), from_ascii(encoding)));
998 if (!openFileWrite(ofs, fname))
1001 //TexStream ts(ofs.rdbuf(), &texrow());
1002 ErrorList & errorList = d->errorLists["Export"];
1004 bool failed_export = false;
1007 writeLaTeXSource(ofs, original_path,
1008 runparams, output_preamble, output_body);
1010 catch (EncodingException & e) {
1011 docstring msg = _("Could not find LaTeX command for character '%'");
1012 msg[msg.size() - 2] = e.failed_char;
1013 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1014 "representable in the chosen encoding.\n"
1015 "Changing the document encoding to utf8 could help."),
1016 e.par_id, e.pos, e.pos + 1));
1017 failed_export = true;
1019 catch (iconv_codecvt_facet_exception & e) {
1020 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1021 _(e.what()), -1, 0, 0));
1022 failed_export = true;
1024 catch (exception const & e) {
1025 errorList.push_back(ErrorItem(_("conversion failed"),
1026 _(e.what()), -1, 0, 0));
1027 failed_export = true;
1030 lyxerr << "Caught some really weird exception..." << endl;
1031 LyX::cref().exit(1);
1036 failed_export = true;
1037 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1041 return !failed_export;
1045 void Buffer::writeLaTeXSource(odocstream & os,
1046 string const & original_path,
1047 OutputParams const & runparams_in,
1048 bool const output_preamble, bool const output_body) const
1050 OutputParams runparams = runparams_in;
1052 // validate the buffer.
1053 LYXERR(Debug::LATEX, " Validating buffer...");
1054 LaTeXFeatures features(*this, params(), runparams);
1056 LYXERR(Debug::LATEX, " Buffer validation done.");
1058 // The starting paragraph of the coming rows is the
1059 // first paragraph of the document. (Asger)
1060 if (output_preamble && runparams.nice) {
1061 os << "%% LyX " << lyx_version << " created this file. "
1062 "For more info, see http://www.lyx.org/.\n"
1063 "%% Do not edit unless you really know what "
1065 d->texrow.newline();
1066 d->texrow.newline();
1068 LYXERR(Debug::INFO, "lyx document header finished");
1069 // There are a few differences between nice LaTeX and usual files:
1070 // usual is \batchmode and has a
1071 // special input@path to allow the including of figures
1072 // with either \input or \includegraphics (what figinsets do).
1073 // input@path is set when the actual parameter
1074 // original_path is set. This is done for usual tex-file, but not
1075 // for nice-latex-file. (Matthias 250696)
1076 // Note that input@path is only needed for something the user does
1077 // in the preamble, included .tex files or ERT, files included by
1078 // LyX work without it.
1079 if (output_preamble) {
1080 if (!runparams.nice) {
1081 // code for usual, NOT nice-latex-file
1082 os << "\\batchmode\n"; // changed
1083 // from \nonstopmode
1084 d->texrow.newline();
1086 if (!original_path.empty()) {
1088 // We don't know the encoding of inputpath
1089 docstring const inputpath = from_utf8(latex_path(original_path));
1090 os << "\\makeatletter\n"
1091 << "\\def\\input@path{{"
1092 << inputpath << "/}}\n"
1093 << "\\makeatother\n";
1094 d->texrow.newline();
1095 d->texrow.newline();
1096 d->texrow.newline();
1099 // Write the preamble
1100 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1106 os << "\\begin{document}\n";
1107 d->texrow.newline();
1108 } // output_preamble
1110 d->texrow.start(paragraphs().begin()->id(), 0);
1112 LYXERR(Debug::INFO, "preamble finished, now the body.");
1114 // if we are doing a real file with body, even if this is the
1115 // child of some other buffer, let's cut the link here.
1116 // This happens for example if only a child document is printed.
1117 Buffer const * save_parent = 0;
1118 if (output_preamble) {
1119 save_parent = d->parent_buffer;
1120 d->parent_buffer = 0;
1123 loadChildDocuments();
1126 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1128 // Restore the parenthood if needed
1129 if (output_preamble)
1130 d->parent_buffer = save_parent;
1132 // add this just in case after all the paragraphs
1134 d->texrow.newline();
1136 if (output_preamble) {
1137 os << "\\end{document}\n";
1138 d->texrow.newline();
1139 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1141 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1143 runparams_in.encoding = runparams.encoding;
1145 // Just to be sure. (Asger)
1146 d->texrow.newline();
1148 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1149 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1153 bool Buffer::isLatex() const
1155 return params().getTextClass().outputType() == LATEX;
1159 bool Buffer::isLiterate() const
1161 return params().getTextClass().outputType() == LITERATE;
1165 bool Buffer::isDocBook() const
1167 return params().getTextClass().outputType() == DOCBOOK;
1171 void Buffer::makeDocBookFile(FileName const & fname,
1172 OutputParams const & runparams,
1173 bool const body_only) const
1175 LYXERR(Debug::LATEX, "makeDocBookFile...");
1179 if (!openFileWrite(ofs, fname))
1182 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1186 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1190 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1191 OutputParams const & runparams,
1192 bool const only_body) const
1194 LaTeXFeatures features(*this, params(), runparams);
1199 TextClass const & tclass = params().getTextClass();
1200 string const top_element = tclass.latexname();
1203 if (runparams.flavor == OutputParams::XML)
1204 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1207 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1210 if (! tclass.class_header().empty())
1211 os << from_ascii(tclass.class_header());
1212 else if (runparams.flavor == OutputParams::XML)
1213 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1214 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1216 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1218 docstring preamble = from_utf8(params().preamble);
1219 if (runparams.flavor != OutputParams::XML ) {
1220 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1221 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1222 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1223 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1226 string const name = runparams.nice
1227 ? changeExtension(absFileName(), ".sgml") : fname;
1228 preamble += features.getIncludedFiles(name);
1229 preamble += features.getLyXSGMLEntities();
1231 if (!preamble.empty()) {
1232 os << "\n [ " << preamble << " ]";
1237 string top = top_element;
1239 if (runparams.flavor == OutputParams::XML)
1240 top += params().language->code();
1242 top += params().language->code().substr(0,2);
1245 if (!params().options.empty()) {
1247 top += params().options;
1250 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1251 << " file was created by LyX " << lyx_version
1252 << "\n See http://www.lyx.org/ for more information -->\n";
1254 params().getTextClass().counters().reset();
1256 loadChildDocuments();
1258 sgml::openTag(os, top);
1260 docbookParagraphs(paragraphs(), *this, os, runparams);
1261 sgml::closeTag(os, top_element);
1265 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1266 // Other flags: -wall -v0 -x
1267 int Buffer::runChktex()
1271 // get LaTeX-Filename
1272 FileName const path(temppath());
1273 string const name = addName(path.absFilename(), latexName());
1274 string const org_path = filePath();
1276 PathChanger p(path); // path to LaTeX file
1277 message(_("Running chktex..."));
1279 // Generate the LaTeX file if neccessary
1280 OutputParams runparams(¶ms().encoding());
1281 runparams.flavor = OutputParams::LATEX;
1282 runparams.nice = false;
1283 makeLaTeXFile(FileName(name), org_path, runparams);
1286 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1287 int const res = chktex.run(terr); // run chktex
1290 Alert::error(_("chktex failure"),
1291 _("Could not run chktex successfully."));
1292 } else if (res > 0) {
1293 ErrorList & errlist = d->errorLists["ChkTeX"];
1295 bufferErrors(terr, errlist);
1306 void Buffer::validate(LaTeXFeatures & features) const
1308 params().validate(features);
1310 loadChildDocuments();
1312 for_each(paragraphs().begin(), paragraphs().end(),
1313 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1315 if (lyxerr.debugging(Debug::LATEX)) {
1316 features.showStruct();
1321 void Buffer::getLabelList(vector<docstring> & list) const
1323 /// if this is a child document and the parent is already loaded
1324 /// Use the parent's list instead [ale990407]
1325 Buffer const * tmp = masterBuffer();
1327 lyxerr << "masterBuffer() failed!" << endl;
1331 tmp->getLabelList(list);
1335 loadChildDocuments();
1337 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1338 it.nextInset()->getLabelList(*this, list);
1342 void Buffer::updateBibfilesCache() const
1344 // if this is a child document and the parent is already loaded
1345 // update the parent's cache instead
1346 Buffer const * tmp = masterBuffer();
1349 tmp->updateBibfilesCache();
1353 d->bibfilesCache_.clear();
1354 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1355 if (it->lyxCode() == BIBTEX_CODE) {
1356 InsetBibtex const & inset =
1357 static_cast<InsetBibtex const &>(*it);
1358 FileNameList const bibfiles = inset.getFiles(*this);
1359 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1362 } else if (it->lyxCode() == INCLUDE_CODE) {
1363 InsetInclude & inset =
1364 static_cast<InsetInclude &>(*it);
1365 inset.updateBibfilesCache(*this);
1366 FileNameList const & bibfiles =
1367 inset.getBibfilesCache(*this);
1368 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1376 FileNameList const & Buffer::getBibfilesCache() const
1378 // if this is a child document and the parent is already loaded
1379 // use the parent's cache instead
1380 Buffer const * tmp = masterBuffer();
1383 return tmp->getBibfilesCache();
1385 // We update the cache when first used instead of at loading time.
1386 if (d->bibfilesCache_.empty())
1387 const_cast<Buffer *>(this)->updateBibfilesCache();
1389 return d->bibfilesCache_;
1393 bool Buffer::isDepClean(string const & name) const
1395 DepClean::const_iterator const it = d->dep_clean.find(name);
1396 if (it == d->dep_clean.end())
1402 void Buffer::markDepClean(string const & name)
1404 d->dep_clean[name] = true;
1408 bool Buffer::dispatch(string const & command, bool * result)
1410 return dispatch(lyxaction.lookupFunc(command), result);
1414 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1416 bool dispatched = true;
1418 switch (func.action) {
1419 case LFUN_BUFFER_EXPORT: {
1420 bool const tmp = doExport(to_utf8(func.argument()), false);
1433 void Buffer::changeLanguage(Language const * from, Language const * to)
1438 for_each(par_iterator_begin(),
1440 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1444 bool Buffer::isMultiLingual() const
1446 ParConstIterator end = par_iterator_end();
1447 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1448 if (it->isMultiLingual(params()))
1455 ParIterator Buffer::getParFromID(int const id) const
1457 ParConstIterator it = par_iterator_begin();
1458 ParConstIterator const end = par_iterator_end();
1461 // John says this is called with id == -1 from undo
1462 lyxerr << "getParFromID(), id: " << id << endl;
1466 for (; it != end; ++it)
1474 bool Buffer::hasParWithID(int const id) const
1476 ParConstIterator const it = getParFromID(id);
1477 return it != par_iterator_end();
1481 ParIterator Buffer::par_iterator_begin()
1483 return lyx::par_iterator_begin(inset());
1487 ParIterator Buffer::par_iterator_end()
1489 return lyx::par_iterator_end(inset());
1493 ParConstIterator Buffer::par_iterator_begin() const
1495 return lyx::par_const_iterator_begin(inset());
1499 ParConstIterator Buffer::par_iterator_end() const
1501 return lyx::par_const_iterator_end(inset());
1505 Language const * Buffer::language() const
1507 return params().language;
1511 docstring const Buffer::B_(string const & l10n) const
1513 return params().B_(l10n);
1517 bool Buffer::isClean() const
1519 return d->lyx_clean;
1523 bool Buffer::isBakClean() const
1525 return d->bak_clean;
1529 bool Buffer::isExternallyModified(CheckMethod method) const
1531 BOOST_ASSERT(d->filename.exists());
1532 // if method == timestamp, check timestamp before checksum
1533 return (method == checksum_method
1534 || d->timestamp_ != d->filename.lastModified())
1535 && d->checksum_ != d->filename.checksum();
1539 void Buffer::saveCheckSum(FileName const & file) const
1541 if (file.exists()) {
1542 d->timestamp_ = file.lastModified();
1543 d->checksum_ = file.checksum();
1545 // in the case of save to a new file.
1552 void Buffer::markClean() const
1554 if (!d->lyx_clean) {
1555 d->lyx_clean = true;
1558 // if the .lyx file has been saved, we don't need an
1560 d->bak_clean = true;
1564 void Buffer::markBakClean() const
1566 d->bak_clean = true;
1570 void Buffer::setUnnamed(bool flag)
1576 bool Buffer::isUnnamed() const
1582 // FIXME: this function should be moved to buffer_pimpl.C
1583 void Buffer::markDirty()
1586 d->lyx_clean = false;
1589 d->bak_clean = false;
1591 DepClean::iterator it = d->dep_clean.begin();
1592 DepClean::const_iterator const end = d->dep_clean.end();
1594 for (; it != end; ++it)
1599 FileName Buffer::fileName() const
1605 string Buffer::absFileName() const
1607 return d->filename.absFilename();
1611 string Buffer::filePath() const
1613 return d->filename.onlyPath().absFilename();
1617 bool Buffer::isReadonly() const
1619 return d->read_only;
1623 void Buffer::setParent(Buffer const * buffer)
1625 // Avoids recursive include.
1626 d->parent_buffer = buffer == this ? 0 : buffer;
1630 Buffer const * Buffer::parent()
1632 return d->parent_buffer;
1636 Buffer const * Buffer::masterBuffer() const
1638 if (!d->parent_buffer)
1641 return d->parent_buffer->masterBuffer();
1645 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1647 Impl::PositionToMacroMap::iterator it;
1648 it = d->macros[name].upper_bound(par.macrocontextPosition());
1649 if (it != d->macros[name].end())
1652 // If there is a master buffer, query that
1653 Buffer const * master = masterBuffer();
1654 if (master && master != this)
1655 return master->hasMacro(name);
1657 return MacroTable::globalMacros().has(name);
1661 bool Buffer::hasMacro(docstring const & name) const
1663 if( !d->macros[name].empty() )
1666 // If there is a master buffer, query that
1667 Buffer const * master = masterBuffer();
1668 if (master && master != this)
1669 return master->hasMacro(name);
1671 return MacroTable::globalMacros().has(name);
1675 MacroData const & Buffer::getMacro(docstring const & name,
1676 Paragraph const & par) const
1678 Impl::PositionToMacroMap::iterator it;
1679 it = d->macros[name].upper_bound(par.macrocontextPosition());
1680 if( it != d->macros[name].end() )
1683 // If there is a master buffer, query that
1684 Buffer const * master = masterBuffer();
1685 if (master && master != this)
1686 return master->getMacro(name);
1688 return MacroTable::globalMacros().get(name);
1692 MacroData const & Buffer::getMacro(docstring const & name) const
1694 Impl::PositionToMacroMap::iterator it;
1695 it = d->macros[name].begin();
1696 if( it != d->macros[name].end() )
1699 // If there is a master buffer, query that
1700 Buffer const * master = masterBuffer();
1701 if (master && master != this)
1702 return master->getMacro(name);
1704 return MacroTable::globalMacros().get(name);
1708 void Buffer::updateMacros()
1710 // start with empty table
1711 d->macros = Impl::NameToPositionMacroMap();
1713 // Iterate over buffer
1714 ParagraphList & pars = text().paragraphs();
1715 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1716 // set position again
1717 pars[i].setMacrocontextPosition(i);
1719 //lyxerr << "searching main par " << i
1720 // << " for macro definitions" << endl;
1721 InsetList const & insets = pars[i].insetList();
1722 InsetList::const_iterator it = insets.begin();
1723 InsetList::const_iterator end = insets.end();
1724 for ( ; it != end; ++it) {
1725 if (it->inset->lyxCode() != MATHMACRO_CODE)
1729 MathMacroTemplate const & macroTemplate
1730 = static_cast<MathMacroTemplate const &>(*it->inset);
1733 if (macroTemplate.validMacro()) {
1734 MacroData macro = macroTemplate.asMacroData();
1737 // call hasMacro here instead of directly querying mc to
1738 // also take the master document into consideration
1739 macro.setRedefinition(hasMacro(macroTemplate.name()));
1741 // register macro (possibly overwrite the previous one of this paragraph)
1742 d->macros[macroTemplate.name()][i] = macro;
1749 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1752 //FIXME: This does not work for child documents yet.
1753 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1754 // Check if the label 'from' appears more than once
1755 vector<docstring> labels;
1758 if (code == CITE_CODE) {
1760 keys.fillWithBibKeys(this);
1761 BiblioInfo::const_iterator bit = keys.begin();
1762 BiblioInfo::const_iterator bend = keys.end();
1764 for (; bit != bend; ++bit)
1766 labels.push_back(bit->first);
1769 getLabelList(labels);
1770 paramName = "reference";
1773 if (count(labels.begin(), labels.end(), from) > 1)
1776 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1777 if (it->lyxCode() == code) {
1778 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1779 docstring const oldValue = inset.getParam(paramName);
1780 if (oldValue == from)
1781 inset.setParam(paramName, to);
1787 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1788 pit_type par_end, bool full_source)
1790 OutputParams runparams(¶ms().encoding());
1791 runparams.nice = true;
1792 runparams.flavor = OutputParams::LATEX;
1793 runparams.linelen = lyxrc.plaintext_linelen;
1794 // No side effect of file copying and image conversion
1795 runparams.dryrun = true;
1799 os << "% " << _("Preview source code") << "\n\n";
1800 d->texrow.newline();
1801 d->texrow.newline();
1803 writeLaTeXSource(os, filePath(), runparams, true, true);
1805 writeDocBookSource(os, absFileName(), runparams, false);
1808 runparams.par_begin = par_begin;
1809 runparams.par_end = par_end;
1810 if (par_begin + 1 == par_end)
1812 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1816 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1817 convert<docstring>(par_begin),
1818 convert<docstring>(par_end - 1))
1820 d->texrow.newline();
1821 d->texrow.newline();
1822 // output paragraphs
1824 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1827 docbookParagraphs(paragraphs(), *this, os, runparams);
1833 ErrorList & Buffer::errorList(string const & type) const
1835 static ErrorList emptyErrorList;
1836 map<string, ErrorList>::iterator I = d->errorLists.find(type);
1837 if (I == d->errorLists.end())
1838 return emptyErrorList;
1844 void Buffer::structureChanged() const
1847 gui_->structureChanged();
1851 void Buffer::errors(string const & err) const
1858 void Buffer::message(docstring const & msg) const
1865 void Buffer::setBusy(bool on) const
1872 void Buffer::setReadOnly(bool on) const
1875 d->wa_->setReadOnly(on);
1879 void Buffer::updateTitles() const
1882 d->wa_->updateTitles();
1886 void Buffer::resetAutosaveTimers() const
1889 gui_->resetAutosaveTimers();
1893 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1902 class AutoSaveBuffer : public ForkedProcess {
1905 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1906 : buffer_(buffer), fname_(fname) {}
1908 virtual boost::shared_ptr<ForkedProcess> clone() const
1910 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1915 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
1916 from_utf8(fname_.absFilename())));
1917 return run(DontWait);
1921 virtual int generateChild();
1923 Buffer const & buffer_;
1928 #if !defined (HAVE_FORK)
1932 int AutoSaveBuffer::generateChild()
1934 // tmp_ret will be located (usually) in /tmp
1935 // will that be a problem?
1936 pid_t const pid = fork();
1937 // If you want to debug the autosave
1938 // you should set pid to -1, and comment out the fork.
1939 if (pid == 0 || pid == -1) {
1940 // pid = -1 signifies that lyx was unable
1941 // to fork. But we will do the save
1943 bool failed = false;
1945 FileName const tmp_ret = FileName::tempName("lyxauto");
1946 if (!tmp_ret.empty()) {
1947 buffer_.writeFile(tmp_ret);
1948 // assume successful write of tmp_ret
1949 if (!tmp_ret.moveTo(fname_)) {
1951 // most likely couldn't move between
1952 // filesystems unless write of tmp_ret
1953 // failed so remove tmp file (if it
1955 tmp_ret.removeFile();
1962 // failed to write/rename tmp_ret so try writing direct
1963 if (!buffer_.writeFile(fname_)) {
1964 // It is dangerous to do this in the child,
1965 // but safe in the parent, so...
1966 if (pid == -1) // emit message signal.
1967 buffer_.message(_("Autosave failed!"));
1970 if (pid == 0) { // we are the child so...
1980 // Perfect target for a thread...
1981 void Buffer::autoSave() const
1983 if (isBakClean() || isReadonly()) {
1984 // We don't save now, but we'll try again later
1985 resetAutosaveTimers();
1989 // emit message signal.
1990 message(_("Autosaving current document..."));
1992 // create autosave filename
1993 string fname = filePath();
1995 fname += d->filename.onlyFileName();
1998 AutoSaveBuffer autosave(*this, FileName(fname));
2002 resetAutosaveTimers();
2006 void Buffer::resetChildDocuments(bool close_them) const
2008 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2009 if (it->lyxCode() != INCLUDE_CODE)
2011 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2012 InsetCommandParams const & ip = inset.params();
2014 resetParentBuffer(this, ip, close_them);
2017 if (use_gui && masterBuffer() == this)
2018 updateLabels(*this);
2022 void Buffer::loadChildDocuments() const
2024 bool parse_error = false;
2026 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2027 if (it->lyxCode() != INCLUDE_CODE)
2029 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2030 InsetCommandParams const & ip = inset.params();
2031 Buffer * child = loadIfNeeded(*this, ip);
2034 parse_error |= !child->errorList("Parse").empty();
2035 child->loadChildDocuments();
2038 if (use_gui && masterBuffer() == this)
2039 updateLabels(*this);
2043 string Buffer::bufferFormat() const
2053 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2054 string & result_file) const
2056 string backend_format;
2057 OutputParams runparams(¶ms().encoding());
2058 runparams.flavor = OutputParams::LATEX;
2059 runparams.linelen = lyxrc.plaintext_linelen;
2060 vector<string> backs = backends();
2061 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2062 // Get shortest path to format
2063 Graph::EdgePath path;
2064 for (vector<string>::const_iterator it = backs.begin();
2065 it != backs.end(); ++it) {
2066 Graph::EdgePath p = theConverters().getPath(*it, format);
2067 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2068 backend_format = *it;
2073 runparams.flavor = theConverters().getFlavor(path);
2075 Alert::error(_("Couldn't export file"),
2076 bformat(_("No information for exporting the format %1$s."),
2077 formats.prettyName(format)));
2081 backend_format = format;
2082 // FIXME: Don't hardcode format names here, but use a flag
2083 if (backend_format == "pdflatex")
2084 runparams.flavor = OutputParams::PDFLATEX;
2087 string filename = latexName(false);
2088 filename = addName(temppath(), filename);
2089 filename = changeExtension(filename,
2090 formats.extension(backend_format));
2092 // Plain text backend
2093 if (backend_format == "text")
2094 writePlaintextFile(*this, FileName(filename), runparams);
2096 else if (backend_format == "lyx")
2097 writeFile(FileName(filename));
2099 else if (isDocBook()) {
2100 runparams.nice = !put_in_tempdir;
2101 makeDocBookFile(FileName(filename), runparams);
2104 else if (backend_format == format) {
2105 runparams.nice = true;
2106 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2108 } else if (!lyxrc.tex_allows_spaces
2109 && contains(filePath(), ' ')) {
2110 Alert::error(_("File name error"),
2111 _("The directory path to the document cannot contain spaces."));
2114 runparams.nice = false;
2115 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2119 string const error_type = (format == "program")
2120 ? "Build" : bufferFormat();
2121 string const ext = formats.extension(format);
2122 FileName const tmp_result_file(changeExtension(filename, ext));
2123 bool const success = theConverters().convert(this, FileName(filename),
2124 tmp_result_file, FileName(absFileName()), backend_format, format,
2125 errorList(error_type));
2126 // Emit the signal to show the error list.
2127 if (format != backend_format)
2133 result_file = tmp_result_file.absFilename();
2135 result_file = changeExtension(absFileName(), ext);
2136 // We need to copy referenced files (e. g. included graphics
2137 // if format == "dvi") to the result dir.
2138 vector<ExportedFile> const files =
2139 runparams.exportdata->externalFiles(format);
2140 string const dest = onlyPath(result_file);
2141 CopyStatus status = SUCCESS;
2142 for (vector<ExportedFile>::const_iterator it = files.begin();
2143 it != files.end() && status != CANCEL; ++it) {
2145 formats.getFormatFromFile(it->sourceName);
2146 status = copyFile(fmt, it->sourceName,
2147 makeAbsPath(it->exportName, dest),
2148 it->exportName, status == FORCE);
2150 if (status == CANCEL) {
2151 message(_("Document export cancelled."));
2152 } else if (tmp_result_file.exists()) {
2153 // Finally copy the main file
2154 status = copyFile(format, tmp_result_file,
2155 FileName(result_file), result_file,
2157 message(bformat(_("Document exported as %1$s "
2159 formats.prettyName(format),
2160 makeDisplayPath(result_file)));
2162 // This must be a dummy converter like fax (bug 1888)
2163 message(bformat(_("Document exported as %1$s"),
2164 formats.prettyName(format)));
2172 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2175 return doExport(format, put_in_tempdir, result_file);
2179 bool Buffer::preview(string const & format) const
2182 if (!doExport(format, true, result_file))
2184 return formats.view(*this, FileName(result_file), format);
2188 bool Buffer::isExportable(string const & format) const
2190 vector<string> backs = backends();
2191 for (vector<string>::const_iterator it = backs.begin();
2192 it != backs.end(); ++it)
2193 if (theConverters().isReachable(*it, format))
2199 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2201 vector<string> backs = backends();
2202 vector<Format const *> result =
2203 theConverters().getReachable(backs[0], only_viewable, true);
2204 for (vector<string>::const_iterator it = backs.begin() + 1;
2205 it != backs.end(); ++it) {
2206 vector<Format const *> r =
2207 theConverters().getReachable(*it, only_viewable, false);
2208 result.insert(result.end(), r.begin(), r.end());
2214 vector<string> Buffer::backends() const
2217 if (params().getTextClass().isTeXClassAvailable()) {
2218 v.push_back(bufferFormat());
2219 // FIXME: Don't hardcode format names here, but use a flag
2220 if (v.back() == "latex")
2221 v.push_back("pdflatex");
2223 v.push_back("text");
2229 bool Buffer::readFileHelper(FileName const & s)
2231 // File information about normal file
2233 docstring const file = makeDisplayPath(s.absFilename(), 50);
2234 docstring text = bformat(_("The specified document\n%1$s"
2235 "\ncould not be read."), file);
2236 Alert::error(_("Could not read document"), text);
2240 // Check if emergency save file exists and is newer.
2241 FileName const e(s.absFilename() + ".emergency");
2243 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2244 docstring const file = makeDisplayPath(s.absFilename(), 20);
2245 docstring const text =
2246 bformat(_("An emergency save of the document "
2248 "Recover emergency save?"), file);
2249 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2250 _("&Recover"), _("&Load Original"),
2254 // the file is not saved if we load the emergency file.
2264 // Now check if autosave file is newer.
2265 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2267 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2268 docstring const file = makeDisplayPath(s.absFilename(), 20);
2269 docstring const text =
2270 bformat(_("The backup of the document "
2271 "%1$s is newer.\n\nLoad the "
2272 "backup instead?"), file);
2273 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2274 _("&Load backup"), _("Load &original"),
2278 // the file is not saved if we load the autosave file.
2282 // Here we delete the autosave
2293 bool Buffer::loadLyXFile(FileName const & s)
2295 if (s.isReadableFile()) {
2296 if (readFileHelper(s)) {
2297 lyxvc().file_found_hook(s);
2298 if (!s.isWritable())
2303 docstring const file = makeDisplayPath(s.absFilename(), 20);
2304 // Here we probably should run
2305 if (LyXVC::file_not_found_hook(s)) {
2306 docstring const text =
2307 bformat(_("Do you want to retrieve the document"
2308 " %1$s from version control?"), file);
2309 int const ret = Alert::prompt(_("Retrieve from version control?"),
2310 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2313 // How can we know _how_ to do the checkout?
2314 // With the current VC support it has to be,
2315 // a RCS file since CVS do not have special ,v files.
2317 return loadLyXFile(s);
2325 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2327 TeXErrors::Errors::const_iterator cit = terr.begin();
2328 TeXErrors::Errors::const_iterator end = terr.end();
2330 for (; cit != end; ++cit) {
2333 int errorRow = cit->error_in_line;
2334 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2340 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2341 } while (found && id_start == id_end && pos_start == pos_end);
2343 errorList.push_back(ErrorItem(cit->error_desc,
2344 cit->error_text, id_start, pos_start, pos_end));