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 "LayoutFile.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 "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibtex.h"
70 #include "insets/InsetBranch.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetTabular.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 413; // rgh: html_css_as_file
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
160 /// search for macro in local (buffer) table or in children
161 MacroData const * getBufferMacro(docstring const & name,
162 DocIterator const & pos) const;
164 /// Update macro table starting with position of it \param it in some
166 void updateMacros(DocIterator & it, DocIterator & scope);
168 void setLabel(ParIterator & it, UpdateType utype) const;
170 /** If we have branches that use the file suffix
171 feature, return the file name with suffix appended.
173 support::FileName exportFileName() const;
180 mutable TexRow texrow;
182 /// need to regenerate .tex?
186 mutable bool lyx_clean;
188 /// is autosave needed?
189 mutable bool bak_clean;
191 /// is this an unnamed file (New...)?
197 /// name of the file the buffer is associated with.
200 /** Set to true only when the file is fully loaded.
201 * Used to prevent the premature generation of previews
202 * and by the citation inset.
204 bool file_fully_loaded;
207 mutable TocBackend toc_backend;
210 typedef pair<DocIterator, MacroData> ScopeMacro;
211 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
212 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
213 /// map from the macro name to the position map,
214 /// which maps the macro definition position to the scope and the MacroData.
215 NamePositionScopeMacroMap macros;
216 /// This seem to change the way Buffer::getMacro() works
217 mutable bool macro_lock;
219 /// positions of child buffers in the buffer
220 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
221 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
222 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
223 /// position of children buffers in this buffer
224 BufferPositionMap children_positions;
225 /// map from children inclusion positions to their scope and their buffer
226 PositionScopeBufferMap position_to_children;
228 /// Container for all sort of Buffer dependant errors.
229 map<string, ErrorList> errorLists;
231 /// timestamp and checksum used to test if the file has been externally
232 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
234 unsigned long checksum_;
237 frontend::WorkAreaManager * wa_;
239 frontend::GuiBufferDelegate * gui_;
244 /// A cache for the bibfiles (including bibfiles of loaded child
245 /// documents), needed for appropriate update of natbib labels.
246 mutable support::FileNameList bibfiles_cache_;
248 // FIXME The caching mechanism could be improved. At present, we have a
249 // cache for each Buffer, that caches all the bibliography info for that
250 // Buffer. A more efficient solution would be to have a global cache per
251 // file, and then to construct the Buffer's bibinfo from that.
252 /// A cache for bibliography info
253 mutable BiblioInfo bibinfo_;
254 /// whether the bibinfo cache is valid
255 mutable bool bibinfo_cache_valid_;
256 /// whether the bibfile cache is valid
257 mutable bool bibfile_cache_valid_;
258 /// Cache of timestamps of .bib files
259 map<FileName, time_t> bibfile_status_;
260 /// Indicates whether the bibinfo has changed since the last time
261 /// we ran updateBuffer(), i.e., whether citation labels may need
263 mutable bool cite_labels_valid_;
265 mutable RefCache ref_cache_;
267 /// our Text that should be wrapped in an InsetText
270 /// This is here to force the test to be done whenever parent_buffer
272 Buffer const * parent() const {
273 // if parent_buffer is not loaded, then it has been unloaded,
274 // which means that parent_buffer is an invalid pointer. So we
275 // set it to null in that case.
276 // however, the BufferList doesn't know about cloned buffers, so
277 // they will always be regarded as unloaded. in that case, we hope
279 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
281 return parent_buffer;
285 void setParent(Buffer const * pb) {
286 if (parent_buffer == pb)
289 if (!cloned_buffer_ && parent_buffer && pb)
290 LYXERR0("Warning: a buffer should not have two parents!");
292 if (!cloned_buffer_ && parent_buffer) {
293 parent_buffer->invalidateBibfileCache();
294 parent_buffer->invalidateBibinfoCache();
298 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
299 /// This one is useful for preview detached in a thread.
300 Buffer const * cloned_buffer_;
301 /// are we in the process of exporting this buffer?
302 mutable bool doing_export;
305 /// So we can force access via the accessors.
306 mutable Buffer const * parent_buffer;
311 /// Creates the per buffer temporary directory
312 static FileName createBufferTmpDir()
315 // We are in our own directory. Why bother to mangle name?
316 // In fact I wrote this code to circumvent a problematic behaviour
317 // (bug?) of EMX mkstemp().
318 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
319 convert<string>(count++));
321 if (!tmpfl.createDirectory(0777)) {
322 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
323 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
324 from_utf8(tmpfl.absFileName())));
330 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
331 Buffer const * cloned_buffer)
332 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
333 read_only(readonly_), filename(file), file_fully_loaded(false),
334 toc_backend(owner), macro_lock(false), timestamp_(0),
335 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
336 bibfile_cache_valid_(false), cite_labels_valid_(false),
337 cloned_buffer_(cloned_buffer), doing_export(false), parent_buffer(0)
339 if (!cloned_buffer_) {
340 temppath = createBufferTmpDir();
341 lyxvc.setBuffer(owner_);
343 wa_ = new frontend::WorkAreaManager;
346 temppath = cloned_buffer_->d->temppath;
347 file_fully_loaded = true;
348 params = cloned_buffer_->d->params;
349 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
350 bibinfo_ = cloned_buffer_->d->bibinfo_;
351 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
352 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
353 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
354 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
358 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
359 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
361 LYXERR(Debug::INFO, "Buffer::Buffer()");
363 d->inset = new InsetText(*cloned_buffer->d->inset);
364 d->inset->setBuffer(*this);
365 // FIXME: optimize this loop somewhat, maybe by creating a new
366 // general recursive Inset::setId().
367 DocIterator it = doc_iterator_begin(this);
368 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
369 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
370 it.paragraph().setId(cloned_it.paragraph().id());
372 d->inset = new InsetText(this);
373 d->inset->setAutoBreakRows(true);
374 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
380 LYXERR(Debug::INFO, "Buffer::~Buffer()");
381 // here the buffer should take care that it is
382 // saved properly, before it goes into the void.
384 // GuiView already destroyed
388 // No need to do additional cleanups for internal buffer.
393 // loop over children
394 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
395 Impl::BufferPositionMap::iterator end = d->children_positions.end();
396 for (; it != end; ++it) {
397 Buffer * child = const_cast<Buffer *>(it->first);
398 if (d->cloned_buffer_)
400 // The child buffer might have been closed already.
401 else if (theBufferList().isLoaded(child))
402 theBufferList().releaseChild(this, child);
406 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
407 msg += emergencyWrite();
408 Alert::warning(_("Attempting to close changed document!"), msg);
411 // clear references to children in macro tables
412 d->children_positions.clear();
413 d->position_to_children.clear();
415 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
416 Alert::warning(_("Could not remove temporary directory"),
417 bformat(_("Could not remove the temporary directory %1$s"),
418 from_utf8(d->temppath.absFileName())));
428 Buffer * Buffer::clone() const
430 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
431 buffer_clone->d->macro_lock = true;
432 buffer_clone->d->children_positions.clear();
433 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
434 // math macro caches need to be rethought and simplified.
435 // I am not sure wether we should handle Buffer cloning here or in BufferList.
436 // Right now BufferList knows nothing about buffer clones.
437 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
438 Impl::BufferPositionMap::iterator end = d->children_positions.end();
439 for (; it != end; ++it) {
440 DocIterator dit = it->second.clone(buffer_clone);
441 dit.setBuffer(buffer_clone);
442 Buffer * child = const_cast<Buffer *>(it->first);
443 Buffer * child_clone = child->clone();
444 Inset * inset = dit.nextInset();
445 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
446 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
447 inset_inc->setChildBuffer(child_clone);
448 child_clone->d->setParent(buffer_clone);
449 buffer_clone->setChild(dit, child_clone);
451 buffer_clone->d->macro_lock = false;
456 bool Buffer::isClone() const
458 return d->cloned_buffer_;
462 void Buffer::changed(bool update_metrics) const
465 d->wa_->redrawAll(update_metrics);
469 frontend::WorkAreaManager & Buffer::workAreaManager() const
471 LASSERT(d->wa_, /**/);
476 Text & Buffer::text() const
478 return d->inset->text();
482 Inset & Buffer::inset() const
488 BufferParams & Buffer::params()
494 BufferParams const & Buffer::params() const
500 ParagraphList & Buffer::paragraphs()
502 return text().paragraphs();
506 ParagraphList const & Buffer::paragraphs() const
508 return text().paragraphs();
512 LyXVC & Buffer::lyxvc()
518 LyXVC const & Buffer::lyxvc() const
524 string const Buffer::temppath() const
526 return d->temppath.absFileName();
530 TexRow & Buffer::texrow()
536 TexRow const & Buffer::texrow() const
542 TocBackend & Buffer::tocBackend() const
544 return d->toc_backend;
548 Undo & Buffer::undo()
554 void Buffer::setChild(DocIterator const & dit, Buffer * child)
556 d->children_positions[child] = dit;
560 string Buffer::latexName(bool const no_path) const
562 FileName latex_name =
563 makeLatexName(d->exportFileName());
564 return no_path ? latex_name.onlyFileName()
565 : latex_name.absFileName();
569 FileName Buffer::Impl::exportFileName() const
571 docstring const branch_suffix =
572 params.branchlist().getFileNameSuffix();
573 if (branch_suffix.empty())
576 string const name = filename.onlyFileNameWithoutExt()
577 + to_utf8(branch_suffix);
578 FileName res(filename.onlyPath().absFileName() + "/" + name);
579 res.changeExtension(filename.extension());
585 string Buffer::logName(LogType * type) const
587 string const filename = latexName(false);
589 if (filename.empty()) {
595 string const path = temppath();
597 FileName const fname(addName(temppath(),
598 onlyFileName(changeExtension(filename,
601 // FIXME: how do we know this is the name of the build log?
602 FileName const bname(
603 addName(path, onlyFileName(
604 changeExtension(filename,
605 formats.extension(params().bufferFormat()) + ".out"))));
607 // Also consider the master buffer log file
608 FileName masterfname = fname;
610 if (masterBuffer() != this) {
611 string const mlogfile = masterBuffer()->logName(&mtype);
612 masterfname = FileName(mlogfile);
615 // If no Latex log or Build log is newer, show Build log
616 if (bname.exists() &&
617 ((!fname.exists() && !masterfname.exists())
618 || (fname.lastModified() < bname.lastModified()
619 && masterfname.lastModified() < bname.lastModified()))) {
620 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
623 return bname.absFileName();
624 // If we have a newer master file log or only a master log, show this
625 } else if (fname != masterfname
626 && (!fname.exists() && (masterfname.exists()
627 || fname.lastModified() < masterfname.lastModified()))) {
628 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
631 return masterfname.absFileName();
633 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
636 return fname.absFileName();
640 void Buffer::setReadonly(bool const flag)
642 if (d->read_only != flag) {
649 void Buffer::setFileName(FileName const & fname)
652 setReadonly(d->filename.isReadOnly());
658 int Buffer::readHeader(Lexer & lex)
660 int unknown_tokens = 0;
662 int begin_header_line = -1;
664 // Initialize parameters that may be/go lacking in header:
665 params().branchlist().clear();
666 params().preamble.erase();
667 params().options.erase();
668 params().master.erase();
669 params().float_placement.erase();
670 params().paperwidth.erase();
671 params().paperheight.erase();
672 params().leftmargin.erase();
673 params().rightmargin.erase();
674 params().topmargin.erase();
675 params().bottommargin.erase();
676 params().headheight.erase();
677 params().headsep.erase();
678 params().footskip.erase();
679 params().columnsep.erase();
680 params().fonts_cjk.erase();
681 params().listings_params.clear();
682 params().clearLayoutModules();
683 params().clearRemovedModules();
684 params().clearIncludedChildren();
685 params().pdfoptions().clear();
686 params().indiceslist().clear();
687 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
688 params().isbackgroundcolor = false;
689 params().fontcolor = lyx::rgbFromHexName("#000000");
690 params().isfontcolor = false;
691 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
692 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
693 params().html_latex_start.clear();
694 params().html_latex_end.clear();
695 params().html_math_img_scale = 1.0;
696 params().output_sync_macro.erase();
698 for (int i = 0; i < 4; ++i) {
699 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
700 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
703 ErrorList & errorList = d->errorLists["Parse"];
712 if (token == "\\end_header")
716 if (token == "\\begin_header") {
717 begin_header_line = line;
721 LYXERR(Debug::PARSER, "Handling document header token: `"
724 string unknown = params().readToken(lex, token, d->filename.onlyPath());
725 if (!unknown.empty()) {
726 if (unknown[0] != '\\' && token == "\\textclass") {
727 Alert::warning(_("Unknown document class"),
728 bformat(_("Using the default document class, because the "
729 "class %1$s is unknown."), from_utf8(unknown)));
732 docstring const s = bformat(_("Unknown token: "
736 errorList.push_back(ErrorItem(_("Document header error"),
741 if (begin_header_line) {
742 docstring const s = _("\\begin_header is missing");
743 errorList.push_back(ErrorItem(_("Document header error"),
747 params().makeDocumentClass();
749 return unknown_tokens;
754 // changed to be public and have one parameter
755 // Returns true if "\end_document" is not read (Asger)
756 bool Buffer::readDocument(Lexer & lex)
758 ErrorList & errorList = d->errorLists["Parse"];
761 // remove dummy empty par
762 paragraphs().clear();
764 if (!lex.checkFor("\\begin_document")) {
765 docstring const s = _("\\begin_document is missing");
766 errorList.push_back(ErrorItem(_("Document header error"),
772 if (params().outputChanges) {
773 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
774 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
775 LaTeXFeatures::isAvailable("xcolor");
777 if (!dvipost && !xcolorulem) {
778 Alert::warning(_("Changes not shown in LaTeX output"),
779 _("Changes will not be highlighted in LaTeX output, "
780 "because neither dvipost nor xcolor/ulem are installed.\n"
781 "Please install these packages or redefine "
782 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
783 } else if (!xcolorulem) {
784 Alert::warning(_("Changes not shown in LaTeX output"),
785 _("Changes will not be highlighted in LaTeX output "
786 "when using pdflatex, because xcolor and ulem are not installed.\n"
787 "Please install both packages or redefine "
788 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
792 if (!params().master.empty()) {
793 FileName const master_file = makeAbsPath(params().master,
794 onlyPath(absFileName()));
795 if (isLyXFileName(master_file.absFileName())) {
797 checkAndLoadLyXFile(master_file, true);
799 // necessary e.g. after a reload
800 // to re-register the child (bug 5873)
801 // FIXME: clean up updateMacros (here, only
802 // child registering is needed).
803 master->updateMacros();
804 // set master as master buffer, but only
805 // if we are a real child
806 if (master->isChild(this))
808 // if the master is not fully loaded
809 // it is probably just loading this
810 // child. No warning needed then.
811 else if (master->isFullyLoaded())
812 LYXERR0("The master '"
814 << "' assigned to this document ("
816 << ") does not include "
817 "this document. Ignoring the master assignment.");
822 // assure we have a default index
823 params().indiceslist().addDefault(B_("Index"));
826 bool const res = text().read(lex, errorList, d->inset);
828 // inform parent buffer about local macros
830 Buffer const * pbuf = parent();
831 UserMacroSet::const_iterator cit = usermacros.begin();
832 UserMacroSet::const_iterator end = usermacros.end();
833 for (; cit != end; ++cit)
834 pbuf->usermacros.insert(*cit);
838 updateMacroInstances(InternalUpdate);
843 bool Buffer::readString(string const & s)
845 params().compressed = false;
850 FileName const fn = FileName::tempName("Buffer_readString");
853 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
854 if (ret_plf != ReadSuccess)
857 if (file_format != LYX_FORMAT) {
858 // We need to call lyx2lyx, so write the input to a file
859 ofstream os(fn.toFilesystemEncoding().c_str());
863 return readFile(fn) == ReadSuccess;
866 if (readDocument(lex))
872 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
876 if (!lex.setFile(fname)) {
877 Alert::error(_("File Not Found"),
878 bformat(_("Unable to open file `%1$s'."),
879 from_utf8(fn.absFileName())));
880 return ReadFileNotFound;
884 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
885 if (ret_plf != ReadSuccess)
888 if (file_format != LYX_FORMAT) {
890 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
891 if (ret_clf != ReadSuccess)
893 return readFile(tmpFile);
896 // FIXME: InsetInfo needs to know whether the file is under VCS
897 // during the parse process, so this has to be done before.
898 lyxvc().file_found_hook(d->filename);
900 if (readDocument(lex)) {
901 Alert::error(_("Document format failure"),
902 bformat(_("%1$s ended unexpectedly, which means"
903 " that it is probably corrupted."),
904 from_utf8(fn.absFileName())));
905 return ReadDocumentFailure;
908 d->file_fully_loaded = true;
909 d->read_only = !d->filename.isWritable();
910 params().compressed = d->filename.isZippedFile();
916 bool Buffer::isFullyLoaded() const
918 return d->file_fully_loaded;
922 void Buffer::setFullyLoaded(bool value)
924 d->file_fully_loaded = value;
928 void Buffer::updatePreviews() const
930 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
931 thePreviews().generateBufferPreviews(*this);
935 void Buffer::removePreviews() const
937 thePreviews().removeLoader(*this);
941 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
942 FileName const & fn, int & file_format) const
944 if(!lex.checkFor("\\lyxformat")) {
945 Alert::error(_("Document format failure"),
946 bformat(_("%1$s is not a readable LyX document."),
947 from_utf8(fn.absFileName())));
948 return ReadNoLyXFormat;
954 // LyX formats 217 and earlier were written as 2.17. This corresponds
955 // to files from LyX versions < 1.1.6.3. We just remove the dot in
956 // these cases. See also: www.lyx.org/trac/changeset/1313.
957 size_t dot = tmp_format.find_first_of(".,");
958 if (dot != string::npos)
959 tmp_format.erase(dot, 1);
961 file_format = convert<int>(tmp_format);
966 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
967 FileName & tmpfile, int from_format)
969 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
970 if(tmpfile.empty()) {
971 Alert::error(_("Conversion failed"),
972 bformat(_("%1$s is from a different"
973 " version of LyX, but a temporary"
974 " file for converting it could"
976 from_utf8(fn.absFileName())));
977 return LyX2LyXNoTempFile;
980 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
981 if (lyx2lyx.empty()) {
982 Alert::error(_("Conversion script not found"),
983 bformat(_("%1$s is from a different"
984 " version of LyX, but the"
985 " conversion script lyx2lyx"
986 " could not be found."),
987 from_utf8(fn.absFileName())));
988 return LyX2LyXNotFound;
992 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
993 ostringstream command;
994 command << os::python()
995 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
996 << " -t " << convert<string>(LYX_FORMAT)
997 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
998 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
999 string const command_str = command.str();
1001 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1003 cmd_ret const ret = runCommand(command_str);
1004 if (ret.first != 0) {
1005 if (from_format < LYX_FORMAT) {
1006 Alert::error(_("Conversion script failed"),
1007 bformat(_("%1$s is from an older version"
1008 " of LyX and the lyx2lyx script"
1009 " failed to convert it."),
1010 from_utf8(fn.absFileName())));
1011 return LyX2LyXOlderFormat;
1013 Alert::error(_("Conversion script failed"),
1014 bformat(_("%1$s is from a newer version"
1015 " of LyX and the lyx2lyx script"
1016 " failed to convert it."),
1017 from_utf8(fn.absFileName())));
1018 return LyX2LyXNewerFormat;
1025 // Should probably be moved to somewhere else: BufferView? GuiView?
1026 bool Buffer::save() const
1028 docstring const file = makeDisplayPath(absFileName(), 20);
1029 d->filename.refresh();
1031 // check the read-only status before moving the file as a backup
1032 if (d->filename.exists()) {
1033 bool const read_only = !d->filename.isWritable();
1035 Alert::warning(_("File is read-only"),
1036 bformat(_("The file %1$s cannot be written because it "
1037 "is marked as read-only."), file));
1042 // ask if the disk file has been externally modified (use checksum method)
1043 if (fileName().exists() && isExternallyModified(checksum_method)) {
1045 bformat(_("Document %1$s has been externally modified. "
1046 "Are you sure you want to overwrite this file?"), file);
1047 int const ret = Alert::prompt(_("Overwrite modified file?"),
1048 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1053 // We don't need autosaves in the immediate future. (Asger)
1054 resetAutosaveTimers();
1056 FileName backupName;
1057 bool madeBackup = false;
1059 // make a backup if the file already exists
1060 if (lyxrc.make_backup && fileName().exists()) {
1061 backupName = FileName(absFileName() + '~');
1062 if (!lyxrc.backupdir_path.empty()) {
1063 string const mangledName =
1064 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1065 backupName = FileName(addName(lyxrc.backupdir_path,
1069 // Except file is symlink do not copy because of #6587.
1070 // Hard links have bad luck.
1071 if (fileName().isSymLink())
1072 madeBackup = fileName().copyTo(backupName);
1074 madeBackup = fileName().moveTo(backupName);
1077 Alert::error(_("Backup failure"),
1078 bformat(_("Cannot create backup file %1$s.\n"
1079 "Please check whether the directory exists and is writable."),
1080 from_utf8(backupName.absFileName())));
1081 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1085 if (writeFile(d->filename)) {
1089 // Saving failed, so backup is not backup
1091 backupName.moveTo(d->filename);
1097 bool Buffer::writeFile(FileName const & fname) const
1099 // FIXME Do we need to do these here? I don't think writing
1100 // the LyX file depends upon it. (RGH)
1102 // updateMacroInstances();
1104 if (d->read_only && fname == d->filename)
1107 bool retval = false;
1109 docstring const str = bformat(_("Saving document %1$s..."),
1110 makeDisplayPath(fname.absFileName()));
1113 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1115 if (params().compressed) {
1116 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1117 retval = ofs && write(ofs);
1119 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1120 retval = ofs && write(ofs);
1124 message(str + _(" could not write file!"));
1129 // removeAutosaveFile();
1132 message(str + _(" done."));
1138 docstring Buffer::emergencyWrite()
1140 // No need to save if the buffer has not changed.
1144 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1146 docstring user_message = bformat(
1147 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1149 // We try to save three places:
1150 // 1) Same place as document. Unless it is an unnamed doc.
1152 string s = absFileName();
1155 if (writeFile(FileName(s))) {
1157 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1158 return user_message;
1160 user_message += " " + _("Save failed! Trying again...\n");
1164 // 2) In HOME directory.
1165 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1167 lyxerr << ' ' << s << endl;
1168 if (writeFile(FileName(s))) {
1170 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1171 return user_message;
1174 user_message += " " + _("Save failed! Trying yet again...\n");
1176 // 3) In "/tmp" directory.
1177 // MakeAbsPath to prepend the current
1178 // drive letter on OS/2
1179 s = addName(package().temp_dir().absFileName(), absFileName());
1181 lyxerr << ' ' << s << endl;
1182 if (writeFile(FileName(s))) {
1184 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1185 return user_message;
1188 user_message += " " + _("Save failed! Bummer. Document is lost.");
1191 return user_message;
1195 bool Buffer::write(ostream & ofs) const
1198 // Use the standard "C" locale for file output.
1199 ofs.imbue(locale::classic());
1202 // The top of the file should not be written by params().
1204 // write out a comment in the top of the file
1205 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1206 << " created this file. For more info see http://www.lyx.org/\n"
1207 << "\\lyxformat " << LYX_FORMAT << "\n"
1208 << "\\begin_document\n";
1210 /// For each author, set 'used' to true if there is a change
1211 /// by this author in the document; otherwise set it to 'false'.
1212 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1213 AuthorList::Authors::const_iterator a_end = params().authors().end();
1214 for (; a_it != a_end; ++a_it)
1215 a_it->setUsed(false);
1217 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1218 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1219 for ( ; it != end; ++it)
1220 it->checkAuthors(params().authors());
1222 // now write out the buffer parameters.
1223 ofs << "\\begin_header\n";
1224 params().writeFile(ofs);
1225 ofs << "\\end_header\n";
1228 ofs << "\n\\begin_body\n";
1230 ofs << "\n\\end_body\n";
1232 // Write marker that shows file is complete
1233 ofs << "\\end_document" << endl;
1235 // Shouldn't really be needed....
1238 // how to check if close went ok?
1239 // Following is an attempt... (BE 20001011)
1241 // good() returns false if any error occured, including some
1242 // formatting error.
1243 // bad() returns true if something bad happened in the buffer,
1244 // which should include file system full errors.
1249 lyxerr << "File was not closed properly." << endl;
1256 bool Buffer::makeLaTeXFile(FileName const & fname,
1257 string const & original_path,
1258 OutputParams const & runparams_in,
1259 bool output_preamble, bool output_body) const
1261 OutputParams runparams = runparams_in;
1263 // This is necessary for LuaTeX/XeTeX with tex fonts.
1264 // See FIXME in BufferParams::encoding()
1265 if (runparams.isFullUnicode())
1266 runparams.encoding = encodings.fromLyXName("utf8-plain");
1268 string const encoding = runparams.encoding->iconvName();
1269 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1272 try { ofs.reset(encoding); }
1273 catch (iconv_codecvt_facet_exception & e) {
1274 lyxerr << "Caught iconv exception: " << e.what() << endl;
1275 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1276 "verify that the support software for your encoding (%1$s) is "
1277 "properly installed"), from_ascii(encoding)));
1280 if (!openFileWrite(ofs, fname))
1283 //TexStream ts(ofs.rdbuf(), &texrow());
1284 ErrorList & errorList = d->errorLists["Export"];
1286 bool failed_export = false;
1287 otexstream os(ofs, d->texrow);
1289 // make sure we are ready to export
1290 // this needs to be done before we validate
1291 // FIXME Do we need to do this all the time? I.e., in children
1292 // of a master we are exporting?
1294 updateMacroInstances(OutputUpdate);
1297 os.texrow().reset();
1298 writeLaTeXSource(os, original_path,
1299 runparams, output_preamble, output_body);
1301 catch (EncodingException & e) {
1302 odocstringstream ods;
1303 ods.put(e.failed_char);
1305 oss << "0x" << hex << e.failed_char << dec;
1306 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1307 " (code point %2$s)"),
1308 ods.str(), from_utf8(oss.str()));
1309 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1310 "representable in the chosen encoding.\n"
1311 "Changing the document encoding to utf8 could help."),
1312 e.par_id, e.pos, e.pos + 1));
1313 failed_export = true;
1315 catch (iconv_codecvt_facet_exception & e) {
1316 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1317 _(e.what()), -1, 0, 0));
1318 failed_export = true;
1320 catch (exception const & e) {
1321 errorList.push_back(ErrorItem(_("conversion failed"),
1322 _(e.what()), -1, 0, 0));
1323 failed_export = true;
1326 lyxerr << "Caught some really weird exception..." << endl;
1332 failed_export = true;
1333 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1337 return !failed_export;
1341 void Buffer::writeLaTeXSource(otexstream & os,
1342 string const & original_path,
1343 OutputParams const & runparams_in,
1344 bool const output_preamble, bool const output_body) const
1346 // The child documents, if any, shall be already loaded at this point.
1348 OutputParams runparams = runparams_in;
1350 // Classify the unicode characters appearing in math insets
1351 Encodings::initUnicodeMath(*this);
1353 // validate the buffer.
1354 LYXERR(Debug::LATEX, " Validating buffer...");
1355 LaTeXFeatures features(*this, params(), runparams);
1357 LYXERR(Debug::LATEX, " Buffer validation done.");
1359 // The starting paragraph of the coming rows is the
1360 // first paragraph of the document. (Asger)
1361 if (output_preamble && runparams.nice) {
1362 os << "%% LyX " << lyx_version << " created this file. "
1363 "For more info, see http://www.lyx.org/.\n"
1364 "%% Do not edit unless you really know what "
1367 LYXERR(Debug::INFO, "lyx document header finished");
1369 // There are a few differences between nice LaTeX and usual files:
1370 // usual is \batchmode and has a
1371 // special input@path to allow the including of figures
1372 // with either \input or \includegraphics (what figinsets do).
1373 // input@path is set when the actual parameter
1374 // original_path is set. This is done for usual tex-file, but not
1375 // for nice-latex-file. (Matthias 250696)
1376 // Note that input@path is only needed for something the user does
1377 // in the preamble, included .tex files or ERT, files included by
1378 // LyX work without it.
1379 if (output_preamble) {
1380 if (!runparams.nice) {
1381 // code for usual, NOT nice-latex-file
1382 os << "\\batchmode\n"; // changed from \nonstopmode
1384 if (!original_path.empty()) {
1386 // We don't know the encoding of inputpath
1387 docstring const inputpath = from_utf8(support::latex_path(original_path));
1388 docstring uncodable_glyphs;
1389 Encoding const * const enc = runparams.encoding;
1391 for (size_t n = 0; n < inputpath.size(); ++n) {
1392 docstring const glyph =
1393 docstring(1, inputpath[n]);
1394 if (enc->latexChar(inputpath[n], true) != glyph) {
1395 LYXERR0("Uncodable character '"
1397 << "' in input path!");
1398 uncodable_glyphs += glyph;
1403 // warn user if we found uncodable glyphs.
1404 if (!uncodable_glyphs.empty()) {
1405 frontend::Alert::warning(_("Uncodable character in file path"),
1406 support::bformat(_("The path of your document\n"
1408 "contains glyphs that are unknown in the\n"
1409 "current document encoding (namely %2$s).\n"
1410 "This will likely result in incomplete output.\n\n"
1411 "Choose an appropriate document encoding (such as utf8)\n"
1412 "or change the file path name."), inputpath, uncodable_glyphs));
1414 os << "\\makeatletter\n"
1415 << "\\def\\input@path{{"
1416 << inputpath << "/}}\n"
1417 << "\\makeatother\n";
1421 // get parent macros (if this buffer has a parent) which will be
1422 // written at the document begin further down.
1423 MacroSet parentMacros;
1424 listParentMacros(parentMacros, features);
1426 runparams.use_polyglossia = features.usePolyglossia();
1427 // Write the preamble
1428 runparams.use_babel = params().writeLaTeX(os, features,
1429 d->filename.onlyPath());
1431 runparams.use_japanese = features.isRequired("japanese");
1437 os << "\\begin{document}\n";
1439 // output the parent macros
1440 MacroSet::iterator it = parentMacros.begin();
1441 MacroSet::iterator end = parentMacros.end();
1442 for (; it != end; ++it) {
1443 int num_lines = (*it)->write(os.os(), true);
1444 os.texrow().newlines(num_lines);
1447 } // output_preamble
1449 os.texrow().start(paragraphs().begin()->id(), 0);
1451 LYXERR(Debug::INFO, "preamble finished, now the body.");
1453 // if we are doing a real file with body, even if this is the
1454 // child of some other buffer, let's cut the link here.
1455 // This happens for example if only a child document is printed.
1456 Buffer const * save_parent = 0;
1457 if (output_preamble) {
1458 save_parent = d->parent();
1463 latexParagraphs(*this, text(), os, runparams);
1465 // Restore the parenthood if needed
1466 if (output_preamble)
1467 d->setParent(save_parent);
1469 // add this just in case after all the paragraphs
1472 if (output_preamble) {
1473 os << "\\end{document}\n";
1474 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1476 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1478 runparams_in.encoding = runparams.encoding;
1480 // Just to be sure. (Asger)
1481 os.texrow().newline();
1483 //for (int i = 0; i<d->texrow.rows(); i++) {
1485 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1486 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1489 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1490 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1494 void Buffer::makeDocBookFile(FileName const & fname,
1495 OutputParams const & runparams,
1496 bool const body_only) const
1498 LYXERR(Debug::LATEX, "makeDocBookFile...");
1501 if (!openFileWrite(ofs, fname))
1504 // make sure we are ready to export
1505 // this needs to be done before we validate
1507 updateMacroInstances(OutputUpdate);
1509 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1513 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1517 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1518 OutputParams const & runparams,
1519 bool const only_body) const
1521 LaTeXFeatures features(*this, params(), runparams);
1526 DocumentClass const & tclass = params().documentClass();
1527 string const top_element = tclass.latexname();
1530 if (runparams.flavor == OutputParams::XML)
1531 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1534 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1537 if (! tclass.class_header().empty())
1538 os << from_ascii(tclass.class_header());
1539 else if (runparams.flavor == OutputParams::XML)
1540 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1541 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1543 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1545 docstring preamble = from_utf8(params().preamble);
1546 if (runparams.flavor != OutputParams::XML ) {
1547 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1548 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1549 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1550 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1553 string const name = runparams.nice
1554 ? changeExtension(absFileName(), ".sgml") : fname;
1555 preamble += features.getIncludedFiles(name);
1556 preamble += features.getLyXSGMLEntities();
1558 if (!preamble.empty()) {
1559 os << "\n [ " << preamble << " ]";
1564 string top = top_element;
1566 if (runparams.flavor == OutputParams::XML)
1567 top += params().language->code();
1569 top += params().language->code().substr(0, 2);
1572 if (!params().options.empty()) {
1574 top += params().options;
1577 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1578 << " file was created by LyX " << lyx_version
1579 << "\n See http://www.lyx.org/ for more information -->\n";
1581 params().documentClass().counters().reset();
1583 sgml::openTag(os, top);
1585 docbookParagraphs(text(), *this, os, runparams);
1586 sgml::closeTag(os, top_element);
1590 void Buffer::makeLyXHTMLFile(FileName const & fname,
1591 OutputParams const & runparams,
1592 bool const body_only) const
1594 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1597 if (!openFileWrite(ofs, fname))
1600 // make sure we are ready to export
1601 // this has to be done before we validate
1602 updateBuffer(UpdateMaster, OutputUpdate);
1603 updateMacroInstances(OutputUpdate);
1605 writeLyXHTMLSource(ofs, runparams, body_only);
1609 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1613 void Buffer::writeLyXHTMLSource(odocstream & os,
1614 OutputParams const & runparams,
1615 bool const only_body) const
1617 LaTeXFeatures features(*this, params(), runparams);
1619 d->bibinfo_.makeCitationLabels(*this);
1622 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1623 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n"
1624 // FIXME Language should be set properly.
1625 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1627 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1628 // FIXME Presumably need to set this right
1629 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1631 docstring const & doctitle = features.htmlTitle();
1633 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1636 os << "\n<!-- Text Class Preamble -->\n"
1637 << features.getTClassHTMLPreamble()
1638 << "\n<!-- Preamble Snippets -->\n"
1639 << from_utf8(features.getPreambleSnippets());
1641 os << "\n<!-- Layout-provided Styles -->\n";
1642 docstring const styleinfo = features.getTClassHTMLStyles();
1643 if (!styleinfo.empty()) {
1644 os << "<style type='text/css'>\n"
1648 os << "</head>\n<body>\n";
1652 params().documentClass().counters().reset();
1653 xhtmlParagraphs(text(), *this, xs, runparams);
1655 os << "</body>\n</html>\n";
1659 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1660 // Other flags: -wall -v0 -x
1661 int Buffer::runChktex()
1665 // get LaTeX-Filename
1666 FileName const path(temppath());
1667 string const name = addName(path.absFileName(), latexName());
1668 string const org_path = filePath();
1670 PathChanger p(path); // path to LaTeX file
1671 message(_("Running chktex..."));
1673 // Generate the LaTeX file if neccessary
1674 OutputParams runparams(¶ms().encoding());
1675 runparams.flavor = OutputParams::LATEX;
1676 runparams.nice = false;
1677 runparams.linelen = lyxrc.plaintext_linelen;
1678 makeLaTeXFile(FileName(name), org_path, runparams);
1681 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1682 int const res = chktex.run(terr); // run chktex
1685 Alert::error(_("chktex failure"),
1686 _("Could not run chktex successfully."));
1687 } else if (res > 0) {
1688 ErrorList & errlist = d->errorLists["ChkTeX"];
1690 bufferErrors(terr, errlist);
1701 void Buffer::validate(LaTeXFeatures & features) const
1703 params().validate(features);
1705 for_each(paragraphs().begin(), paragraphs().end(),
1706 bind(&Paragraph::validate, _1, ref(features)));
1708 if (lyxerr.debugging(Debug::LATEX)) {
1709 features.showStruct();
1714 void Buffer::getLabelList(vector<docstring> & list) const
1716 // If this is a child document, use the master's list instead.
1718 masterBuffer()->getLabelList(list);
1723 Toc & toc = d->toc_backend.toc("label");
1724 TocIterator toc_it = toc.begin();
1725 TocIterator end = toc.end();
1726 for (; toc_it != end; ++toc_it) {
1727 if (toc_it->depth() == 0)
1728 list.push_back(toc_it->str());
1733 void Buffer::updateBibfilesCache(UpdateScope scope) const
1735 // FIXME This is probably unnecssary, given where we call this.
1736 // If this is a child document, use the parent's cache instead.
1737 if (parent() && scope != UpdateChildOnly) {
1738 masterBuffer()->updateBibfilesCache();
1742 d->bibfiles_cache_.clear();
1743 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1744 if (it->lyxCode() == BIBTEX_CODE) {
1745 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1746 support::FileNameList const bibfiles = inset.getBibFiles();
1747 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1750 } else if (it->lyxCode() == INCLUDE_CODE) {
1751 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1752 Buffer const * const incbuf = inset.getChildBuffer();
1755 support::FileNameList const & bibfiles =
1756 incbuf->getBibfilesCache(UpdateChildOnly);
1757 if (!bibfiles.empty()) {
1758 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1764 d->bibfile_cache_valid_ = true;
1765 d->bibinfo_cache_valid_ = false;
1766 d->cite_labels_valid_ = false;
1770 void Buffer::invalidateBibinfoCache() const
1772 d->bibinfo_cache_valid_ = false;
1773 d->cite_labels_valid_ = false;
1774 // also invalidate the cache for the parent buffer
1775 Buffer const * const pbuf = d->parent();
1777 pbuf->invalidateBibinfoCache();
1781 void Buffer::invalidateBibfileCache() const
1783 d->bibfile_cache_valid_ = false;
1784 d->bibinfo_cache_valid_ = false;
1785 d->cite_labels_valid_ = false;
1786 // also invalidate the cache for the parent buffer
1787 Buffer const * const pbuf = d->parent();
1789 pbuf->invalidateBibfileCache();
1793 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1795 // FIXME This is probably unnecessary, given where we call this.
1796 // If this is a child document, use the master's cache instead.
1797 Buffer const * const pbuf = masterBuffer();
1798 if (pbuf != this && scope != UpdateChildOnly)
1799 return pbuf->getBibfilesCache();
1801 if (!d->bibfile_cache_valid_)
1802 this->updateBibfilesCache(scope);
1804 return d->bibfiles_cache_;
1808 BiblioInfo const & Buffer::masterBibInfo() const
1810 Buffer const * const tmp = masterBuffer();
1812 return tmp->masterBibInfo();
1817 void Buffer::checkIfBibInfoCacheIsValid() const
1819 // use the master's cache
1820 Buffer const * const tmp = masterBuffer();
1822 tmp->checkIfBibInfoCacheIsValid();
1826 // compare the cached timestamps with the actual ones.
1827 FileNameList const & bibfiles_cache = getBibfilesCache();
1828 FileNameList::const_iterator ei = bibfiles_cache.begin();
1829 FileNameList::const_iterator en = bibfiles_cache.end();
1830 for (; ei != en; ++ ei) {
1831 time_t lastw = ei->lastModified();
1832 time_t prevw = d->bibfile_status_[*ei];
1833 if (lastw != prevw) {
1834 d->bibinfo_cache_valid_ = false;
1835 d->cite_labels_valid_ = false;
1836 d->bibfile_status_[*ei] = lastw;
1842 void Buffer::reloadBibInfoCache() const
1844 // use the master's cache
1845 Buffer const * const tmp = masterBuffer();
1847 tmp->reloadBibInfoCache();
1851 checkIfBibInfoCacheIsValid();
1852 if (d->bibinfo_cache_valid_)
1855 d->bibinfo_.clear();
1857 d->bibinfo_cache_valid_ = true;
1861 void Buffer::collectBibKeys() const
1863 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1864 it->collectBibKeys(it);
1868 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1870 Buffer const * tmp = masterBuffer();
1871 BiblioInfo & masterbi = (tmp == this) ?
1872 d->bibinfo_ : tmp->d->bibinfo_;
1873 masterbi.mergeBiblioInfo(bi);
1877 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1879 Buffer const * tmp = masterBuffer();
1880 BiblioInfo & masterbi = (tmp == this) ?
1881 d->bibinfo_ : tmp->d->bibinfo_;
1886 bool Buffer::citeLabelsValid() const
1888 return masterBuffer()->d->cite_labels_valid_;
1892 bool Buffer::isDepClean(string const & name) const
1894 DepClean::const_iterator const it = d->dep_clean.find(name);
1895 if (it == d->dep_clean.end())
1901 void Buffer::markDepClean(string const & name)
1903 d->dep_clean[name] = true;
1907 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1910 // FIXME? if there is an Buffer LFUN that can be dispatched even
1911 // if internal, put a switch '(cmd.action)' here.
1917 switch (cmd.action()) {
1919 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1920 flag.setOnOff(isReadonly());
1923 // FIXME: There is need for a command-line import.
1924 //case LFUN_BUFFER_IMPORT:
1926 case LFUN_BUFFER_AUTO_SAVE:
1929 case LFUN_BUFFER_EXPORT_CUSTOM:
1930 // FIXME: Nothing to check here?
1933 case LFUN_BUFFER_EXPORT: {
1934 docstring const arg = cmd.argument();
1935 enable = arg == "custom" || params().isExportable(to_utf8(arg));
1937 flag.message(bformat(
1938 _("Don't know how to export to format: %1$s"), arg));
1942 case LFUN_BUFFER_CHKTEX:
1943 enable = params().isLatex() && !lyxrc.chktex_command.empty();
1946 case LFUN_BUILD_PROGRAM:
1947 enable = params().isExportable("program");
1950 case LFUN_BRANCH_ACTIVATE:
1951 case LFUN_BRANCH_DEACTIVATE: {
1952 BranchList const & branchList = params().branchlist();
1953 docstring const branchName = cmd.argument();
1954 enable = !branchName.empty() && branchList.find(branchName);
1958 case LFUN_BRANCH_ADD:
1959 case LFUN_BRANCHES_RENAME:
1960 case LFUN_BUFFER_PRINT:
1961 // if no Buffer is present, then of course we won't be called!
1964 case LFUN_BUFFER_LANGUAGE:
1965 enable = !isReadonly();
1971 flag.setEnabled(enable);
1976 void Buffer::dispatch(string const & command, DispatchResult & result)
1978 return dispatch(lyxaction.lookupFunc(command), result);
1982 // NOTE We can end up here even if we have no GUI, because we are called
1983 // by LyX::exec to handled command-line requests. So we may need to check
1984 // whether we have a GUI or not. The boolean use_gui holds this information.
1985 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1988 // FIXME? if there is an Buffer LFUN that can be dispatched even
1989 // if internal, put a switch '(cmd.action())' here.
1990 dr.dispatched(false);
1993 string const argument = to_utf8(func.argument());
1994 // We'll set this back to false if need be.
1995 bool dispatched = true;
1996 undo().beginUndoGroup();
1998 switch (func.action()) {
1999 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2000 if (lyxvc().inUse())
2001 lyxvc().toggleReadOnly();
2003 setReadonly(!isReadonly());
2006 case LFUN_BUFFER_EXPORT: {
2007 bool success = doExport(argument, false, false);
2008 dr.setError(!success);
2010 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2015 case LFUN_BUILD_PROGRAM:
2016 doExport("program", true, false);
2019 case LFUN_BUFFER_CHKTEX:
2023 case LFUN_BUFFER_EXPORT_CUSTOM: {
2025 string command = split(argument, format_name, ' ');
2026 Format const * format = formats.getFormat(format_name);
2028 lyxerr << "Format \"" << format_name
2029 << "\" not recognized!"
2034 // The name of the file created by the conversion process
2037 // Output to filename
2038 if (format->name() == "lyx") {
2039 string const latexname = latexName(false);
2040 filename = changeExtension(latexname,
2041 format->extension());
2042 filename = addName(temppath(), filename);
2044 if (!writeFile(FileName(filename)))
2048 doExport(format_name, true, false, filename);
2051 // Substitute $$FName for filename
2052 if (!contains(command, "$$FName"))
2053 command = "( " + command + " ) < $$FName";
2054 command = subst(command, "$$FName", filename);
2056 // Execute the command in the background
2058 call.startscript(Systemcall::DontWait, command, filePath());
2062 // FIXME: There is need for a command-line import.
2064 case LFUN_BUFFER_IMPORT:
2069 case LFUN_BUFFER_AUTO_SAVE:
2071 resetAutosaveTimers();
2074 case LFUN_BRANCH_ADD: {
2075 docstring branch_name = func.argument();
2076 if (branch_name.empty()) {
2080 BranchList & branch_list = params().branchlist();
2081 vector<docstring> const branches =
2082 getVectorFromString(branch_name, branch_list.separator());
2084 for (vector<docstring>::const_iterator it = branches.begin();
2085 it != branches.end(); ++it) {
2087 Branch * branch = branch_list.find(branch_name);
2089 LYXERR0("Branch " << branch_name << " already exists.");
2093 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2095 branch_list.add(branch_name);
2096 branch = branch_list.find(branch_name);
2097 string const x11hexname = X11hexname(branch->color());
2098 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2099 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2101 dr.screenUpdate(Update::Force);
2109 case LFUN_BRANCH_ACTIVATE:
2110 case LFUN_BRANCH_DEACTIVATE: {
2111 BranchList & branchList = params().branchlist();
2112 docstring const branchName = func.argument();
2113 // the case without a branch name is handled elsewhere
2114 if (branchName.empty()) {
2118 Branch * branch = branchList.find(branchName);
2120 LYXERR0("Branch " << branchName << " does not exist.");
2122 docstring const msg =
2123 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2126 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2128 dr.screenUpdate(Update::Force);
2129 dr.forceBufferUpdate();
2134 case LFUN_BRANCHES_RENAME: {
2135 if (func.argument().empty())
2138 docstring const oldname = from_utf8(func.getArg(0));
2139 docstring const newname = from_utf8(func.getArg(1));
2140 InsetIterator it = inset_iterator_begin(inset());
2141 InsetIterator const end = inset_iterator_end(inset());
2142 bool success = false;
2143 for (; it != end; ++it) {
2144 if (it->lyxCode() == BRANCH_CODE) {
2145 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2146 if (ins.branch() == oldname) {
2147 undo().recordUndo(it);
2148 ins.rename(newname);
2153 if (it->lyxCode() == INCLUDE_CODE) {
2154 // get buffer of external file
2155 InsetInclude const & ins =
2156 static_cast<InsetInclude const &>(*it);
2157 Buffer * child = ins.getChildBuffer();
2160 child->dispatch(func, dr);
2165 dr.screenUpdate(Update::Force);
2166 dr.forceBufferUpdate();
2171 case LFUN_BUFFER_PRINT: {
2172 // we'll assume there's a problem until we succeed
2174 string target = func.getArg(0);
2175 string target_name = func.getArg(1);
2176 string command = func.getArg(2);
2179 || target_name.empty()
2180 || command.empty()) {
2181 LYXERR0("Unable to parse " << func.argument());
2182 docstring const msg =
2183 bformat(_("Unable to parse \"%1$s\""), func.argument());
2187 if (target != "printer" && target != "file") {
2188 LYXERR0("Unrecognized target \"" << target << '"');
2189 docstring const msg =
2190 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2195 bool const update_unincluded =
2196 params().maintain_unincluded_children
2197 && !params().getIncludedChildren().empty();
2198 if (!doExport("dvi", true, update_unincluded)) {
2199 showPrintError(absFileName());
2200 dr.setMessage(_("Error exporting to DVI."));
2204 // Push directory path.
2205 string const path = temppath();
2206 // Prevent the compiler from optimizing away p
2210 // there are three cases here:
2211 // 1. we print to a file
2212 // 2. we print directly to a printer
2213 // 3. we print using a spool command (print to file first)
2216 string const dviname = changeExtension(latexName(true), "dvi");
2218 if (target == "printer") {
2219 if (!lyxrc.print_spool_command.empty()) {
2220 // case 3: print using a spool
2221 string const psname = changeExtension(dviname,".ps");
2222 command += ' ' + lyxrc.print_to_file
2225 + quoteName(dviname);
2227 string command2 = lyxrc.print_spool_command + ' ';
2228 if (target_name != "default") {
2229 command2 += lyxrc.print_spool_printerprefix
2233 command2 += quoteName(psname);
2235 // If successful, then spool command
2236 res = one.startscript(Systemcall::Wait, command,
2240 // If there's no GUI, we have to wait on this command. Otherwise,
2241 // LyX deletes the temporary directory, and with it the spooled
2242 // file, before it can be printed!!
2243 Systemcall::Starttype stype = use_gui ?
2244 Systemcall::DontWait : Systemcall::Wait;
2245 res = one.startscript(stype, command2,
2249 // case 2: print directly to a printer
2250 if (target_name != "default")
2251 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2253 Systemcall::Starttype stype = use_gui ?
2254 Systemcall::DontWait : Systemcall::Wait;
2255 res = one.startscript(stype, command +
2256 quoteName(dviname), filePath());
2260 // case 1: print to a file
2261 FileName const filename(makeAbsPath(target_name, filePath()));
2262 FileName const dvifile(makeAbsPath(dviname, path));
2263 if (filename.exists()) {
2264 docstring text = bformat(
2265 _("The file %1$s already exists.\n\n"
2266 "Do you want to overwrite that file?"),
2267 makeDisplayPath(filename.absFileName()));
2268 if (Alert::prompt(_("Overwrite file?"),
2269 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2272 command += ' ' + lyxrc.print_to_file
2273 + quoteName(filename.toFilesystemEncoding())
2275 + quoteName(dvifile.toFilesystemEncoding());
2277 Systemcall::Starttype stype = use_gui ?
2278 Systemcall::DontWait : Systemcall::Wait;
2279 res = one.startscript(stype, command, filePath());
2285 dr.setMessage(_("Error running external commands."));
2286 showPrintError(absFileName());
2291 case LFUN_BUFFER_LANGUAGE: {
2292 Language const * oldL = params().language;
2293 Language const * newL = languages.getLanguage(argument);
2294 if (!newL || oldL == newL)
2296 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2297 changeLanguage(oldL, newL);
2298 dr.forceBufferUpdate();
2307 dr.dispatched(dispatched);
2308 undo().endUndoGroup();
2312 void Buffer::changeLanguage(Language const * from, Language const * to)
2314 LASSERT(from, /**/);
2317 for_each(par_iterator_begin(),
2319 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2323 bool Buffer::isMultiLingual() const
2325 ParConstIterator end = par_iterator_end();
2326 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2327 if (it->isMultiLingual(params()))
2334 std::set<Language const *> Buffer::getLanguages() const
2336 std::set<Language const *> languages;
2337 getLanguages(languages);
2342 void Buffer::getLanguages(std::set<Language const *> & languages) const
2344 ParConstIterator end = par_iterator_end();
2345 // add the buffer language, even if it's not actively used
2346 languages.insert(language());
2347 // iterate over the paragraphs
2348 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2349 it->getLanguages(languages);
2351 ListOfBuffers clist = getDescendents();
2352 ListOfBuffers::const_iterator cit = clist.begin();
2353 ListOfBuffers::const_iterator const cen = clist.end();
2354 for (; cit != cen; ++cit)
2355 (*cit)->getLanguages(languages);
2359 DocIterator Buffer::getParFromID(int const id) const
2361 Buffer * buf = const_cast<Buffer *>(this);
2363 // John says this is called with id == -1 from undo
2364 lyxerr << "getParFromID(), id: " << id << endl;
2365 return doc_iterator_end(buf);
2368 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2369 if (it.paragraph().id() == id)
2372 return doc_iterator_end(buf);
2376 bool Buffer::hasParWithID(int const id) const
2378 return !getParFromID(id).atEnd();
2382 ParIterator Buffer::par_iterator_begin()
2384 return ParIterator(doc_iterator_begin(this));
2388 ParIterator Buffer::par_iterator_end()
2390 return ParIterator(doc_iterator_end(this));
2394 ParConstIterator Buffer::par_iterator_begin() const
2396 return ParConstIterator(doc_iterator_begin(this));
2400 ParConstIterator Buffer::par_iterator_end() const
2402 return ParConstIterator(doc_iterator_end(this));
2406 Language const * Buffer::language() const
2408 return params().language;
2412 docstring const Buffer::B_(string const & l10n) const
2414 return params().B_(l10n);
2418 bool Buffer::isClean() const
2420 return d->lyx_clean;
2424 bool Buffer::isExternallyModified(CheckMethod method) const
2426 LASSERT(d->filename.exists(), /**/);
2427 // if method == timestamp, check timestamp before checksum
2428 return (method == checksum_method
2429 || d->timestamp_ != d->filename.lastModified())
2430 && d->checksum_ != d->filename.checksum();
2434 void Buffer::saveCheckSum() const
2436 FileName const & file = d->filename;
2439 if (file.exists()) {
2440 d->timestamp_ = file.lastModified();
2441 d->checksum_ = file.checksum();
2443 // in the case of save to a new file.
2450 void Buffer::markClean() const
2452 if (!d->lyx_clean) {
2453 d->lyx_clean = true;
2456 // if the .lyx file has been saved, we don't need an
2458 d->bak_clean = true;
2459 d->undo_.markDirty();
2463 void Buffer::setUnnamed(bool flag)
2469 bool Buffer::isUnnamed() const
2476 /// Don't check unnamed, here: isInternal() is used in
2477 /// newBuffer(), where the unnamed flag has not been set by anyone
2478 /// yet. Also, for an internal buffer, there should be no need for
2479 /// retrieving fileName() nor for checking if it is unnamed or not.
2480 bool Buffer::isInternal() const
2482 return fileName().extension() == "internal";
2486 void Buffer::markDirty()
2489 d->lyx_clean = false;
2492 d->bak_clean = false;
2494 DepClean::iterator it = d->dep_clean.begin();
2495 DepClean::const_iterator const end = d->dep_clean.end();
2497 for (; it != end; ++it)
2502 FileName Buffer::fileName() const
2508 string Buffer::absFileName() const
2510 return d->filename.absFileName();
2514 string Buffer::filePath() const
2516 return d->filename.onlyPath().absFileName() + "/";
2520 bool Buffer::isReadonly() const
2522 return d->read_only;
2526 void Buffer::setParent(Buffer const * buffer)
2528 // Avoids recursive include.
2529 d->setParent(buffer == this ? 0 : buffer);
2534 Buffer const * Buffer::parent() const
2540 ListOfBuffers Buffer::allRelatives() const
2542 ListOfBuffers lb = masterBuffer()->getDescendents();
2543 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2548 Buffer const * Buffer::masterBuffer() const
2550 // FIXME Should be make sure we are not in some kind
2551 // of recursive include? A -> B -> A will crash this.
2552 Buffer const * const pbuf = d->parent();
2556 return pbuf->masterBuffer();
2560 bool Buffer::isChild(Buffer * child) const
2562 return d->children_positions.find(child) != d->children_positions.end();
2566 DocIterator Buffer::firstChildPosition(Buffer const * child)
2568 Impl::BufferPositionMap::iterator it;
2569 it = d->children_positions.find(child);
2570 if (it == d->children_positions.end())
2571 return DocIterator(this);
2576 bool Buffer::hasChildren() const
2578 return !d->children_positions.empty();
2582 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2584 // loop over children
2585 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2586 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2587 for (; it != end; ++it) {
2588 Buffer * child = const_cast<Buffer *>(it->first);
2590 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2591 if (bit != clist.end())
2593 clist.push_back(child);
2595 // there might be grandchildren
2596 child->collectChildren(clist, true);
2601 ListOfBuffers Buffer::getChildren() const
2604 collectChildren(v, false);
2609 ListOfBuffers Buffer::getDescendents() const
2612 collectChildren(v, true);
2617 template<typename M>
2618 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2623 typename M::const_iterator it = m.lower_bound(x);
2624 if (it == m.begin())
2632 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2633 DocIterator const & pos) const
2635 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2637 // if paragraphs have no macro context set, pos will be empty
2641 // we haven't found anything yet
2642 DocIterator bestPos = owner_->par_iterator_begin();
2643 MacroData const * bestData = 0;
2645 // find macro definitions for name
2646 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2647 if (nameIt != macros.end()) {
2648 // find last definition in front of pos or at pos itself
2649 PositionScopeMacroMap::const_iterator it
2650 = greatest_below(nameIt->second, pos);
2651 if (it != nameIt->second.end()) {
2653 // scope ends behind pos?
2654 if (pos < it->second.first) {
2655 // Looks good, remember this. If there
2656 // is no external macro behind this,
2657 // we found the right one already.
2658 bestPos = it->first;
2659 bestData = &it->second.second;
2663 // try previous macro if there is one
2664 if (it == nameIt->second.begin())
2671 // find macros in included files
2672 PositionScopeBufferMap::const_iterator it
2673 = greatest_below(position_to_children, pos);
2674 if (it == position_to_children.end())
2675 // no children before
2679 // do we know something better (i.e. later) already?
2680 if (it->first < bestPos )
2683 // scope ends behind pos?
2684 if (pos < it->second.first
2685 && (cloned_buffer_ ||
2686 theBufferList().isLoaded(it->second.second))) {
2687 // look for macro in external file
2689 MacroData const * data
2690 = it->second.second->getMacro(name, false);
2693 bestPos = it->first;
2699 // try previous file if there is one
2700 if (it == position_to_children.begin())
2705 // return the best macro we have found
2710 MacroData const * Buffer::getMacro(docstring const & name,
2711 DocIterator const & pos, bool global) const
2716 // query buffer macros
2717 MacroData const * data = d->getBufferMacro(name, pos);
2721 // If there is a master buffer, query that
2722 Buffer const * const pbuf = d->parent();
2724 d->macro_lock = true;
2725 MacroData const * macro = pbuf->getMacro(
2726 name, *this, false);
2727 d->macro_lock = false;
2733 data = MacroTable::globalMacros().get(name);
2742 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2744 // set scope end behind the last paragraph
2745 DocIterator scope = par_iterator_begin();
2746 scope.pit() = scope.lastpit() + 1;
2748 return getMacro(name, scope, global);
2752 MacroData const * Buffer::getMacro(docstring const & name,
2753 Buffer const & child, bool global) const
2755 // look where the child buffer is included first
2756 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2757 if (it == d->children_positions.end())
2760 // check for macros at the inclusion position
2761 return getMacro(name, it->second, global);
2765 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2767 pit_type const lastpit = it.lastpit();
2769 // look for macros in each paragraph
2770 while (it.pit() <= lastpit) {
2771 Paragraph & par = it.paragraph();
2773 // iterate over the insets of the current paragraph
2774 InsetList const & insets = par.insetList();
2775 InsetList::const_iterator iit = insets.begin();
2776 InsetList::const_iterator end = insets.end();
2777 for (; iit != end; ++iit) {
2778 it.pos() = iit->pos;
2780 // is it a nested text inset?
2781 if (iit->inset->asInsetText()) {
2782 // Inset needs its own scope?
2783 InsetText const * itext = iit->inset->asInsetText();
2784 bool newScope = itext->isMacroScope();
2786 // scope which ends just behind the inset
2787 DocIterator insetScope = it;
2790 // collect macros in inset
2791 it.push_back(CursorSlice(*iit->inset));
2792 updateMacros(it, newScope ? insetScope : scope);
2797 if (iit->inset->asInsetTabular()) {
2798 CursorSlice slice(*iit->inset);
2799 size_t const numcells = slice.nargs();
2800 for (; slice.idx() < numcells; slice.forwardIdx()) {
2801 it.push_back(slice);
2802 updateMacros(it, scope);
2808 // is it an external file?
2809 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2810 // get buffer of external file
2811 InsetInclude const & inset =
2812 static_cast<InsetInclude const &>(*iit->inset);
2814 Buffer * child = inset.getChildBuffer();
2819 // register its position, but only when it is
2820 // included first in the buffer
2821 if (children_positions.find(child) ==
2822 children_positions.end())
2823 children_positions[child] = it;
2825 // register child with its scope
2826 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2830 InsetMath * im = iit->inset->asInsetMath();
2831 if (doing_export && im) {
2832 InsetMathHull * hull = im->asHullInset();
2834 hull->recordLocation(it);
2837 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2841 MathMacroTemplate & macroTemplate =
2842 *iit->inset->asInsetMath()->asMacroTemplate();
2843 MacroContext mc(owner_, it);
2844 macroTemplate.updateToContext(mc);
2847 bool valid = macroTemplate.validMacro();
2848 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2849 // then the BufferView's cursor will be invalid in
2850 // some cases which leads to crashes.
2855 // FIXME (Abdel), I don't understandt why we pass 'it' here
2856 // instead of 'macroTemplate' defined above... is this correct?
2857 macros[macroTemplate.name()][it] =
2858 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2868 void Buffer::updateMacros() const
2873 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2875 // start with empty table
2877 d->children_positions.clear();
2878 d->position_to_children.clear();
2880 // Iterate over buffer, starting with first paragraph
2881 // The scope must be bigger than any lookup DocIterator
2882 // later. For the global lookup, lastpit+1 is used, hence
2883 // we use lastpit+2 here.
2884 DocIterator it = par_iterator_begin();
2885 DocIterator outerScope = it;
2886 outerScope.pit() = outerScope.lastpit() + 2;
2887 d->updateMacros(it, outerScope);
2891 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2893 InsetIterator it = inset_iterator_begin(inset());
2894 InsetIterator const end = inset_iterator_end(inset());
2895 for (; it != end; ++it) {
2896 if (it->lyxCode() == BRANCH_CODE) {
2897 InsetBranch & br = static_cast<InsetBranch &>(*it);
2898 docstring const name = br.branch();
2899 if (!from_master && !params().branchlist().find(name))
2900 result.push_back(name);
2901 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2902 result.push_back(name);
2905 if (it->lyxCode() == INCLUDE_CODE) {
2906 // get buffer of external file
2907 InsetInclude const & ins =
2908 static_cast<InsetInclude const &>(*it);
2909 Buffer * child = ins.getChildBuffer();
2912 child->getUsedBranches(result, true);
2915 // remove duplicates
2920 void Buffer::updateMacroInstances(UpdateType utype) const
2922 LYXERR(Debug::MACROS, "updateMacroInstances for "
2923 << d->filename.onlyFileName());
2924 DocIterator it = doc_iterator_begin(this);
2926 DocIterator const end = doc_iterator_end(this);
2927 for (; it != end; it.forwardInset()) {
2928 // look for MathData cells in InsetMathNest insets
2929 InsetMath * minset = it.nextInset()->asInsetMath();
2933 // update macro in all cells of the InsetMathNest
2934 DocIterator::idx_type n = minset->nargs();
2935 MacroContext mc = MacroContext(this, it);
2936 for (DocIterator::idx_type i = 0; i < n; ++i) {
2937 MathData & data = minset->cell(i);
2938 data.updateMacros(0, mc, utype);
2944 void Buffer::listMacroNames(MacroNameSet & macros) const
2949 d->macro_lock = true;
2951 // loop over macro names
2952 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2953 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2954 for (; nameIt != nameEnd; ++nameIt)
2955 macros.insert(nameIt->first);
2957 // loop over children
2958 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2959 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2960 for (; it != end; ++it)
2961 it->first->listMacroNames(macros);
2964 Buffer const * const pbuf = d->parent();
2966 pbuf->listMacroNames(macros);
2968 d->macro_lock = false;
2972 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2974 Buffer const * const pbuf = d->parent();
2979 pbuf->listMacroNames(names);
2982 MacroNameSet::iterator it = names.begin();
2983 MacroNameSet::iterator end = names.end();
2984 for (; it != end; ++it) {
2986 MacroData const * data =
2987 pbuf->getMacro(*it, *this, false);
2989 macros.insert(data);
2991 // we cannot access the original MathMacroTemplate anymore
2992 // here to calls validate method. So we do its work here manually.
2993 // FIXME: somehow make the template accessible here.
2994 if (data->optionals() > 0)
2995 features.require("xargs");
3001 Buffer::References & Buffer::references(docstring const & label)
3004 return const_cast<Buffer *>(masterBuffer())->references(label);
3006 RefCache::iterator it = d->ref_cache_.find(label);
3007 if (it != d->ref_cache_.end())
3008 return it->second.second;
3010 static InsetLabel const * dummy_il = 0;
3011 static References const dummy_refs;
3012 it = d->ref_cache_.insert(
3013 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3014 return it->second.second;
3018 Buffer::References const & Buffer::references(docstring const & label) const
3020 return const_cast<Buffer *>(this)->references(label);
3024 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3026 masterBuffer()->d->ref_cache_[label].first = il;
3030 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3032 return masterBuffer()->d->ref_cache_[label].first;
3036 void Buffer::clearReferenceCache() const
3039 d->ref_cache_.clear();
3043 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3046 //FIXME: This does not work for child documents yet.
3047 LASSERT(code == CITE_CODE, /**/);
3049 reloadBibInfoCache();
3051 // Check if the label 'from' appears more than once
3052 BiblioInfo const & keys = masterBibInfo();
3053 BiblioInfo::const_iterator bit = keys.begin();
3054 BiblioInfo::const_iterator bend = keys.end();
3055 vector<docstring> labels;
3057 for (; bit != bend; ++bit)
3059 labels.push_back(bit->first);
3061 if (count(labels.begin(), labels.end(), from) > 1)
3064 string const paramName = "key";
3065 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3066 if (it->lyxCode() == code) {
3067 InsetCommand * inset = it->asInsetCommand();
3070 docstring const oldValue = inset->getParam(paramName);
3071 if (oldValue == from)
3072 inset->setParam(paramName, to);
3078 void Buffer::getSourceCode(odocstream & os, string const format,
3079 pit_type par_begin, pit_type par_end,
3080 bool full_source) const
3082 OutputParams runparams(¶ms().encoding());
3083 runparams.nice = true;
3084 runparams.flavor = params().getOutputFlavor(format);
3085 runparams.linelen = lyxrc.plaintext_linelen;
3086 // No side effect of file copying and image conversion
3087 runparams.dryrun = true;
3090 os << "% " << _("Preview source code") << "\n\n";
3092 d->texrow.newline();
3093 d->texrow.newline();
3094 if (params().isDocBook())
3095 writeDocBookSource(os, absFileName(), runparams, false);
3096 else if (runparams.flavor == OutputParams::HTML)
3097 writeLyXHTMLSource(os, runparams, false);
3099 // latex or literate
3100 otexstream ots(os, d->texrow);
3101 writeLaTeXSource(ots, string(), runparams, true, true);
3104 runparams.par_begin = par_begin;
3105 runparams.par_end = par_end;
3106 if (par_begin + 1 == par_end) {
3108 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3112 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3113 convert<docstring>(par_begin),
3114 convert<docstring>(par_end - 1))
3121 // output paragraphs
3122 if (params().isDocBook())
3123 docbookParagraphs(text(), *this, os, runparams);
3124 else if (runparams.flavor == OutputParams::HTML) {
3126 xhtmlParagraphs(text(), *this, xs, runparams);
3128 // latex or literate
3129 otexstream ots(os, texrow);
3130 latexParagraphs(*this, text(), ots, runparams);
3136 ErrorList & Buffer::errorList(string const & type) const
3138 static ErrorList emptyErrorList;
3139 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3140 if (it == d->errorLists.end())
3141 return emptyErrorList;
3147 void Buffer::updateTocItem(std::string const & type,
3148 DocIterator const & dit) const
3151 d->gui_->updateTocItem(type, dit);
3155 void Buffer::structureChanged() const
3158 d->gui_->structureChanged();
3162 void Buffer::errors(string const & err, bool from_master) const
3165 d->gui_->errors(err, from_master);
3169 void Buffer::message(docstring const & msg) const
3172 d->gui_->message(msg);
3176 void Buffer::setBusy(bool on) const
3179 d->gui_->setBusy(on);
3183 void Buffer::updateTitles() const
3186 d->wa_->updateTitles();
3190 void Buffer::resetAutosaveTimers() const
3193 d->gui_->resetAutosaveTimers();
3197 bool Buffer::hasGuiDelegate() const
3203 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3212 class AutoSaveBuffer : public ForkedProcess {
3215 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3216 : buffer_(buffer), fname_(fname) {}
3218 virtual shared_ptr<ForkedProcess> clone() const
3220 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3225 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3226 from_utf8(fname_.absFileName())));
3227 return run(DontWait);
3231 virtual int generateChild();
3233 Buffer const & buffer_;
3238 int AutoSaveBuffer::generateChild()
3240 #if defined(__APPLE__)
3241 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3242 * We should use something else like threads.
3244 * Since I do not know how to determine at run time what is the OS X
3245 * version, I just disable forking altogether for now (JMarc)
3247 pid_t const pid = -1;
3249 // tmp_ret will be located (usually) in /tmp
3250 // will that be a problem?
3251 // Note that this calls ForkedCalls::fork(), so it's
3252 // ok cross-platform.
3253 pid_t const pid = fork();
3254 // If you want to debug the autosave
3255 // you should set pid to -1, and comment out the fork.
3256 if (pid != 0 && pid != -1)
3260 // pid = -1 signifies that lyx was unable
3261 // to fork. But we will do the save
3263 bool failed = false;
3264 FileName const tmp_ret = FileName::tempName("lyxauto");
3265 if (!tmp_ret.empty()) {
3266 buffer_.writeFile(tmp_ret);
3267 // assume successful write of tmp_ret
3268 if (!tmp_ret.moveTo(fname_))
3274 // failed to write/rename tmp_ret so try writing direct
3275 if (!buffer_.writeFile(fname_)) {
3276 // It is dangerous to do this in the child,
3277 // but safe in the parent, so...
3278 if (pid == -1) // emit message signal.
3279 buffer_.message(_("Autosave failed!"));
3283 if (pid == 0) // we are the child so...
3292 FileName Buffer::getEmergencyFileName() const
3294 return FileName(d->filename.absFileName() + ".emergency");
3298 FileName Buffer::getAutosaveFileName() const
3300 // if the document is unnamed try to save in the backup dir, else
3301 // in the default document path, and as a last try in the filePath,
3302 // which will most often be the temporary directory
3305 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3306 : lyxrc.backupdir_path;
3307 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3310 string const fname = "#" + d->filename.onlyFileName() + "#";
3312 return makeAbsPath(fname, fpath);
3316 void Buffer::removeAutosaveFile() const
3318 FileName const f = getAutosaveFileName();
3324 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3326 FileName const newauto = getAutosaveFileName();
3328 if (newauto != oldauto && oldauto.exists())
3329 if (!oldauto.moveTo(newauto))
3330 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3334 bool Buffer::autoSave() const
3336 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3337 if (buf->d->bak_clean || isReadonly())
3340 message(_("Autosaving current document..."));
3341 buf->d->bak_clean = true;
3343 FileName const fname = getAutosaveFileName();
3344 if (d->cloned_buffer_) {
3345 // If this buffer is cloned, we assume that
3346 // we are running in a separate thread already.
3347 FileName const tmp_ret = FileName::tempName("lyxauto");
3348 if (!tmp_ret.empty()) {
3350 // assume successful write of tmp_ret
3351 if (tmp_ret.moveTo(fname))
3354 // failed to write/rename tmp_ret so try writing direct
3355 return writeFile(fname);
3357 /// This function is deprecated as the frontend needs to take care
3358 /// of cloning the buffer and autosaving it in another thread. It
3359 /// is still here to allow (QT_VERSION < 0x040400).
3360 AutoSaveBuffer autosave(*this, fname);
3368 // helper class, to guarantee this gets reset properly
3369 class MarkAsExporting {
3371 MarkAsExporting(Buffer const * buf) : buf_(buf)
3373 LASSERT(buf_, /* */);
3374 buf_->setExportStatus(true);
3378 buf_->setExportStatus(false);
3381 Buffer const * const buf_;
3386 void Buffer::setExportStatus(bool e) const
3388 d->doing_export = e;
3389 ListOfBuffers clist = getDescendents();
3390 ListOfBuffers::const_iterator cit = clist.begin();
3391 ListOfBuffers::const_iterator const cen = clist.end();
3392 for (; cit != cen; ++cit)
3393 (*cit)->d->doing_export = e;
3397 bool Buffer::isExporting() const
3399 return d->doing_export;
3403 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3404 bool includeall, string & result_file) const
3406 MarkAsExporting exporting(this);
3407 string backend_format;
3408 OutputParams runparams(¶ms().encoding());
3409 runparams.flavor = OutputParams::LATEX;
3410 runparams.linelen = lyxrc.plaintext_linelen;
3411 runparams.includeall = includeall;
3412 vector<string> backs = params().backends();
3413 Converters converters = theConverters();
3414 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3415 // Get shortest path to format
3416 converters.buildGraph();
3417 Graph::EdgePath path;
3418 for (vector<string>::const_iterator it = backs.begin();
3419 it != backs.end(); ++it) {
3420 Graph::EdgePath p = converters.getPath(*it, format);
3421 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3422 backend_format = *it;
3427 if (!put_in_tempdir) {
3428 // Only show this alert if this is an export to a non-temporary
3429 // file (not for previewing).
3430 Alert::error(_("Couldn't export file"), bformat(
3431 _("No information for exporting the format %1$s."),
3432 formats.prettyName(format)));
3436 runparams.flavor = converters.getFlavor(path);
3439 backend_format = format;
3440 // FIXME: Don't hardcode format names here, but use a flag
3441 if (backend_format == "pdflatex")
3442 runparams.flavor = OutputParams::PDFLATEX;
3443 else if (backend_format == "luatex")
3444 runparams.flavor = OutputParams::LUATEX;
3445 else if (backend_format == "xetex")
3446 runparams.flavor = OutputParams::XETEX;
3449 string filename = latexName(false);
3450 filename = addName(temppath(), filename);
3451 filename = changeExtension(filename,
3452 formats.extension(backend_format));
3454 // Plain text backend
3455 if (backend_format == "text") {
3456 runparams.flavor = OutputParams::TEXT;
3457 writePlaintextFile(*this, FileName(filename), runparams);
3460 else if (backend_format == "xhtml") {
3461 runparams.flavor = OutputParams::HTML;
3462 switch (params().html_math_output) {
3463 case BufferParams::MathML:
3464 runparams.math_flavor = OutputParams::MathAsMathML;
3466 case BufferParams::HTML:
3467 runparams.math_flavor = OutputParams::MathAsHTML;
3469 case BufferParams::Images:
3470 runparams.math_flavor = OutputParams::MathAsImages;
3472 case BufferParams::LaTeX:
3473 runparams.math_flavor = OutputParams::MathAsLaTeX;
3476 makeLyXHTMLFile(FileName(filename), runparams);
3477 } else if (backend_format == "lyx")
3478 writeFile(FileName(filename));
3480 else if (params().isDocBook()) {
3481 runparams.nice = !put_in_tempdir;
3482 makeDocBookFile(FileName(filename), runparams);
3485 else if (backend_format == format) {
3486 runparams.nice = true;
3487 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3488 if (d->cloned_buffer_) {
3489 d->cloned_buffer_->d->errorLists["Export"] =
3490 d->errorLists["Export"];
3494 } else if (!lyxrc.tex_allows_spaces
3495 && contains(filePath(), ' ')) {
3496 Alert::error(_("File name error"),
3497 _("The directory path to the document cannot contain spaces."));
3500 runparams.nice = false;
3501 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3502 if (d->cloned_buffer_) {
3503 d->cloned_buffer_->d->errorLists["Export"] =
3504 d->errorLists["Export"];
3510 string const error_type = (format == "program")
3511 ? "Build" : params().bufferFormat();
3512 ErrorList & error_list = d->errorLists[error_type];
3513 string const ext = formats.extension(format);
3514 FileName const tmp_result_file(changeExtension(filename, ext));
3515 bool const success = converters.convert(this, FileName(filename),
3516 tmp_result_file, FileName(absFileName()), backend_format, format,
3519 // Emit the signal to show the error list or copy it back to the
3520 // cloned Buffer so that it can be emitted afterwards.
3521 if (format != backend_format) {
3522 if (d->cloned_buffer_) {
3523 d->cloned_buffer_->d->errorLists[error_type] =
3524 d->errorLists[error_type];
3527 // also to the children, in case of master-buffer-view
3528 ListOfBuffers clist = getDescendents();
3529 ListOfBuffers::const_iterator cit = clist.begin();
3530 ListOfBuffers::const_iterator const cen = clist.end();
3531 for (; cit != cen; ++cit) {
3532 if (d->cloned_buffer_) {
3533 // Enable reverse search by copying back the
3534 // texrow object to the cloned buffer.
3535 // FIXME: this is not thread safe.
3536 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3537 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3538 (*cit)->d->errorLists[error_type];
3540 (*cit)->errors(error_type, true);
3544 if (d->cloned_buffer_) {
3545 // Enable reverse dvi or pdf to work by copying back the texrow
3546 // object to the cloned buffer.
3547 // FIXME: There is a possibility of concurrent access to texrow
3548 // here from the main GUI thread that should be securized.
3549 d->cloned_buffer_->d->texrow = d->texrow;
3550 string const error_type = params().bufferFormat();
3551 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3557 if (put_in_tempdir) {
3558 result_file = tmp_result_file.absFileName();
3562 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3563 // We need to copy referenced files (e. g. included graphics
3564 // if format == "dvi") to the result dir.
3565 vector<ExportedFile> const files =
3566 runparams.exportdata->externalFiles(format);
3567 string const dest = onlyPath(result_file);
3568 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3569 : force_overwrite == ALL_FILES;
3570 CopyStatus status = use_force ? FORCE : SUCCESS;
3572 vector<ExportedFile>::const_iterator it = files.begin();
3573 vector<ExportedFile>::const_iterator const en = files.end();
3574 for (; it != en && status != CANCEL; ++it) {
3575 string const fmt = formats.getFormatFromFile(it->sourceName);
3576 status = copyFile(fmt, it->sourceName,
3577 makeAbsPath(it->exportName, dest),
3578 it->exportName, status == FORCE);
3581 if (status == CANCEL) {
3582 message(_("Document export cancelled."));
3583 } else if (tmp_result_file.exists()) {
3584 // Finally copy the main file
3585 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3586 : force_overwrite != NO_FILES;
3587 if (status == SUCCESS && use_force)
3589 status = copyFile(format, tmp_result_file,
3590 FileName(result_file), result_file,
3592 message(bformat(_("Document exported as %1$s "
3594 formats.prettyName(format),
3595 makeDisplayPath(result_file)));
3597 // This must be a dummy converter like fax (bug 1888)
3598 message(bformat(_("Document exported as %1$s"),
3599 formats.prettyName(format)));
3606 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3607 bool includeall) const
3610 // (1) export with all included children (omit \includeonly)
3611 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3613 // (2) export with included children only
3614 return doExport(format, put_in_tempdir, false, result_file);
3618 bool Buffer::preview(string const & format, bool includeall) const
3620 MarkAsExporting exporting(this);
3622 // (1) export with all included children (omit \includeonly)
3623 if (includeall && !doExport(format, true, true))
3625 // (2) export with included children only
3626 if (!doExport(format, true, false, result_file))
3628 return formats.view(*this, FileName(result_file), format);
3632 Buffer::ReadStatus Buffer::extractFromVC()
3634 bool const found = LyXVC::file_not_found_hook(d->filename);
3636 return ReadFileNotFound;
3637 if (!d->filename.isReadableFile())
3643 Buffer::ReadStatus Buffer::loadEmergency()
3645 FileName const emergencyFile = getEmergencyFileName();
3646 if (!emergencyFile.exists()
3647 || emergencyFile.lastModified() <= d->filename.lastModified())
3648 return ReadFileNotFound;
3650 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3651 docstring const text = bformat(_("An emergency save of the document "
3652 "%1$s exists.\n\nRecover emergency save?"), file);
3654 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3655 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3661 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3662 bool const success = (ret_llf == ReadSuccess);
3665 Alert::warning(_("File is read-only"),
3666 bformat(_("An emergency file is successfully loaded, "
3667 "but the original file %1$s is marked read-only. "
3668 "Please make sure to save the document as a different "
3669 "file."), from_utf8(d->filename.absFileName())));
3672 str = _("Document was successfully recovered.");
3674 str = _("Document was NOT successfully recovered.");
3675 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3676 makeDisplayPath(emergencyFile.absFileName()));
3678 int const del_emerg =
3679 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3680 _("&Remove"), _("&Keep"));
3681 if (del_emerg == 0) {
3682 emergencyFile.removeFile();
3684 Alert::warning(_("Emergency file deleted"),
3685 _("Do not forget to save your file now!"), true);
3687 return success ? ReadSuccess : ReadEmergencyFailure;
3690 int const del_emerg =
3691 Alert::prompt(_("Delete emergency file?"),
3692 _("Remove emergency file now?"), 1, 1,
3693 _("&Remove"), _("&Keep"));
3695 emergencyFile.removeFile();
3696 return ReadOriginal;
3706 Buffer::ReadStatus Buffer::loadAutosave()
3708 // Now check if autosave file is newer.
3709 FileName const autosaveFile = getAutosaveFileName();
3710 if (!autosaveFile.exists()
3711 || autosaveFile.lastModified() <= d->filename.lastModified())
3712 return ReadFileNotFound;
3714 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3715 docstring const text = bformat(_("The backup of the document %1$s "
3716 "is newer.\n\nLoad the backup instead?"), file);
3717 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3718 _("&Load backup"), _("Load &original"), _("&Cancel"));
3723 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3724 // the file is not saved if we load the autosave file.
3725 if (ret_llf == ReadSuccess) {
3727 Alert::warning(_("File is read-only"),
3728 bformat(_("A backup file is successfully loaded, "
3729 "but the original file %1$s is marked read-only. "
3730 "Please make sure to save the document as a "
3732 from_utf8(d->filename.absFileName())));
3737 return ReadAutosaveFailure;
3740 // Here we delete the autosave
3741 autosaveFile.removeFile();
3742 return ReadOriginal;
3750 Buffer::ReadStatus Buffer::loadLyXFile()
3752 if (!d->filename.isReadableFile()) {
3753 ReadStatus const ret_rvc = extractFromVC();
3754 if (ret_rvc != ReadSuccess)
3758 ReadStatus const ret_re = loadEmergency();
3759 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3762 ReadStatus const ret_ra = loadAutosave();
3763 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3766 return loadThisLyXFile(d->filename);
3770 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3772 return readFile(fn);
3776 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3778 TeXErrors::Errors::const_iterator it = terr.begin();
3779 TeXErrors::Errors::const_iterator end = terr.end();
3780 ListOfBuffers clist = getDescendents();
3781 ListOfBuffers::const_iterator cen = clist.end();
3783 for (; it != end; ++it) {
3786 int errorRow = it->error_in_line;
3787 Buffer const * buf = 0;
3789 if (it->child_name.empty())
3790 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3792 // The error occurred in a child
3793 ListOfBuffers::const_iterator cit = clist.begin();
3794 for (; cit != cen; ++cit) {
3795 string const child_name =
3796 DocFileName(changeExtension(
3797 (*cit)->absFileName(), "tex")).
3799 if (it->child_name != child_name)
3801 (*cit)->d->texrow.getIdFromRow(errorRow,
3802 id_start, pos_start);
3803 if (id_start != -1) {
3804 buf = d->cloned_buffer_
3805 ? (*cit)->d->cloned_buffer_->d->owner_
3806 : (*cit)->d->owner_;
3817 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
3818 } while (found && id_start == id_end && pos_start == pos_end);
3820 if (id_start != id_end) {
3821 // Next registered position is outside the inset where
3822 // the error occurred, so signal end-of-paragraph
3826 errorList.push_back(ErrorItem(it->error_desc,
3827 it->error_text, id_start, pos_start, pos_end, buf));
3832 void Buffer::setBuffersForInsets() const
3834 inset().setBuffer(const_cast<Buffer &>(*this));
3838 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3840 // Use the master text class also for child documents
3841 Buffer const * const master = masterBuffer();
3842 DocumentClass const & textclass = master->params().documentClass();
3844 // do this only if we are the top-level Buffer
3846 reloadBibInfoCache();
3848 // keep the buffers to be children in this set. If the call from the
3849 // master comes back we can see which of them were actually seen (i.e.
3850 // via an InsetInclude). The remaining ones in the set need still be updated.
3851 static std::set<Buffer const *> bufToUpdate;
3852 if (scope == UpdateMaster) {
3853 // If this is a child document start with the master
3854 if (master != this) {
3855 bufToUpdate.insert(this);
3856 master->updateBuffer(UpdateMaster, utype);
3857 // Do this here in case the master has no gui associated with it. Then,
3858 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3859 if (!master->d->gui_)
3862 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3863 if (bufToUpdate.find(this) == bufToUpdate.end())
3867 // start over the counters in the master
3868 textclass.counters().reset();
3871 // update will be done below for this buffer
3872 bufToUpdate.erase(this);
3874 // update all caches
3875 clearReferenceCache();
3878 Buffer & cbuf = const_cast<Buffer &>(*this);
3880 LASSERT(!text().paragraphs().empty(), /**/);
3883 ParIterator parit = cbuf.par_iterator_begin();
3884 updateBuffer(parit, utype);
3887 // TocBackend update will be done later.
3890 d->bibinfo_cache_valid_ = true;
3891 d->cite_labels_valid_ = true;
3892 cbuf.tocBackend().update();
3893 if (scope == UpdateMaster)
3894 cbuf.structureChanged();
3898 static depth_type getDepth(DocIterator const & it)
3900 depth_type depth = 0;
3901 for (size_t i = 0 ; i < it.depth() ; ++i)
3902 if (!it[i].inset().inMathed())
3903 depth += it[i].paragraph().getDepth() + 1;
3904 // remove 1 since the outer inset does not count
3908 static depth_type getItemDepth(ParIterator const & it)
3910 Paragraph const & par = *it;
3911 LabelType const labeltype = par.layout().labeltype;
3913 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3916 // this will hold the lowest depth encountered up to now.
3917 depth_type min_depth = getDepth(it);
3918 ParIterator prev_it = it;
3921 --prev_it.top().pit();
3923 // start of nested inset: go to outer par
3925 if (prev_it.empty()) {
3926 // start of document: nothing to do
3931 // We search for the first paragraph with same label
3932 // that is not more deeply nested.
3933 Paragraph & prev_par = *prev_it;
3934 depth_type const prev_depth = getDepth(prev_it);
3935 if (labeltype == prev_par.layout().labeltype) {
3936 if (prev_depth < min_depth)
3937 return prev_par.itemdepth + 1;
3938 if (prev_depth == min_depth)
3939 return prev_par.itemdepth;
3941 min_depth = min(min_depth, prev_depth);
3942 // small optimization: if we are at depth 0, we won't
3943 // find anything else
3944 if (prev_depth == 0)
3950 static bool needEnumCounterReset(ParIterator const & it)
3952 Paragraph const & par = *it;
3953 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3954 depth_type const cur_depth = par.getDepth();
3955 ParIterator prev_it = it;
3956 while (prev_it.pit()) {
3957 --prev_it.top().pit();
3958 Paragraph const & prev_par = *prev_it;
3959 if (prev_par.getDepth() <= cur_depth)
3960 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3962 // start of nested inset: reset
3967 // set the label of a paragraph. This includes the counters.
3968 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3970 BufferParams const & bp = owner_->masterBuffer()->params();
3971 DocumentClass const & textclass = bp.documentClass();
3972 Paragraph & par = it.paragraph();
3973 Layout const & layout = par.layout();
3974 Counters & counters = textclass.counters();
3976 if (par.params().startOfAppendix()) {
3977 // FIXME: only the counter corresponding to toplevel
3978 // sectioning should be reset
3980 counters.appendix(true);
3982 par.params().appendix(counters.appendix());
3984 // Compute the item depth of the paragraph
3985 par.itemdepth = getItemDepth(it);
3987 if (layout.margintype == MARGIN_MANUAL
3988 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3989 if (par.params().labelWidthString().empty())
3990 par.params().labelWidthString(par.expandLabel(layout, bp));
3992 par.params().labelWidthString(docstring());
3995 switch(layout.labeltype) {
3997 if (layout.toclevel <= bp.secnumdepth
3998 && (layout.latextype != LATEX_ENVIRONMENT
3999 || it.text()->isFirstInSequence(it.pit()))) {
4000 if (counters.hasCounter(layout.counter))
4001 counters.step(layout.counter, utype);
4002 par.params().labelString(par.expandLabel(layout, bp));
4004 par.params().labelString(docstring());
4007 case LABEL_ITEMIZE: {
4008 // At some point of time we should do something more
4009 // clever here, like:
4010 // par.params().labelString(
4011 // bp.user_defined_bullet(par.itemdepth).getText());
4012 // for now, use a simple hardcoded label
4013 docstring itemlabel;
4014 switch (par.itemdepth) {
4016 itemlabel = char_type(0x2022);
4019 itemlabel = char_type(0x2013);
4022 itemlabel = char_type(0x2217);
4025 itemlabel = char_type(0x2219); // or 0x00b7
4028 par.params().labelString(itemlabel);
4032 case LABEL_ENUMERATE: {
4033 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4035 switch (par.itemdepth) {
4044 enumcounter += "iv";
4047 // not a valid enumdepth...
4051 // Maybe we have to reset the enumeration counter.
4052 if (needEnumCounterReset(it))
4053 counters.reset(enumcounter);
4054 counters.step(enumcounter, utype);
4056 string const & lang = par.getParLanguage(bp)->code();
4057 par.params().labelString(counters.theCounter(enumcounter, lang));
4062 case LABEL_SENSITIVE: {
4063 string const & type = counters.current_float();
4064 docstring full_label;
4066 full_label = owner_->B_("Senseless!!! ");
4068 docstring name = owner_->B_(textclass.floats().getType(type).name());
4069 if (counters.hasCounter(from_utf8(type))) {
4070 string const & lang = par.getParLanguage(bp)->code();
4071 counters.step(from_utf8(type), utype);
4072 full_label = bformat(from_ascii("%1$s %2$s:"),
4074 counters.theCounter(from_utf8(type), lang));
4076 full_label = bformat(from_ascii("%1$s #:"), name);
4078 par.params().labelString(full_label);
4082 case LABEL_NO_LABEL:
4083 par.params().labelString(docstring());
4087 case LABEL_TOP_ENVIRONMENT:
4088 case LABEL_CENTERED_TOP_ENVIRONMENT:
4091 par.params().labelString(par.expandLabel(layout, bp));
4097 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4099 LASSERT(parit.pit() == 0, /**/);
4101 // Set the position of the text in the buffer to be able
4102 // to resolve macros in it.
4103 parit.text()->setMacrocontextPosition(parit);
4105 depth_type maxdepth = 0;
4106 pit_type const lastpit = parit.lastpit();
4107 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4108 // reduce depth if necessary
4109 parit->params().depth(min(parit->params().depth(), maxdepth));
4110 maxdepth = parit->getMaxDepthAfter();
4112 if (utype == OutputUpdate) {
4113 // track the active counters
4114 // we have to do this for the master buffer, since the local
4115 // buffer isn't tracking anything.
4116 masterBuffer()->params().documentClass().counters().
4117 setActiveLayout(parit->layout());
4120 // set the counter for this paragraph
4121 d->setLabel(parit, utype);
4124 InsetList::const_iterator iit = parit->insetList().begin();
4125 InsetList::const_iterator end = parit->insetList().end();
4126 for (; iit != end; ++iit) {
4127 parit.pos() = iit->pos;
4128 iit->inset->updateBuffer(parit, utype);
4134 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4135 WordLangTuple & word_lang, docstring_list & suggestions) const
4139 suggestions.clear();
4140 word_lang = WordLangTuple();
4141 // OK, we start from here.
4142 DocIterator const end = doc_iterator_end(this);
4143 for (; from != end; from.forwardPos()) {
4144 // We are only interested in text so remove the math CursorSlice.
4145 while (from.inMathed()) {
4149 // If from is at the end of the document (which is possible
4150 // when leaving the mathed) LyX will crash later.
4154 from.paragraph().spellCheck();
4155 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4156 if (SpellChecker::misspelled(res)) {
4161 // Do not increase progress when from == to, otherwise the word
4162 // count will be wrong.
4172 Buffer::ReadStatus Buffer::reload()
4175 // c.f. bug http://www.lyx.org/trac/ticket/6587
4176 removeAutosaveFile();
4177 // e.g., read-only status could have changed due to version control
4178 d->filename.refresh();
4179 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4181 ReadStatus const status = loadLyXFile();
4182 if (status == ReadSuccess) {
4187 message(bformat(_("Document %1$s reloaded."), disp_fn));
4190 message(bformat(_("Could not reload document %1$s."), disp_fn));
4200 bool Buffer::saveAs(FileName const & fn)
4202 FileName const old_name = fileName();
4203 FileName const old_auto = getAutosaveFileName();
4204 bool const old_unnamed = isUnnamed();
4211 // bring the autosave file with us, just in case.
4212 moveAutosaveFile(old_auto);
4213 // validate version control data and
4214 // correct buffer title
4215 lyxvc().file_found_hook(fileName());
4217 // the file has now been saved to the new location.
4218 // we need to check that the locations of child buffers
4220 checkChildBuffers();
4224 // reset the old filename and unnamed state
4225 setFileName(old_name);
4226 setUnnamed(old_unnamed);
4232 // FIXME We could do better here, but it is complicated. What would be
4233 // nice is to offer either (a) to save the child buffer to an appropriate
4234 // location, so that it would "move with the master", or else (b) to update
4235 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4236 // complicated, because the code for this lives in GuiView.
4237 void Buffer::checkChildBuffers()
4239 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4240 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4241 for (; it != en; ++it) {
4242 DocIterator dit = it->second;
4243 Buffer * cbuf = const_cast<Buffer *>(it->first);
4244 if (!cbuf || !theBufferList().isLoaded(cbuf))
4246 Inset * inset = dit.nextInset();
4247 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4248 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4249 docstring const & incfile = inset_inc->getParam("filename");
4250 string oldloc = cbuf->absFileName();
4251 string newloc = makeAbsPath(to_utf8(incfile),
4252 onlyPath(absFileName())).absFileName();
4253 if (oldloc == newloc)
4255 // the location of the child file is incorrect.
4256 Alert::warning(_("Included File Invalid"),
4257 bformat(_("Saving this document to a new location has made the file:\n"
4259 "inaccessible. You will need to update the included filename."),
4260 from_utf8(oldloc)));
4262 inset_inc->setChildBuffer(0);
4264 // invalidate cache of children
4265 d->children_positions.clear();
4266 d->position_to_children.clear();