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());
1003 bool failed_export = false;
1006 writeLaTeXSource(ofs, original_path,
1007 runparams, output_preamble, output_body);
1009 catch (iconv_codecvt_facet_exception & e) {
1010 lyxerr << "Caught iconv exception: " << e.what() << endl;
1011 failed_export = true;
1013 catch (exception const & e) {
1014 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
1015 failed_export = true;
1018 lyxerr << "Caught some really weird exception..." << endl;
1019 LyX::cref().exit(1);
1024 failed_export = true;
1025 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1028 if (failed_export) {
1029 Alert::error(_("Encoding error"),
1030 _("Some characters of your document are probably not "
1031 "representable in the chosen encoding.\n"
1032 "Changing the document encoding to utf8 could help."));
1039 void Buffer::writeLaTeXSource(odocstream & os,
1040 string const & original_path,
1041 OutputParams const & runparams_in,
1042 bool const output_preamble, bool const output_body) const
1044 OutputParams runparams = runparams_in;
1046 // validate the buffer.
1047 LYXERR(Debug::LATEX, " Validating buffer...");
1048 LaTeXFeatures features(*this, params(), runparams);
1050 LYXERR(Debug::LATEX, " Buffer validation done.");
1052 // The starting paragraph of the coming rows is the
1053 // first paragraph of the document. (Asger)
1054 if (output_preamble && runparams.nice) {
1055 os << "%% LyX " << lyx_version << " created this file. "
1056 "For more info, see http://www.lyx.org/.\n"
1057 "%% Do not edit unless you really know what "
1059 d->texrow.newline();
1060 d->texrow.newline();
1062 LYXERR(Debug::INFO, "lyx document header finished");
1063 // There are a few differences between nice LaTeX and usual files:
1064 // usual is \batchmode and has a
1065 // special input@path to allow the including of figures
1066 // with either \input or \includegraphics (what figinsets do).
1067 // input@path is set when the actual parameter
1068 // original_path is set. This is done for usual tex-file, but not
1069 // for nice-latex-file. (Matthias 250696)
1070 // Note that input@path is only needed for something the user does
1071 // in the preamble, included .tex files or ERT, files included by
1072 // LyX work without it.
1073 if (output_preamble) {
1074 if (!runparams.nice) {
1075 // code for usual, NOT nice-latex-file
1076 os << "\\batchmode\n"; // changed
1077 // from \nonstopmode
1078 d->texrow.newline();
1080 if (!original_path.empty()) {
1082 // We don't know the encoding of inputpath
1083 docstring const inputpath = from_utf8(latex_path(original_path));
1084 os << "\\makeatletter\n"
1085 << "\\def\\input@path{{"
1086 << inputpath << "/}}\n"
1087 << "\\makeatother\n";
1088 d->texrow.newline();
1089 d->texrow.newline();
1090 d->texrow.newline();
1093 // Write the preamble
1094 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1100 os << "\\begin{document}\n";
1101 d->texrow.newline();
1102 } // output_preamble
1104 d->texrow.start(paragraphs().begin()->id(), 0);
1106 LYXERR(Debug::INFO, "preamble finished, now the body.");
1108 // if we are doing a real file with body, even if this is the
1109 // child of some other buffer, let's cut the link here.
1110 // This happens for example if only a child document is printed.
1111 Buffer const * save_parent = 0;
1112 if (output_preamble) {
1113 save_parent = d->parent_buffer;
1114 d->parent_buffer = 0;
1117 loadChildDocuments();
1120 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1122 // Restore the parenthood if needed
1123 if (output_preamble)
1124 d->parent_buffer = save_parent;
1126 // add this just in case after all the paragraphs
1128 d->texrow.newline();
1130 if (output_preamble) {
1131 os << "\\end{document}\n";
1132 d->texrow.newline();
1133 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1135 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1137 runparams_in.encoding = runparams.encoding;
1139 // Just to be sure. (Asger)
1140 d->texrow.newline();
1142 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1143 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1147 bool Buffer::isLatex() const
1149 return params().getTextClass().outputType() == LATEX;
1153 bool Buffer::isLiterate() const
1155 return params().getTextClass().outputType() == LITERATE;
1159 bool Buffer::isDocBook() const
1161 return params().getTextClass().outputType() == DOCBOOK;
1165 void Buffer::makeDocBookFile(FileName const & fname,
1166 OutputParams const & runparams,
1167 bool const body_only) const
1169 LYXERR(Debug::LATEX, "makeDocBookFile...");
1173 if (!openFileWrite(ofs, fname))
1176 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1180 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1184 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1185 OutputParams const & runparams,
1186 bool const only_body) const
1188 LaTeXFeatures features(*this, params(), runparams);
1193 TextClass const & tclass = params().getTextClass();
1194 string const top_element = tclass.latexname();
1197 if (runparams.flavor == OutputParams::XML)
1198 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1201 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1204 if (! tclass.class_header().empty())
1205 os << from_ascii(tclass.class_header());
1206 else if (runparams.flavor == OutputParams::XML)
1207 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1208 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1210 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1212 docstring preamble = from_utf8(params().preamble);
1213 if (runparams.flavor != OutputParams::XML ) {
1214 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1215 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1216 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1217 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1220 string const name = runparams.nice
1221 ? changeExtension(absFileName(), ".sgml") : fname;
1222 preamble += features.getIncludedFiles(name);
1223 preamble += features.getLyXSGMLEntities();
1225 if (!preamble.empty()) {
1226 os << "\n [ " << preamble << " ]";
1231 string top = top_element;
1233 if (runparams.flavor == OutputParams::XML)
1234 top += params().language->code();
1236 top += params().language->code().substr(0,2);
1239 if (!params().options.empty()) {
1241 top += params().options;
1244 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1245 << " file was created by LyX " << lyx_version
1246 << "\n See http://www.lyx.org/ for more information -->\n";
1248 params().getTextClass().counters().reset();
1250 loadChildDocuments();
1252 sgml::openTag(os, top);
1254 docbookParagraphs(paragraphs(), *this, os, runparams);
1255 sgml::closeTag(os, top_element);
1259 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1260 // Other flags: -wall -v0 -x
1261 int Buffer::runChktex()
1265 // get LaTeX-Filename
1266 FileName const path(temppath());
1267 string const name = addName(path.absFilename(), latexName());
1268 string const org_path = filePath();
1270 PathChanger p(path); // path to LaTeX file
1271 message(_("Running chktex..."));
1273 // Generate the LaTeX file if neccessary
1274 OutputParams runparams(¶ms().encoding());
1275 runparams.flavor = OutputParams::LATEX;
1276 runparams.nice = false;
1277 makeLaTeXFile(FileName(name), org_path, runparams);
1280 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1281 int const res = chktex.run(terr); // run chktex
1284 Alert::error(_("chktex failure"),
1285 _("Could not run chktex successfully."));
1286 } else if (res > 0) {
1287 ErrorList & errlist = d->errorLists["ChkTeX"];
1289 bufferErrors(terr, errlist);
1300 void Buffer::validate(LaTeXFeatures & features) const
1302 params().validate(features);
1304 loadChildDocuments();
1306 for_each(paragraphs().begin(), paragraphs().end(),
1307 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1309 if (lyxerr.debugging(Debug::LATEX)) {
1310 features.showStruct();
1315 void Buffer::getLabelList(vector<docstring> & list) const
1317 /// if this is a child document and the parent is already loaded
1318 /// Use the parent's list instead [ale990407]
1319 Buffer const * tmp = masterBuffer();
1321 lyxerr << "masterBuffer() failed!" << endl;
1325 tmp->getLabelList(list);
1329 loadChildDocuments();
1331 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1332 it.nextInset()->getLabelList(*this, list);
1336 void Buffer::updateBibfilesCache() const
1338 // if this is a child document and the parent is already loaded
1339 // update the parent's cache instead
1340 Buffer const * tmp = masterBuffer();
1343 tmp->updateBibfilesCache();
1347 d->bibfilesCache_.clear();
1348 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1349 if (it->lyxCode() == BIBTEX_CODE) {
1350 InsetBibtex const & inset =
1351 static_cast<InsetBibtex const &>(*it);
1352 FileNameList const bibfiles = inset.getFiles(*this);
1353 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1356 } else if (it->lyxCode() == INCLUDE_CODE) {
1357 InsetInclude & inset =
1358 static_cast<InsetInclude &>(*it);
1359 inset.updateBibfilesCache(*this);
1360 FileNameList const & bibfiles =
1361 inset.getBibfilesCache(*this);
1362 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1370 FileNameList const & Buffer::getBibfilesCache() const
1372 // if this is a child document and the parent is already loaded
1373 // use the parent's cache instead
1374 Buffer const * tmp = masterBuffer();
1377 return tmp->getBibfilesCache();
1379 // We update the cache when first used instead of at loading time.
1380 if (d->bibfilesCache_.empty())
1381 const_cast<Buffer *>(this)->updateBibfilesCache();
1383 return d->bibfilesCache_;
1387 bool Buffer::isDepClean(string const & name) const
1389 DepClean::const_iterator const it = d->dep_clean.find(name);
1390 if (it == d->dep_clean.end())
1396 void Buffer::markDepClean(string const & name)
1398 d->dep_clean[name] = true;
1402 bool Buffer::dispatch(string const & command, bool * result)
1404 return dispatch(lyxaction.lookupFunc(command), result);
1408 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1410 bool dispatched = true;
1412 switch (func.action) {
1413 case LFUN_BUFFER_EXPORT: {
1414 bool const tmp = doExport(to_utf8(func.argument()), false);
1427 void Buffer::changeLanguage(Language const * from, Language const * to)
1432 for_each(par_iterator_begin(),
1434 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1438 bool Buffer::isMultiLingual() const
1440 ParConstIterator end = par_iterator_end();
1441 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1442 if (it->isMultiLingual(params()))
1449 ParIterator Buffer::getParFromID(int const id) const
1451 ParConstIterator it = par_iterator_begin();
1452 ParConstIterator const end = par_iterator_end();
1455 // John says this is called with id == -1 from undo
1456 lyxerr << "getParFromID(), id: " << id << endl;
1460 for (; it != end; ++it)
1468 bool Buffer::hasParWithID(int const id) const
1470 ParConstIterator const it = getParFromID(id);
1471 return it != par_iterator_end();
1475 ParIterator Buffer::par_iterator_begin()
1477 return lyx::par_iterator_begin(inset());
1481 ParIterator Buffer::par_iterator_end()
1483 return lyx::par_iterator_end(inset());
1487 ParConstIterator Buffer::par_iterator_begin() const
1489 return lyx::par_const_iterator_begin(inset());
1493 ParConstIterator Buffer::par_iterator_end() const
1495 return lyx::par_const_iterator_end(inset());
1499 Language const * Buffer::language() const
1501 return params().language;
1505 docstring const Buffer::B_(string const & l10n) const
1507 return params().B_(l10n);
1511 bool Buffer::isClean() const
1513 return d->lyx_clean;
1517 bool Buffer::isBakClean() const
1519 return d->bak_clean;
1523 bool Buffer::isExternallyModified(CheckMethod method) const
1525 BOOST_ASSERT(d->filename.exists());
1526 // if method == timestamp, check timestamp before checksum
1527 return (method == checksum_method
1528 || d->timestamp_ != d->filename.lastModified())
1529 && d->checksum_ != d->filename.checksum();
1533 void Buffer::saveCheckSum(FileName const & file) const
1535 if (file.exists()) {
1536 d->timestamp_ = file.lastModified();
1537 d->checksum_ = file.checksum();
1539 // in the case of save to a new file.
1546 void Buffer::markClean() const
1548 if (!d->lyx_clean) {
1549 d->lyx_clean = true;
1552 // if the .lyx file has been saved, we don't need an
1554 d->bak_clean = true;
1558 void Buffer::markBakClean() const
1560 d->bak_clean = true;
1564 void Buffer::setUnnamed(bool flag)
1570 bool Buffer::isUnnamed() const
1576 // FIXME: this function should be moved to buffer_pimpl.C
1577 void Buffer::markDirty()
1580 d->lyx_clean = false;
1583 d->bak_clean = false;
1585 DepClean::iterator it = d->dep_clean.begin();
1586 DepClean::const_iterator const end = d->dep_clean.end();
1588 for (; it != end; ++it)
1593 FileName Buffer::fileName() const
1599 string Buffer::absFileName() const
1601 return d->filename.absFilename();
1605 string Buffer::filePath() const
1607 return d->filename.onlyPath().absFilename();
1611 bool Buffer::isReadonly() const
1613 return d->read_only;
1617 void Buffer::setParent(Buffer const * buffer)
1619 // Avoids recursive include.
1620 d->parent_buffer = buffer == this ? 0 : buffer;
1624 Buffer const * Buffer::parent()
1626 return d->parent_buffer;
1630 Buffer const * Buffer::masterBuffer() const
1632 if (!d->parent_buffer)
1635 return d->parent_buffer->masterBuffer();
1639 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1641 Impl::PositionToMacroMap::iterator it;
1642 it = d->macros[name].upper_bound(par.macrocontextPosition());
1643 if (it != d->macros[name].end())
1646 // If there is a master buffer, query that
1647 Buffer const * master = masterBuffer();
1648 if (master && master != this)
1649 return master->hasMacro(name);
1651 return MacroTable::globalMacros().has(name);
1655 bool Buffer::hasMacro(docstring const & name) const
1657 if( !d->macros[name].empty() )
1660 // If there is a master buffer, query that
1661 Buffer const * master = masterBuffer();
1662 if (master && master != this)
1663 return master->hasMacro(name);
1665 return MacroTable::globalMacros().has(name);
1669 MacroData const & Buffer::getMacro(docstring const & name,
1670 Paragraph const & par) const
1672 Impl::PositionToMacroMap::iterator it;
1673 it = d->macros[name].upper_bound(par.macrocontextPosition());
1674 if( it != d->macros[name].end() )
1677 // If there is a master buffer, query that
1678 Buffer const * master = masterBuffer();
1679 if (master && master != this)
1680 return master->getMacro(name);
1682 return MacroTable::globalMacros().get(name);
1686 MacroData const & Buffer::getMacro(docstring const & name) const
1688 Impl::PositionToMacroMap::iterator it;
1689 it = d->macros[name].begin();
1690 if( it != d->macros[name].end() )
1693 // If there is a master buffer, query that
1694 Buffer const * master = masterBuffer();
1695 if (master && master != this)
1696 return master->getMacro(name);
1698 return MacroTable::globalMacros().get(name);
1702 void Buffer::updateMacros()
1704 // start with empty table
1705 d->macros = Impl::NameToPositionMacroMap();
1707 // Iterate over buffer
1708 ParagraphList & pars = text().paragraphs();
1709 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1710 // set position again
1711 pars[i].setMacrocontextPosition(i);
1713 //lyxerr << "searching main par " << i
1714 // << " for macro definitions" << endl;
1715 InsetList const & insets = pars[i].insetList();
1716 InsetList::const_iterator it = insets.begin();
1717 InsetList::const_iterator end = insets.end();
1718 for ( ; it != end; ++it) {
1719 if (it->inset->lyxCode() != MATHMACRO_CODE)
1723 MathMacroTemplate const & macroTemplate
1724 = static_cast<MathMacroTemplate const &>(*it->inset);
1727 if (macroTemplate.validMacro()) {
1728 MacroData macro = macroTemplate.asMacroData();
1731 // call hasMacro here instead of directly querying mc to
1732 // also take the master document into consideration
1733 macro.setRedefinition(hasMacro(macroTemplate.name()));
1735 // register macro (possibly overwrite the previous one of this paragraph)
1736 d->macros[macroTemplate.name()][i] = macro;
1743 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1746 //FIXME: This does not work for child documents yet.
1747 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1748 // Check if the label 'from' appears more than once
1749 vector<docstring> labels;
1752 if (code == CITE_CODE) {
1754 keys.fillWithBibKeys(this);
1755 BiblioInfo::const_iterator bit = keys.begin();
1756 BiblioInfo::const_iterator bend = keys.end();
1758 for (; bit != bend; ++bit)
1760 labels.push_back(bit->first);
1763 getLabelList(labels);
1764 paramName = "reference";
1767 if (count(labels.begin(), labels.end(), from) > 1)
1770 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1771 if (it->lyxCode() == code) {
1772 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1773 docstring const oldValue = inset.getParam(paramName);
1774 if (oldValue == from)
1775 inset.setParam(paramName, to);
1781 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1782 pit_type par_end, bool full_source)
1784 OutputParams runparams(¶ms().encoding());
1785 runparams.nice = true;
1786 runparams.flavor = OutputParams::LATEX;
1787 runparams.linelen = lyxrc.plaintext_linelen;
1788 // No side effect of file copying and image conversion
1789 runparams.dryrun = true;
1793 os << "% " << _("Preview source code") << "\n\n";
1794 d->texrow.newline();
1795 d->texrow.newline();
1797 writeLaTeXSource(os, filePath(), runparams, true, true);
1799 writeDocBookSource(os, absFileName(), runparams, false);
1802 runparams.par_begin = par_begin;
1803 runparams.par_end = par_end;
1804 if (par_begin + 1 == par_end)
1806 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1810 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1811 convert<docstring>(par_begin),
1812 convert<docstring>(par_end - 1))
1814 d->texrow.newline();
1815 d->texrow.newline();
1816 // output paragraphs
1818 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1821 docbookParagraphs(paragraphs(), *this, os, runparams);
1827 ErrorList & Buffer::errorList(string const & type) const
1829 static ErrorList emptyErrorList;
1830 map<string, ErrorList>::iterator I = d->errorLists.find(type);
1831 if (I == d->errorLists.end())
1832 return emptyErrorList;
1838 void Buffer::structureChanged() const
1841 gui_->structureChanged();
1845 void Buffer::errors(string const & err) const
1852 void Buffer::message(docstring const & msg) const
1859 void Buffer::setBusy(bool on) const
1866 void Buffer::setReadOnly(bool on) const
1869 d->wa_->setReadOnly(on);
1873 void Buffer::updateTitles() const
1876 d->wa_->updateTitles();
1880 void Buffer::resetAutosaveTimers() const
1883 gui_->resetAutosaveTimers();
1887 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1896 class AutoSaveBuffer : public ForkedProcess {
1899 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1900 : buffer_(buffer), fname_(fname) {}
1902 virtual boost::shared_ptr<ForkedProcess> clone() const
1904 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1909 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
1910 from_utf8(fname_.absFilename())));
1911 return run(DontWait);
1915 virtual int generateChild();
1917 Buffer const & buffer_;
1922 #if !defined (HAVE_FORK)
1926 int AutoSaveBuffer::generateChild()
1928 // tmp_ret will be located (usually) in /tmp
1929 // will that be a problem?
1930 pid_t const pid = fork();
1931 // If you want to debug the autosave
1932 // you should set pid to -1, and comment out the fork.
1933 if (pid == 0 || pid == -1) {
1934 // pid = -1 signifies that lyx was unable
1935 // to fork. But we will do the save
1937 bool failed = false;
1939 FileName const tmp_ret = FileName::tempName("lyxauto");
1940 if (!tmp_ret.empty()) {
1941 buffer_.writeFile(tmp_ret);
1942 // assume successful write of tmp_ret
1943 if (!tmp_ret.moveTo(fname_)) {
1945 // most likely couldn't move between
1946 // filesystems unless write of tmp_ret
1947 // failed so remove tmp file (if it
1949 tmp_ret.removeFile();
1956 // failed to write/rename tmp_ret so try writing direct
1957 if (!buffer_.writeFile(fname_)) {
1958 // It is dangerous to do this in the child,
1959 // but safe in the parent, so...
1960 if (pid == -1) // emit message signal.
1961 buffer_.message(_("Autosave failed!"));
1964 if (pid == 0) { // we are the child so...
1974 // Perfect target for a thread...
1975 void Buffer::autoSave() const
1977 if (isBakClean() || isReadonly()) {
1978 // We don't save now, but we'll try again later
1979 resetAutosaveTimers();
1983 // emit message signal.
1984 message(_("Autosaving current document..."));
1986 // create autosave filename
1987 string fname = filePath();
1989 fname += d->filename.onlyFileName();
1992 AutoSaveBuffer autosave(*this, FileName(fname));
1996 resetAutosaveTimers();
2000 void Buffer::resetChildDocuments(bool close_them) const
2002 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2003 if (it->lyxCode() != INCLUDE_CODE)
2005 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2006 InsetCommandParams const & ip = inset.params();
2008 resetParentBuffer(this, ip, close_them);
2011 if (use_gui && masterBuffer() == this)
2012 updateLabels(*this);
2016 void Buffer::loadChildDocuments() const
2018 bool parse_error = false;
2020 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2021 if (it->lyxCode() != INCLUDE_CODE)
2023 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2024 InsetCommandParams const & ip = inset.params();
2025 Buffer * child = loadIfNeeded(*this, ip);
2028 parse_error |= !child->errorList("Parse").empty();
2029 child->loadChildDocuments();
2032 if (use_gui && masterBuffer() == this)
2033 updateLabels(*this);
2037 string Buffer::bufferFormat() const
2047 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2048 string & result_file) const
2050 string backend_format;
2051 OutputParams runparams(¶ms().encoding());
2052 runparams.flavor = OutputParams::LATEX;
2053 runparams.linelen = lyxrc.plaintext_linelen;
2054 vector<string> backs = backends();
2055 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2056 // Get shortest path to format
2057 Graph::EdgePath path;
2058 for (vector<string>::const_iterator it = backs.begin();
2059 it != backs.end(); ++it) {
2060 Graph::EdgePath p = theConverters().getPath(*it, format);
2061 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2062 backend_format = *it;
2067 runparams.flavor = theConverters().getFlavor(path);
2069 Alert::error(_("Couldn't export file"),
2070 bformat(_("No information for exporting the format %1$s."),
2071 formats.prettyName(format)));
2075 backend_format = format;
2076 // FIXME: Don't hardcode format names here, but use a flag
2077 if (backend_format == "pdflatex")
2078 runparams.flavor = OutputParams::PDFLATEX;
2081 string filename = latexName(false);
2082 filename = addName(temppath(), filename);
2083 filename = changeExtension(filename,
2084 formats.extension(backend_format));
2086 // Plain text backend
2087 if (backend_format == "text")
2088 writePlaintextFile(*this, FileName(filename), runparams);
2090 else if (backend_format == "lyx")
2091 writeFile(FileName(filename));
2093 else if (isDocBook()) {
2094 runparams.nice = !put_in_tempdir;
2095 makeDocBookFile(FileName(filename), runparams);
2098 else if (backend_format == format) {
2099 runparams.nice = true;
2100 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2102 } else if (!lyxrc.tex_allows_spaces
2103 && contains(filePath(), ' ')) {
2104 Alert::error(_("File name error"),
2105 _("The directory path to the document cannot contain spaces."));
2108 runparams.nice = false;
2109 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2113 string const error_type = (format == "program")
2114 ? "Build" : bufferFormat();
2115 string const ext = formats.extension(format);
2116 FileName const tmp_result_file(changeExtension(filename, ext));
2117 bool const success = theConverters().convert(this, FileName(filename),
2118 tmp_result_file, FileName(absFileName()), backend_format, format,
2119 errorList(error_type));
2120 // Emit the signal to show the error list.
2121 if (format != backend_format)
2127 result_file = tmp_result_file.absFilename();
2129 result_file = changeExtension(absFileName(), ext);
2130 // We need to copy referenced files (e. g. included graphics
2131 // if format == "dvi") to the result dir.
2132 vector<ExportedFile> const files =
2133 runparams.exportdata->externalFiles(format);
2134 string const dest = onlyPath(result_file);
2135 CopyStatus status = SUCCESS;
2136 for (vector<ExportedFile>::const_iterator it = files.begin();
2137 it != files.end() && status != CANCEL; ++it) {
2139 formats.getFormatFromFile(it->sourceName);
2140 status = copyFile(fmt, it->sourceName,
2141 makeAbsPath(it->exportName, dest),
2142 it->exportName, status == FORCE);
2144 if (status == CANCEL) {
2145 message(_("Document export cancelled."));
2146 } else if (tmp_result_file.exists()) {
2147 // Finally copy the main file
2148 status = copyFile(format, tmp_result_file,
2149 FileName(result_file), result_file,
2151 message(bformat(_("Document exported as %1$s "
2153 formats.prettyName(format),
2154 makeDisplayPath(result_file)));
2156 // This must be a dummy converter like fax (bug 1888)
2157 message(bformat(_("Document exported as %1$s"),
2158 formats.prettyName(format)));
2166 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2169 return doExport(format, put_in_tempdir, result_file);
2173 bool Buffer::preview(string const & format) const
2176 if (!doExport(format, true, result_file))
2178 return formats.view(*this, FileName(result_file), format);
2182 bool Buffer::isExportable(string const & format) const
2184 vector<string> backs = backends();
2185 for (vector<string>::const_iterator it = backs.begin();
2186 it != backs.end(); ++it)
2187 if (theConverters().isReachable(*it, format))
2193 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2195 vector<string> backs = backends();
2196 vector<Format const *> result =
2197 theConverters().getReachable(backs[0], only_viewable, true);
2198 for (vector<string>::const_iterator it = backs.begin() + 1;
2199 it != backs.end(); ++it) {
2200 vector<Format const *> r =
2201 theConverters().getReachable(*it, only_viewable, false);
2202 result.insert(result.end(), r.begin(), r.end());
2208 vector<string> Buffer::backends() const
2211 if (params().getTextClass().isTeXClassAvailable()) {
2212 v.push_back(bufferFormat());
2213 // FIXME: Don't hardcode format names here, but use a flag
2214 if (v.back() == "latex")
2215 v.push_back("pdflatex");
2217 v.push_back("text");
2223 bool Buffer::readFileHelper(FileName const & s)
2225 // File information about normal file
2227 docstring const file = makeDisplayPath(s.absFilename(), 50);
2228 docstring text = bformat(_("The specified document\n%1$s"
2229 "\ncould not be read."), file);
2230 Alert::error(_("Could not read document"), text);
2234 // Check if emergency save file exists and is newer.
2235 FileName const e(s.absFilename() + ".emergency");
2237 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2238 docstring const file = makeDisplayPath(s.absFilename(), 20);
2239 docstring const text =
2240 bformat(_("An emergency save of the document "
2242 "Recover emergency save?"), file);
2243 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2244 _("&Recover"), _("&Load Original"),
2248 // the file is not saved if we load the emergency file.
2258 // Now check if autosave file is newer.
2259 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2261 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2262 docstring const file = makeDisplayPath(s.absFilename(), 20);
2263 docstring const text =
2264 bformat(_("The backup of the document "
2265 "%1$s is newer.\n\nLoad the "
2266 "backup instead?"), file);
2267 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2268 _("&Load backup"), _("Load &original"),
2272 // the file is not saved if we load the autosave file.
2276 // Here we delete the autosave
2287 bool Buffer::loadLyXFile(FileName const & s)
2289 if (s.isReadableFile()) {
2290 if (readFileHelper(s)) {
2291 lyxvc().file_found_hook(s);
2292 if (!s.isWritable())
2297 docstring const file = makeDisplayPath(s.absFilename(), 20);
2298 // Here we probably should run
2299 if (LyXVC::file_not_found_hook(s)) {
2300 docstring const text =
2301 bformat(_("Do you want to retrieve the document"
2302 " %1$s from version control?"), file);
2303 int const ret = Alert::prompt(_("Retrieve from version control?"),
2304 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2307 // How can we know _how_ to do the checkout?
2308 // With the current VC support it has to be,
2309 // a RCS file since CVS do not have special ,v files.
2311 return loadLyXFile(s);
2319 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2321 TeXErrors::Errors::const_iterator cit = terr.begin();
2322 TeXErrors::Errors::const_iterator end = terr.end();
2324 for (; cit != end; ++cit) {
2327 int errorRow = cit->error_in_line;
2328 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2334 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2335 } while (found && id_start == id_end && pos_start == pos_end);
2337 errorList.push_back(ErrorItem(cit->error_desc,
2338 cit->error_text, id_start, pos_start, pos_end));