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 = 309; // Bernhard Reiter: support for \nocite
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 pair<DocIterator, MacroData> ScopeMacro;
179 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
180 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
181 NamePositionScopeMacroMap macros;
184 /// positions of child buffers in the buffer
185 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
186 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
187 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
188 BufferPositionMap children_positions;
189 PositionScopeBufferMap position_to_children;
191 /// Container for all sort of Buffer dependant errors.
192 map<string, ErrorList> errorLists;
194 /// all embedded files of this buffer
195 EmbeddedFiles embedded_files;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
203 frontend::WorkAreaManager * wa_;
208 /// A cache for the bibfiles (including bibfiles of loaded child
209 /// documents), needed for appropriate update of natbib labels.
210 mutable FileNameList bibfilesCache_;
213 /// Creates the per buffer temporary directory
214 static FileName createBufferTmpDir()
217 // We are in our own directory. Why bother to mangle name?
218 // In fact I wrote this code to circumvent a problematic behaviour
219 // (bug?) of EMX mkstemp().
220 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
221 convert<string>(count++));
223 if (!tmpfl.createDirectory(0777)) {
224 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
225 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
226 from_utf8(tmpfl.absFilename())));
232 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
233 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
234 read_only(readonly_), filename(file), file_fully_loaded(false),
235 inset(params), toc_backend(&parent), macro_lock(false),
236 embedded_files(&parent), timestamp_(0), checksum_(0), wa_(0),
239 temppath = createBufferTmpDir();
240 inset.setAutoBreakRows(true);
241 lyxvc.setBuffer(&parent);
243 wa_ = new frontend::WorkAreaManager;
247 Buffer::Buffer(string const & file, bool readonly)
248 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
250 LYXERR(Debug::INFO, "Buffer::Buffer()");
252 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
258 LYXERR(Debug::INFO, "Buffer::~Buffer()");
259 // here the buffer should take care that it is
260 // saved properly, before it goes into the void.
262 // GuiView already destroyed
265 Buffer const * master = masterBuffer();
266 if (master != this && use_gui) {
267 // We are closing buf which was a child document so we
268 // must update the labels and section numbering of its master
270 updateLabels(*master);
271 master->updateMacros();
274 resetChildDocuments(false);
276 if (!d->temppath.destroyDirectory()) {
277 Alert::warning(_("Could not remove temporary directory"),
278 bformat(_("Could not remove the temporary directory %1$s"),
279 from_utf8(d->temppath.absFilename())));
282 // Remove any previewed LaTeX snippets associated with this buffer.
283 graphics::Previews::get().removeLoader(*this);
289 void Buffer::changed() const
296 frontend::WorkAreaManager & Buffer::workAreaManager() const
298 BOOST_ASSERT(d->wa_);
303 Text & Buffer::text() const
305 return const_cast<Text &>(d->inset.text_);
309 Inset & Buffer::inset() const
311 return const_cast<InsetText &>(d->inset);
315 BufferParams & Buffer::params()
321 BufferParams const & Buffer::params() const
327 ParagraphList & Buffer::paragraphs()
329 return text().paragraphs();
333 ParagraphList const & Buffer::paragraphs() const
335 return text().paragraphs();
339 LyXVC & Buffer::lyxvc()
345 LyXVC const & Buffer::lyxvc() const
351 string const Buffer::temppath() const
353 return d->temppath.absFilename();
357 TexRow const & Buffer::texrow() const
363 TocBackend & Buffer::tocBackend() const
365 return d->toc_backend;
369 EmbeddedFiles & Buffer::embeddedFiles()
371 return d->embedded_files;
375 EmbeddedFiles const & Buffer::embeddedFiles() const
377 return d->embedded_files;
381 Undo & Buffer::undo()
387 string Buffer::latexName(bool const no_path) const
389 FileName latex_name = makeLatexName(d->filename);
390 return no_path ? latex_name.onlyFileName()
391 : latex_name.absFilename();
395 string Buffer::logName(LogType * type) const
397 string const filename = latexName(false);
399 if (filename.empty()) {
405 string const path = temppath();
407 FileName const fname(addName(temppath(),
408 onlyFilename(changeExtension(filename,
410 FileName const bname(
411 addName(path, onlyFilename(
412 changeExtension(filename,
413 formats.extension("literate") + ".out"))));
415 // If no Latex log or Build log is newer, show Build log
417 if (bname.exists() &&
418 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
419 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
422 return bname.absFilename();
424 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
427 return fname.absFilename();
431 void Buffer::setReadonly(bool const flag)
433 if (d->read_only != flag) {
440 void Buffer::setFileName(string const & newfile)
442 d->filename = makeAbsPath(newfile);
443 setReadonly(d->filename.isReadOnly());
448 int Buffer::readHeader(Lexer & lex)
450 int unknown_tokens = 0;
452 int begin_header_line = -1;
454 // Initialize parameters that may be/go lacking in header:
455 params().branchlist().clear();
456 params().preamble.erase();
457 params().options.erase();
458 params().float_placement.erase();
459 params().paperwidth.erase();
460 params().paperheight.erase();
461 params().leftmargin.erase();
462 params().rightmargin.erase();
463 params().topmargin.erase();
464 params().bottommargin.erase();
465 params().headheight.erase();
466 params().headsep.erase();
467 params().footskip.erase();
468 params().listings_params.clear();
469 params().clearLayoutModules();
470 params().pdfoptions().clear();
472 for (int i = 0; i < 4; ++i) {
473 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
474 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
477 ErrorList & errorList = d->errorLists["Parse"];
481 string const token = lex.getString();
486 if (token == "\\end_header")
490 if (token == "\\begin_header") {
491 begin_header_line = line;
495 LYXERR(Debug::PARSER, "Handling document header token: `"
498 string unknown = params().readToken(lex, token, d->filename.onlyPath());
499 if (!unknown.empty()) {
500 if (unknown[0] != '\\' && token == "\\textclass") {
501 Alert::warning(_("Unknown document class"),
502 bformat(_("Using the default document class, because the "
503 "class %1$s is unknown."), from_utf8(unknown)));
506 docstring const s = bformat(_("Unknown token: "
510 errorList.push_back(ErrorItem(_("Document header error"),
515 if (begin_header_line) {
516 docstring const s = _("\\begin_header is missing");
517 errorList.push_back(ErrorItem(_("Document header error"),
521 return unknown_tokens;
526 // changed to be public and have one parameter
527 // Returns false if "\end_document" is not read (Asger)
528 bool Buffer::readDocument(Lexer & lex)
530 ErrorList & errorList = d->errorLists["Parse"];
534 string const token = lex.getString();
535 if (token != "\\begin_document") {
536 docstring const s = _("\\begin_document is missing");
537 errorList.push_back(ErrorItem(_("Document header error"),
541 // we are reading in a brand new document
542 BOOST_ASSERT(paragraphs().empty());
545 TextClass const & baseClass = textclasslist[params().getBaseClass()];
546 if (!baseClass.load(filePath())) {
547 string theclass = baseClass.name();
548 Alert::error(_("Can't load document class"), bformat(
549 _("Using the default document class, because the "
550 "class %1$s could not be loaded."), from_utf8(theclass)));
551 params().setBaseClass(defaultTextclass());
554 if (params().outputChanges) {
555 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
556 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
557 LaTeXFeatures::isAvailable("xcolor");
559 if (!dvipost && !xcolorsoul) {
560 Alert::warning(_("Changes not shown in LaTeX output"),
561 _("Changes will not be highlighted in LaTeX output, "
562 "because neither dvipost nor xcolor/soul are installed.\n"
563 "Please install these packages or redefine "
564 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
565 } else if (!xcolorsoul) {
566 Alert::warning(_("Changes not shown in LaTeX output"),
567 _("Changes will not be highlighted in LaTeX output "
568 "when using pdflatex, because xcolor and soul are not installed.\n"
569 "Please install both packages or redefine "
570 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
575 bool const res = text().read(*this, lex, errorList);
576 for_each(text().paragraphs().begin(),
577 text().paragraphs().end(),
578 bind(&Paragraph::setInsetOwner, _1, &inset()));
581 updateMacroInstances();
586 // needed to insert the selection
587 void Buffer::insertStringAsLines(ParagraphList & pars,
588 pit_type & pit, pos_type & pos,
589 Font const & fn, docstring const & str, bool autobreakrows)
593 // insert the string, don't insert doublespace
594 bool space_inserted = true;
595 for (docstring::const_iterator cit = str.begin();
596 cit != str.end(); ++cit) {
597 Paragraph & par = pars[pit];
599 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
600 breakParagraph(params(), pars, pit, pos,
601 par.layout()->isEnvironment());
604 space_inserted = true;
608 // do not insert consecutive spaces if !free_spacing
609 } else if ((*cit == ' ' || *cit == '\t') &&
610 space_inserted && !par.isFreeSpacing()) {
612 } else if (*cit == '\t') {
613 if (!par.isFreeSpacing()) {
614 // tabs are like spaces here
615 par.insertChar(pos, ' ', font, params().trackChanges);
617 space_inserted = true;
619 const pos_type n = 8 - pos % 8;
620 for (pos_type i = 0; i < n; ++i) {
621 par.insertChar(pos, ' ', font, params().trackChanges);
624 space_inserted = true;
626 } else if (!isPrintable(*cit)) {
627 // Ignore unprintables
630 // just insert the character
631 par.insertChar(pos, *cit, font, params().trackChanges);
633 space_inserted = (*cit == ' ');
640 bool Buffer::readString(string const & s)
642 params().compressed = false;
644 // remove dummy empty par
645 paragraphs().clear();
649 FileName const name = FileName::tempName();
650 switch (readFile(lex, name, true)) {
654 // We need to call lyx2lyx, so write the input to a file
655 ofstream os(name.toFilesystemEncoding().c_str());
658 return readFile(name);
668 bool Buffer::readFile(FileName const & filename)
670 FileName fname(filename);
671 // Check if the file is compressed.
672 string format = filename.guessFormatFromContents();
673 if (format == "zip") {
674 // decompress to a temp directory
675 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
676 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
678 FileName lyxfile(addName(temppath(), "content.lyx"));
679 // if both manifest.txt and file.lyx exist, this is am embedded file
680 if (lyxfile.exists()) {
681 params().embedded = true;
685 // The embedded lyx file can also be compressed, for backward compatibility
686 format = fname.guessFormatFromContents();
687 if (format == "gzip" || format == "zip" || format == "compress")
688 params().compressed = true;
690 // remove dummy empty par
691 paragraphs().clear();
694 if (readFile(lex, fname) != success)
701 bool Buffer::isFullyLoaded() const
703 return d->file_fully_loaded;
707 void Buffer::setFullyLoaded(bool value)
709 d->file_fully_loaded = value;
713 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
716 BOOST_ASSERT(!filename.empty());
719 Alert::error(_("Document could not be read"),
720 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
725 string const token = lex.getString();
728 Alert::error(_("Document could not be read"),
729 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
733 // the first token _must_ be...
734 if (token != "\\lyxformat") {
735 lyxerr << "Token: " << token << endl;
737 Alert::error(_("Document format failure"),
738 bformat(_("%1$s is not a LyX document."),
739 from_utf8(filename.absFilename())));
744 string tmp_format = lex.getString();
745 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
746 // if present remove ".," from string.
747 string::size_type dot = tmp_format.find_first_of(".,");
748 //lyxerr << " dot found at " << dot << endl;
749 if (dot != string::npos)
750 tmp_format.erase(dot, 1);
751 int const file_format = convert<int>(tmp_format);
752 //lyxerr << "format: " << file_format << endl;
754 // save timestamp and checksum of the original disk file, making sure
755 // to not overwrite them with those of the file created in the tempdir
756 // when it has to be converted to the current format.
758 // Save the timestamp and checksum of disk file. If filename is an
759 // emergency file, save the timestamp and checksum of the original lyx file
760 // because isExternallyModified will check for this file. (BUG4193)
761 string diskfile = filename.absFilename();
762 if (suffixIs(diskfile, ".emergency"))
763 diskfile = diskfile.substr(0, diskfile.size() - 10);
764 saveCheckSum(FileName(diskfile));
767 if (file_format != LYX_FORMAT) {
770 // lyx2lyx would fail
773 FileName const tmpfile = FileName::tempName();
774 if (tmpfile.empty()) {
775 Alert::error(_("Conversion failed"),
776 bformat(_("%1$s is from a different"
777 " version of LyX, but a temporary"
778 " file for converting it could"
780 from_utf8(filename.absFilename())));
783 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
784 if (lyx2lyx.empty()) {
785 Alert::error(_("Conversion script not found"),
786 bformat(_("%1$s is from a different"
787 " version of LyX, but the"
788 " conversion script lyx2lyx"
789 " could not be found."),
790 from_utf8(filename.absFilename())));
793 ostringstream command;
794 command << os::python()
795 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
796 << " -t " << convert<string>(LYX_FORMAT)
797 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
798 << ' ' << quoteName(filename.toFilesystemEncoding());
799 string const command_str = command.str();
801 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
803 cmd_ret const ret = runCommand(command_str);
804 if (ret.first != 0) {
805 Alert::error(_("Conversion script failed"),
806 bformat(_("%1$s is from a different version"
807 " of LyX, but the lyx2lyx script"
808 " failed to convert it."),
809 from_utf8(filename.absFilename())));
812 bool const ret = readFile(tmpfile);
813 // Do stuff with tmpfile name and buffer name here.
814 return ret ? success : failure;
819 if (readDocument(lex)) {
820 Alert::error(_("Document format failure"),
821 bformat(_("%1$s ended unexpectedly, which means"
822 " that it is probably corrupted."),
823 from_utf8(filename.absFilename())));
826 d->file_fully_loaded = true;
831 // Should probably be moved to somewhere else: BufferView? LyXView?
832 bool Buffer::save() const
834 // We don't need autosaves in the immediate future. (Asger)
835 resetAutosaveTimers();
837 string const encodedFilename = d->filename.toFilesystemEncoding();
840 bool madeBackup = false;
842 // make a backup if the file already exists
843 if (lyxrc.make_backup && fileName().exists()) {
844 backupName = FileName(absFileName() + '~');
845 if (!lyxrc.backupdir_path.empty()) {
846 string const mangledName =
847 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
848 backupName = FileName(addName(lyxrc.backupdir_path,
851 if (fileName().copyTo(backupName)) {
854 Alert::error(_("Backup failure"),
855 bformat(_("Cannot create backup file %1$s.\n"
856 "Please check whether the directory exists and is writeable."),
857 from_utf8(backupName.absFilename())));
858 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
862 // ask if the disk file has been externally modified (use checksum method)
863 if (fileName().exists() && isExternallyModified(checksum_method)) {
864 docstring const file = makeDisplayPath(absFileName(), 20);
865 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
866 "you want to overwrite this file?"), file);
867 int const ret = Alert::prompt(_("Overwrite modified file?"),
868 text, 1, 1, _("&Overwrite"), _("&Cancel"));
873 if (writeFile(d->filename)) {
877 // Saving failed, so backup is not backup
879 backupName.moveTo(d->filename);
885 bool Buffer::writeFile(FileName const & fname) const
887 if (d->read_only && fname == d->filename)
893 if (params().embedded)
894 // first write the .lyx file to the temporary directory
895 content = FileName(addName(temppath(), "content.lyx"));
899 docstring const str = bformat(_("Saving document %1$s..."),
900 makeDisplayPath(content.absFilename()));
903 if (params().compressed) {
904 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
905 retval = ofs && write(ofs);
907 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
908 retval = ofs && write(ofs);
912 message(str + _(" could not write file!."));
916 removeAutosaveFile(d->filename.absFilename());
917 saveCheckSum(d->filename);
918 message(str + _(" done."));
920 if (!params().embedded)
923 message(str + _(" writing embedded files!."));
924 // if embedding is enabled, write file.lyx and all the embedded files
925 // to the zip file fname.
926 if (!d->embedded_files.writeFile(fname)) {
927 message(str + _(" could not write embedded files!."));
930 message(str + _(" error while writing embedded files."));
935 bool Buffer::write(ostream & ofs) const
938 // Use the standard "C" locale for file output.
939 ofs.imbue(locale::classic());
942 // The top of the file should not be written by params().
944 // write out a comment in the top of the file
945 ofs << "#LyX " << lyx_version
946 << " created this file. For more info see http://www.lyx.org/\n"
947 << "\\lyxformat " << LYX_FORMAT << "\n"
948 << "\\begin_document\n";
951 /// For each author, set 'used' to true if there is a change
952 /// by this author in the document; otherwise set it to 'false'.
953 AuthorList::Authors::const_iterator a_it = params().authors().begin();
954 AuthorList::Authors::const_iterator a_end = params().authors().end();
955 for (; a_it != a_end; ++a_it)
956 a_it->second.setUsed(false);
958 ParIterator const end = par_iterator_end();
959 ParIterator it = par_iterator_begin();
960 for ( ; it != end; ++it)
961 it->checkAuthors(params().authors());
963 // now write out the buffer parameters.
964 ofs << "\\begin_header\n";
965 params().writeFile(ofs);
966 ofs << "\\end_header\n";
969 ofs << "\n\\begin_body\n";
970 text().write(*this, ofs);
971 ofs << "\n\\end_body\n";
973 // Write marker that shows file is complete
974 ofs << "\\end_document" << endl;
976 // Shouldn't really be needed....
979 // how to check if close went ok?
980 // Following is an attempt... (BE 20001011)
982 // good() returns false if any error occured, including some
984 // bad() returns true if something bad happened in the buffer,
985 // which should include file system full errors.
990 lyxerr << "File was not closed properly." << endl;
997 bool Buffer::makeLaTeXFile(FileName const & fname,
998 string const & original_path,
999 OutputParams const & runparams,
1000 bool output_preamble, bool output_body) const
1002 string const encoding = runparams.encoding->iconvName();
1003 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1006 try { ofs.reset(encoding); }
1007 catch (iconv_codecvt_facet_exception & e) {
1008 lyxerr << "Caught iconv exception: " << e.what() << endl;
1009 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1010 "verify that the support software for your encoding (%1$s) is "
1011 "properly installed"), from_ascii(encoding)));
1014 if (!openFileWrite(ofs, fname))
1017 //TexStream ts(ofs.rdbuf(), &texrow());
1018 ErrorList & errorList = d->errorLists["Export"];
1020 bool failed_export = false;
1023 writeLaTeXSource(ofs, original_path,
1024 runparams, output_preamble, output_body);
1026 catch (EncodingException & e) {
1027 docstring msg = _("Could not find LaTeX command for character '%'");
1028 msg[msg.size() - 2] = e.failed_char;
1029 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1030 "representable in the chosen encoding.\n"
1031 "Changing the document encoding to utf8 could help."),
1032 e.par_id, e.pos, e.pos + 1));
1033 failed_export = true;
1035 catch (iconv_codecvt_facet_exception & e) {
1036 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1037 _(e.what()), -1, 0, 0));
1038 failed_export = true;
1040 catch (exception const & e) {
1041 errorList.push_back(ErrorItem(_("conversion failed"),
1042 _(e.what()), -1, 0, 0));
1043 failed_export = true;
1046 lyxerr << "Caught some really weird exception..." << endl;
1047 LyX::cref().exit(1);
1052 failed_export = true;
1053 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1057 return !failed_export;
1061 void Buffer::writeLaTeXSource(odocstream & os,
1062 string const & original_path,
1063 OutputParams const & runparams_in,
1064 bool const output_preamble, bool const output_body) const
1066 OutputParams runparams = runparams_in;
1068 // validate the buffer.
1069 LYXERR(Debug::LATEX, " Validating buffer...");
1070 LaTeXFeatures features(*this, params(), runparams);
1072 LYXERR(Debug::LATEX, " Buffer validation done.");
1074 // The starting paragraph of the coming rows is the
1075 // first paragraph of the document. (Asger)
1076 if (output_preamble && runparams.nice) {
1077 os << "%% LyX " << lyx_version << " created this file. "
1078 "For more info, see http://www.lyx.org/.\n"
1079 "%% Do not edit unless you really know what "
1081 d->texrow.newline();
1082 d->texrow.newline();
1084 LYXERR(Debug::INFO, "lyx document header finished");
1085 // There are a few differences between nice LaTeX and usual files:
1086 // usual is \batchmode and has a
1087 // special input@path to allow the including of figures
1088 // with either \input or \includegraphics (what figinsets do).
1089 // input@path is set when the actual parameter
1090 // original_path is set. This is done for usual tex-file, but not
1091 // for nice-latex-file. (Matthias 250696)
1092 // Note that input@path is only needed for something the user does
1093 // in the preamble, included .tex files or ERT, files included by
1094 // LyX work without it.
1095 if (output_preamble) {
1096 if (!runparams.nice) {
1097 // code for usual, NOT nice-latex-file
1098 os << "\\batchmode\n"; // changed
1099 // from \nonstopmode
1100 d->texrow.newline();
1102 if (!original_path.empty()) {
1104 // We don't know the encoding of inputpath
1105 docstring const inputpath = from_utf8(latex_path(original_path));
1106 os << "\\makeatletter\n"
1107 << "\\def\\input@path{{"
1108 << inputpath << "/}}\n"
1109 << "\\makeatother\n";
1110 d->texrow.newline();
1111 d->texrow.newline();
1112 d->texrow.newline();
1115 // Write the preamble
1116 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1122 os << "\\begin{document}\n";
1123 d->texrow.newline();
1124 } // output_preamble
1126 d->texrow.start(paragraphs().begin()->id(), 0);
1128 LYXERR(Debug::INFO, "preamble finished, now the body.");
1130 // fold macros if possible, still with parent buffer as the
1131 // macros will be put in the prefix anyway.
1133 updateMacroInstances();
1135 // if we are doing a real file with body, even if this is the
1136 // child of some other buffer, let's cut the link here.
1137 // This happens for example if only a child document is printed.
1138 Buffer const * save_parent = 0;
1139 if (output_preamble) {
1140 // output the macros visible for this buffer
1141 writeParentMacros(os);
1143 save_parent = d->parent_buffer;
1144 d->parent_buffer = 0;
1147 loadChildDocuments();
1150 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1152 // Restore the parenthood if needed
1153 if (output_preamble) {
1154 d->parent_buffer = save_parent;
1156 // restore macros with correct parent buffer (especially
1157 // important for the redefinition flag which depends on the
1162 // add this just in case after all the paragraphs
1164 d->texrow.newline();
1166 if (output_preamble) {
1167 os << "\\end{document}\n";
1168 d->texrow.newline();
1169 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1171 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1173 runparams_in.encoding = runparams.encoding;
1175 // Just to be sure. (Asger)
1176 d->texrow.newline();
1178 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1179 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1183 bool Buffer::isLatex() const
1185 return params().getTextClass().outputType() == LATEX;
1189 bool Buffer::isLiterate() const
1191 return params().getTextClass().outputType() == LITERATE;
1195 bool Buffer::isDocBook() const
1197 return params().getTextClass().outputType() == DOCBOOK;
1201 void Buffer::makeDocBookFile(FileName const & fname,
1202 OutputParams const & runparams,
1203 bool const body_only) const
1205 LYXERR(Debug::LATEX, "makeDocBookFile...");
1209 if (!openFileWrite(ofs, fname))
1212 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1216 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1220 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1221 OutputParams const & runparams,
1222 bool const only_body) const
1224 LaTeXFeatures features(*this, params(), runparams);
1229 TextClass const & tclass = params().getTextClass();
1230 string const top_element = tclass.latexname();
1233 if (runparams.flavor == OutputParams::XML)
1234 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1237 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1240 if (! tclass.class_header().empty())
1241 os << from_ascii(tclass.class_header());
1242 else if (runparams.flavor == OutputParams::XML)
1243 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1244 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1246 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1248 docstring preamble = from_utf8(params().preamble);
1249 if (runparams.flavor != OutputParams::XML ) {
1250 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1251 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1252 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1256 string const name = runparams.nice
1257 ? changeExtension(absFileName(), ".sgml") : fname;
1258 preamble += features.getIncludedFiles(name);
1259 preamble += features.getLyXSGMLEntities();
1261 if (!preamble.empty()) {
1262 os << "\n [ " << preamble << " ]";
1267 string top = top_element;
1269 if (runparams.flavor == OutputParams::XML)
1270 top += params().language->code();
1272 top += params().language->code().substr(0,2);
1275 if (!params().options.empty()) {
1277 top += params().options;
1280 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1281 << " file was created by LyX " << lyx_version
1282 << "\n See http://www.lyx.org/ for more information -->\n";
1284 params().getTextClass().counters().reset();
1286 loadChildDocuments();
1288 sgml::openTag(os, top);
1290 docbookParagraphs(paragraphs(), *this, os, runparams);
1291 sgml::closeTag(os, top_element);
1295 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1296 // Other flags: -wall -v0 -x
1297 int Buffer::runChktex()
1301 // get LaTeX-Filename
1302 FileName const path(temppath());
1303 string const name = addName(path.absFilename(), latexName());
1304 string const org_path = filePath();
1306 PathChanger p(path); // path to LaTeX file
1307 message(_("Running chktex..."));
1309 // Generate the LaTeX file if neccessary
1310 OutputParams runparams(¶ms().encoding());
1311 runparams.flavor = OutputParams::LATEX;
1312 runparams.nice = false;
1313 makeLaTeXFile(FileName(name), org_path, runparams);
1316 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1317 int const res = chktex.run(terr); // run chktex
1320 Alert::error(_("chktex failure"),
1321 _("Could not run chktex successfully."));
1322 } else if (res > 0) {
1323 ErrorList & errlist = d->errorLists["ChkTeX"];
1325 bufferErrors(terr, errlist);
1336 void Buffer::validate(LaTeXFeatures & features) const
1338 params().validate(features);
1340 loadChildDocuments();
1342 for_each(paragraphs().begin(), paragraphs().end(),
1343 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1345 if (lyxerr.debugging(Debug::LATEX)) {
1346 features.showStruct();
1351 void Buffer::getLabelList(vector<docstring> & list) const
1353 /// if this is a child document and the parent is already loaded
1354 /// Use the parent's list instead [ale990407]
1355 Buffer const * tmp = masterBuffer();
1357 lyxerr << "masterBuffer() failed!" << endl;
1361 tmp->getLabelList(list);
1365 loadChildDocuments();
1367 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1368 it.nextInset()->getLabelList(*this, list);
1372 void Buffer::updateBibfilesCache() const
1374 // if this is a child document and the parent is already loaded
1375 // update the parent's cache instead
1376 Buffer const * tmp = masterBuffer();
1379 tmp->updateBibfilesCache();
1383 d->bibfilesCache_.clear();
1384 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1385 if (it->lyxCode() == BIBTEX_CODE) {
1386 InsetBibtex const & inset =
1387 static_cast<InsetBibtex const &>(*it);
1388 FileNameList const bibfiles = inset.getFiles(*this);
1389 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1392 } else if (it->lyxCode() == INCLUDE_CODE) {
1393 InsetInclude & inset =
1394 static_cast<InsetInclude &>(*it);
1395 inset.updateBibfilesCache(*this);
1396 FileNameList const & bibfiles =
1397 inset.getBibfilesCache(*this);
1398 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1406 FileNameList const & Buffer::getBibfilesCache() const
1408 // if this is a child document and the parent is already loaded
1409 // use the parent's cache instead
1410 Buffer const * tmp = masterBuffer();
1413 return tmp->getBibfilesCache();
1415 // We update the cache when first used instead of at loading time.
1416 if (d->bibfilesCache_.empty())
1417 const_cast<Buffer *>(this)->updateBibfilesCache();
1419 return d->bibfilesCache_;
1423 bool Buffer::isDepClean(string const & name) const
1425 DepClean::const_iterator const it = d->dep_clean.find(name);
1426 if (it == d->dep_clean.end())
1432 void Buffer::markDepClean(string const & name)
1434 d->dep_clean[name] = true;
1438 bool Buffer::dispatch(string const & command, bool * result)
1440 return dispatch(lyxaction.lookupFunc(command), result);
1444 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1446 bool dispatched = true;
1448 switch (func.action) {
1449 case LFUN_BUFFER_EXPORT: {
1450 bool const tmp = doExport(to_utf8(func.argument()), false);
1463 void Buffer::changeLanguage(Language const * from, Language const * to)
1468 for_each(par_iterator_begin(),
1470 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1474 bool Buffer::isMultiLingual() const
1476 ParConstIterator end = par_iterator_end();
1477 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1478 if (it->isMultiLingual(params()))
1485 ParIterator Buffer::getParFromID(int const id) const
1487 ParConstIterator it = par_iterator_begin();
1488 ParConstIterator const end = par_iterator_end();
1491 // John says this is called with id == -1 from undo
1492 lyxerr << "getParFromID(), id: " << id << endl;
1496 for (; it != end; ++it)
1504 bool Buffer::hasParWithID(int const id) const
1506 ParConstIterator const it = getParFromID(id);
1507 return it != par_iterator_end();
1511 ParIterator Buffer::par_iterator_begin()
1513 return lyx::par_iterator_begin(inset());
1517 ParIterator Buffer::par_iterator_end()
1519 return lyx::par_iterator_end(inset());
1523 ParConstIterator Buffer::par_iterator_begin() const
1525 return lyx::par_const_iterator_begin(inset());
1529 ParConstIterator Buffer::par_iterator_end() const
1531 return lyx::par_const_iterator_end(inset());
1535 Language const * Buffer::language() const
1537 return params().language;
1541 docstring const Buffer::B_(string const & l10n) const
1543 return params().B_(l10n);
1547 bool Buffer::isClean() const
1549 return d->lyx_clean;
1553 bool Buffer::isBakClean() const
1555 return d->bak_clean;
1559 bool Buffer::isExternallyModified(CheckMethod method) const
1561 BOOST_ASSERT(d->filename.exists());
1562 // if method == timestamp, check timestamp before checksum
1563 return (method == checksum_method
1564 || d->timestamp_ != d->filename.lastModified())
1565 && d->checksum_ != d->filename.checksum();
1569 void Buffer::saveCheckSum(FileName const & file) const
1571 if (file.exists()) {
1572 d->timestamp_ = file.lastModified();
1573 d->checksum_ = file.checksum();
1575 // in the case of save to a new file.
1582 void Buffer::markClean() const
1584 if (!d->lyx_clean) {
1585 d->lyx_clean = true;
1588 // if the .lyx file has been saved, we don't need an
1590 d->bak_clean = true;
1594 void Buffer::markBakClean() const
1596 d->bak_clean = true;
1600 void Buffer::setUnnamed(bool flag)
1606 bool Buffer::isUnnamed() const
1612 // FIXME: this function should be moved to buffer_pimpl.C
1613 void Buffer::markDirty()
1616 d->lyx_clean = false;
1619 d->bak_clean = false;
1621 DepClean::iterator it = d->dep_clean.begin();
1622 DepClean::const_iterator const end = d->dep_clean.end();
1624 for (; it != end; ++it)
1629 FileName Buffer::fileName() const
1635 string Buffer::absFileName() const
1637 return d->filename.absFilename();
1641 string Buffer::filePath() const
1643 return d->filename.onlyPath().absFilename();
1647 bool Buffer::isReadonly() const
1649 return d->read_only;
1653 void Buffer::setParent(Buffer const * buffer)
1655 // Avoids recursive include.
1656 d->parent_buffer = buffer == this ? 0 : buffer;
1661 Buffer const * Buffer::parent()
1663 return d->parent_buffer;
1667 Buffer const * Buffer::masterBuffer() const
1669 if (!d->parent_buffer)
1672 return d->parent_buffer->masterBuffer();
1676 template<typename M>
1677 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1682 typename M::iterator it = m.lower_bound(x);
1683 if (it == m.begin())
1691 MacroData const * Buffer::getBufferMacro(docstring const & name,
1692 DocIterator const & pos) const
1694 LYXERR(Debug::DEBUG, "Searching for " << to_ascii(name) << " at " << pos);
1696 // if paragraphs have no macro context set, pos will be empty
1700 // we haven't found anything yet
1701 DocIterator bestPos = par_iterator_begin();
1702 MacroData const * bestData = 0;
1704 // find macro definitions for name
1705 Impl::NamePositionScopeMacroMap::iterator nameIt
1706 = d->macros.find(name);
1707 if (nameIt != d->macros.end()) {
1708 // find last definition in front of pos or at pos itself
1709 Impl::PositionScopeMacroMap::const_iterator it
1710 = greatest_below(nameIt->second, pos);
1711 if (it != nameIt->second.end()) {
1713 // scope ends behind pos?
1714 if (pos < it->second.first) {
1715 // Looks good, remember this. If there
1716 // is no external macro behind this,
1717 // we found the right one already.
1718 bestPos = it->first;
1719 bestData = &it->second.second;
1723 // try previous macro if there is one
1724 if (it == nameIt->second.begin())
1731 // find macros in included files
1732 Impl::PositionScopeBufferMap::const_iterator it
1733 = greatest_below(d->position_to_children, pos);
1734 if (it != d->position_to_children.end()) {
1736 // do we know something better (i.e. later) already?
1737 if (it->first < bestPos )
1740 // scope ends behind pos?
1741 if (pos < it->second.first) {
1742 // look for macro in external file
1743 d->macro_lock = true;
1744 MacroData const * data
1745 = it->second.second->getMacro(name, false);
1746 d->macro_lock = false;
1748 bestPos = it->first;
1754 // try previous file if there is one
1755 if (it == d->position_to_children.begin())
1761 // return the best macro we have found
1766 MacroData const * Buffer::getMacro(docstring const & name,
1767 DocIterator const & pos, bool global) const
1772 // query buffer macros
1773 MacroData const * data = getBufferMacro(name, pos);
1777 // If there is a master buffer, query that
1778 if (d->parent_buffer) {
1779 d->macro_lock = true;
1780 MacroData const * macro
1781 = d->parent_buffer->getMacro(name, *this, false);
1782 d->macro_lock = false;
1788 data = MacroTable::globalMacros().get(name);
1797 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1799 // set scope end behind the last paragraph
1800 DocIterator scope = par_iterator_begin();
1801 scope.pit() = scope.lastpit() + 1;
1803 return getMacro(name, scope, global);
1807 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1809 // look where the child buffer is included first
1810 Impl::BufferPositionMap::iterator it
1811 = d->children_positions.find(&child);
1812 if (it == d->children_positions.end())
1815 // check for macros at the inclusion position
1816 return getMacro(name, it->second, global);
1820 void Buffer::updateEnvironmentMacros(DocIterator & it,
1822 DocIterator & scope) const
1824 Paragraph & par = it.paragraph();
1826 = par.params().depth();
1827 Length const & leftIndent
1828 = par.params().leftIndent();
1830 // look for macros in each paragraph
1831 while (it.pit() <= lastpit) {
1832 Paragraph & par = it.paragraph();
1835 if ((par.params().depth() > depth
1836 || par.params().leftIndent() != leftIndent)
1837 && par.layout()->isEnvironment()) {
1838 updateBlockMacros(it, scope);
1842 // iterate over the insets of the current paragraph
1843 InsetList const & insets = par.insetList();
1844 InsetList::const_iterator iit = insets.begin();
1845 InsetList::const_iterator end = insets.end();
1846 for (; iit != end; ++iit) {
1847 it.pos() = iit->pos;
1849 // is it a nested text inset?
1850 if (iit->inset->asInsetText()) {
1851 // Inset needs its own scope?
1852 InsetText const * itext
1853 = iit->inset->asInsetText();
1854 bool newScope = itext->isMacroScope(*this);
1856 // scope which ends just behind die inset
1857 DocIterator insetScope = it;
1860 // collect macros in inset
1861 it.push_back(CursorSlice(*iit->inset));
1862 updateInsetMacros(it, newScope ? insetScope : scope);
1867 // is it an external file?
1868 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1869 // get buffer of external file
1870 InsetCommand const & inset
1871 = static_cast<InsetCommand const &>(*iit->inset);
1872 InsetCommandParams const & ip = inset.params();
1873 d->macro_lock = true;
1874 Buffer * child = loadIfNeeded(*this, ip);
1875 d->macro_lock = false;
1879 // register it, but only when it is
1880 // included first in the buffer
1881 if (d->children_positions.find(child)
1882 == d->children_positions.end())
1883 d->children_positions[child] = it;
1885 // register child with its scope
1886 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1891 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1895 MathMacroTemplate & macroTemplate
1896 = static_cast<MathMacroTemplate &>(*iit->inset);
1897 MacroContext mc(*this, it);
1898 macroTemplate.updateToContext(mc);
1901 bool valid = macroTemplate.validMacro();
1902 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1903 // then the BufferView's cursor will be invalid in
1904 // some cases which leads to crashes.
1909 d->macros[macroTemplate.name()][it]
1910 = Impl::ScopeMacro(scope, MacroData(*this, it));
1920 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1922 Paragraph & par = it.paragraph();
1924 // set scope for macros in this paragraph:
1925 // * either the "old" outer scope
1926 // * or the scope ending after the environment
1927 if (par.layout()->isEnvironment()) {
1928 // find end of environment block,
1929 DocIterator envEnd = it;
1930 pit_type n = it.lastpit() + 1;
1931 depth_type depth = par.params().depth();
1932 Length const & length = par.params().leftIndent();
1933 // looping through the paragraph, basically until
1934 // the layout changes or the depth gets smaller.
1935 // (the logic of output_latex.cpp's TeXEnvironment)
1938 if (envEnd.pit() == n)
1940 } while (par.layout() == envEnd.paragraph().layout()
1941 || depth < envEnd.paragraph().params().depth()
1942 || length != envEnd.paragraph().params().leftIndent());
1944 // collect macros from environment block
1945 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1947 // collect macros from paragraph
1948 updateEnvironmentMacros(it, it.pit(), scope);
1953 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1955 // look for macros in each paragraph
1956 pit_type n = it.lastpit() + 1;
1957 while (it.pit() < n)
1958 updateBlockMacros(it, scope);
1962 void Buffer::updateMacros() const
1967 LYXERR(Debug::DEBUG, "updateMacro of " << d->filename.onlyFileName());
1969 // start with empty table
1971 d->children_positions.clear();
1972 d->position_to_children.clear();
1974 // Iterate over buffer, starting with first paragraph
1975 // The scope must be bigger than any lookup DocIterator
1976 // later. For the global lookup, lastpit+1 is used, hence
1977 // we use lastpit+2 here.
1978 DocIterator it = par_iterator_begin();
1979 DocIterator outerScope = it;
1980 outerScope.pit() = outerScope.lastpit() + 2;
1981 updateInsetMacros(it, outerScope);
1985 void Buffer::updateMacroInstances() const
1987 LYXERR(Debug::DEBUG, "updateMacroInstances for " << d->filename.onlyFileName());
1988 ParIterator it = par_iterator_begin();
1989 ParIterator end = par_iterator_end();
1990 for (; it != end; it.forwardPos()) {
1991 // look for MathData cells in InsetMathNest insets
1992 Inset * inset = it.nextInset();
1996 InsetMath * minset = inset->asInsetMath();
2000 // update macro in all cells of the InsetMathNest
2001 DocIterator::idx_type n = minset->nargs();
2002 MacroContext mc = MacroContext(*this, it);
2003 for (DocIterator::idx_type i = 0; i < n; ++i) {
2004 MathData & data = minset->cell(i);
2005 data.updateMacros(0, mc);
2011 void Buffer::listMacroNames(MacroNameSet & macros) const
2016 d->macro_lock = true;
2018 // loop over macro names
2019 Impl::NamePositionScopeMacroMap::iterator nameIt
2020 = d->macros.begin();
2021 Impl::NamePositionScopeMacroMap::iterator nameEnd
2023 for (; nameIt != nameEnd; ++nameIt)
2024 macros.insert(nameIt->first);
2026 // loop over children
2027 Impl::BufferPositionMap::iterator it
2028 = d->children_positions.begin();
2029 Impl::BufferPositionMap::iterator end
2030 = d->children_positions.end();
2031 for (; it != end; ++it)
2032 it->first->listMacroNames(macros);
2035 if (d->parent_buffer)
2036 d->parent_buffer->listMacroNames(macros);
2038 d->macro_lock = false;
2042 void Buffer::writeParentMacros(odocstream & os) const
2044 if (!d->parent_buffer)
2047 // collect macro names
2049 d->parent_buffer->listMacroNames(names);
2051 // resolve and output them
2052 MacroNameSet::iterator it = names.begin();
2053 MacroNameSet::iterator end = names.end();
2054 for (; it != end; ++it) {
2056 MacroData const * data =
2057 d->parent_buffer->getMacro(*it, *this, false);
2059 data->write(os, true);
2064 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2067 //FIXME: This does not work for child documents yet.
2068 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2069 // Check if the label 'from' appears more than once
2070 vector<docstring> labels;
2073 if (code == CITE_CODE) {
2075 keys.fillWithBibKeys(this);
2076 BiblioInfo::const_iterator bit = keys.begin();
2077 BiblioInfo::const_iterator bend = keys.end();
2079 for (; bit != bend; ++bit)
2081 labels.push_back(bit->first);
2084 getLabelList(labels);
2085 paramName = "reference";
2088 if (count(labels.begin(), labels.end(), from) > 1)
2091 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2092 if (it->lyxCode() == code) {
2093 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2094 docstring const oldValue = inset.getParam(paramName);
2095 if (oldValue == from)
2096 inset.setParam(paramName, to);
2102 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2103 pit_type par_end, bool full_source)
2105 OutputParams runparams(¶ms().encoding());
2106 runparams.nice = true;
2107 runparams.flavor = OutputParams::LATEX;
2108 runparams.linelen = lyxrc.plaintext_linelen;
2109 // No side effect of file copying and image conversion
2110 runparams.dryrun = true;
2114 os << "% " << _("Preview source code") << "\n\n";
2115 d->texrow.newline();
2116 d->texrow.newline();
2118 writeLaTeXSource(os, filePath(), runparams, true, true);
2120 writeDocBookSource(os, absFileName(), runparams, false);
2123 runparams.par_begin = par_begin;
2124 runparams.par_end = par_end;
2125 if (par_begin + 1 == par_end)
2127 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2131 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2132 convert<docstring>(par_begin),
2133 convert<docstring>(par_end - 1))
2135 d->texrow.newline();
2136 d->texrow.newline();
2137 // output paragraphs
2139 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
2142 docbookParagraphs(paragraphs(), *this, os, runparams);
2148 ErrorList & Buffer::errorList(string const & type) const
2150 static ErrorList emptyErrorList;
2151 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2152 if (I == d->errorLists.end())
2153 return emptyErrorList;
2159 void Buffer::structureChanged() const
2162 gui_->structureChanged();
2166 void Buffer::errors(string const & err) const
2173 void Buffer::message(docstring const & msg) const
2180 void Buffer::setBusy(bool on) const
2187 void Buffer::setReadOnly(bool on) const
2190 d->wa_->setReadOnly(on);
2194 void Buffer::updateTitles() const
2197 d->wa_->updateTitles();
2201 void Buffer::resetAutosaveTimers() const
2204 gui_->resetAutosaveTimers();
2208 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2217 class AutoSaveBuffer : public ForkedProcess {
2220 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2221 : buffer_(buffer), fname_(fname) {}
2223 virtual boost::shared_ptr<ForkedProcess> clone() const
2225 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2230 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2231 from_utf8(fname_.absFilename())));
2232 return run(DontWait);
2236 virtual int generateChild();
2238 Buffer const & buffer_;
2243 #if !defined (HAVE_FORK)
2247 int AutoSaveBuffer::generateChild()
2249 // tmp_ret will be located (usually) in /tmp
2250 // will that be a problem?
2251 pid_t const pid = fork();
2252 // If you want to debug the autosave
2253 // you should set pid to -1, and comment out the fork.
2254 if (pid == 0 || pid == -1) {
2255 // pid = -1 signifies that lyx was unable
2256 // to fork. But we will do the save
2258 bool failed = false;
2260 FileName const tmp_ret = FileName::tempName("lyxauto");
2261 if (!tmp_ret.empty()) {
2262 buffer_.writeFile(tmp_ret);
2263 // assume successful write of tmp_ret
2264 if (!tmp_ret.moveTo(fname_)) {
2266 // most likely couldn't move between
2267 // filesystems unless write of tmp_ret
2268 // failed so remove tmp file (if it
2270 tmp_ret.removeFile();
2277 // failed to write/rename tmp_ret so try writing direct
2278 if (!buffer_.writeFile(fname_)) {
2279 // It is dangerous to do this in the child,
2280 // but safe in the parent, so...
2281 if (pid == -1) // emit message signal.
2282 buffer_.message(_("Autosave failed!"));
2285 if (pid == 0) { // we are the child so...
2295 // Perfect target for a thread...
2296 void Buffer::autoSave() const
2298 if (isBakClean() || isReadonly()) {
2299 // We don't save now, but we'll try again later
2300 resetAutosaveTimers();
2304 // emit message signal.
2305 message(_("Autosaving current document..."));
2307 // create autosave filename
2308 string fname = filePath();
2310 fname += d->filename.onlyFileName();
2313 AutoSaveBuffer autosave(*this, FileName(fname));
2317 resetAutosaveTimers();
2321 void Buffer::resetChildDocuments(bool close_them) const
2323 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2324 if (it->lyxCode() != INCLUDE_CODE)
2326 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2327 InsetCommandParams const & ip = inset.params();
2329 resetParentBuffer(this, ip, close_them);
2332 if (use_gui && masterBuffer() == this)
2333 updateLabels(*this);
2335 // clear references to children in macro tables
2336 d->children_positions.clear();
2337 d->position_to_children.clear();
2341 void Buffer::loadChildDocuments() const
2343 bool parse_error = false;
2345 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2346 if (it->lyxCode() != INCLUDE_CODE)
2348 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2349 InsetCommandParams const & ip = inset.params();
2350 Buffer * child = loadIfNeeded(*this, ip);
2353 parse_error |= !child->errorList("Parse").empty();
2354 child->loadChildDocuments();
2357 if (use_gui && masterBuffer() == this)
2358 updateLabels(*this);
2364 string Buffer::bufferFormat() const
2374 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2375 string & result_file) const
2377 string backend_format;
2378 OutputParams runparams(¶ms().encoding());
2379 runparams.flavor = OutputParams::LATEX;
2380 runparams.linelen = lyxrc.plaintext_linelen;
2381 vector<string> backs = backends();
2382 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2383 // Get shortest path to format
2384 Graph::EdgePath path;
2385 for (vector<string>::const_iterator it = backs.begin();
2386 it != backs.end(); ++it) {
2387 Graph::EdgePath p = theConverters().getPath(*it, format);
2388 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2389 backend_format = *it;
2394 runparams.flavor = theConverters().getFlavor(path);
2396 Alert::error(_("Couldn't export file"),
2397 bformat(_("No information for exporting the format %1$s."),
2398 formats.prettyName(format)));
2402 backend_format = format;
2403 // FIXME: Don't hardcode format names here, but use a flag
2404 if (backend_format == "pdflatex")
2405 runparams.flavor = OutputParams::PDFLATEX;
2408 string filename = latexName(false);
2409 filename = addName(temppath(), filename);
2410 filename = changeExtension(filename,
2411 formats.extension(backend_format));
2414 updateMacroInstances();
2416 // Plain text backend
2417 if (backend_format == "text")
2418 writePlaintextFile(*this, FileName(filename), runparams);
2420 else if (backend_format == "lyx")
2421 writeFile(FileName(filename));
2423 else if (isDocBook()) {
2424 runparams.nice = !put_in_tempdir;
2425 makeDocBookFile(FileName(filename), runparams);
2428 else if (backend_format == format) {
2429 runparams.nice = true;
2430 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2432 } else if (!lyxrc.tex_allows_spaces
2433 && contains(filePath(), ' ')) {
2434 Alert::error(_("File name error"),
2435 _("The directory path to the document cannot contain spaces."));
2438 runparams.nice = false;
2439 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2443 string const error_type = (format == "program")
2444 ? "Build" : bufferFormat();
2445 string const ext = formats.extension(format);
2446 FileName const tmp_result_file(changeExtension(filename, ext));
2447 bool const success = theConverters().convert(this, FileName(filename),
2448 tmp_result_file, FileName(absFileName()), backend_format, format,
2449 errorList(error_type));
2450 // Emit the signal to show the error list.
2451 if (format != backend_format)
2457 result_file = tmp_result_file.absFilename();
2459 result_file = changeExtension(absFileName(), ext);
2460 // We need to copy referenced files (e. g. included graphics
2461 // if format == "dvi") to the result dir.
2462 vector<ExportedFile> const files =
2463 runparams.exportdata->externalFiles(format);
2464 string const dest = onlyPath(result_file);
2465 CopyStatus status = SUCCESS;
2466 for (vector<ExportedFile>::const_iterator it = files.begin();
2467 it != files.end() && status != CANCEL; ++it) {
2469 formats.getFormatFromFile(it->sourceName);
2470 status = copyFile(fmt, it->sourceName,
2471 makeAbsPath(it->exportName, dest),
2472 it->exportName, status == FORCE);
2474 if (status == CANCEL) {
2475 message(_("Document export cancelled."));
2476 } else if (tmp_result_file.exists()) {
2477 // Finally copy the main file
2478 status = copyFile(format, tmp_result_file,
2479 FileName(result_file), result_file,
2481 message(bformat(_("Document exported as %1$s "
2483 formats.prettyName(format),
2484 makeDisplayPath(result_file)));
2486 // This must be a dummy converter like fax (bug 1888)
2487 message(bformat(_("Document exported as %1$s"),
2488 formats.prettyName(format)));
2496 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2499 return doExport(format, put_in_tempdir, result_file);
2503 bool Buffer::preview(string const & format) const
2506 if (!doExport(format, true, result_file))
2508 return formats.view(*this, FileName(result_file), format);
2512 bool Buffer::isExportable(string const & format) const
2514 vector<string> backs = backends();
2515 for (vector<string>::const_iterator it = backs.begin();
2516 it != backs.end(); ++it)
2517 if (theConverters().isReachable(*it, format))
2523 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2525 vector<string> backs = backends();
2526 vector<Format const *> result =
2527 theConverters().getReachable(backs[0], only_viewable, true);
2528 for (vector<string>::const_iterator it = backs.begin() + 1;
2529 it != backs.end(); ++it) {
2530 vector<Format const *> r =
2531 theConverters().getReachable(*it, only_viewable, false);
2532 result.insert(result.end(), r.begin(), r.end());
2538 vector<string> Buffer::backends() const
2541 if (params().getTextClass().isTeXClassAvailable()) {
2542 v.push_back(bufferFormat());
2543 // FIXME: Don't hardcode format names here, but use a flag
2544 if (v.back() == "latex")
2545 v.push_back("pdflatex");
2547 v.push_back("text");
2553 bool Buffer::readFileHelper(FileName const & s)
2555 // File information about normal file
2557 docstring const file = makeDisplayPath(s.absFilename(), 50);
2558 docstring text = bformat(_("The specified document\n%1$s"
2559 "\ncould not be read."), file);
2560 Alert::error(_("Could not read document"), text);
2564 // Check if emergency save file exists and is newer.
2565 FileName const e(s.absFilename() + ".emergency");
2567 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2568 docstring const file = makeDisplayPath(s.absFilename(), 20);
2569 docstring const text =
2570 bformat(_("An emergency save of the document "
2572 "Recover emergency save?"), file);
2573 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2574 _("&Recover"), _("&Load Original"),
2578 // the file is not saved if we load the emergency file.
2588 // Now check if autosave file is newer.
2589 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2591 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2592 docstring const file = makeDisplayPath(s.absFilename(), 20);
2593 docstring const text =
2594 bformat(_("The backup of the document "
2595 "%1$s is newer.\n\nLoad the "
2596 "backup instead?"), file);
2597 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2598 _("&Load backup"), _("Load &original"),
2602 // the file is not saved if we load the autosave file.
2606 // Here we delete the autosave
2617 bool Buffer::loadLyXFile(FileName const & s)
2619 if (s.isReadableFile()) {
2620 if (readFileHelper(s)) {
2621 lyxvc().file_found_hook(s);
2622 if (!s.isWritable())
2627 docstring const file = makeDisplayPath(s.absFilename(), 20);
2628 // Here we probably should run
2629 if (LyXVC::file_not_found_hook(s)) {
2630 docstring const text =
2631 bformat(_("Do you want to retrieve the document"
2632 " %1$s from version control?"), file);
2633 int const ret = Alert::prompt(_("Retrieve from version control?"),
2634 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2637 // How can we know _how_ to do the checkout?
2638 // With the current VC support it has to be,
2639 // a RCS file since CVS do not have special ,v files.
2641 return loadLyXFile(s);
2649 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2651 TeXErrors::Errors::const_iterator cit = terr.begin();
2652 TeXErrors::Errors::const_iterator end = terr.end();
2654 for (; cit != end; ++cit) {
2657 int errorRow = cit->error_in_line;
2658 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2664 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2665 } while (found && id_start == id_end && pos_start == pos_end);
2667 errorList.push_back(ErrorItem(cit->error_desc,
2668 cit->error_text, id_start, pos_start, pos_end));