3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
24 #include "Converter.h"
26 #include "DocIterator.h"
27 #include "EmbeddedFiles.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
56 #include "TexStream.h"
57 #include "TextClassList.h"
59 #include "TocBackend.h"
61 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/convert.h"
80 #include "support/debug.h"
81 #include "support/FileFilterList.h"
82 #include "support/FileNameList.h"
83 #include "support/filetools.h"
84 #include "support/ForkedCalls.h"
85 #include "support/gettext.h"
86 #include "support/gzstream.h"
87 #include "support/lstrings.h"
88 #include "support/lyxalgo.h"
89 #include "support/os.h"
90 #include "support/Path.h"
91 #include "support/textutils.h"
92 #include "support/types.h"
93 #include "support/FileZipListDir.h"
95 #if !defined (HAVE_FORK)
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
109 using namespace lyx::support;
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
118 int const LYX_FORMAT = 308; // Uwe: Serbian-Latin
123 typedef map<string, bool> DepClean;
128 Impl(Buffer & parent, FileName const & file, bool readonly);
141 mutable TexRow texrow;
142 Buffer const * parent_buffer;
144 /// need to regenerate .tex?
148 mutable bool lyx_clean;
150 /// is autosave needed?
151 mutable bool bak_clean;
153 /// is this a unnamed file (New...)?
159 /// name of the file the buffer is associated with.
162 /** Set to true only when the file is fully loaded.
163 * Used to prevent the premature generation of previews
164 * and by the citation inset.
166 bool file_fully_loaded;
168 /// our Text that should be wrapped in an InsetText
172 mutable TocBackend toc_backend;
175 typedef map<unsigned int, MacroData, greater<int> > PositionToMacroMap;
176 typedef map<docstring, PositionToMacroMap> NameToPositionMacroMap;
177 NameToPositionMacroMap macros;
179 /// Container for all sort of Buffer dependant errors.
180 map<string, ErrorList> errorLists;
182 /// all embedded files of this buffer
183 EmbeddedFiles embedded_files;
185 /// timestamp and checksum used to test if the file has been externally
186 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
188 unsigned long checksum_;
191 frontend::WorkAreaManager * wa_;
196 /// A cache for the bibfiles (including bibfiles of loaded child
197 /// documents), needed for appropriate update of natbib labels.
198 mutable FileNameList bibfilesCache_;
202 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
203 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
204 read_only(readonly_), filename(file), file_fully_loaded(false),
205 inset(params), toc_backend(&parent), embedded_files(&parent),
206 timestamp_(0), checksum_(0), wa_(0), undo_(parent)
208 inset.setAutoBreakRows(true);
209 lyxvc.setBuffer(&parent);
210 temppath = createBufferTmpDir();
212 // FIXME: And now do something if temppath == string(), because we
213 // assume from now on that temppath points to a valid temp dir.
214 // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
217 wa_ = new frontend::WorkAreaManager;
221 Buffer::Buffer(string const & file, bool readonly)
222 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
224 LYXERR(Debug::INFO, "Buffer::Buffer()");
230 LYXERR(Debug::INFO, "Buffer::~Buffer()");
231 // here the buffer should take care that it is
232 // saved properly, before it goes into the void.
234 // GuiView already destroyed
237 Buffer const * master = masterBuffer();
238 if (master != this && use_gui)
239 // We are closing buf which was a child document so we
240 // must update the labels and section numbering of its master
242 updateLabels(*master);
244 resetChildDocuments(false);
246 if (!temppath().empty() && !FileName(temppath()).destroyDirectory()) {
247 Alert::warning(_("Could not remove temporary directory"),
248 bformat(_("Could not remove the temporary directory %1$s"),
249 from_utf8(temppath())));
252 // Remove any previewed LaTeX snippets associated with this buffer.
253 graphics::Previews::get().removeLoader(*this);
259 void Buffer::changed() const
266 frontend::WorkAreaManager & Buffer::workAreaManager() const
268 BOOST_ASSERT(d->wa_);
273 Text & Buffer::text() const
275 return const_cast<Text &>(d->inset.text_);
279 Inset & Buffer::inset() const
281 return const_cast<InsetText &>(d->inset);
285 BufferParams & Buffer::params()
291 BufferParams const & Buffer::params() const
297 ParagraphList & Buffer::paragraphs()
299 return text().paragraphs();
303 ParagraphList const & Buffer::paragraphs() const
305 return text().paragraphs();
309 LyXVC & Buffer::lyxvc()
315 LyXVC const & Buffer::lyxvc() const
321 string const & Buffer::temppath() const
327 TexRow const & Buffer::texrow() const
333 TocBackend & Buffer::tocBackend() const
335 return d->toc_backend;
339 EmbeddedFiles & Buffer::embeddedFiles()
341 return d->embedded_files;
345 EmbeddedFiles const & Buffer::embeddedFiles() const
347 return d->embedded_files;
351 Undo & Buffer::undo()
357 string Buffer::latexName(bool const no_path) const
359 FileName latex_name = makeLatexName(d->filename);
360 return no_path ? latex_name.onlyFileName()
361 : latex_name.absFilename();
365 string Buffer::logName(LogType * type) const
367 string const filename = latexName(false);
369 if (filename.empty()) {
375 string const path = temppath();
377 FileName const fname(addName(temppath(),
378 onlyFilename(changeExtension(filename,
380 FileName const bname(
381 addName(path, onlyFilename(
382 changeExtension(filename,
383 formats.extension("literate") + ".out"))));
385 // If no Latex log or Build log is newer, show Build log
387 if (bname.exists() &&
388 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
389 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
392 return bname.absFilename();
394 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
397 return fname.absFilename();
401 void Buffer::setReadonly(bool const flag)
403 if (d->read_only != flag) {
410 void Buffer::setFileName(string const & newfile)
412 d->filename = makeAbsPath(newfile);
413 setReadonly(d->filename.isReadOnly());
418 int Buffer::readHeader(Lexer & lex)
420 int unknown_tokens = 0;
422 int begin_header_line = -1;
424 // Initialize parameters that may be/go lacking in header:
425 params().branchlist().clear();
426 params().preamble.erase();
427 params().options.erase();
428 params().float_placement.erase();
429 params().paperwidth.erase();
430 params().paperheight.erase();
431 params().leftmargin.erase();
432 params().rightmargin.erase();
433 params().topmargin.erase();
434 params().bottommargin.erase();
435 params().headheight.erase();
436 params().headsep.erase();
437 params().footskip.erase();
438 params().listings_params.clear();
439 params().clearLayoutModules();
440 params().pdfoptions().clear();
442 for (int i = 0; i < 4; ++i) {
443 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
444 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
447 ErrorList & errorList = d->errorLists["Parse"];
451 string const token = lex.getString();
456 if (token == "\\end_header")
460 if (token == "\\begin_header") {
461 begin_header_line = line;
465 LYXERR(Debug::PARSER, "Handling document header token: `"
468 string unknown = params().readToken(lex, token, d->filename.onlyPath());
469 if (!unknown.empty()) {
470 if (unknown[0] != '\\' && token == "\\textclass") {
471 Alert::warning(_("Unknown document class"),
472 bformat(_("Using the default document class, because the "
473 "class %1$s is unknown."), from_utf8(unknown)));
476 docstring const s = bformat(_("Unknown token: "
480 errorList.push_back(ErrorItem(_("Document header error"),
485 if (begin_header_line) {
486 docstring const s = _("\\begin_header is missing");
487 errorList.push_back(ErrorItem(_("Document header error"),
491 return unknown_tokens;
496 // changed to be public and have one parameter
497 // Returns false if "\end_document" is not read (Asger)
498 bool Buffer::readDocument(Lexer & lex)
500 ErrorList & errorList = d->errorLists["Parse"];
504 string const token = lex.getString();
505 if (token != "\\begin_document") {
506 docstring const s = _("\\begin_document is missing");
507 errorList.push_back(ErrorItem(_("Document header error"),
511 // we are reading in a brand new document
512 BOOST_ASSERT(paragraphs().empty());
515 TextClass const & baseClass = textclasslist[params().getBaseClass()];
516 if (!baseClass.load(filePath())) {
517 string theclass = baseClass.name();
518 Alert::error(_("Can't load document class"), bformat(
519 _("Using the default document class, because the "
520 "class %1$s could not be loaded."), from_utf8(theclass)));
521 params().setBaseClass(defaultTextclass());
524 if (params().outputChanges) {
525 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
526 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
527 LaTeXFeatures::isAvailable("xcolor");
529 if (!dvipost && !xcolorsoul) {
530 Alert::warning(_("Changes not shown in LaTeX output"),
531 _("Changes will not be highlighted in LaTeX output, "
532 "because neither dvipost nor xcolor/soul are installed.\n"
533 "Please install these packages or redefine "
534 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
535 } else if (!xcolorsoul) {
536 Alert::warning(_("Changes not shown in LaTeX output"),
537 _("Changes will not be highlighted in LaTeX output "
538 "when using pdflatex, because xcolor and soul are not installed.\n"
539 "Please install both packages or redefine "
540 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
545 bool const res = text().read(*this, lex, errorList);
546 for_each(text().paragraphs().begin(),
547 text().paragraphs().end(),
548 bind(&Paragraph::setInsetOwner, _1, &inset()));
554 // needed to insert the selection
555 void Buffer::insertStringAsLines(ParagraphList & pars,
556 pit_type & pit, pos_type & pos,
557 Font const & fn, docstring const & str, bool autobreakrows)
561 // insert the string, don't insert doublespace
562 bool space_inserted = true;
563 for (docstring::const_iterator cit = str.begin();
564 cit != str.end(); ++cit) {
565 Paragraph & par = pars[pit];
567 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
568 breakParagraph(params(), pars, pit, pos,
569 par.layout()->isEnvironment());
572 space_inserted = true;
576 // do not insert consecutive spaces if !free_spacing
577 } else if ((*cit == ' ' || *cit == '\t') &&
578 space_inserted && !par.isFreeSpacing()) {
580 } else if (*cit == '\t') {
581 if (!par.isFreeSpacing()) {
582 // tabs are like spaces here
583 par.insertChar(pos, ' ', font, params().trackChanges);
585 space_inserted = true;
587 const pos_type n = 8 - pos % 8;
588 for (pos_type i = 0; i < n; ++i) {
589 par.insertChar(pos, ' ', font, params().trackChanges);
592 space_inserted = true;
594 } else if (!isPrintable(*cit)) {
595 // Ignore unprintables
598 // just insert the character
599 par.insertChar(pos, *cit, font, params().trackChanges);
601 space_inserted = (*cit == ' ');
608 bool Buffer::readString(string const & s)
610 params().compressed = false;
612 // remove dummy empty par
613 paragraphs().clear();
617 FileName const name = FileName::tempName();
618 switch (readFile(lex, name, true)) {
622 // We need to call lyx2lyx, so write the input to a file
623 ofstream os(name.toFilesystemEncoding().c_str());
626 return readFile(name);
636 bool Buffer::readFile(FileName const & filename)
638 FileName fname(filename);
639 // Check if the file is compressed.
640 string format = filename.guessFormatFromContents();
641 if (format == "zip") {
642 // decompress to a temp directory
643 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
644 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
646 FileName lyxfile(addName(temppath(), "content.lyx"));
647 // if both manifest.txt and file.lyx exist, this is am embedded file
648 if (lyxfile.exists()) {
649 params().embedded = true;
653 // The embedded lyx file can also be compressed, for backward compatibility
654 format = fname.guessFormatFromContents();
655 if (format == "gzip" || format == "zip" || format == "compress")
656 params().compressed = true;
658 // remove dummy empty par
659 paragraphs().clear();
662 if (readFile(lex, fname) != success)
669 bool Buffer::isFullyLoaded() const
671 return d->file_fully_loaded;
675 void Buffer::setFullyLoaded(bool value)
677 d->file_fully_loaded = value;
681 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
684 BOOST_ASSERT(!filename.empty());
687 Alert::error(_("Document could not be read"),
688 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
693 string const token = lex.getString();
696 Alert::error(_("Document could not be read"),
697 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
701 // the first token _must_ be...
702 if (token != "\\lyxformat") {
703 lyxerr << "Token: " << token << endl;
705 Alert::error(_("Document format failure"),
706 bformat(_("%1$s is not a LyX document."),
707 from_utf8(filename.absFilename())));
712 string tmp_format = lex.getString();
713 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
714 // if present remove ".," from string.
715 string::size_type dot = tmp_format.find_first_of(".,");
716 //lyxerr << " dot found at " << dot << endl;
717 if (dot != string::npos)
718 tmp_format.erase(dot, 1);
719 int const file_format = convert<int>(tmp_format);
720 //lyxerr << "format: " << file_format << endl;
722 // save timestamp and checksum of the original disk file, making sure
723 // to not overwrite them with those of the file created in the tempdir
724 // when it has to be converted to the current format.
726 // Save the timestamp and checksum of disk file. If filename is an
727 // emergency file, save the timestamp and checksum of the original lyx file
728 // because isExternallyModified will check for this file. (BUG4193)
729 string diskfile = filename.absFilename();
730 if (suffixIs(diskfile, ".emergency"))
731 diskfile = diskfile.substr(0, diskfile.size() - 10);
732 saveCheckSum(FileName(diskfile));
735 if (file_format != LYX_FORMAT) {
738 // lyx2lyx would fail
741 FileName const tmpfile = FileName::tempName();
742 if (tmpfile.empty()) {
743 Alert::error(_("Conversion failed"),
744 bformat(_("%1$s is from a different"
745 " version of LyX, but a temporary"
746 " file for converting it could"
748 from_utf8(filename.absFilename())));
751 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
752 if (lyx2lyx.empty()) {
753 Alert::error(_("Conversion script not found"),
754 bformat(_("%1$s is from a different"
755 " version of LyX, but the"
756 " conversion script lyx2lyx"
757 " could not be found."),
758 from_utf8(filename.absFilename())));
761 ostringstream command;
762 command << os::python()
763 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
764 << " -t " << convert<string>(LYX_FORMAT)
765 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
766 << ' ' << quoteName(filename.toFilesystemEncoding());
767 string const command_str = command.str();
769 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
771 cmd_ret const ret = runCommand(command_str);
772 if (ret.first != 0) {
773 Alert::error(_("Conversion script failed"),
774 bformat(_("%1$s is from a different version"
775 " of LyX, but the lyx2lyx script"
776 " failed to convert it."),
777 from_utf8(filename.absFilename())));
780 bool const ret = readFile(tmpfile);
781 // Do stuff with tmpfile name and buffer name here.
782 return ret ? success : failure;
787 if (readDocument(lex)) {
788 Alert::error(_("Document format failure"),
789 bformat(_("%1$s ended unexpectedly, which means"
790 " that it is probably corrupted."),
791 from_utf8(filename.absFilename())));
794 d->file_fully_loaded = true;
799 // Should probably be moved to somewhere else: BufferView? LyXView?
800 bool Buffer::save() const
802 // We don't need autosaves in the immediate future. (Asger)
803 resetAutosaveTimers();
805 string const encodedFilename = d->filename.toFilesystemEncoding();
808 bool madeBackup = false;
810 // make a backup if the file already exists
811 if (lyxrc.make_backup && fileName().exists()) {
812 backupName = FileName(absFileName() + '~');
813 if (!lyxrc.backupdir_path.empty()) {
814 string const mangledName =
815 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
816 backupName = FileName(addName(lyxrc.backupdir_path,
819 if (fileName().copyTo(backupName)) {
822 Alert::error(_("Backup failure"),
823 bformat(_("Cannot create backup file %1$s.\n"
824 "Please check whether the directory exists and is writeable."),
825 from_utf8(backupName.absFilename())));
826 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
830 // ask if the disk file has been externally modified (use checksum method)
831 if (fileName().exists() && isExternallyModified(checksum_method)) {
832 docstring const file = makeDisplayPath(absFileName(), 20);
833 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
834 "you want to overwrite this file?"), file);
835 int const ret = Alert::prompt(_("Overwrite modified file?"),
836 text, 1, 1, _("&Overwrite"), _("&Cancel"));
841 if (writeFile(d->filename)) {
845 // Saving failed, so backup is not backup
847 backupName.moveTo(d->filename);
853 bool Buffer::writeFile(FileName const & fname) const
855 if (d->read_only && fname == d->filename)
861 if (params().embedded)
862 // first write the .lyx file to the temporary directory
863 content = FileName(addName(temppath(), "content.lyx"));
867 docstring const str = bformat(_("Saving document %1$s..."),
868 makeDisplayPath(content.absFilename()));
871 if (params().compressed) {
872 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
873 retval = ofs && write(ofs);
875 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
876 retval = ofs && write(ofs);
880 message(str + _(" could not write file!."));
884 removeAutosaveFile(d->filename.absFilename());
885 saveCheckSum(d->filename);
886 message(str + _(" done."));
888 if (!params().embedded)
891 message(str + _(" writing embedded files!."));
892 // if embedding is enabled, write file.lyx and all the embedded files
893 // to the zip file fname.
894 if (!d->embedded_files.writeFile(fname)) {
895 message(str + _(" could not write embedded files!."));
898 message(str + _(" error while writing embedded files."));
903 bool Buffer::write(ostream & ofs) const
906 // Use the standard "C" locale for file output.
907 ofs.imbue(locale::classic());
910 // The top of the file should not be written by params().
912 // write out a comment in the top of the file
913 ofs << "#LyX " << lyx_version
914 << " created this file. For more info see http://www.lyx.org/\n"
915 << "\\lyxformat " << LYX_FORMAT << "\n"
916 << "\\begin_document\n";
919 /// For each author, set 'used' to true if there is a change
920 /// by this author in the document; otherwise set it to 'false'.
921 AuthorList::Authors::const_iterator a_it = params().authors().begin();
922 AuthorList::Authors::const_iterator a_end = params().authors().end();
923 for (; a_it != a_end; ++a_it)
924 a_it->second.setUsed(false);
926 ParIterator const end = par_iterator_end();
927 ParIterator it = par_iterator_begin();
928 for ( ; it != end; ++it)
929 it->checkAuthors(params().authors());
931 // now write out the buffer parameters.
932 ofs << "\\begin_header\n";
933 params().writeFile(ofs);
934 ofs << "\\end_header\n";
937 ofs << "\n\\begin_body\n";
938 text().write(*this, ofs);
939 ofs << "\n\\end_body\n";
941 // Write marker that shows file is complete
942 ofs << "\\end_document" << endl;
944 // Shouldn't really be needed....
947 // how to check if close went ok?
948 // Following is an attempt... (BE 20001011)
950 // good() returns false if any error occured, including some
952 // bad() returns true if something bad happened in the buffer,
953 // which should include file system full errors.
958 lyxerr << "File was not closed properly." << endl;
965 bool Buffer::makeLaTeXFile(FileName const & fname,
966 string const & original_path,
967 OutputParams const & runparams,
968 bool output_preamble, bool output_body) const
970 string const encoding = runparams.encoding->iconvName();
971 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
974 try { ofs.reset(encoding); }
975 catch (iconv_codecvt_facet_exception & e) {
976 lyxerr << "Caught iconv exception: " << e.what() << endl;
977 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
978 "verify that the support software for your encoding (%1$s) is "
979 "properly installed"), from_ascii(encoding)));
982 if (!openFileWrite(ofs, fname))
985 //TexStream ts(ofs.rdbuf(), &texrow());
987 bool failed_export = false;
990 writeLaTeXSource(ofs, original_path,
991 runparams, output_preamble, output_body);
993 catch (iconv_codecvt_facet_exception & e) {
994 lyxerr << "Caught iconv exception: " << e.what() << endl;
995 failed_export = true;
997 catch (exception const & e) {
998 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
999 failed_export = true;
1002 lyxerr << "Caught some really weird exception..." << endl;
1003 LyX::cref().exit(1);
1008 failed_export = true;
1009 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1012 if (failed_export) {
1013 Alert::error(_("Encoding error"),
1014 _("Some characters of your document are probably not "
1015 "representable in the chosen encoding.\n"
1016 "Changing the document encoding to utf8 could help."));
1023 void Buffer::writeLaTeXSource(odocstream & os,
1024 string const & original_path,
1025 OutputParams const & runparams_in,
1026 bool const output_preamble, bool const output_body) const
1028 OutputParams runparams = runparams_in;
1030 // validate the buffer.
1031 LYXERR(Debug::LATEX, " Validating buffer...");
1032 LaTeXFeatures features(*this, params(), runparams);
1034 LYXERR(Debug::LATEX, " Buffer validation done.");
1036 // The starting paragraph of the coming rows is the
1037 // first paragraph of the document. (Asger)
1038 if (output_preamble && runparams.nice) {
1039 os << "%% LyX " << lyx_version << " created this file. "
1040 "For more info, see http://www.lyx.org/.\n"
1041 "%% Do not edit unless you really know what "
1043 d->texrow.newline();
1044 d->texrow.newline();
1046 LYXERR(Debug::INFO, "lyx document header finished");
1047 // There are a few differences between nice LaTeX and usual files:
1048 // usual is \batchmode and has a
1049 // special input@path to allow the including of figures
1050 // with either \input or \includegraphics (what figinsets do).
1051 // input@path is set when the actual parameter
1052 // original_path is set. This is done for usual tex-file, but not
1053 // for nice-latex-file. (Matthias 250696)
1054 // Note that input@path is only needed for something the user does
1055 // in the preamble, included .tex files or ERT, files included by
1056 // LyX work without it.
1057 if (output_preamble) {
1058 if (!runparams.nice) {
1059 // code for usual, NOT nice-latex-file
1060 os << "\\batchmode\n"; // changed
1061 // from \nonstopmode
1062 d->texrow.newline();
1064 if (!original_path.empty()) {
1066 // We don't know the encoding of inputpath
1067 docstring const inputpath = from_utf8(latex_path(original_path));
1068 os << "\\makeatletter\n"
1069 << "\\def\\input@path{{"
1070 << inputpath << "/}}\n"
1071 << "\\makeatother\n";
1072 d->texrow.newline();
1073 d->texrow.newline();
1074 d->texrow.newline();
1077 // Write the preamble
1078 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1084 os << "\\begin{document}\n";
1085 d->texrow.newline();
1086 } // output_preamble
1088 d->texrow.start(paragraphs().begin()->id(), 0);
1090 LYXERR(Debug::INFO, "preamble finished, now the body.");
1092 // if we are doing a real file with body, even if this is the
1093 // child of some other buffer, let's cut the link here.
1094 // This happens for example if only a child document is printed.
1095 Buffer const * save_parent = 0;
1096 if (output_preamble) {
1097 save_parent = d->parent_buffer;
1098 d->parent_buffer = 0;
1101 loadChildDocuments();
1104 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1106 // Restore the parenthood if needed
1107 if (output_preamble)
1108 d->parent_buffer = save_parent;
1110 // add this just in case after all the paragraphs
1112 d->texrow.newline();
1114 if (output_preamble) {
1115 os << "\\end{document}\n";
1116 d->texrow.newline();
1117 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1119 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1121 runparams_in.encoding = runparams.encoding;
1123 // Just to be sure. (Asger)
1124 d->texrow.newline();
1126 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1127 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1131 bool Buffer::isLatex() const
1133 return params().getTextClass().outputType() == LATEX;
1137 bool Buffer::isLiterate() const
1139 return params().getTextClass().outputType() == LITERATE;
1143 bool Buffer::isDocBook() const
1145 return params().getTextClass().outputType() == DOCBOOK;
1149 void Buffer::makeDocBookFile(FileName const & fname,
1150 OutputParams const & runparams,
1151 bool const body_only) const
1153 LYXERR(Debug::LATEX, "makeDocBookFile...");
1157 if (!openFileWrite(ofs, fname))
1160 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1164 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1168 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1169 OutputParams const & runparams,
1170 bool const only_body) const
1172 LaTeXFeatures features(*this, params(), runparams);
1177 TextClass const & tclass = params().getTextClass();
1178 string const top_element = tclass.latexname();
1181 if (runparams.flavor == OutputParams::XML)
1182 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1185 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1188 if (! tclass.class_header().empty())
1189 os << from_ascii(tclass.class_header());
1190 else if (runparams.flavor == OutputParams::XML)
1191 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1192 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1194 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1196 docstring preamble = from_utf8(params().preamble);
1197 if (runparams.flavor != OutputParams::XML ) {
1198 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1199 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1200 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1201 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1204 string const name = runparams.nice
1205 ? changeExtension(absFileName(), ".sgml") : fname;
1206 preamble += features.getIncludedFiles(name);
1207 preamble += features.getLyXSGMLEntities();
1209 if (!preamble.empty()) {
1210 os << "\n [ " << preamble << " ]";
1215 string top = top_element;
1217 if (runparams.flavor == OutputParams::XML)
1218 top += params().language->code();
1220 top += params().language->code().substr(0,2);
1223 if (!params().options.empty()) {
1225 top += params().options;
1228 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1229 << " file was created by LyX " << lyx_version
1230 << "\n See http://www.lyx.org/ for more information -->\n";
1232 params().getTextClass().counters().reset();
1234 loadChildDocuments();
1236 sgml::openTag(os, top);
1238 docbookParagraphs(paragraphs(), *this, os, runparams);
1239 sgml::closeTag(os, top_element);
1243 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1244 // Other flags: -wall -v0 -x
1245 int Buffer::runChktex()
1249 // get LaTeX-Filename
1250 FileName const path(temppath());
1251 string const name = addName(path.absFilename(), latexName());
1252 string const org_path = filePath();
1254 PathChanger p(path); // path to LaTeX file
1255 message(_("Running chktex..."));
1257 // Generate the LaTeX file if neccessary
1258 OutputParams runparams(¶ms().encoding());
1259 runparams.flavor = OutputParams::LATEX;
1260 runparams.nice = false;
1261 makeLaTeXFile(FileName(name), org_path, runparams);
1264 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1265 int const res = chktex.run(terr); // run chktex
1268 Alert::error(_("chktex failure"),
1269 _("Could not run chktex successfully."));
1270 } else if (res > 0) {
1271 ErrorList & errlist = d->errorLists["ChkTeX"];
1273 bufferErrors(terr, errlist);
1284 void Buffer::validate(LaTeXFeatures & features) const
1286 params().validate(features);
1288 loadChildDocuments();
1290 for_each(paragraphs().begin(), paragraphs().end(),
1291 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1293 if (lyxerr.debugging(Debug::LATEX)) {
1294 features.showStruct();
1299 void Buffer::getLabelList(vector<docstring> & list) const
1301 /// if this is a child document and the parent is already loaded
1302 /// Use the parent's list instead [ale990407]
1303 Buffer const * tmp = masterBuffer();
1305 lyxerr << "masterBuffer() failed!" << endl;
1309 tmp->getLabelList(list);
1313 loadChildDocuments();
1315 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1316 it.nextInset()->getLabelList(*this, list);
1320 void Buffer::updateBibfilesCache() const
1322 // if this is a child document and the parent is already loaded
1323 // update the parent's cache instead
1324 Buffer const * tmp = masterBuffer();
1327 tmp->updateBibfilesCache();
1331 d->bibfilesCache_.clear();
1332 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1333 if (it->lyxCode() == BIBTEX_CODE) {
1334 InsetBibtex const & inset =
1335 static_cast<InsetBibtex const &>(*it);
1336 FileNameList const bibfiles = inset.getFiles(*this);
1337 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1340 } else if (it->lyxCode() == INCLUDE_CODE) {
1341 InsetInclude & inset =
1342 static_cast<InsetInclude &>(*it);
1343 inset.updateBibfilesCache(*this);
1344 FileNameList const & bibfiles =
1345 inset.getBibfilesCache(*this);
1346 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1354 FileNameList const & Buffer::getBibfilesCache() const
1356 // if this is a child document and the parent is already loaded
1357 // use the parent's cache instead
1358 Buffer const * tmp = masterBuffer();
1361 return tmp->getBibfilesCache();
1363 // We update the cache when first used instead of at loading time.
1364 if (d->bibfilesCache_.empty())
1365 const_cast<Buffer *>(this)->updateBibfilesCache();
1367 return d->bibfilesCache_;
1371 bool Buffer::isDepClean(string const & name) const
1373 DepClean::const_iterator const it = d->dep_clean.find(name);
1374 if (it == d->dep_clean.end())
1380 void Buffer::markDepClean(string const & name)
1382 d->dep_clean[name] = true;
1386 bool Buffer::dispatch(string const & command, bool * result)
1388 return dispatch(lyxaction.lookupFunc(command), result);
1392 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1394 bool dispatched = true;
1396 switch (func.action) {
1397 case LFUN_BUFFER_EXPORT: {
1398 bool const tmp = doExport(to_utf8(func.argument()), false);
1411 void Buffer::changeLanguage(Language const * from, Language const * to)
1416 for_each(par_iterator_begin(),
1418 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1422 bool Buffer::isMultiLingual() const
1424 ParConstIterator end = par_iterator_end();
1425 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1426 if (it->isMultiLingual(params()))
1433 ParIterator Buffer::getParFromID(int const id) const
1435 ParConstIterator it = par_iterator_begin();
1436 ParConstIterator const end = par_iterator_end();
1439 // John says this is called with id == -1 from undo
1440 lyxerr << "getParFromID(), id: " << id << endl;
1444 for (; it != end; ++it)
1452 bool Buffer::hasParWithID(int const id) const
1454 ParConstIterator const it = getParFromID(id);
1455 return it != par_iterator_end();
1459 ParIterator Buffer::par_iterator_begin()
1461 return lyx::par_iterator_begin(inset());
1465 ParIterator Buffer::par_iterator_end()
1467 return lyx::par_iterator_end(inset());
1471 ParConstIterator Buffer::par_iterator_begin() const
1473 return lyx::par_const_iterator_begin(inset());
1477 ParConstIterator Buffer::par_iterator_end() const
1479 return lyx::par_const_iterator_end(inset());
1483 Language const * Buffer::language() const
1485 return params().language;
1489 docstring const Buffer::B_(string const & l10n) const
1491 return params().B_(l10n);
1495 bool Buffer::isClean() const
1497 return d->lyx_clean;
1501 bool Buffer::isBakClean() const
1503 return d->bak_clean;
1507 bool Buffer::isExternallyModified(CheckMethod method) const
1509 BOOST_ASSERT(d->filename.exists());
1510 // if method == timestamp, check timestamp before checksum
1511 return (method == checksum_method
1512 || d->timestamp_ != d->filename.lastModified())
1513 && d->checksum_ != d->filename.checksum();
1517 void Buffer::saveCheckSum(FileName const & file) const
1519 if (file.exists()) {
1520 d->timestamp_ = file.lastModified();
1521 d->checksum_ = file.checksum();
1523 // in the case of save to a new file.
1530 void Buffer::markClean() const
1532 if (!d->lyx_clean) {
1533 d->lyx_clean = true;
1536 // if the .lyx file has been saved, we don't need an
1538 d->bak_clean = true;
1542 void Buffer::markBakClean() const
1544 d->bak_clean = true;
1548 void Buffer::setUnnamed(bool flag)
1554 bool Buffer::isUnnamed() const
1560 // FIXME: this function should be moved to buffer_pimpl.C
1561 void Buffer::markDirty()
1564 d->lyx_clean = false;
1567 d->bak_clean = false;
1569 DepClean::iterator it = d->dep_clean.begin();
1570 DepClean::const_iterator const end = d->dep_clean.end();
1572 for (; it != end; ++it)
1577 FileName Buffer::fileName() const
1583 string Buffer::absFileName() const
1585 return d->filename.absFilename();
1589 string Buffer::filePath() const
1591 return d->filename.onlyPath().absFilename();
1595 bool Buffer::isReadonly() const
1597 return d->read_only;
1601 void Buffer::setParent(Buffer const * buffer)
1603 // Avoids recursive include.
1604 d->parent_buffer = buffer == this ? 0 : buffer;
1608 Buffer const * Buffer::parent()
1610 return d->parent_buffer;
1614 Buffer const * Buffer::masterBuffer() const
1616 if (!d->parent_buffer)
1619 return d->parent_buffer->masterBuffer();
1623 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1625 Impl::PositionToMacroMap::iterator it;
1626 it = d->macros[name].upper_bound(par.macrocontextPosition());
1627 if (it != d->macros[name].end())
1630 // If there is a master buffer, query that
1631 Buffer const * master = masterBuffer();
1632 if (master && master != this)
1633 return master->hasMacro(name);
1635 return MacroTable::globalMacros().has(name);
1639 bool Buffer::hasMacro(docstring const & name) const
1641 if( !d->macros[name].empty() )
1644 // If there is a master buffer, query that
1645 Buffer const * master = masterBuffer();
1646 if (master && master != this)
1647 return master->hasMacro(name);
1649 return MacroTable::globalMacros().has(name);
1653 MacroData const & Buffer::getMacro(docstring const & name,
1654 Paragraph const & par) const
1656 Impl::PositionToMacroMap::iterator it;
1657 it = d->macros[name].upper_bound(par.macrocontextPosition());
1658 if( it != d->macros[name].end() )
1661 // If there is a master buffer, query that
1662 Buffer const * master = masterBuffer();
1663 if (master && master != this)
1664 return master->getMacro(name);
1666 return MacroTable::globalMacros().get(name);
1670 MacroData const & Buffer::getMacro(docstring const & name) const
1672 Impl::PositionToMacroMap::iterator it;
1673 it = d->macros[name].begin();
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 void Buffer::updateMacros()
1688 // start with empty table
1689 d->macros = Impl::NameToPositionMacroMap();
1691 // Iterate over buffer
1692 ParagraphList & pars = text().paragraphs();
1693 for (size_t i = 0, n = pars.size(); i != n; ++i) {
1694 // set position again
1695 pars[i].setMacrocontextPosition(i);
1697 //lyxerr << "searching main par " << i
1698 // << " for macro definitions" << endl;
1699 InsetList const & insets = pars[i].insetList();
1700 InsetList::const_iterator it = insets.begin();
1701 InsetList::const_iterator end = insets.end();
1702 for ( ; it != end; ++it) {
1703 if (it->inset->lyxCode() != MATHMACRO_CODE)
1707 MathMacroTemplate const & macroTemplate
1708 = static_cast<MathMacroTemplate const &>(*it->inset);
1711 if (macroTemplate.validMacro()) {
1712 MacroData macro = macroTemplate.asMacroData();
1715 // call hasMacro here instead of directly querying mc to
1716 // also take the master document into consideration
1717 macro.setRedefinition(hasMacro(macroTemplate.name()));
1719 // register macro (possibly overwrite the previous one of this paragraph)
1720 d->macros[macroTemplate.name()][i] = macro;
1727 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1730 //FIXME: This does not work for child documents yet.
1731 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1732 // Check if the label 'from' appears more than once
1733 vector<docstring> labels;
1736 if (code == CITE_CODE) {
1738 keys.fillWithBibKeys(this);
1739 BiblioInfo::const_iterator bit = keys.begin();
1740 BiblioInfo::const_iterator bend = keys.end();
1742 for (; bit != bend; ++bit)
1744 labels.push_back(bit->first);
1747 getLabelList(labels);
1748 paramName = "reference";
1751 if (count(labels.begin(), labels.end(), from) > 1)
1754 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1755 if (it->lyxCode() == code) {
1756 InsetCommand & inset = static_cast<InsetCommand &>(*it);
1757 docstring const oldValue = inset.getParam(paramName);
1758 if (oldValue == from)
1759 inset.setParam(paramName, to);
1765 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1766 pit_type par_end, bool full_source)
1768 OutputParams runparams(¶ms().encoding());
1769 runparams.nice = true;
1770 runparams.flavor = OutputParams::LATEX;
1771 runparams.linelen = lyxrc.plaintext_linelen;
1772 // No side effect of file copying and image conversion
1773 runparams.dryrun = true;
1777 os << "% " << _("Preview source code") << "\n\n";
1778 d->texrow.newline();
1779 d->texrow.newline();
1781 writeLaTeXSource(os, filePath(), runparams, true, true);
1783 writeDocBookSource(os, absFileName(), runparams, false);
1786 runparams.par_begin = par_begin;
1787 runparams.par_end = par_end;
1788 if (par_begin + 1 == par_end)
1790 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1794 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1795 convert<docstring>(par_begin),
1796 convert<docstring>(par_end - 1))
1798 d->texrow.newline();
1799 d->texrow.newline();
1800 // output paragraphs
1802 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1805 docbookParagraphs(paragraphs(), *this, os, runparams);
1811 ErrorList & Buffer::errorList(string const & type) const
1813 static ErrorList emptyErrorList;
1814 map<string, ErrorList>::iterator I = d->errorLists.find(type);
1815 if (I == d->errorLists.end())
1816 return emptyErrorList;
1822 void Buffer::structureChanged() const
1825 gui_->structureChanged();
1829 void Buffer::errors(string const & err) const
1836 void Buffer::message(docstring const & msg) const
1843 void Buffer::setBusy(bool on) const
1850 void Buffer::setReadOnly(bool on) const
1853 d->wa_->setReadOnly(on);
1857 void Buffer::updateTitles() const
1860 d->wa_->updateTitles();
1864 void Buffer::resetAutosaveTimers() const
1867 gui_->resetAutosaveTimers();
1871 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1880 class AutoSaveBuffer : public ForkedProcess {
1883 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1884 : buffer_(buffer), fname_(fname) {}
1886 virtual boost::shared_ptr<ForkedProcess> clone() const
1888 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1893 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
1894 from_utf8(fname_.absFilename())));
1895 return run(DontWait);
1899 virtual int generateChild();
1901 Buffer const & buffer_;
1906 #if !defined (HAVE_FORK)
1910 int AutoSaveBuffer::generateChild()
1912 // tmp_ret will be located (usually) in /tmp
1913 // will that be a problem?
1914 pid_t const pid = fork();
1915 // If you want to debug the autosave
1916 // you should set pid to -1, and comment out the fork.
1917 if (pid == 0 || pid == -1) {
1918 // pid = -1 signifies that lyx was unable
1919 // to fork. But we will do the save
1921 bool failed = false;
1923 FileName const tmp_ret = FileName::tempName("lyxauto");
1924 if (!tmp_ret.empty()) {
1925 buffer_.writeFile(tmp_ret);
1926 // assume successful write of tmp_ret
1927 if (!tmp_ret.moveTo(fname_)) {
1929 // most likely couldn't move between
1930 // filesystems unless write of tmp_ret
1931 // failed so remove tmp file (if it
1933 tmp_ret.removeFile();
1940 // failed to write/rename tmp_ret so try writing direct
1941 if (!buffer_.writeFile(fname_)) {
1942 // It is dangerous to do this in the child,
1943 // but safe in the parent, so...
1944 if (pid == -1) // emit message signal.
1945 buffer_.message(_("Autosave failed!"));
1948 if (pid == 0) { // we are the child so...
1958 // Perfect target for a thread...
1959 void Buffer::autoSave() const
1961 if (isBakClean() || isReadonly()) {
1962 // We don't save now, but we'll try again later
1963 resetAutosaveTimers();
1967 // emit message signal.
1968 message(_("Autosaving current document..."));
1970 // create autosave filename
1971 string fname = filePath();
1973 fname += d->filename.onlyFileName();
1976 AutoSaveBuffer autosave(*this, FileName(fname));
1980 resetAutosaveTimers();
1984 void Buffer::resetChildDocuments(bool close_them) const
1986 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1987 if (it->lyxCode() != INCLUDE_CODE)
1989 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
1990 InsetCommandParams const & ip = inset.params();
1992 resetParentBuffer(this, ip, close_them);
1995 if (use_gui && masterBuffer() == this)
1996 updateLabels(*this);
2000 void Buffer::loadChildDocuments() const
2002 bool parse_error = false;
2004 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2005 if (it->lyxCode() != INCLUDE_CODE)
2007 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2008 InsetCommandParams const & ip = inset.params();
2009 Buffer * child = loadIfNeeded(*this, ip);
2012 parse_error |= !child->errorList("Parse").empty();
2013 child->loadChildDocuments();
2016 if (use_gui && masterBuffer() == this)
2017 updateLabels(*this);
2021 string Buffer::bufferFormat() const
2031 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2032 string & result_file) const
2034 string backend_format;
2035 OutputParams runparams(¶ms().encoding());
2036 runparams.flavor = OutputParams::LATEX;
2037 runparams.linelen = lyxrc.plaintext_linelen;
2038 vector<string> backs = backends();
2039 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2040 // Get shortest path to format
2041 Graph::EdgePath path;
2042 for (vector<string>::const_iterator it = backs.begin();
2043 it != backs.end(); ++it) {
2044 Graph::EdgePath p = theConverters().getPath(*it, format);
2045 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2046 backend_format = *it;
2051 runparams.flavor = theConverters().getFlavor(path);
2053 Alert::error(_("Couldn't export file"),
2054 bformat(_("No information for exporting the format %1$s."),
2055 formats.prettyName(format)));
2059 backend_format = format;
2060 // FIXME: Don't hardcode format names here, but use a flag
2061 if (backend_format == "pdflatex")
2062 runparams.flavor = OutputParams::PDFLATEX;
2065 string filename = latexName(false);
2066 filename = addName(temppath(), filename);
2067 filename = changeExtension(filename,
2068 formats.extension(backend_format));
2070 // Plain text backend
2071 if (backend_format == "text")
2072 writePlaintextFile(*this, FileName(filename), runparams);
2074 else if (backend_format == "lyx")
2075 writeFile(FileName(filename));
2077 else if (isDocBook()) {
2078 runparams.nice = !put_in_tempdir;
2079 makeDocBookFile(FileName(filename), runparams);
2082 else if (backend_format == format) {
2083 runparams.nice = true;
2084 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2086 } else if (!lyxrc.tex_allows_spaces
2087 && contains(filePath(), ' ')) {
2088 Alert::error(_("File name error"),
2089 _("The directory path to the document cannot contain spaces."));
2092 runparams.nice = false;
2093 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2097 string const error_type = (format == "program")
2098 ? "Build" : bufferFormat();
2099 string const ext = formats.extension(format);
2100 FileName const tmp_result_file(changeExtension(filename, ext));
2101 bool const success = theConverters().convert(this, FileName(filename),
2102 tmp_result_file, FileName(absFileName()), backend_format, format,
2103 errorList(error_type));
2104 // Emit the signal to show the error list.
2105 if (format != backend_format)
2111 result_file = tmp_result_file.absFilename();
2113 result_file = changeExtension(absFileName(), ext);
2114 // We need to copy referenced files (e. g. included graphics
2115 // if format == "dvi") to the result dir.
2116 vector<ExportedFile> const files =
2117 runparams.exportdata->externalFiles(format);
2118 string const dest = onlyPath(result_file);
2119 CopyStatus status = SUCCESS;
2120 for (vector<ExportedFile>::const_iterator it = files.begin();
2121 it != files.end() && status != CANCEL; ++it) {
2123 formats.getFormatFromFile(it->sourceName);
2124 status = copyFile(fmt, it->sourceName,
2125 makeAbsPath(it->exportName, dest),
2126 it->exportName, status == FORCE);
2128 if (status == CANCEL) {
2129 message(_("Document export cancelled."));
2130 } else if (tmp_result_file.exists()) {
2131 // Finally copy the main file
2132 status = copyFile(format, tmp_result_file,
2133 FileName(result_file), result_file,
2135 message(bformat(_("Document exported as %1$s "
2137 formats.prettyName(format),
2138 makeDisplayPath(result_file)));
2140 // This must be a dummy converter like fax (bug 1888)
2141 message(bformat(_("Document exported as %1$s"),
2142 formats.prettyName(format)));
2150 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2153 return doExport(format, put_in_tempdir, result_file);
2157 bool Buffer::preview(string const & format) const
2160 if (!doExport(format, true, result_file))
2162 return formats.view(*this, FileName(result_file), format);
2166 bool Buffer::isExportable(string const & format) const
2168 vector<string> backs = backends();
2169 for (vector<string>::const_iterator it = backs.begin();
2170 it != backs.end(); ++it)
2171 if (theConverters().isReachable(*it, format))
2177 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2179 vector<string> backs = backends();
2180 vector<Format const *> result =
2181 theConverters().getReachable(backs[0], only_viewable, true);
2182 for (vector<string>::const_iterator it = backs.begin() + 1;
2183 it != backs.end(); ++it) {
2184 vector<Format const *> r =
2185 theConverters().getReachable(*it, only_viewable, false);
2186 result.insert(result.end(), r.begin(), r.end());
2192 vector<string> Buffer::backends() const
2195 if (params().getTextClass().isTeXClassAvailable()) {
2196 v.push_back(bufferFormat());
2197 // FIXME: Don't hardcode format names here, but use a flag
2198 if (v.back() == "latex")
2199 v.push_back("pdflatex");
2201 v.push_back("text");
2207 bool Buffer::readFileHelper(FileName const & s)
2209 // File information about normal file
2211 docstring const file = makeDisplayPath(s.absFilename(), 50);
2212 docstring text = bformat(_("The specified document\n%1$s"
2213 "\ncould not be read."), file);
2214 Alert::error(_("Could not read document"), text);
2218 // Check if emergency save file exists and is newer.
2219 FileName const e(s.absFilename() + ".emergency");
2221 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2222 docstring const file = makeDisplayPath(s.absFilename(), 20);
2223 docstring const text =
2224 bformat(_("An emergency save of the document "
2226 "Recover emergency save?"), file);
2227 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2228 _("&Recover"), _("&Load Original"),
2232 // the file is not saved if we load the emergency file.
2242 // Now check if autosave file is newer.
2243 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2245 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2246 docstring const file = makeDisplayPath(s.absFilename(), 20);
2247 docstring const text =
2248 bformat(_("The backup of the document "
2249 "%1$s is newer.\n\nLoad the "
2250 "backup instead?"), file);
2251 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2252 _("&Load backup"), _("Load &original"),
2256 // the file is not saved if we load the autosave file.
2260 // Here we delete the autosave
2271 bool Buffer::loadLyXFile(FileName const & s)
2273 if (s.isReadableFile()) {
2274 if (readFileHelper(s)) {
2275 lyxvc().file_found_hook(s);
2276 if (!s.isWritable())
2281 docstring const file = makeDisplayPath(s.absFilename(), 20);
2282 // Here we probably should run
2283 if (LyXVC::file_not_found_hook(s)) {
2284 docstring const text =
2285 bformat(_("Do you want to retrieve the document"
2286 " %1$s from version control?"), file);
2287 int const ret = Alert::prompt(_("Retrieve from version control?"),
2288 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2291 // How can we know _how_ to do the checkout?
2292 // With the current VC support it has to be,
2293 // a RCS file since CVS do not have special ,v files.
2295 return loadLyXFile(s);
2303 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2305 TeXErrors::Errors::const_iterator cit = terr.begin();
2306 TeXErrors::Errors::const_iterator end = terr.end();
2308 for (; cit != end; ++cit) {
2311 int errorRow = cit->error_in_line;
2312 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2318 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2319 } while (found && id_start == id_end && pos_start == pos_end);
2321 errorList.push_back(ErrorItem(cit->error_desc,
2322 cit->error_text, id_start, pos_start, pos_end));