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 "BaseClassList.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
28 #include "EmbeddedFiles.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "InsetIterator.h"
35 #include "InsetList.h"
37 #include "LaTeXFeatures.h"
41 #include "LyXAction.h"
45 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "output_plaintext.h"
49 #include "paragraph_funcs.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
53 #include "PDFOptions.h"
57 #include "TexStream.h"
59 #include "TextClass.h"
60 #include "TocBackend.h"
62 #include "VCBackend.h"
66 #include "insets/InsetBibitem.h"
67 #include "insets/InsetBibtex.h"
68 #include "insets/InsetInclude.h"
69 #include "insets/InsetText.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathMacroTemplate.h"
73 #include "mathed/MathSupport.h"
75 #include "frontends/alert.h"
76 #include "frontends/Delegates.h"
77 #include "frontends/WorkAreaManager.h"
79 #include "graphics/Previews.h"
81 #include "support/convert.h"
82 #include "support/debug.h"
83 #include "support/ExceptionMessage.h"
84 #include "support/FileName.h"
85 #include "support/FileNameList.h"
86 #include "support/filetools.h"
87 #include "support/ForkedCalls.h"
88 #include "support/gettext.h"
89 #include "support/gzstream.h"
90 #include "support/lstrings.h"
91 #include "support/lyxalgo.h"
92 #include "support/os.h"
93 #include "support/Package.h"
94 #include "support/Path.h"
95 #include "support/textutils.h"
96 #include "support/types.h"
97 #include "support/FileZipListDir.h"
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
111 using namespace lyx::support;
115 namespace Alert = frontend::Alert;
116 namespace os = support::os;
120 int const LYX_FORMAT = 317; // Uwe Stöhr: float placement support for wrap floats
122 typedef map<string, bool> DepClean;
123 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
130 Impl(Buffer & parent, FileName const & file, bool readonly);
143 mutable TexRow texrow;
144 Buffer const * parent_buffer;
146 /// need to regenerate .tex?
150 mutable bool lyx_clean;
152 /// is autosave needed?
153 mutable bool bak_clean;
155 /// is this a unnamed file (New...)?
161 /// name of the file the buffer is associated with.
164 /** Set to true only when the file is fully loaded.
165 * Used to prevent the premature generation of previews
166 * and by the citation inset.
168 bool file_fully_loaded;
170 /// our Text that should be wrapped in an InsetText
174 mutable TocBackend toc_backend;
177 typedef pair<DocIterator, MacroData> ScopeMacro;
178 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
179 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
180 NamePositionScopeMacroMap macros;
183 /// positions of child buffers in the buffer
184 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
185 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
186 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
187 BufferPositionMap children_positions;
188 PositionScopeBufferMap position_to_children;
190 /// Container for all sort of Buffer dependant errors.
191 map<string, ErrorList> errorLists;
193 /// all embedded files of this buffer
194 EmbeddedFileList embedded_files;
196 /// timestamp and checksum used to test if the file has been externally
197 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199 unsigned long checksum_;
202 frontend::WorkAreaManager * wa_;
207 /// A cache for the bibfiles (including bibfiles of loaded child
208 /// documents), needed for appropriate update of natbib labels.
209 mutable EmbeddedFileList bibfilesCache_;
211 mutable RefCache ref_cache_;
214 /// Creates the per buffer temporary directory
215 static FileName createBufferTmpDir()
218 // We are in our own directory. Why bother to mangle name?
219 // In fact I wrote this code to circumvent a problematic behaviour
220 // (bug?) of EMX mkstemp().
221 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
222 convert<string>(count++));
224 if (!tmpfl.createDirectory(0777)) {
225 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
226 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
227 from_utf8(tmpfl.absFilename())));
233 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
234 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
235 read_only(readonly_), filename(file), file_fully_loaded(false),
236 inset(params), toc_backend(&parent), macro_lock(false),
237 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
240 temppath = createBufferTmpDir();
241 inset.setBuffer(parent);
242 inset.setAutoBreakRows(true);
243 lyxvc.setBuffer(&parent);
245 wa_ = new frontend::WorkAreaManager;
249 Buffer::Buffer(string const & file, bool readonly)
250 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
252 LYXERR(Debug::INFO, "Buffer::Buffer()");
254 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
260 LYXERR(Debug::INFO, "Buffer::~Buffer()");
261 // here the buffer should take care that it is
262 // saved properly, before it goes into the void.
264 // GuiView already destroyed
267 Buffer const * master = masterBuffer();
268 if (master != this && use_gui) {
269 // We are closing buf which was a child document so we
270 // must update the labels and section numbering of its master
272 updateLabels(*master);
273 master->updateMacros();
276 resetChildDocuments(false);
278 if (!d->temppath.destroyDirectory()) {
279 Alert::warning(_("Could not remove temporary directory"),
280 bformat(_("Could not remove the temporary directory %1$s"),
281 from_utf8(d->temppath.absFilename())));
284 // Remove any previewed LaTeX snippets associated with this buffer.
285 graphics::Previews::get().removeLoader(*this);
291 void Buffer::changed() const
298 frontend::WorkAreaManager & Buffer::workAreaManager() const
300 BOOST_ASSERT(d->wa_);
305 Text & Buffer::text() const
307 return const_cast<Text &>(d->inset.text_);
311 Inset & Buffer::inset() const
313 return const_cast<InsetText &>(d->inset);
317 BufferParams & Buffer::params()
323 BufferParams const & Buffer::params() const
329 ParagraphList & Buffer::paragraphs()
331 return text().paragraphs();
335 ParagraphList const & Buffer::paragraphs() const
337 return text().paragraphs();
341 LyXVC & Buffer::lyxvc()
347 LyXVC const & Buffer::lyxvc() const
353 string const Buffer::temppath() const
355 return d->temppath.absFilename();
359 TexRow const & Buffer::texrow() const
365 TocBackend & Buffer::tocBackend() const
367 return d->toc_backend;
371 EmbeddedFileList & Buffer::embeddedFiles()
373 return d->embedded_files;
377 EmbeddedFileList const & Buffer::embeddedFiles() const
379 return d->embedded_files;
383 bool Buffer::embedded() const
385 return params().embedded;
389 Undo & Buffer::undo()
395 string Buffer::latexName(bool const no_path) const
397 FileName latex_name = makeLatexName(d->filename);
398 return no_path ? latex_name.onlyFileName()
399 : latex_name.absFilename();
403 string Buffer::logName(LogType * type) const
405 string const filename = latexName(false);
407 if (filename.empty()) {
413 string const path = temppath();
415 FileName const fname(addName(temppath(),
416 onlyFilename(changeExtension(filename,
418 FileName const bname(
419 addName(path, onlyFilename(
420 changeExtension(filename,
421 formats.extension("literate") + ".out"))));
423 // If no Latex log or Build log is newer, show Build log
425 if (bname.exists() &&
426 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
427 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
430 return bname.absFilename();
432 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
435 return fname.absFilename();
439 void Buffer::setReadonly(bool const flag)
441 if (d->read_only != flag) {
448 void Buffer::setFileName(string const & newfile)
450 d->filename = makeAbsPath(newfile);
451 setReadonly(d->filename.isReadOnly());
456 int Buffer::readHeader(Lexer & lex)
458 int unknown_tokens = 0;
460 int begin_header_line = -1;
462 // Initialize parameters that may be/go lacking in header:
463 params().branchlist().clear();
464 params().preamble.erase();
465 params().options.erase();
466 params().float_placement.erase();
467 params().paperwidth.erase();
468 params().paperheight.erase();
469 params().leftmargin.erase();
470 params().rightmargin.erase();
471 params().topmargin.erase();
472 params().bottommargin.erase();
473 params().headheight.erase();
474 params().headsep.erase();
475 params().footskip.erase();
476 params().columnsep.erase();
477 params().listings_params.clear();
478 params().clearLayoutModules();
479 params().pdfoptions().clear();
481 for (int i = 0; i < 4; ++i) {
482 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
483 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
486 ErrorList & errorList = d->errorLists["Parse"];
490 string const token = lex.getString();
495 if (token == "\\end_header")
499 if (token == "\\begin_header") {
500 begin_header_line = line;
504 LYXERR(Debug::PARSER, "Handling document header token: `"
507 string unknown = params().readToken(lex, token, d->filename.onlyPath());
508 if (!unknown.empty()) {
509 if (unknown[0] != '\\' && token == "\\textclass") {
510 Alert::warning(_("Unknown document class"),
511 bformat(_("Using the default document class, because the "
512 "class %1$s is unknown."), from_utf8(unknown)));
515 docstring const s = bformat(_("Unknown token: "
519 errorList.push_back(ErrorItem(_("Document header error"),
524 if (begin_header_line) {
525 docstring const s = _("\\begin_header is missing");
526 errorList.push_back(ErrorItem(_("Document header error"),
530 params().makeDocumentClass();
532 return unknown_tokens;
537 // changed to be public and have one parameter
538 // Returns false if "\end_document" is not read (Asger)
539 bool Buffer::readDocument(Lexer & lex)
541 ErrorList & errorList = d->errorLists["Parse"];
545 string const token = lex.getString();
546 if (token != "\\begin_document") {
547 docstring const s = _("\\begin_document is missing");
548 errorList.push_back(ErrorItem(_("Document header error"),
552 // we are reading in a brand new document
553 BOOST_ASSERT(paragraphs().empty());
557 if (params().outputChanges) {
558 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
559 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
560 LaTeXFeatures::isAvailable("xcolor");
562 if (!dvipost && !xcolorsoul) {
563 Alert::warning(_("Changes not shown in LaTeX output"),
564 _("Changes will not be highlighted in LaTeX output, "
565 "because neither dvipost nor xcolor/soul are installed.\n"
566 "Please install these packages or redefine "
567 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
568 } else if (!xcolorsoul) {
569 Alert::warning(_("Changes not shown in LaTeX output"),
570 _("Changes will not be highlighted in LaTeX output "
571 "when using pdflatex, because xcolor and soul are not installed.\n"
572 "Please install both packages or redefine "
573 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578 bool const res = text().read(*this, lex, errorList, &(d->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 // if in bundled format, save checksum of the compressed file, not content.lyx
682 saveCheckSum(filename);
683 params().embedded = true;
687 // The embedded lyx file can also be compressed, for backward compatibility
688 format = fname.guessFormatFromContents();
689 if (format == "gzip" || format == "zip" || format == "compress")
690 params().compressed = true;
692 // remove dummy empty par
693 paragraphs().clear();
696 if (readFile(lex, fname) != success)
699 // FIXME: there are insets that don't set the buffer reference
700 // (InsetMathHull at least) so wet explicitely set the buffer in all insets.
701 InsetIterator it = inset_iterator_begin(inset());
702 InsetIterator end = inset_iterator_end(inset());
703 for (; it != end; ++it)
704 it->setBuffer(*this);
710 bool Buffer::isFullyLoaded() const
712 return d->file_fully_loaded;
716 void Buffer::setFullyLoaded(bool value)
718 d->file_fully_loaded = value;
722 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
725 BOOST_ASSERT(!filename.empty());
728 Alert::error(_("Document could not be read"),
729 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
734 string const token = lex.getString();
737 Alert::error(_("Document could not be read"),
738 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
742 // the first token _must_ be...
743 if (token != "\\lyxformat") {
744 lyxerr << "Token: " << token << endl;
746 Alert::error(_("Document format failure"),
747 bformat(_("%1$s is not a LyX document."),
748 from_utf8(filename.absFilename())));
753 string tmp_format = lex.getString();
754 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
755 // if present remove ".," from string.
756 string::size_type dot = tmp_format.find_first_of(".,");
757 //lyxerr << " dot found at " << dot << endl;
758 if (dot != string::npos)
759 tmp_format.erase(dot, 1);
760 int const file_format = convert<int>(tmp_format);
761 //lyxerr << "format: " << file_format << endl;
763 // save timestamp and checksum of the original disk file, making sure
764 // to not overwrite them with those of the file created in the tempdir
765 // when it has to be converted to the current format.
767 // Save the timestamp and checksum of disk file. If filename is an
768 // emergency file, save the timestamp and checksum of the original lyx file
769 // because isExternallyModified will check for this file. (BUG4193)
770 string diskfile = filename.absFilename();
771 if (suffixIs(diskfile, ".emergency"))
772 diskfile = diskfile.substr(0, diskfile.size() - 10);
773 saveCheckSum(FileName(diskfile));
776 if (file_format != LYX_FORMAT) {
779 // lyx2lyx would fail
782 FileName const tmpfile = FileName::tempName();
783 if (tmpfile.empty()) {
784 Alert::error(_("Conversion failed"),
785 bformat(_("%1$s is from a different"
786 " version of LyX, but a temporary"
787 " file for converting it could"
789 from_utf8(filename.absFilename())));
792 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
793 if (lyx2lyx.empty()) {
794 Alert::error(_("Conversion script not found"),
795 bformat(_("%1$s is from a different"
796 " version of LyX, but the"
797 " conversion script lyx2lyx"
798 " could not be found."),
799 from_utf8(filename.absFilename())));
802 ostringstream command;
803 command << os::python()
804 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
805 << " -t " << convert<string>(LYX_FORMAT)
806 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
807 << ' ' << quoteName(filename.toFilesystemEncoding());
808 string const command_str = command.str();
810 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
812 cmd_ret const ret = runCommand(command_str);
813 if (ret.first != 0) {
814 Alert::error(_("Conversion script failed"),
815 bformat(_("%1$s is from a different version"
816 " of LyX, but the lyx2lyx script"
817 " failed to convert it."),
818 from_utf8(filename.absFilename())));
821 bool const ret = readFile(tmpfile);
822 // Do stuff with tmpfile name and buffer name here.
823 return ret ? success : failure;
828 if (readDocument(lex)) {
829 Alert::error(_("Document format failure"),
830 bformat(_("%1$s ended unexpectedly, which means"
831 " that it is probably corrupted."),
832 from_utf8(filename.absFilename())));
835 d->file_fully_loaded = true;
840 // Should probably be moved to somewhere else: BufferView? LyXView?
841 bool Buffer::save() const
843 // We don't need autosaves in the immediate future. (Asger)
844 resetAutosaveTimers();
846 string const encodedFilename = d->filename.toFilesystemEncoding();
849 bool madeBackup = false;
851 // make a backup if the file already exists
852 if (lyxrc.make_backup && fileName().exists()) {
853 backupName = FileName(absFileName() + '~');
854 if (!lyxrc.backupdir_path.empty()) {
855 string const mangledName =
856 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
857 backupName = FileName(addName(lyxrc.backupdir_path,
860 if (fileName().copyTo(backupName)) {
863 Alert::error(_("Backup failure"),
864 bformat(_("Cannot create backup file %1$s.\n"
865 "Please check whether the directory exists and is writeable."),
866 from_utf8(backupName.absFilename())));
867 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
871 // ask if the disk file has been externally modified (use checksum method)
872 if (fileName().exists() && isExternallyModified(checksum_method)) {
873 docstring const file = makeDisplayPath(absFileName(), 20);
874 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
875 "you want to overwrite this file?"), file);
876 int const ret = Alert::prompt(_("Overwrite modified file?"),
877 text, 1, 1, _("&Overwrite"), _("&Cancel"));
882 if (writeFile(d->filename)) {
886 // Saving failed, so backup is not backup
888 backupName.moveTo(d->filename);
894 bool Buffer::writeFile(FileName const & fname) const
896 if (d->read_only && fname == d->filename)
902 if (params().embedded)
903 // first write the .lyx file to the temporary directory
904 content = FileName(addName(temppath(), "content.lyx"));
908 docstring const str = bformat(_("Saving document %1$s..."),
909 makeDisplayPath(content.absFilename()));
912 if (params().compressed) {
913 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
914 retval = ofs && write(ofs);
916 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
917 retval = ofs && write(ofs);
921 message(str + _(" could not write file!."));
925 removeAutosaveFile(d->filename.absFilename());
927 if (params().embedded) {
928 message(str + _(" writing embedded files!."));
929 // if embedding is enabled, write file.lyx and all the embedded files
930 // to the zip file fname.
931 if (!d->embedded_files.writeFile(fname, *this)) {
932 message(str + _(" could not write embedded files!."));
936 saveCheckSum(d->filename);
937 message(str + _(" done."));
943 bool Buffer::write(ostream & ofs) const
946 // Use the standard "C" locale for file output.
947 ofs.imbue(locale::classic());
950 // The top of the file should not be written by params().
952 // write out a comment in the top of the file
953 ofs << "#LyX " << lyx_version
954 << " created this file. For more info see http://www.lyx.org/\n"
955 << "\\lyxformat " << LYX_FORMAT << "\n"
956 << "\\begin_document\n";
958 /// For each author, set 'used' to true if there is a change
959 /// by this author in the document; otherwise set it to 'false'.
960 AuthorList::Authors::const_iterator a_it = params().authors().begin();
961 AuthorList::Authors::const_iterator a_end = params().authors().end();
962 for (; a_it != a_end; ++a_it)
963 a_it->second.setUsed(false);
965 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
966 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
967 for ( ; it != end; ++it)
968 it->checkAuthors(params().authors());
970 // now write out the buffer parameters.
971 ofs << "\\begin_header\n";
972 params().writeFile(ofs);
973 ofs << "\\end_header\n";
976 ofs << "\n\\begin_body\n";
977 text().write(*this, ofs);
978 ofs << "\n\\end_body\n";
980 // Write marker that shows file is complete
981 ofs << "\\end_document" << endl;
983 // Shouldn't really be needed....
986 // how to check if close went ok?
987 // Following is an attempt... (BE 20001011)
989 // good() returns false if any error occured, including some
991 // bad() returns true if something bad happened in the buffer,
992 // which should include file system full errors.
997 lyxerr << "File was not closed properly." << endl;
1004 bool Buffer::makeLaTeXFile(FileName const & fname,
1005 string const & original_path,
1006 OutputParams const & runparams,
1007 bool output_preamble, bool output_body) const
1009 string const encoding = runparams.encoding->iconvName();
1010 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1013 try { ofs.reset(encoding); }
1014 catch (iconv_codecvt_facet_exception & e) {
1015 lyxerr << "Caught iconv exception: " << e.what() << endl;
1016 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1017 "verify that the support software for your encoding (%1$s) is "
1018 "properly installed"), from_ascii(encoding)));
1021 if (!openFileWrite(ofs, fname))
1024 //TexStream ts(ofs.rdbuf(), &texrow());
1025 ErrorList & errorList = d->errorLists["Export"];
1027 bool failed_export = false;
1030 writeLaTeXSource(ofs, original_path,
1031 runparams, output_preamble, output_body);
1033 catch (EncodingException & e) {
1034 odocstringstream ods;
1035 ods.put(e.failed_char);
1037 oss << "0x" << hex << e.failed_char << dec;
1038 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1039 " (code point %2$s)"),
1040 ods.str(), from_utf8(oss.str()));
1041 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1042 "representable in the chosen encoding.\n"
1043 "Changing the document encoding to utf8 could help."),
1044 e.par_id, e.pos, e.pos + 1));
1045 failed_export = true;
1047 catch (iconv_codecvt_facet_exception & e) {
1048 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1049 _(e.what()), -1, 0, 0));
1050 failed_export = true;
1052 catch (exception const & e) {
1053 errorList.push_back(ErrorItem(_("conversion failed"),
1054 _(e.what()), -1, 0, 0));
1055 failed_export = true;
1058 lyxerr << "Caught some really weird exception..." << endl;
1059 LyX::cref().exit(1);
1064 failed_export = true;
1065 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1069 return !failed_export;
1073 void Buffer::writeLaTeXSource(odocstream & os,
1074 string const & original_path,
1075 OutputParams const & runparams_in,
1076 bool const output_preamble, bool const output_body) const
1078 OutputParams runparams = runparams_in;
1080 // validate the buffer.
1081 LYXERR(Debug::LATEX, " Validating buffer...");
1082 LaTeXFeatures features(*this, params(), runparams);
1084 LYXERR(Debug::LATEX, " Buffer validation done.");
1086 // The starting paragraph of the coming rows is the
1087 // first paragraph of the document. (Asger)
1088 if (output_preamble && runparams.nice) {
1089 os << "%% LyX " << lyx_version << " created this file. "
1090 "For more info, see http://www.lyx.org/.\n"
1091 "%% Do not edit unless you really know what "
1093 d->texrow.newline();
1094 d->texrow.newline();
1096 LYXERR(Debug::INFO, "lyx document header finished");
1097 // There are a few differences between nice LaTeX and usual files:
1098 // usual is \batchmode and has a
1099 // special input@path to allow the including of figures
1100 // with either \input or \includegraphics (what figinsets do).
1101 // input@path is set when the actual parameter
1102 // original_path is set. This is done for usual tex-file, but not
1103 // for nice-latex-file. (Matthias 250696)
1104 // Note that input@path is only needed for something the user does
1105 // in the preamble, included .tex files or ERT, files included by
1106 // LyX work without it.
1107 if (output_preamble) {
1108 if (!runparams.nice) {
1109 // code for usual, NOT nice-latex-file
1110 os << "\\batchmode\n"; // changed
1111 // from \nonstopmode
1112 d->texrow.newline();
1114 if (!original_path.empty()) {
1116 // We don't know the encoding of inputpath
1117 docstring const inputpath = from_utf8(latex_path(original_path));
1118 os << "\\makeatletter\n"
1119 << "\\def\\input@path{{"
1120 << inputpath << "/}}\n"
1121 << "\\makeatother\n";
1122 d->texrow.newline();
1123 d->texrow.newline();
1124 d->texrow.newline();
1127 // Write the preamble
1128 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1134 os << "\\begin{document}\n";
1135 d->texrow.newline();
1136 } // output_preamble
1138 d->texrow.start(paragraphs().begin()->id(), 0);
1140 LYXERR(Debug::INFO, "preamble finished, now the body.");
1142 // load children, if not already done.
1143 // This includes an updateMacro() call.
1144 // Don't move this behind the parent_buffer=0 code below,
1145 // because then the macros will not get the right "redefinition"
1146 // flag as they don't see the parent macros which are output before.
1147 loadChildDocuments();
1149 // fold macros if possible, still with parent buffer as the
1150 // macros will be put in the prefix anyway.
1151 updateMacroInstances();
1153 // if we are doing a real file with body, even if this is the
1154 // child of some other buffer, let's cut the link here.
1155 // This happens for example if only a child document is printed.
1156 Buffer const * save_parent = 0;
1157 if (output_preamble) {
1158 // output the macros visible for this buffer
1159 writeParentMacros(os);
1161 save_parent = d->parent_buffer;
1162 d->parent_buffer = 0;
1166 latexParagraphs(*this, text(), os, d->texrow, runparams);
1168 // Restore the parenthood if needed
1169 if (output_preamble) {
1170 d->parent_buffer = save_parent;
1172 // restore macros with correct parent buffer (especially
1173 // important for the redefinition flag which depends on the
1178 // add this just in case after all the paragraphs
1180 d->texrow.newline();
1182 if (output_preamble) {
1183 os << "\\end{document}\n";
1184 d->texrow.newline();
1185 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1187 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1189 runparams_in.encoding = runparams.encoding;
1191 // Just to be sure. (Asger)
1192 d->texrow.newline();
1194 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1195 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1199 bool Buffer::isLatex() const
1201 return params().documentClass().outputType() == LATEX;
1205 bool Buffer::isLiterate() const
1207 return params().documentClass().outputType() == LITERATE;
1211 bool Buffer::isDocBook() const
1213 return params().documentClass().outputType() == DOCBOOK;
1217 void Buffer::makeDocBookFile(FileName const & fname,
1218 OutputParams const & runparams,
1219 bool const body_only) const
1221 LYXERR(Debug::LATEX, "makeDocBookFile...");
1224 if (!openFileWrite(ofs, fname))
1227 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1231 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1235 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1236 OutputParams const & runparams,
1237 bool const only_body) const
1239 LaTeXFeatures features(*this, params(), runparams);
1244 DocumentClass const & tclass = params().documentClass();
1245 string const top_element = tclass.latexname();
1248 if (runparams.flavor == OutputParams::XML)
1249 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1252 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1255 if (! tclass.class_header().empty())
1256 os << from_ascii(tclass.class_header());
1257 else if (runparams.flavor == OutputParams::XML)
1258 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1259 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1261 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1263 docstring preamble = from_utf8(params().preamble);
1264 if (runparams.flavor != OutputParams::XML ) {
1265 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1266 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1267 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1268 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1271 string const name = runparams.nice
1272 ? changeExtension(absFileName(), ".sgml") : fname;
1273 preamble += features.getIncludedFiles(name);
1274 preamble += features.getLyXSGMLEntities();
1276 if (!preamble.empty()) {
1277 os << "\n [ " << preamble << " ]";
1282 string top = top_element;
1284 if (runparams.flavor == OutputParams::XML)
1285 top += params().language->code();
1287 top += params().language->code().substr(0,2);
1290 if (!params().options.empty()) {
1292 top += params().options;
1295 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1296 << " file was created by LyX " << lyx_version
1297 << "\n See http://www.lyx.org/ for more information -->\n";
1299 params().documentClass().counters().reset();
1301 loadChildDocuments();
1303 sgml::openTag(os, top);
1305 docbookParagraphs(paragraphs(), *this, os, runparams);
1306 sgml::closeTag(os, top_element);
1310 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1311 // Other flags: -wall -v0 -x
1312 int Buffer::runChktex()
1316 // get LaTeX-Filename
1317 FileName const path(temppath());
1318 string const name = addName(path.absFilename(), latexName());
1319 string const org_path = filePath();
1321 PathChanger p(path); // path to LaTeX file
1322 message(_("Running chktex..."));
1324 // Generate the LaTeX file if neccessary
1325 OutputParams runparams(¶ms().encoding());
1326 runparams.flavor = OutputParams::LATEX;
1327 runparams.nice = false;
1328 makeLaTeXFile(FileName(name), org_path, runparams);
1331 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1332 int const res = chktex.run(terr); // run chktex
1335 Alert::error(_("chktex failure"),
1336 _("Could not run chktex successfully."));
1337 } else if (res > 0) {
1338 ErrorList & errlist = d->errorLists["ChkTeX"];
1340 bufferErrors(terr, errlist);
1351 void Buffer::validate(LaTeXFeatures & features) const
1353 params().validate(features);
1355 loadChildDocuments();
1357 for_each(paragraphs().begin(), paragraphs().end(),
1358 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1360 if (lyxerr.debugging(Debug::LATEX)) {
1361 features.showStruct();
1366 void Buffer::getLabelList(vector<docstring> & list) const
1368 /// if this is a child document and the parent is already loaded
1369 /// Use the parent's list instead [ale990407]
1370 Buffer const * tmp = masterBuffer();
1372 lyxerr << "masterBuffer() failed!" << endl;
1376 tmp->getLabelList(list);
1380 loadChildDocuments();
1382 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1383 it.nextInset()->getLabelList(list);
1387 void Buffer::updateBibfilesCache() const
1389 // if this is a child document and the parent is already loaded
1390 // update the parent's cache instead
1391 Buffer const * tmp = masterBuffer();
1394 tmp->updateBibfilesCache();
1398 d->bibfilesCache_.clear();
1399 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1400 if (it->lyxCode() == BIBTEX_CODE) {
1401 InsetBibtex const & inset =
1402 static_cast<InsetBibtex const &>(*it);
1403 EmbeddedFileList const bibfiles = inset.embeddedFiles();
1404 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1407 } else if (it->lyxCode() == INCLUDE_CODE) {
1408 InsetInclude & inset =
1409 static_cast<InsetInclude &>(*it);
1410 inset.updateBibfilesCache();
1411 EmbeddedFileList const & bibfiles =
1412 inset.getBibfilesCache(*this);
1413 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1421 EmbeddedFileList const & Buffer::getBibfilesCache() const
1423 // if this is a child document and the parent is already loaded
1424 // use the parent's cache instead
1425 Buffer const * tmp = masterBuffer();
1428 return tmp->getBibfilesCache();
1430 // We update the cache when first used instead of at loading time.
1431 if (d->bibfilesCache_.empty())
1432 const_cast<Buffer *>(this)->updateBibfilesCache();
1434 return d->bibfilesCache_;
1438 bool Buffer::isDepClean(string const & name) const
1440 DepClean::const_iterator const it = d->dep_clean.find(name);
1441 if (it == d->dep_clean.end())
1447 void Buffer::markDepClean(string const & name)
1449 d->dep_clean[name] = true;
1453 bool Buffer::dispatch(string const & command, bool * result)
1455 return dispatch(lyxaction.lookupFunc(command), result);
1459 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1461 bool dispatched = true;
1463 switch (func.action) {
1464 case LFUN_BUFFER_EXPORT: {
1465 bool const tmp = doExport(to_utf8(func.argument()), false);
1478 void Buffer::changeLanguage(Language const * from, Language const * to)
1483 for_each(par_iterator_begin(),
1485 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1489 bool Buffer::isMultiLingual() const
1491 ParConstIterator end = par_iterator_end();
1492 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1493 if (it->isMultiLingual(params()))
1500 DocIterator Buffer::getParFromID(int const id) const
1503 // John says this is called with id == -1 from undo
1504 lyxerr << "getParFromID(), id: " << id << endl;
1505 return doc_iterator_end(inset());
1508 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1509 if (it.paragraph().id() == id)
1512 return doc_iterator_end(inset());
1516 bool Buffer::hasParWithID(int const id) const
1518 return !getParFromID(id).atEnd();
1522 ParIterator Buffer::par_iterator_begin()
1524 return ParIterator(doc_iterator_begin(inset()));
1528 ParIterator Buffer::par_iterator_end()
1530 return ParIterator(doc_iterator_end(inset()));
1534 ParConstIterator Buffer::par_iterator_begin() const
1536 return lyx::par_const_iterator_begin(inset());
1540 ParConstIterator Buffer::par_iterator_end() const
1542 return lyx::par_const_iterator_end(inset());
1546 Language const * Buffer::language() const
1548 return params().language;
1552 docstring const Buffer::B_(string const & l10n) const
1554 return params().B_(l10n);
1558 bool Buffer::isClean() const
1560 return d->lyx_clean;
1564 bool Buffer::isBakClean() const
1566 return d->bak_clean;
1570 bool Buffer::isExternallyModified(CheckMethod method) const
1572 BOOST_ASSERT(d->filename.exists());
1573 // if method == timestamp, check timestamp before checksum
1574 return (method == checksum_method
1575 || d->timestamp_ != d->filename.lastModified())
1576 && d->checksum_ != d->filename.checksum();
1580 void Buffer::saveCheckSum(FileName const & file) const
1582 if (file.exists()) {
1583 d->timestamp_ = file.lastModified();
1584 d->checksum_ = file.checksum();
1586 // in the case of save to a new file.
1593 void Buffer::markClean() const
1595 if (!d->lyx_clean) {
1596 d->lyx_clean = true;
1599 // if the .lyx file has been saved, we don't need an
1601 d->bak_clean = true;
1605 void Buffer::markBakClean() const
1607 d->bak_clean = true;
1611 void Buffer::setUnnamed(bool flag)
1617 bool Buffer::isUnnamed() const
1623 // FIXME: this function should be moved to buffer_pimpl.C
1624 void Buffer::markDirty()
1627 d->lyx_clean = false;
1630 d->bak_clean = false;
1632 DepClean::iterator it = d->dep_clean.begin();
1633 DepClean::const_iterator const end = d->dep_clean.end();
1635 for (; it != end; ++it)
1640 FileName Buffer::fileName() const
1646 string Buffer::absFileName() const
1648 return d->filename.absFilename();
1652 string Buffer::filePath() const
1654 return d->filename.onlyPath().absFilename() + "/";
1658 bool Buffer::isReadonly() const
1660 return d->read_only;
1664 void Buffer::setParent(Buffer const * buffer)
1666 // Avoids recursive include.
1667 d->parent_buffer = buffer == this ? 0 : buffer;
1672 Buffer const * Buffer::parent()
1674 return d->parent_buffer;
1678 Buffer const * Buffer::masterBuffer() const
1680 if (!d->parent_buffer)
1683 return d->parent_buffer->masterBuffer();
1687 template<typename M>
1688 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1693 typename M::iterator it = m.lower_bound(x);
1694 if (it == m.begin())
1702 MacroData const * Buffer::getBufferMacro(docstring const & name,
1703 DocIterator const & pos) const
1705 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1707 // if paragraphs have no macro context set, pos will be empty
1711 // we haven't found anything yet
1712 DocIterator bestPos = par_iterator_begin();
1713 MacroData const * bestData = 0;
1715 // find macro definitions for name
1716 Impl::NamePositionScopeMacroMap::iterator nameIt
1717 = d->macros.find(name);
1718 if (nameIt != d->macros.end()) {
1719 // find last definition in front of pos or at pos itself
1720 Impl::PositionScopeMacroMap::const_iterator it
1721 = greatest_below(nameIt->second, pos);
1722 if (it != nameIt->second.end()) {
1724 // scope ends behind pos?
1725 if (pos < it->second.first) {
1726 // Looks good, remember this. If there
1727 // is no external macro behind this,
1728 // we found the right one already.
1729 bestPos = it->first;
1730 bestData = &it->second.second;
1734 // try previous macro if there is one
1735 if (it == nameIt->second.begin())
1742 // find macros in included files
1743 Impl::PositionScopeBufferMap::const_iterator it
1744 = greatest_below(d->position_to_children, pos);
1745 if (it == d->position_to_children.end())
1746 // no children before
1750 // do we know something better (i.e. later) already?
1751 if (it->first < bestPos )
1754 // scope ends behind pos?
1755 if (pos < it->second.first) {
1756 // look for macro in external file
1757 d->macro_lock = true;
1758 MacroData const * data
1759 = it->second.second->getMacro(name, false);
1760 d->macro_lock = false;
1762 bestPos = it->first;
1768 // try previous file if there is one
1769 if (it == d->position_to_children.begin())
1774 // return the best macro we have found
1779 MacroData const * Buffer::getMacro(docstring const & name,
1780 DocIterator const & pos, bool global) const
1785 // query buffer macros
1786 MacroData const * data = getBufferMacro(name, pos);
1790 // If there is a master buffer, query that
1791 if (d->parent_buffer) {
1792 d->macro_lock = true;
1793 MacroData const * macro
1794 = d->parent_buffer->getMacro(name, *this, false);
1795 d->macro_lock = false;
1801 data = MacroTable::globalMacros().get(name);
1810 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1812 // set scope end behind the last paragraph
1813 DocIterator scope = par_iterator_begin();
1814 scope.pit() = scope.lastpit() + 1;
1816 return getMacro(name, scope, global);
1820 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1822 // look where the child buffer is included first
1823 Impl::BufferPositionMap::iterator it
1824 = d->children_positions.find(&child);
1825 if (it == d->children_positions.end())
1828 // check for macros at the inclusion position
1829 return getMacro(name, it->second, global);
1833 void Buffer::updateEnvironmentMacros(DocIterator & it,
1835 DocIterator & scope) const
1837 Paragraph & par = it.paragraph();
1839 = par.params().depth();
1840 Length const & leftIndent
1841 = par.params().leftIndent();
1843 // look for macros in each paragraph
1844 while (it.pit() <= lastpit) {
1845 Paragraph & par = it.paragraph();
1848 if ((par.params().depth() > depth
1849 || par.params().leftIndent() != leftIndent)
1850 && par.layout()->isEnvironment()) {
1851 updateBlockMacros(it, scope);
1855 // iterate over the insets of the current paragraph
1856 InsetList const & insets = par.insetList();
1857 InsetList::const_iterator iit = insets.begin();
1858 InsetList::const_iterator end = insets.end();
1859 for (; iit != end; ++iit) {
1860 it.pos() = iit->pos;
1862 // is it a nested text inset?
1863 if (iit->inset->asInsetText()) {
1864 // Inset needs its own scope?
1865 InsetText const * itext
1866 = iit->inset->asInsetText();
1867 bool newScope = itext->isMacroScope();
1869 // scope which ends just behind the inset
1870 DocIterator insetScope = it;
1873 // collect macros in inset
1874 it.push_back(CursorSlice(*iit->inset));
1875 updateInsetMacros(it, newScope ? insetScope : scope);
1880 // is it an external file?
1881 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1882 // get buffer of external file
1883 InsetCommand const & inset
1884 = static_cast<InsetCommand const &>(*iit->inset);
1885 InsetCommandParams const & ip = inset.params();
1886 d->macro_lock = true;
1887 Buffer * child = loadIfNeeded(*this, ip);
1888 d->macro_lock = false;
1892 // register its position, but only when it is
1893 // included first in the buffer
1894 if (d->children_positions.find(child)
1895 == d->children_positions.end())
1896 d->children_positions[child] = it;
1898 // register child with its scope
1899 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1904 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1908 MathMacroTemplate & macroTemplate
1909 = static_cast<MathMacroTemplate &>(*iit->inset);
1910 MacroContext mc(*this, it);
1911 macroTemplate.updateToContext(mc);
1914 bool valid = macroTemplate.validMacro();
1915 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1916 // then the BufferView's cursor will be invalid in
1917 // some cases which leads to crashes.
1922 d->macros[macroTemplate.name()][it]
1923 = Impl::ScopeMacro(scope, MacroData(*this, it));
1933 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1935 Paragraph & par = it.paragraph();
1937 // set scope for macros in this paragraph:
1938 // * either the "old" outer scope
1939 // * or the scope ending after the environment
1940 if (par.layout()->isEnvironment()) {
1941 // find end of environment block,
1942 DocIterator envEnd = it;
1943 pit_type n = it.lastpit() + 1;
1944 depth_type depth = par.params().depth();
1945 Length const & length = par.params().leftIndent();
1946 // looping through the paragraph, basically until
1947 // the layout changes or the depth gets smaller.
1948 // (the logic of output_latex.cpp's TeXEnvironment)
1951 if (envEnd.pit() == n)
1953 } while (par.layout() == envEnd.paragraph().layout()
1954 || depth < envEnd.paragraph().params().depth()
1955 || length != envEnd.paragraph().params().leftIndent());
1957 // collect macros from environment block
1958 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1960 // collect macros from paragraph
1961 updateEnvironmentMacros(it, it.pit(), scope);
1966 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1968 // look for macros in each paragraph
1969 pit_type n = it.lastpit() + 1;
1970 while (it.pit() < n)
1971 updateBlockMacros(it, scope);
1975 void Buffer::updateMacros() const
1980 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1982 // start with empty table
1984 d->children_positions.clear();
1985 d->position_to_children.clear();
1987 // Iterate over buffer, starting with first paragraph
1988 // The scope must be bigger than any lookup DocIterator
1989 // later. For the global lookup, lastpit+1 is used, hence
1990 // we use lastpit+2 here.
1991 DocIterator it = par_iterator_begin();
1992 DocIterator outerScope = it;
1993 outerScope.pit() = outerScope.lastpit() + 2;
1994 updateInsetMacros(it, outerScope);
1998 void Buffer::updateMacroInstances() const
2000 LYXERR(Debug::MACROS, "updateMacroInstances for "
2001 << d->filename.onlyFileName());
2002 DocIterator it = doc_iterator_begin(inset());
2003 DocIterator end = doc_iterator_end(inset());
2004 for (; it != end; it.forwardPos()) {
2005 // look for MathData cells in InsetMathNest insets
2006 Inset * inset = it.nextInset();
2010 InsetMath * minset = inset->asInsetMath();
2014 // update macro in all cells of the InsetMathNest
2015 DocIterator::idx_type n = minset->nargs();
2016 MacroContext mc = MacroContext(*this, it);
2017 for (DocIterator::idx_type i = 0; i < n; ++i) {
2018 MathData & data = minset->cell(i);
2019 data.updateMacros(0, mc);
2025 void Buffer::listMacroNames(MacroNameSet & macros) const
2030 d->macro_lock = true;
2032 // loop over macro names
2033 Impl::NamePositionScopeMacroMap::iterator nameIt
2034 = d->macros.begin();
2035 Impl::NamePositionScopeMacroMap::iterator nameEnd
2037 for (; nameIt != nameEnd; ++nameIt)
2038 macros.insert(nameIt->first);
2040 // loop over children
2041 Impl::BufferPositionMap::iterator it
2042 = d->children_positions.begin();
2043 Impl::BufferPositionMap::iterator end
2044 = d->children_positions.end();
2045 for (; it != end; ++it)
2046 it->first->listMacroNames(macros);
2049 if (d->parent_buffer)
2050 d->parent_buffer->listMacroNames(macros);
2052 d->macro_lock = false;
2056 void Buffer::writeParentMacros(odocstream & os) const
2058 if (!d->parent_buffer)
2061 // collect macro names
2063 d->parent_buffer->listMacroNames(names);
2065 // resolve and output them
2066 MacroNameSet::iterator it = names.begin();
2067 MacroNameSet::iterator end = names.end();
2068 for (; it != end; ++it) {
2070 MacroData const * data =
2071 d->parent_buffer->getMacro(*it, *this, false);
2073 data->write(os, true);
2078 Buffer::References & Buffer::references(docstring const & label)
2080 if (d->parent_buffer)
2081 return const_cast<Buffer *>(masterBuffer())->references(label);
2083 RefCache::iterator it = d->ref_cache_.find(label);
2084 if (it != d->ref_cache_.end())
2085 return it->second.second;
2087 static InsetLabel const * dummy_il = 0;
2088 static References const dummy_refs;
2089 it = d->ref_cache_.insert(make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2090 return it->second.second;
2094 Buffer::References const & Buffer::references(docstring const & label) const
2096 return const_cast<Buffer *>(this)->references(label);
2100 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2102 masterBuffer()->d->ref_cache_[label].first = il;
2106 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2108 return masterBuffer()->d->ref_cache_[label].first;
2112 void Buffer::clearReferenceCache() const
2114 if (!d->parent_buffer)
2115 d->ref_cache_.clear();
2119 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2122 //FIXME: This does not work for child documents yet.
2123 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2124 // Check if the label 'from' appears more than once
2125 vector<docstring> labels;
2128 if (code == CITE_CODE) {
2130 keys.fillWithBibKeys(this);
2131 BiblioInfo::const_iterator bit = keys.begin();
2132 BiblioInfo::const_iterator bend = keys.end();
2134 for (; bit != bend; ++bit)
2136 labels.push_back(bit->first);
2139 getLabelList(labels);
2140 paramName = "reference";
2143 if (count(labels.begin(), labels.end(), from) > 1)
2146 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2147 if (it->lyxCode() == code) {
2148 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2149 docstring const oldValue = inset.getParam(paramName);
2150 if (oldValue == from)
2151 inset.setParam(paramName, to);
2157 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2158 pit_type par_end, bool full_source)
2160 OutputParams runparams(¶ms().encoding());
2161 runparams.nice = true;
2162 runparams.flavor = OutputParams::LATEX;
2163 runparams.linelen = lyxrc.plaintext_linelen;
2164 // No side effect of file copying and image conversion
2165 runparams.dryrun = true;
2169 os << "% " << _("Preview source code") << "\n\n";
2170 d->texrow.newline();
2171 d->texrow.newline();
2173 writeLaTeXSource(os, filePath(), runparams, true, true);
2175 writeDocBookSource(os, absFileName(), runparams, false);
2178 runparams.par_begin = par_begin;
2179 runparams.par_end = par_end;
2180 if (par_begin + 1 == par_end)
2182 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2186 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2187 convert<docstring>(par_begin),
2188 convert<docstring>(par_end - 1))
2190 d->texrow.newline();
2191 d->texrow.newline();
2192 // output paragraphs
2194 latexParagraphs(*this, text(), os, d->texrow, runparams);
2197 docbookParagraphs(paragraphs(), *this, os, runparams);
2203 ErrorList & Buffer::errorList(string const & type) const
2205 static ErrorList emptyErrorList;
2206 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2207 if (I == d->errorLists.end())
2208 return emptyErrorList;
2214 void Buffer::structureChanged() const
2217 gui_->structureChanged();
2221 void Buffer::errors(string const & err) const
2228 void Buffer::message(docstring const & msg) const
2235 void Buffer::setBusy(bool on) const
2242 void Buffer::setReadOnly(bool on) const
2245 d->wa_->setReadOnly(on);
2249 void Buffer::updateTitles() const
2252 d->wa_->updateTitles();
2256 void Buffer::resetAutosaveTimers() const
2259 gui_->resetAutosaveTimers();
2263 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2272 class AutoSaveBuffer : public ForkedProcess {
2275 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2276 : buffer_(buffer), fname_(fname) {}
2278 virtual boost::shared_ptr<ForkedProcess> clone() const
2280 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2285 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2286 from_utf8(fname_.absFilename())));
2287 return run(DontWait);
2291 virtual int generateChild();
2293 Buffer const & buffer_;
2298 int AutoSaveBuffer::generateChild()
2300 // tmp_ret will be located (usually) in /tmp
2301 // will that be a problem?
2302 // Note that this calls ForkedCalls::fork(), so it's
2303 // ok cross-platform.
2304 pid_t const pid = fork();
2305 // If you want to debug the autosave
2306 // you should set pid to -1, and comment out the fork.
2307 if (pid != 0 && pid != -1)
2310 // pid = -1 signifies that lyx was unable
2311 // to fork. But we will do the save
2313 bool failed = false;
2314 FileName const tmp_ret = FileName::tempName("lyxauto");
2315 if (!tmp_ret.empty()) {
2316 buffer_.writeFile(tmp_ret);
2317 // assume successful write of tmp_ret
2318 if (!tmp_ret.moveTo(fname_))
2324 // failed to write/rename tmp_ret so try writing direct
2325 if (!buffer_.writeFile(fname_)) {
2326 // It is dangerous to do this in the child,
2327 // but safe in the parent, so...
2328 if (pid == -1) // emit message signal.
2329 buffer_.message(_("Autosave failed!"));
2333 if (pid == 0) // we are the child so...
2342 // Perfect target for a thread...
2343 void Buffer::autoSave() const
2345 if (isBakClean() || isReadonly()) {
2346 // We don't save now, but we'll try again later
2347 resetAutosaveTimers();
2351 // emit message signal.
2352 message(_("Autosaving current document..."));
2354 // create autosave filename
2355 string fname = filePath();
2357 fname += d->filename.onlyFileName();
2360 AutoSaveBuffer autosave(*this, FileName(fname));
2364 resetAutosaveTimers();
2368 void Buffer::resetChildDocuments(bool close_them) const
2373 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2374 if (it->lyxCode() != INCLUDE_CODE)
2376 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2377 InsetCommandParams const & ip = inset.params();
2379 resetParentBuffer(this, ip, close_them);
2382 // clear references to children in macro tables
2383 d->children_positions.clear();
2384 d->position_to_children.clear();
2388 void Buffer::loadChildDocuments() const
2390 bool parse_error = false;
2392 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2393 if (it->lyxCode() != INCLUDE_CODE)
2395 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2396 InsetCommandParams const & ip = inset.params();
2397 Buffer * child = loadIfNeeded(*this, ip);
2400 parse_error |= !child->errorList("Parse").empty();
2401 child->loadChildDocuments();
2404 if (use_gui && masterBuffer() == this)
2405 updateLabels(*this);
2411 string Buffer::bufferFormat() const
2421 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2422 string & result_file) const
2424 string backend_format;
2425 OutputParams runparams(¶ms().encoding());
2426 runparams.flavor = OutputParams::LATEX;
2427 runparams.linelen = lyxrc.plaintext_linelen;
2428 vector<string> backs = backends();
2429 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2430 // Get shortest path to format
2431 Graph::EdgePath path;
2432 for (vector<string>::const_iterator it = backs.begin();
2433 it != backs.end(); ++it) {
2434 Graph::EdgePath p = theConverters().getPath(*it, format);
2435 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2436 backend_format = *it;
2441 runparams.flavor = theConverters().getFlavor(path);
2443 Alert::error(_("Couldn't export file"),
2444 bformat(_("No information for exporting the format %1$s."),
2445 formats.prettyName(format)));
2449 backend_format = format;
2450 // FIXME: Don't hardcode format names here, but use a flag
2451 if (backend_format == "pdflatex")
2452 runparams.flavor = OutputParams::PDFLATEX;
2455 string filename = latexName(false);
2456 filename = addName(temppath(), filename);
2457 filename = changeExtension(filename,
2458 formats.extension(backend_format));
2461 updateMacroInstances();
2463 // Plain text backend
2464 if (backend_format == "text")
2465 writePlaintextFile(*this, FileName(filename), runparams);
2467 else if (backend_format == "lyx")
2468 writeFile(FileName(filename));
2470 else if (isDocBook()) {
2471 runparams.nice = !put_in_tempdir;
2472 makeDocBookFile(FileName(filename), runparams);
2475 else if (backend_format == format) {
2476 runparams.nice = true;
2477 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2479 } else if (!lyxrc.tex_allows_spaces
2480 && contains(filePath(), ' ')) {
2481 Alert::error(_("File name error"),
2482 _("The directory path to the document cannot contain spaces."));
2485 runparams.nice = false;
2486 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2490 string const error_type = (format == "program")
2491 ? "Build" : bufferFormat();
2492 string const ext = formats.extension(format);
2493 FileName const tmp_result_file(changeExtension(filename, ext));
2494 bool const success = theConverters().convert(this, FileName(filename),
2495 tmp_result_file, FileName(absFileName()), backend_format, format,
2496 errorList(error_type));
2497 // Emit the signal to show the error list.
2498 if (format != backend_format)
2503 if (put_in_tempdir) {
2504 result_file = tmp_result_file.absFilename();
2508 result_file = changeExtension(absFileName(), ext);
2509 // We need to copy referenced files (e. g. included graphics
2510 // if format == "dvi") to the result dir.
2511 vector<ExportedFile> const files =
2512 runparams.exportdata->externalFiles(format);
2513 string const dest = onlyPath(result_file);
2514 CopyStatus status = SUCCESS;
2515 for (vector<ExportedFile>::const_iterator it = files.begin();
2516 it != files.end() && status != CANCEL; ++it) {
2517 string const fmt = formats.getFormatFromFile(it->sourceName);
2518 status = copyFile(fmt, it->sourceName,
2519 makeAbsPath(it->exportName, dest),
2520 it->exportName, status == FORCE);
2522 if (status == CANCEL) {
2523 message(_("Document export cancelled."));
2524 } else if (tmp_result_file.exists()) {
2525 // Finally copy the main file
2526 status = copyFile(format, tmp_result_file,
2527 FileName(result_file), result_file,
2529 message(bformat(_("Document exported as %1$s "
2531 formats.prettyName(format),
2532 makeDisplayPath(result_file)));
2534 // This must be a dummy converter like fax (bug 1888)
2535 message(bformat(_("Document exported as %1$s"),
2536 formats.prettyName(format)));
2543 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2546 return doExport(format, put_in_tempdir, result_file);
2550 bool Buffer::preview(string const & format) const
2553 if (!doExport(format, true, result_file))
2555 return formats.view(*this, FileName(result_file), format);
2559 bool Buffer::isExportable(string const & format) const
2561 vector<string> backs = backends();
2562 for (vector<string>::const_iterator it = backs.begin();
2563 it != backs.end(); ++it)
2564 if (theConverters().isReachable(*it, format))
2570 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2572 vector<string> backs = backends();
2573 vector<Format const *> result =
2574 theConverters().getReachable(backs[0], only_viewable, true);
2575 for (vector<string>::const_iterator it = backs.begin() + 1;
2576 it != backs.end(); ++it) {
2577 vector<Format const *> r =
2578 theConverters().getReachable(*it, only_viewable, false);
2579 result.insert(result.end(), r.begin(), r.end());
2585 vector<string> Buffer::backends() const
2588 if (params().baseClass()->isTeXClassAvailable()) {
2589 v.push_back(bufferFormat());
2590 // FIXME: Don't hardcode format names here, but use a flag
2591 if (v.back() == "latex")
2592 v.push_back("pdflatex");
2594 v.push_back("text");
2600 bool Buffer::readFileHelper(FileName const & s)
2602 // File information about normal file
2604 docstring const file = makeDisplayPath(s.absFilename(), 50);
2605 docstring text = bformat(_("The specified document\n%1$s"
2606 "\ncould not be read."), file);
2607 Alert::error(_("Could not read document"), text);
2611 // Check if emergency save file exists and is newer.
2612 FileName const e(s.absFilename() + ".emergency");
2614 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2615 docstring const file = makeDisplayPath(s.absFilename(), 20);
2616 docstring const text =
2617 bformat(_("An emergency save of the document "
2619 "Recover emergency save?"), file);
2620 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2621 _("&Recover"), _("&Load Original"),
2625 // the file is not saved if we load the emergency file.
2635 // Now check if autosave file is newer.
2636 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2638 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2639 docstring const file = makeDisplayPath(s.absFilename(), 20);
2640 docstring const text =
2641 bformat(_("The backup of the document "
2642 "%1$s is newer.\n\nLoad the "
2643 "backup instead?"), file);
2644 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2645 _("&Load backup"), _("Load &original"),
2649 // the file is not saved if we load the autosave file.
2653 // Here we delete the autosave
2664 bool Buffer::loadLyXFile(FileName const & s)
2666 if (s.isReadableFile()) {
2667 if (readFileHelper(s)) {
2668 lyxvc().file_found_hook(s);
2669 if (!s.isWritable())
2674 docstring const file = makeDisplayPath(s.absFilename(), 20);
2675 // Here we probably should run
2676 if (LyXVC::file_not_found_hook(s)) {
2677 docstring const text =
2678 bformat(_("Do you want to retrieve the document"
2679 " %1$s from version control?"), file);
2680 int const ret = Alert::prompt(_("Retrieve from version control?"),
2681 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2684 // How can we know _how_ to do the checkout?
2685 // With the current VC support it has to be,
2686 // a RCS file since CVS do not have special ,v files.
2688 return loadLyXFile(s);
2696 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2698 TeXErrors::Errors::const_iterator cit = terr.begin();
2699 TeXErrors::Errors::const_iterator end = terr.end();
2701 for (; cit != end; ++cit) {
2704 int errorRow = cit->error_in_line;
2705 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2711 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2712 } while (found && id_start == id_end && pos_start == pos_end);
2714 errorList.push_back(ErrorItem(cit->error_desc,
2715 cit->error_text, id_start, pos_start, pos_end));