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"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
60 #include "texstream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/GraphicsCache.h"
83 #include "graphics/PreviewLoader.h"
85 #include "frontends/alert.h"
86 #include "frontends/Delegates.h"
87 #include "frontends/WorkAreaManager.h"
89 #include "support/lassert.h"
90 #include "support/convert.h"
91 #include "support/debug.h"
92 #include "support/docstring_list.h"
93 #include "support/ExceptionMessage.h"
94 #include "support/FileName.h"
95 #include "support/FileNameList.h"
96 #include "support/filetools.h"
97 #include "support/ForkedCalls.h"
98 #include "support/gettext.h"
99 #include "support/gzstream.h"
100 #include "support/lstrings.h"
101 #include "support/lyxalgo.h"
102 #include "support/mutex.h"
103 #include "support/os.h"
104 #include "support/Package.h"
105 #include "support/PathChanger.h"
106 #include "support/Systemcall.h"
107 #include "support/TempFile.h"
108 #include "support/textutils.h"
109 #include "support/types.h"
111 #include "support/bind.h"
123 using namespace lyx::support;
124 using namespace lyx::graphics;
128 namespace Alert = frontend::Alert;
129 namespace os = support::os;
133 int const LYX_FORMAT = LYX_FORMAT_LYX;
135 typedef map<string, bool> DepClean;
136 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
141 // A storehouse for the cloned buffers.
142 list<CloneList *> cloned_buffers;
148 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
152 delete preview_loader_;
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...)?
194 /// is this an internal bufffer?
195 bool internal_buffer;
200 /// name of the file the buffer is associated with.
203 /** Set to true only when the file is fully loaded.
204 * Used to prevent the premature generation of previews
205 * and by the citation inset.
207 bool file_fully_loaded;
209 /// original format of loaded file
212 /// if the file was originally loaded from an older format, do
213 /// we need to back it up still?
214 bool need_format_backup;
216 /// Ignore the parent (e.g. when exporting a child standalone)?
220 mutable TocBackend toc_backend;
225 ScopeMacro(DocIterator const & s, MacroData const & m)
226 : scope(s), macro(m) {}
230 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
231 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
232 /// map from the macro name to the position map,
233 /// which maps the macro definition position to the scope and the MacroData.
234 NamePositionScopeMacroMap macros;
235 /// This seem to change the way Buffer::getMacro() works
236 mutable bool macro_lock;
238 /// positions of child buffers in the buffer
239 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer() : buffer(0) {}
242 ScopeBuffer(DocIterator const & s, Buffer const * b)
243 : scope(s), buffer(b) {}
245 Buffer const * buffer;
247 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
248 /// position of children buffers in this buffer
249 BufferPositionMap children_positions;
250 /// map from children inclusion positions to their scope and their buffer
251 PositionScopeBufferMap position_to_children;
253 /// Contains the old buffer filePath() while saving-as, or the
254 /// directory where the document was last saved while loading.
257 /** Keeps track of the path of local layout files.
258 * If possible, it is always relative to the buffer path.
259 * Empty for layouts in system or user directory.
261 string layout_position;
263 /// Container for all sort of Buffer dependant errors.
264 map<string, ErrorList> errorLists;
266 /// timestamp and checksum used to test if the file has been externally
267 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
269 unsigned long checksum_;
272 frontend::WorkAreaManager * wa_;
274 frontend::GuiBufferDelegate * gui_;
279 /// A cache for the bibfiles (including bibfiles of loaded child
280 /// documents), needed for appropriate update of natbib labels.
281 mutable support::FileNamePairList bibfiles_cache_;
283 // FIXME The caching mechanism could be improved. At present, we have a
284 // cache for each Buffer, that caches all the bibliography info for that
285 // Buffer. A more efficient solution would be to have a global cache per
286 // file, and then to construct the Buffer's bibinfo from that.
287 /// A cache for bibliography info
288 mutable BiblioInfo bibinfo_;
289 /// whether the bibinfo cache is valid
290 mutable bool bibinfo_cache_valid_;
291 /// whether the bibfile cache is valid
292 mutable bool bibfile_cache_valid_;
293 /// Cache of timestamps of .bib files
294 map<FileName, time_t> bibfile_status_;
295 /// Indicates whether the bibinfo has changed since the last time
296 /// we ran updateBuffer(), i.e., whether citation labels may need
298 mutable bool cite_labels_valid_;
300 /// These two hold the file name and format, written to by
301 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
302 FileName preview_file_;
303 string preview_format_;
304 /// If there was an error when previewing, on the next preview we do
305 /// a fresh compile (e.g. in case the user installed a package that
309 mutable RefCache ref_cache_;
311 /// our Text that should be wrapped in an InsetText
315 PreviewLoader * preview_loader_;
317 /// This is here to force the test to be done whenever parent_buffer
319 Buffer const * parent() const
321 // ignore_parent temporarily "orphans" a buffer
322 // (e.g. if a child is compiled standalone)
325 // if parent_buffer is not loaded, then it has been unloaded,
326 // which means that parent_buffer is an invalid pointer. So we
327 // set it to null in that case.
328 // however, the BufferList doesn't know about cloned buffers, so
329 // they will always be regarded as unloaded. in that case, we hope
331 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
333 return parent_buffer;
337 void setParent(Buffer const * pb)
339 if (parent_buffer == pb)
342 if (!cloned_buffer_ && parent_buffer && pb)
343 LYXERR0("Warning: a buffer should not have two parents!");
345 if (!cloned_buffer_ && parent_buffer) {
346 parent_buffer->invalidateBibfileCache();
347 parent_buffer->invalidateBibinfoCache();
351 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
352 /// This one is useful for preview detached in a thread.
353 Buffer const * cloned_buffer_;
355 CloneList * clone_list_;
356 /// are we in the process of exporting this buffer?
357 mutable bool doing_export;
359 /// compute statistics
360 /// \p from initial position
361 /// \p to points to the end position
362 void updateStatistics(DocIterator & from, DocIterator & to,
363 bool skipNoOutput = true);
364 /// statistics accessor functions
365 int wordCount() const
369 int charCount(bool with_blanks) const
372 + (with_blanks ? blank_count_ : 0);
375 // does the buffer contain tracked changes? (if so, we automatically
376 // display the review toolbar, for instance)
377 mutable bool tracked_changes_present_;
380 /// So we can force access via the accessors.
381 mutable Buffer const * parent_buffer;
390 /// Creates the per buffer temporary directory
391 static FileName createBufferTmpDir()
393 // FIXME This would be the ideal application for a TempDir class (like
394 // TempFile but for directories)
399 Mutex::Locker locker(&mutex);
400 counter = convert<string>(count++);
402 // We are in our own directory. Why bother to mangle name?
403 // In fact I wrote this code to circumvent a problematic behaviour
404 // (bug?) of EMX mkstemp().
405 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
408 if (!tmpfl.createDirectory(0777)) {
409 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
410 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
411 from_utf8(tmpfl.absFileName())));
417 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
418 Buffer const * cloned_buffer)
419 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
420 internal_buffer(false), read_only(readonly_), filename(file),
421 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
422 ignore_parent(false), toc_backend(owner), macro_lock(false), timestamp_(0),
423 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
424 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
425 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
426 clone_list_(0), doing_export(false),
427 tracked_changes_present_(0), parent_buffer(0),
428 word_count_(0), char_count_(0), blank_count_(0)
430 if (!cloned_buffer_) {
431 temppath = createBufferTmpDir();
432 lyxvc.setBuffer(owner_);
434 wa_ = new frontend::WorkAreaManager;
437 temppath = cloned_buffer_->d->temppath;
438 file_fully_loaded = true;
439 params = cloned_buffer_->d->params;
440 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
441 bibinfo_ = cloned_buffer_->d->bibinfo_;
442 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
443 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
444 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
445 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
446 unnamed = cloned_buffer_->d->unnamed;
447 internal_buffer = cloned_buffer_->d->internal_buffer;
448 layout_position = cloned_buffer_->d->layout_position;
449 preview_file_ = cloned_buffer_->d->preview_file_;
450 preview_format_ = cloned_buffer_->d->preview_format_;
451 preview_error_ = cloned_buffer_->d->preview_error_;
452 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
456 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
457 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
459 LYXERR(Debug::INFO, "Buffer::Buffer()");
461 d->inset = new InsetText(*cloned_buffer->d->inset);
462 d->inset->setBuffer(*this);
463 // FIXME: optimize this loop somewhat, maybe by creating a new
464 // general recursive Inset::setId().
465 DocIterator it = doc_iterator_begin(this);
466 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
467 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
468 it.paragraph().setId(cloned_it.paragraph().id());
470 d->inset = new InsetText(this);
471 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
477 LYXERR(Debug::INFO, "Buffer::~Buffer()");
478 // here the buffer should take care that it is
479 // saved properly, before it goes into the void.
481 // GuiView already destroyed
485 // No need to do additional cleanups for internal buffer.
491 // this is in case of recursive includes: we won't try to delete
492 // ourselves as a child.
493 d->clone_list_->erase(this);
494 // loop over children
495 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
496 Impl::BufferPositionMap::iterator end = d->children_positions.end();
497 for (; it != end; ++it) {
498 Buffer * child = const_cast<Buffer *>(it->first);
499 if (d->clone_list_->erase(child))
502 // if we're the master buffer, then we should get rid of the list
505 // If this is not empty, we have leaked something. Worse, one of the
506 // children still has a reference to this list. But we will try to
507 // continue, rather than shut down.
508 LATTEST(d->clone_list_->empty());
509 list<CloneList *>::iterator it =
510 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
511 if (it == cloned_buffers.end()) {
512 // We will leak in this case, but it is safe to continue.
515 cloned_buffers.erase(it);
516 delete d->clone_list_;
518 // FIXME Do we really need to do this right before we delete d?
519 // clear references to children in macro tables
520 d->children_positions.clear();
521 d->position_to_children.clear();
523 // loop over children
524 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
525 Impl::BufferPositionMap::iterator end = d->children_positions.end();
526 for (; it != end; ++it) {
527 Buffer * child = const_cast<Buffer *>(it->first);
528 if (theBufferList().isLoaded(child)) {
529 if (theBufferList().isOthersChild(this, child))
532 theBufferList().release(child);
537 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
538 msg += emergencyWrite();
539 Alert::warning(_("Attempting to close changed document!"), msg);
542 // FIXME Do we really need to do this right before we delete d?
543 // clear references to children in macro tables
544 d->children_positions.clear();
545 d->position_to_children.clear();
547 if (!d->temppath.destroyDirectory()) {
548 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
549 from_utf8(d->temppath.absFileName())));
558 Buffer * Buffer::cloneFromMaster() const
561 cloned_buffers.push_back(new CloneList);
562 CloneList * clones = cloned_buffers.back();
564 masterBuffer()->cloneWithChildren(bufmap, clones);
566 // make sure we got cloned
567 BufferMap::const_iterator bit = bufmap.find(this);
568 LASSERT(bit != bufmap.end(), return 0);
569 Buffer * cloned_buffer = bit->second;
571 return cloned_buffer;
575 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
577 // have we already been cloned?
578 if (bufmap.find(this) != bufmap.end())
581 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
583 // The clone needs its own DocumentClass, since running updateBuffer() will
584 // modify it, and we would otherwise be sharing it with the original Buffer.
585 buffer_clone->params().makeDocumentClass(true);
587 cap::switchBetweenClasses(
588 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
589 static_cast<InsetText &>(buffer_clone->inset()), el);
591 bufmap[this] = buffer_clone;
592 clones->insert(buffer_clone);
593 buffer_clone->d->clone_list_ = clones;
594 buffer_clone->d->macro_lock = true;
595 buffer_clone->d->children_positions.clear();
597 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
598 // math macro caches need to be rethought and simplified.
599 // I am not sure wether we should handle Buffer cloning here or in BufferList.
600 // Right now BufferList knows nothing about buffer clones.
601 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
602 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
603 for (; it != end; ++it) {
604 DocIterator dit = it->first.clone(buffer_clone);
605 dit.setBuffer(buffer_clone);
606 Buffer * child = const_cast<Buffer *>(it->second.buffer);
608 child->cloneWithChildren(bufmap, clones);
609 BufferMap::iterator const bit = bufmap.find(child);
610 LASSERT(bit != bufmap.end(), continue);
611 Buffer * child_clone = bit->second;
613 Inset * inset = dit.nextInset();
614 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
615 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
616 inset_inc->setChildBuffer(child_clone);
617 child_clone->d->setParent(buffer_clone);
618 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
619 buffer_clone->setChild(dit, child_clone);
621 buffer_clone->d->macro_lock = false;
626 Buffer * Buffer::cloneBufferOnly() const {
627 cloned_buffers.push_back(new CloneList);
628 CloneList * clones = cloned_buffers.back();
629 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
631 // The clone needs its own DocumentClass, since running updateBuffer() will
632 // modify it, and we would otherwise be sharing it with the original Buffer.
633 buffer_clone->params().makeDocumentClass(true);
635 cap::switchBetweenClasses(
636 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
637 static_cast<InsetText &>(buffer_clone->inset()), el);
639 clones->insert(buffer_clone);
640 buffer_clone->d->clone_list_ = clones;
642 // we won't be cloning the children
643 buffer_clone->d->children_positions.clear();
648 bool Buffer::isClone() const
650 return d->cloned_buffer_;
654 void Buffer::changed(bool update_metrics) const
657 d->wa_->redrawAll(update_metrics);
661 frontend::WorkAreaManager & Buffer::workAreaManager() const
668 Text & Buffer::text() const
670 return d->inset->text();
674 Inset & Buffer::inset() const
680 BufferParams & Buffer::params()
686 BufferParams const & Buffer::params() const
692 BufferParams const & Buffer::masterParams() const
694 if (masterBuffer() == this)
697 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
698 // Copy child authors to the params. We need those pointers.
699 AuthorList const & child_authors = params().authors();
700 AuthorList::Authors::const_iterator it = child_authors.begin();
701 for (; it != child_authors.end(); ++it)
702 mparams.authors().record(*it);
707 double Buffer::fontScalingFactor() const
709 return isExporting() ? 75.0 * params().html_math_img_scale
710 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
714 ParagraphList & Buffer::paragraphs()
716 return text().paragraphs();
720 ParagraphList const & Buffer::paragraphs() const
722 return text().paragraphs();
726 LyXVC & Buffer::lyxvc()
732 LyXVC const & Buffer::lyxvc() const
738 string const Buffer::temppath() const
740 return d->temppath.absFileName();
744 TexRow & Buffer::texrow()
750 TexRow const & Buffer::texrow() const
756 TocBackend & Buffer::tocBackend() const
758 return d->toc_backend;
762 Undo & Buffer::undo()
768 void Buffer::setChild(DocIterator const & dit, Buffer * child)
770 d->children_positions[child] = dit;
774 string Buffer::latexName(bool const no_path) const
776 FileName latex_name =
777 makeLatexName(d->exportFileName());
778 return no_path ? latex_name.onlyFileName()
779 : latex_name.absFileName();
783 FileName Buffer::Impl::exportFileName() const
785 docstring const branch_suffix =
786 params.branchlist().getFileNameSuffix();
787 if (branch_suffix.empty())
790 string const name = filename.onlyFileNameWithoutExt()
791 + to_utf8(branch_suffix);
792 FileName res(filename.onlyPath().absFileName() + "/" + name);
793 res.changeExtension(filename.extension());
799 string Buffer::logName(LogType * type) const
801 string const filename = latexName(false);
803 if (filename.empty()) {
809 string const path = temppath();
811 FileName const fname(addName(temppath(),
812 onlyFileName(changeExtension(filename,
815 // FIXME: how do we know this is the name of the build log?
816 FileName const bname(
817 addName(path, onlyFileName(
818 changeExtension(filename,
819 formats.extension(params().bufferFormat()) + ".out"))));
821 // Also consider the master buffer log file
822 FileName masterfname = fname;
823 LogType mtype = latexlog;
824 if (masterBuffer() != this) {
825 string const mlogfile = masterBuffer()->logName(&mtype);
826 masterfname = FileName(mlogfile);
829 // If no Latex log or Build log is newer, show Build log
830 if (bname.exists() &&
831 ((!fname.exists() && !masterfname.exists())
832 || (fname.lastModified() < bname.lastModified()
833 && masterfname.lastModified() < bname.lastModified()))) {
834 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
837 return bname.absFileName();
838 // If we have a newer master file log or only a master log, show this
839 } else if (fname != masterfname
840 && (!fname.exists() && (masterfname.exists()
841 || fname.lastModified() < masterfname.lastModified()))) {
842 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
845 return masterfname.absFileName();
847 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
850 return fname.absFileName();
854 void Buffer::setReadonly(bool const flag)
856 if (d->read_only != flag) {
863 void Buffer::setFileName(FileName const & fname)
865 bool const changed = fname != d->filename;
868 lyxvc().file_found_hook(fname);
869 setReadonly(d->filename.isReadOnly());
875 int Buffer::readHeader(Lexer & lex)
877 int unknown_tokens = 0;
879 int begin_header_line = -1;
881 // Initialize parameters that may be/go lacking in header:
882 params().branchlist().clear();
883 params().preamble.erase();
884 params().options.erase();
885 params().master.erase();
886 params().float_placement.erase();
887 params().paperwidth.erase();
888 params().paperheight.erase();
889 params().leftmargin.erase();
890 params().rightmargin.erase();
891 params().topmargin.erase();
892 params().bottommargin.erase();
893 params().headheight.erase();
894 params().headsep.erase();
895 params().footskip.erase();
896 params().columnsep.erase();
897 params().fonts_cjk.erase();
898 params().listings_params.clear();
899 params().clearLayoutModules();
900 params().clearRemovedModules();
901 params().clearIncludedChildren();
902 params().pdfoptions().clear();
903 params().indiceslist().clear();
904 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
905 params().isbackgroundcolor = false;
906 params().fontcolor = RGBColor(0, 0, 0);
907 params().isfontcolor = false;
908 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
909 params().boxbgcolor = RGBColor(0xFF, 0, 0);
910 params().html_latex_start.clear();
911 params().html_latex_end.clear();
912 params().html_math_img_scale = 1.0;
913 params().output_sync_macro.erase();
914 params().setLocalLayout(docstring(), false);
915 params().setLocalLayout(docstring(), true);
916 params().biblio_opts.erase();
917 params().biblatex_bibstyle.erase();
918 params().biblatex_citestyle.erase();
919 params().multibib.erase();
921 for (int i = 0; i < 4; ++i) {
922 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
923 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
926 ErrorList & errorList = d->errorLists["Parse"];
935 if (token == "\\end_header")
939 if (token == "\\begin_header") {
940 begin_header_line = line;
944 LYXERR(Debug::PARSER, "Handling document header token: `"
947 string const result =
948 params().readToken(lex, token, d->filename.onlyPath());
949 if (!result.empty()) {
950 if (token == "\\textclass") {
951 d->layout_position = result;
954 docstring const s = bformat(_("Unknown token: "
958 errorList.push_back(ErrorItem(_("Document header error"), s));
962 if (begin_header_line) {
963 docstring const s = _("\\begin_header is missing");
964 errorList.push_back(ErrorItem(_("Document header error"), s));
967 params().makeDocumentClass();
969 return unknown_tokens;
974 // changed to be public and have one parameter
975 // Returns true if "\end_document" is not read (Asger)
976 bool Buffer::readDocument(Lexer & lex)
978 ErrorList & errorList = d->errorLists["Parse"];
981 // remove dummy empty par
982 paragraphs().clear();
984 if (!lex.checkFor("\\begin_document")) {
985 docstring const s = _("\\begin_document is missing");
986 errorList.push_back(ErrorItem(_("Document header error"), s));
991 if (params().output_changes) {
992 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
993 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
994 LaTeXFeatures::isAvailable("xcolor");
996 if (!dvipost && !xcolorulem) {
997 Alert::warning(_("Changes not shown in LaTeX output"),
998 _("Changes will not be highlighted in LaTeX output, "
999 "because neither dvipost nor xcolor/ulem are installed.\n"
1000 "Please install these packages or redefine "
1001 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1002 } else if (!xcolorulem) {
1003 Alert::warning(_("Changes not shown in LaTeX output"),
1004 _("Changes will not be highlighted in LaTeX output "
1005 "when using pdflatex, because xcolor and ulem are not installed.\n"
1006 "Please install both packages or redefine "
1007 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1011 if (!parent() && !params().master.empty()) {
1012 FileName const master_file = makeAbsPath(params().master,
1013 onlyPath(absFileName()));
1014 if (isLyXFileName(master_file.absFileName())) {
1016 checkAndLoadLyXFile(master_file, true);
1018 // necessary e.g. after a reload
1019 // to re-register the child (bug 5873)
1020 // FIXME: clean up updateMacros (here, only
1021 // child registering is needed).
1022 master->updateMacros();
1023 // set master as master buffer, but only
1024 // if we are a real child
1025 if (master->isChild(this))
1027 // if the master is not fully loaded
1028 // it is probably just loading this
1029 // child. No warning needed then.
1030 else if (master->isFullyLoaded())
1031 LYXERR0("The master '"
1033 << "' assigned to this document ("
1035 << ") does not include "
1036 "this document. Ignoring the master assignment.");
1041 // assure we have a default index
1042 params().indiceslist().addDefault(B_("Index"));
1045 if (FileName::isAbsolute(params().origin))
1046 d->old_position = params().origin;
1048 d->old_position = filePath();
1049 bool const res = text().read(lex, errorList, d->inset);
1050 d->old_position.clear();
1052 // inform parent buffer about local macros
1054 Buffer const * pbuf = parent();
1055 UserMacroSet::const_iterator cit = usermacros.begin();
1056 UserMacroSet::const_iterator end = usermacros.end();
1057 for (; cit != end; ++cit)
1058 pbuf->usermacros.insert(*cit);
1062 updateMacroInstances(InternalUpdate);
1067 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1069 Format const * fmt = formats.getFormat(format);
1072 // It is important to use the correct extension here, since some
1073 // converters create a wrong output file otherwise (e.g. html2latex)
1074 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1075 FileName const name(tempfile.name());
1076 ofdocstream os(name.toFilesystemEncoding().c_str());
1077 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1078 bool const success = !(os << contents).fail();
1081 bool converted = false;
1083 params().compressed = false;
1085 // remove dummy empty par
1086 paragraphs().clear();
1088 converted = importFile(format, name, errorList);
1097 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1099 if (!theConverters().isReachable(format, "lyx"))
1102 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1103 FileName const lyx(tempfile.name());
1104 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1105 return readFile(lyx) == ReadSuccess;
1111 bool Buffer::readString(string const & s)
1113 params().compressed = false;
1116 istringstream is(s);
1118 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1119 FileName const fn = tempfile.name();
1122 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1124 if (success && file_format != LYX_FORMAT) {
1125 // We need to call lyx2lyx, so write the input to a file
1126 ofstream os(fn.toFilesystemEncoding().c_str());
1129 // lyxvc in readFile
1130 if (readFile(fn) != ReadSuccess)
1134 if (readDocument(lex))
1140 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1144 if (!lex.setFile(fname)) {
1145 Alert::error(_("File Not Found"),
1146 bformat(_("Unable to open file `%1$s'."),
1147 from_utf8(fn.absFileName())));
1148 return ReadFileNotFound;
1152 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1153 if (ret_plf != ReadSuccess)
1156 if (file_format != LYX_FORMAT) {
1158 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1159 if (ret_clf != ReadSuccess)
1161 ret_clf = readFile(tmpFile);
1162 if (ret_clf == ReadSuccess) {
1163 d->file_format = file_format;
1164 d->need_format_backup = true;
1169 // FIXME: InsetInfo needs to know whether the file is under VCS
1170 // during the parse process, so this has to be done before.
1171 lyxvc().file_found_hook(d->filename);
1173 if (readDocument(lex)) {
1174 Alert::error(_("Document format failure"),
1175 bformat(_("%1$s ended unexpectedly, which means"
1176 " that it is probably corrupted."),
1177 from_utf8(fn.absFileName())));
1178 return ReadDocumentFailure;
1181 d->file_fully_loaded = true;
1182 d->read_only = !d->filename.isWritable();
1183 params().compressed = formats.isZippedFile(d->filename);
1189 bool Buffer::isFullyLoaded() const
1191 return d->file_fully_loaded;
1195 void Buffer::setFullyLoaded(bool value)
1197 d->file_fully_loaded = value;
1201 bool Buffer::lastPreviewError() const
1203 return d->preview_error_;
1207 PreviewLoader * Buffer::loader() const
1209 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1211 if (!d->preview_loader_)
1212 d->preview_loader_ = new PreviewLoader(*this);
1213 return d->preview_loader_;
1217 void Buffer::removePreviews() const
1219 delete d->preview_loader_;
1220 d->preview_loader_ = 0;
1224 void Buffer::updatePreviews() const
1226 PreviewLoader * ploader = loader();
1230 InsetIterator it = inset_iterator_begin(*d->inset);
1231 InsetIterator const end = inset_iterator_end(*d->inset);
1232 for (; it != end; ++it)
1233 it->addPreview(it, *ploader);
1235 ploader->startLoading();
1239 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1240 FileName const & fn, int & file_format) const
1242 if(!lex.checkFor("\\lyxformat")) {
1243 Alert::error(_("Document format failure"),
1244 bformat(_("%1$s is not a readable LyX document."),
1245 from_utf8(fn.absFileName())));
1246 return ReadNoLyXFormat;
1252 // LyX formats 217 and earlier were written as 2.17. This corresponds
1253 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1254 // these cases. See also: www.lyx.org/trac/changeset/1313.
1255 size_t dot = tmp_format.find_first_of(".,");
1256 if (dot != string::npos)
1257 tmp_format.erase(dot, 1);
1259 file_format = convert<int>(tmp_format);
1264 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1265 FileName & tmpfile, int from_format)
1267 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1268 tempfile.setAutoRemove(false);
1269 tmpfile = tempfile.name();
1270 if(tmpfile.empty()) {
1271 Alert::error(_("Conversion failed"),
1272 bformat(_("%1$s is from a different"
1273 " version of LyX, but a temporary"
1274 " file for converting it could"
1275 " not be created."),
1276 from_utf8(fn.absFileName())));
1277 return LyX2LyXNoTempFile;
1280 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1281 if (lyx2lyx.empty()) {
1282 Alert::error(_("Conversion script not found"),
1283 bformat(_("%1$s is from a different"
1284 " version of LyX, but the"
1285 " conversion script lyx2lyx"
1286 " could not be found."),
1287 from_utf8(fn.absFileName())));
1288 return LyX2LyXNotFound;
1292 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1293 ostringstream command;
1294 command << os::python()
1295 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1296 << " -t " << convert<string>(LYX_FORMAT)
1297 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1298 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1299 string const command_str = command.str();
1301 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1303 cmd_ret const ret = runCommand(command_str);
1304 if (ret.first != 0) {
1305 if (from_format < LYX_FORMAT) {
1306 Alert::error(_("Conversion script failed"),
1307 bformat(_("%1$s is from an older version"
1308 " of LyX and the lyx2lyx script"
1309 " failed to convert it."),
1310 from_utf8(fn.absFileName())));
1311 return LyX2LyXOlderFormat;
1313 Alert::error(_("Conversion script failed"),
1314 bformat(_("%1$s is from a newer version"
1315 " of LyX and the lyx2lyx script"
1316 " failed to convert it."),
1317 from_utf8(fn.absFileName())));
1318 return LyX2LyXNewerFormat;
1325 FileName Buffer::getBackupName() const {
1326 FileName const & fn = fileName();
1327 string const fname = fn.onlyFileNameWithoutExt();
1328 string const fext = fn.extension() + "~";
1329 string const fpath = lyxrc.backupdir_path.empty() ?
1330 fn.onlyPath().absFileName() :
1331 lyxrc.backupdir_path;
1332 string const fform = convert<string>(d->file_format);
1333 string const backname = fname + "-lyxformat-" + fform;
1334 FileName backup(addName(fpath, addExtension(backname, fext)));
1336 // limit recursion, just in case
1338 unsigned long orig_checksum = 0;
1339 while (backup.exists() && v < 100) {
1340 if (orig_checksum == 0)
1341 orig_checksum = fn.checksum();
1342 unsigned long new_checksum = backup.checksum();
1343 if (orig_checksum == new_checksum) {
1344 LYXERR(Debug::FILES, "Not backing up " << fn <<
1345 "since " << backup << "has the same checksum.");
1346 // a bit of a hack, but we have to check this anyway
1347 // below, and setting this is simpler than introducing
1348 // a special boolean for this purpose.
1352 string const newbackname = backname + "-" + convert<string>(v);
1353 backup.set(addName(fpath, addExtension(newbackname, fext)));
1356 return v < 100 ? backup : FileName();
1360 // Should probably be moved to somewhere else: BufferView? GuiView?
1361 bool Buffer::save() const
1363 docstring const file = makeDisplayPath(absFileName(), 20);
1364 d->filename.refresh();
1366 // check the read-only status before moving the file as a backup
1367 if (d->filename.exists()) {
1368 bool const read_only = !d->filename.isWritable();
1370 Alert::warning(_("File is read-only"),
1371 bformat(_("The file %1$s cannot be written because it "
1372 "is marked as read-only."), file));
1377 // ask if the disk file has been externally modified (use checksum method)
1378 if (fileName().exists() && isExternallyModified(checksum_method)) {
1380 bformat(_("Document %1$s has been externally modified. "
1381 "Are you sure you want to overwrite this file?"), file);
1382 int const ret = Alert::prompt(_("Overwrite modified file?"),
1383 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1388 // We don't need autosaves in the immediate future. (Asger)
1389 resetAutosaveTimers();
1391 // if the file does not yet exist, none of the backup activity
1392 // that follows is necessary
1393 if (!fileName().exists()) {
1394 if (!writeFile(fileName()))
1400 // we first write the file to a new name, then move it to its
1401 // proper location once that has been done successfully. that
1402 // way we preserve the original file if something goes wrong.
1403 string const justname = fileName().onlyFileNameWithoutExt();
1404 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1405 justname + "-XXXXXX.lyx");
1406 bool const symlink = fileName().isSymLink();
1408 tempfile->setAutoRemove(false);
1410 FileName savefile(tempfile->name());
1411 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1412 if (!writeFile(savefile))
1415 // we will set this to false if we fail
1416 bool made_backup = true;
1418 FileName backupName;
1419 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1421 if (d->need_format_backup)
1422 backupName = getBackupName();
1424 // If we for some reason failed to find a backup name in case of
1425 // a format change, this will still set one. It's the best we can
1427 if (backupName.empty()) {
1428 backupName.set(fileName().absFileName() + "~");
1429 if (!lyxrc.backupdir_path.empty()) {
1430 string const mangledName =
1431 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1432 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1436 LYXERR(Debug::FILES, "Backing up original file to " <<
1437 backupName.absFileName());
1438 // Except file is symlink do not copy because of #6587.
1439 // Hard links have bad luck.
1440 made_backup = symlink ?
1441 fileName().copyTo(backupName):
1442 fileName().moveTo(backupName);
1445 Alert::error(_("Backup failure"),
1446 bformat(_("Cannot create backup file %1$s.\n"
1447 "Please check whether the directory exists and is writable."),
1448 from_utf8(backupName.absFileName())));
1449 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1450 } else if (d->need_format_backup) {
1451 // the original file has been backed up successfully, so we
1452 // will not need to do that again
1453 d->need_format_backup = false;
1457 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1458 // Only do this if tempfile is not in autoremove mode
1461 // If we have no symlink, we can simply rename the temp file.
1462 // Otherwise, we need to copy it so the symlink stays intact.
1463 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1464 savefile.moveTo(fileName()))
1466 // saveCheckSum() was already called by writeFile(), but the
1467 // time stamp is invalidated by copying/moving
1470 if (d->file_format != LYX_FORMAT)
1471 // the file associated with this buffer is now in the current format
1472 d->file_format = LYX_FORMAT;
1475 // else we saved the file, but failed to move it to the right location.
1477 if (needBackup && made_backup && !symlink) {
1478 // the original file was moved to some new location, so it will look
1479 // to the user as if it was deleted. (see bug #9234.) we could try
1480 // to restore it, but that would basically mean trying to do again
1481 // what we just failed to do. better to leave things as they are.
1482 Alert::error(_("Write failure"),
1483 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1484 "But LyX could not move it to:\n %2$s.\n"
1485 "Your original file has been backed up to:\n %3$s"),
1486 from_utf8(savefile.absFileName()),
1487 from_utf8(fileName().absFileName()),
1488 from_utf8(backupName.absFileName())));
1490 // either we did not try to make a backup, or else we tried and failed,
1491 // or else the original file was a symlink, in which case it was copied,
1492 // not moved. so the original file is intact.
1493 Alert::error(_("Write failure"),
1494 bformat(_("Cannot move saved file to:\n %1$s.\n"
1495 "But the file has successfully been saved as:\n %2$s."),
1496 from_utf8(fileName().absFileName()),
1497 from_utf8(savefile.absFileName())));
1503 bool Buffer::writeFile(FileName const & fname) const
1505 if (d->read_only && fname == d->filename)
1508 bool retval = false;
1510 docstring const str = bformat(_("Saving document %1$s..."),
1511 makeDisplayPath(fname.absFileName()));
1514 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1516 if (params().compressed) {
1517 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1518 retval = ofs && write(ofs);
1520 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1521 retval = ofs && write(ofs);
1525 message(str + _(" could not write file!"));
1530 // removeAutosaveFile();
1533 message(str + _(" done."));
1539 docstring Buffer::emergencyWrite()
1541 // No need to save if the buffer has not changed.
1545 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1547 docstring user_message = bformat(
1548 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1550 // We try to save three places:
1551 // 1) Same place as document. Unless it is an unnamed doc.
1553 string s = absFileName();
1556 if (writeFile(FileName(s))) {
1558 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1559 return user_message;
1561 user_message += " " + _("Save failed! Trying again...\n");
1565 // 2) In HOME directory.
1566 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1568 lyxerr << ' ' << s << endl;
1569 if (writeFile(FileName(s))) {
1571 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1572 return user_message;
1575 user_message += " " + _("Save failed! Trying yet again...\n");
1577 // 3) In "/tmp" directory.
1578 // MakeAbsPath to prepend the current
1579 // drive letter on OS/2
1580 s = addName(package().temp_dir().absFileName(), absFileName());
1582 lyxerr << ' ' << s << endl;
1583 if (writeFile(FileName(s))) {
1585 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1586 return user_message;
1589 user_message += " " + _("Save failed! Bummer. Document is lost.");
1592 return user_message;
1596 bool Buffer::write(ostream & ofs) const
1599 // Use the standard "C" locale for file output.
1600 ofs.imbue(locale::classic());
1603 // The top of the file should not be written by params().
1605 // write out a comment in the top of the file
1606 // Important: Keep the version formatting in sync with lyx2lyx and
1607 // tex2lyx (bug 7951)
1608 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1609 << " created this file. For more info see http://www.lyx.org/\n"
1610 << "\\lyxformat " << LYX_FORMAT << "\n"
1611 << "\\begin_document\n";
1613 /// For each author, set 'used' to true if there is a change
1614 /// by this author in the document; otherwise set it to 'false'.
1615 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1616 AuthorList::Authors::const_iterator a_end = params().authors().end();
1617 for (; a_it != a_end; ++a_it)
1618 a_it->setUsed(false);
1620 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1621 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1622 for ( ; it != end; ++it)
1623 it->checkAuthors(params().authors());
1625 // now write out the buffer parameters.
1626 ofs << "\\begin_header\n";
1627 params().writeFile(ofs, this);
1628 ofs << "\\end_header\n";
1631 ofs << "\n\\begin_body\n";
1633 ofs << "\n\\end_body\n";
1635 // Write marker that shows file is complete
1636 ofs << "\\end_document" << endl;
1638 // Shouldn't really be needed....
1641 // how to check if close went ok?
1642 // Following is an attempt... (BE 20001011)
1644 // good() returns false if any error occurred, including some
1645 // formatting error.
1646 // bad() returns true if something bad happened in the buffer,
1647 // which should include file system full errors.
1652 lyxerr << "File was not closed properly." << endl;
1659 bool Buffer::makeLaTeXFile(FileName const & fname,
1660 string const & original_path,
1661 OutputParams const & runparams_in,
1662 OutputWhat output) const
1664 OutputParams runparams = runparams_in;
1666 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1667 // Check here, because the "flavor" is not known in BufferParams::encoding()
1668 // (power users can override this safety measure selecting "utf8-plain").
1669 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1670 && (runparams.encoding->name() != "utf8-plain"))
1671 runparams.encoding = encodings.fromLyXName("ascii");
1673 string const encoding = runparams.encoding->iconvName();
1674 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1677 try { ofs.reset(encoding); }
1678 catch (iconv_codecvt_facet_exception const & e) {
1679 lyxerr << "Caught iconv exception: " << e.what() << endl;
1680 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1681 "verify that the support software for your encoding (%1$s) is "
1682 "properly installed"), from_ascii(encoding)));
1685 if (!openFileWrite(ofs, fname))
1688 ErrorList & errorList = d->errorLists["Export"];
1690 bool failed_export = false;
1693 // make sure we are ready to export
1694 // this needs to be done before we validate
1695 // FIXME Do we need to do this all the time? I.e., in children
1696 // of a master we are exporting?
1698 updateMacroInstances(OutputUpdate);
1701 writeLaTeXSource(os, original_path, runparams, output);
1703 catch (EncodingException const & e) {
1704 docstring const failed(1, e.failed_char);
1706 oss << "0x" << hex << e.failed_char << dec;
1707 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1708 " (code point %2$s)"),
1709 failed, from_utf8(oss.str()));
1710 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1711 "representable in the chosen encoding.\n"
1712 "Changing the document encoding to utf8 could help."),
1713 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1714 failed_export = true;
1716 catch (iconv_codecvt_facet_exception const & e) {
1717 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1719 failed_export = true;
1721 catch (exception const & e) {
1722 errorList.push_back(ErrorItem(_("conversion failed"),
1724 failed_export = true;
1727 lyxerr << "Caught some really weird exception..." << endl;
1731 d->texrow = move(os.texrow());
1735 failed_export = true;
1736 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1739 if (runparams_in.silent)
1743 return !failed_export;
1747 void Buffer::writeLaTeXSource(otexstream & os,
1748 string const & original_path,
1749 OutputParams const & runparams_in,
1750 OutputWhat output) const
1752 // The child documents, if any, shall be already loaded at this point.
1754 OutputParams runparams = runparams_in;
1756 // XeTeX with TeX fonts is only safe with ASCII encoding,
1757 // Check here, because the "flavor" is not known in BufferParams::encoding()
1758 // (power users can override this safety measure selecting "utf8-plain").
1759 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1760 && (runparams.encoding->name() != "utf8-plain"))
1761 runparams.encoding = encodings.fromLyXName("ascii");
1762 // FIXME: when only the current paragraph is shown, this is ignored
1763 // (or not reached) and characters encodable in the current
1764 // encoding are not converted to ASCII-representation.
1766 // If we are compiling a file standalone, even if this is the
1767 // child of some other buffer, let's cut the link here, so the
1768 // file is really independent and no concurring settings from
1769 // the master (e.g. branch state) interfere (see #8100).
1770 if (!runparams.is_child)
1771 d->ignore_parent = true;
1773 // Classify the unicode characters appearing in math insets
1774 BufferEncodings::initUnicodeMath(*this);
1776 // validate the buffer.
1777 LYXERR(Debug::LATEX, " Validating buffer...");
1778 LaTeXFeatures features(*this, params(), runparams);
1780 // This is only set once per document (in master)
1781 if (!runparams.is_child)
1782 runparams.use_polyglossia = features.usePolyglossia();
1783 LYXERR(Debug::LATEX, " Buffer validation done.");
1785 bool const output_preamble =
1786 output == FullSource || output == OnlyPreamble;
1787 bool const output_body =
1788 output == FullSource || output == OnlyBody;
1790 // The starting paragraph of the coming rows is the
1791 // first paragraph of the document. (Asger)
1792 if (output_preamble && runparams.nice) {
1793 os << "%% LyX " << lyx_version << " created this file. "
1794 "For more info, see http://www.lyx.org/.\n"
1795 "%% Do not edit unless you really know what "
1798 LYXERR(Debug::INFO, "lyx document header finished");
1800 // There are a few differences between nice LaTeX and usual files:
1801 // usual files have \batchmode and special input@path to allow
1802 // inclusion of figures specified by an explicitly relative path
1803 // (i.e., a path starting with './' or '../') with either \input or
1804 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1805 // input@path is set when the actual parameter original_path is set.
1806 // This is done for usual tex-file, but not for nice-latex-file.
1807 // (Matthias 250696)
1808 // Note that input@path is only needed for something the user does
1809 // in the preamble, included .tex files or ERT, files included by
1810 // LyX work without it.
1811 if (output_preamble) {
1812 if (!runparams.nice) {
1813 // code for usual, NOT nice-latex-file
1814 os << "\\batchmode\n"; // changed from \nonstopmode
1816 if (!original_path.empty()) {
1818 // We don't know the encoding of inputpath
1819 docstring const inputpath = from_utf8(original_path);
1820 docstring uncodable_glyphs;
1821 Encoding const * const enc = runparams.encoding;
1823 for (size_t n = 0; n < inputpath.size(); ++n) {
1824 if (!enc->encodable(inputpath[n])) {
1825 docstring const glyph(1, inputpath[n]);
1826 LYXERR0("Uncodable character '"
1828 << "' in input path!");
1829 uncodable_glyphs += glyph;
1834 // warn user if we found uncodable glyphs.
1835 if (!uncodable_glyphs.empty()) {
1836 frontend::Alert::warning(
1837 _("Uncodable character in file path"),
1839 _("The path of your document\n"
1841 "contains glyphs that are unknown "
1842 "in the current document encoding "
1843 "(namely %2$s). This may result in "
1844 "incomplete output, unless "
1845 "TEXINPUTS contains the document "
1846 "directory and you don't use "
1847 "explicitly relative paths (i.e., "
1848 "paths starting with './' or "
1849 "'../') in the preamble or in ERT."
1850 "\n\nIn case of problems, choose "
1851 "an appropriate document encoding\n"
1852 "(such as utf8) or change the "
1854 inputpath, uncodable_glyphs));
1857 support::latex_path(original_path);
1858 if (contains(docdir, '#')) {
1859 docdir = subst(docdir, "#", "\\#");
1860 os << "\\catcode`\\#=11"
1861 "\\def\\#{#}\\catcode`\\#=6\n";
1863 if (contains(docdir, '%')) {
1864 docdir = subst(docdir, "%", "\\%");
1865 os << "\\catcode`\\%=11"
1866 "\\def\\%{%}\\catcode`\\%=14\n";
1868 os << "\\makeatletter\n"
1869 << "\\def\\input@path{{"
1871 << "\\makeatother\n";
1875 // get parent macros (if this buffer has a parent) which will be
1876 // written at the document begin further down.
1877 MacroSet parentMacros;
1878 listParentMacros(parentMacros, features);
1880 // Write the preamble
1881 runparams.use_babel = params().writeLaTeX(os, features,
1882 d->filename.onlyPath());
1884 // Biblatex bibliographies are loaded here
1885 if (params().useBiblatex()) {
1886 vector<docstring> const bibfiles =
1887 prepareBibFilePaths(runparams, getBibfilesCache(), true);
1888 for (docstring const & file: bibfiles)
1889 os << "\\addbibresource{" << file << "}\n";
1892 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1893 && !features.hasOnlyPolyglossiaLanguages()) {
1896 vector<string> bll = features.getBabelExclusiveLanguages();
1897 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1900 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1905 blangs = bll.size() > 1 ?
1906 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1907 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1911 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1916 plangs = pll.size() > 1 ?
1917 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1918 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1919 if (!blangs.empty())
1923 frontend::Alert::warning(
1924 _("Incompatible Languages!"),
1926 _("You cannot use the following languages "
1927 "together in one LaTeX document because "
1928 "they require conflicting language packages:\n"
1933 // Japanese might be required only in some children of a document,
1934 // but once required, we must keep use_japanese true.
1935 runparams.use_japanese |= features.isRequired("japanese");
1938 // Restore the parenthood if needed
1939 if (!runparams.is_child)
1940 d->ignore_parent = false;
1945 // mark the beginning of the body to separate it from InPreamble insets
1946 os.texrow().start(TexRow::beginDocument());
1947 os << "\\begin{document}\n";
1949 // mark the start of a new paragraph by simulating a newline,
1950 // so that os.afterParbreak() returns true at document start
1953 // output the parent macros
1954 MacroSet::iterator it = parentMacros.begin();
1955 MacroSet::iterator end = parentMacros.end();
1956 for (; it != end; ++it) {
1957 int num_lines = (*it)->write(os.os(), true);
1958 os.texrow().newlines(num_lines);
1961 } // output_preamble
1963 LYXERR(Debug::INFO, "preamble finished, now the body.");
1966 latexParagraphs(*this, text(), os, runparams);
1968 // Restore the parenthood if needed
1969 if (!runparams.is_child)
1970 d->ignore_parent = false;
1972 // add this just in case after all the paragraphs
1975 if (output_preamble) {
1976 os << "\\end{document}\n";
1977 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1979 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1981 runparams_in.encoding = runparams.encoding;
1983 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1984 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1988 void Buffer::makeDocBookFile(FileName const & fname,
1989 OutputParams const & runparams,
1990 OutputWhat output) const
1992 LYXERR(Debug::LATEX, "makeDocBookFile...");
1995 if (!openFileWrite(ofs, fname))
1998 // make sure we are ready to export
1999 // this needs to be done before we validate
2001 updateMacroInstances(OutputUpdate);
2003 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2007 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2011 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2012 OutputParams const & runparams,
2013 OutputWhat output) const
2015 LaTeXFeatures features(*this, params(), runparams);
2020 DocumentClass const & tclass = params().documentClass();
2021 string const & top_element = tclass.latexname();
2023 bool const output_preamble =
2024 output == FullSource || output == OnlyPreamble;
2025 bool const output_body =
2026 output == FullSource || output == OnlyBody;
2028 if (output_preamble) {
2029 if (runparams.flavor == OutputParams::XML)
2030 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2033 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2036 if (! tclass.class_header().empty())
2037 os << from_ascii(tclass.class_header());
2038 else if (runparams.flavor == OutputParams::XML)
2039 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2040 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2042 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2044 docstring preamble = params().preamble;
2045 if (runparams.flavor != OutputParams::XML ) {
2046 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2047 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2048 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2049 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2052 string const name = runparams.nice
2053 ? changeExtension(absFileName(), ".sgml") : fname;
2054 preamble += features.getIncludedFiles(name);
2055 preamble += features.getLyXSGMLEntities();
2057 if (!preamble.empty()) {
2058 os << "\n [ " << preamble << " ]";
2064 string top = top_element;
2066 if (runparams.flavor == OutputParams::XML)
2067 top += params().language->code();
2069 top += params().language->code().substr(0, 2);
2072 if (!params().options.empty()) {
2074 top += params().options;
2077 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2078 << " file was created by LyX " << lyx_version
2079 << "\n See http://www.lyx.org/ for more information -->\n";
2081 params().documentClass().counters().reset();
2083 sgml::openTag(os, top);
2085 docbookParagraphs(text(), *this, os, runparams);
2086 sgml::closeTag(os, top_element);
2091 void Buffer::makeLyXHTMLFile(FileName const & fname,
2092 OutputParams const & runparams) const
2094 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2097 if (!openFileWrite(ofs, fname))
2100 // make sure we are ready to export
2101 // this has to be done before we validate
2102 updateBuffer(UpdateMaster, OutputUpdate);
2103 updateMacroInstances(OutputUpdate);
2105 writeLyXHTMLSource(ofs, runparams, FullSource);
2109 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2113 void Buffer::writeLyXHTMLSource(odocstream & os,
2114 OutputParams const & runparams,
2115 OutputWhat output) const
2117 LaTeXFeatures features(*this, params(), runparams);
2119 d->bibinfo_.makeCitationLabels(*this);
2121 bool const output_preamble =
2122 output == FullSource || output == OnlyPreamble;
2123 bool const output_body =
2124 output == FullSource || output == OnlyBody || output == IncludedFile;
2126 if (output_preamble) {
2127 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2128 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
2129 // FIXME Language should be set properly.
2130 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2132 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2133 // FIXME Presumably need to set this right
2134 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2136 docstring const & doctitle = features.htmlTitle();
2138 << (doctitle.empty() ?
2139 from_ascii("LyX Document") :
2140 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2143 docstring styles = features.getTClassHTMLPreamble();
2144 if (!styles.empty())
2145 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2147 styles = features.getPreambleSnippets().str;
2148 if (!styles.empty())
2149 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2151 // we will collect CSS information in a stream, and then output it
2152 // either here, as part of the header, or else in a separate file.
2153 odocstringstream css;
2154 styles = features.getCSSSnippets();
2155 if (!styles.empty())
2156 css << "/* LyX Provided Styles */\n" << styles << '\n';
2158 styles = features.getTClassHTMLStyles();
2159 if (!styles.empty())
2160 css << "/* Layout-provided Styles */\n" << styles << '\n';
2162 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2163 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2164 if (needfg || needbg) {
2165 css << "\nbody {\n";
2168 << from_ascii(X11hexname(params().fontcolor))
2171 css << " background-color: "
2172 << from_ascii(X11hexname(params().backgroundcolor))
2177 docstring const dstyles = css.str();
2178 if (!dstyles.empty()) {
2179 bool written = false;
2180 if (params().html_css_as_file) {
2181 // open a file for CSS info
2183 string const fcssname = addName(temppath(), "docstyle.css");
2184 FileName const fcssfile = FileName(fcssname);
2185 if (openFileWrite(ocss, fcssfile)) {
2189 // write link to header
2190 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2192 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2195 // we are here if the CSS is supposed to be written to the header
2196 // or if we failed to write it to an external file.
2198 os << "<style type='text/css'>\n"
2207 bool const output_body_tag = (output != IncludedFile);
2208 if (output_body_tag)
2209 os << "<body dir=\"auto\">\n";
2211 if (output != IncludedFile)
2212 // if we're an included file, the counters are in the master.
2213 params().documentClass().counters().reset();
2214 xhtmlParagraphs(text(), *this, xs, runparams);
2215 if (output_body_tag)
2219 if (output_preamble)
2224 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2225 // Other flags: -wall -v0 -x
2226 int Buffer::runChktex()
2230 // get LaTeX-Filename
2231 FileName const path(temppath());
2232 string const name = addName(path.absFileName(), latexName());
2233 string const org_path = filePath();
2235 PathChanger p(path); // path to LaTeX file
2236 message(_("Running chktex..."));
2238 // Generate the LaTeX file if neccessary
2239 OutputParams runparams(¶ms().encoding());
2240 runparams.flavor = OutputParams::LATEX;
2241 runparams.nice = false;
2242 runparams.linelen = lyxrc.plaintext_linelen;
2243 makeLaTeXFile(FileName(name), org_path, runparams);
2246 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2247 int const res = chktex.run(terr); // run chktex
2250 Alert::error(_("chktex failure"),
2251 _("Could not run chktex successfully."));
2253 ErrorList & errlist = d->errorLists["ChkTeX"];
2255 bufferErrors(terr, errlist);
2260 if (runparams.silent)
2261 d->errorLists["ChkTeX"].clear();
2269 void Buffer::validate(LaTeXFeatures & features) const
2271 // Validate the buffer params, but not for included
2272 // files, since they also use the parent buffer's
2274 if (!features.runparams().is_child)
2275 params().validate(features);
2277 for (Paragraph const & p : paragraphs())
2278 p.validate(features);
2280 if (lyxerr.debugging(Debug::LATEX)) {
2281 features.showStruct();
2286 void Buffer::getLabelList(vector<docstring> & list) const
2288 // If this is a child document, use the master's list instead.
2290 masterBuffer()->getLabelList(list);
2295 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2296 Toc::const_iterator toc_it = toc->begin();
2297 Toc::const_iterator end = toc->end();
2298 for (; toc_it != end; ++toc_it) {
2299 if (toc_it->depth() == 0)
2300 list.push_back(toc_it->str());
2305 void Buffer::updateBibfilesCache(UpdateScope scope) const
2307 // FIXME This is probably unnecssary, given where we call this.
2308 // If this is a child document, use the parent's cache instead.
2309 if (parent() && scope != UpdateChildOnly) {
2310 masterBuffer()->updateBibfilesCache();
2314 d->bibfiles_cache_.clear();
2315 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2316 if (it->lyxCode() == BIBTEX_CODE) {
2317 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2318 support::FileNamePairList const bibfiles = inset.getBibFiles();
2319 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2322 } else if (it->lyxCode() == INCLUDE_CODE) {
2323 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2324 Buffer const * const incbuf = inset.getChildBuffer();
2327 support::FileNamePairList const & bibfiles =
2328 incbuf->getBibfilesCache(UpdateChildOnly);
2329 if (!bibfiles.empty()) {
2330 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2336 d->bibfile_cache_valid_ = true;
2337 d->bibinfo_cache_valid_ = false;
2338 d->cite_labels_valid_ = false;
2342 void Buffer::invalidateBibinfoCache() const
2344 d->bibinfo_cache_valid_ = false;
2345 d->cite_labels_valid_ = false;
2346 // also invalidate the cache for the parent buffer
2347 Buffer const * const pbuf = d->parent();
2349 pbuf->invalidateBibinfoCache();
2353 void Buffer::invalidateBibfileCache() const
2355 d->bibfile_cache_valid_ = false;
2356 d->bibinfo_cache_valid_ = false;
2357 d->cite_labels_valid_ = false;
2358 // also invalidate the cache for the parent buffer
2359 Buffer const * const pbuf = d->parent();
2361 pbuf->invalidateBibfileCache();
2365 support::FileNamePairList const & Buffer::getBibfilesCache(UpdateScope scope) const
2367 // FIXME This is probably unnecessary, given where we call this.
2368 // If this is a child document, use the master's cache instead.
2369 Buffer const * const pbuf = masterBuffer();
2370 if (pbuf != this && scope != UpdateChildOnly)
2371 return pbuf->getBibfilesCache();
2373 if (!d->bibfile_cache_valid_)
2374 this->updateBibfilesCache(scope);
2376 return d->bibfiles_cache_;
2380 BiblioInfo const & Buffer::masterBibInfo() const
2382 Buffer const * const tmp = masterBuffer();
2384 return tmp->masterBibInfo();
2389 void Buffer::checkIfBibInfoCacheIsValid() const
2391 // use the master's cache
2392 Buffer const * const tmp = masterBuffer();
2394 tmp->checkIfBibInfoCacheIsValid();
2398 // compare the cached timestamps with the actual ones.
2399 FileNamePairList const & bibfiles_cache = getBibfilesCache();
2400 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2401 FileNamePairList::const_iterator en = bibfiles_cache.end();
2402 for (; ei != en; ++ ei) {
2403 FileName const fn = ei->second;
2404 time_t lastw = fn.lastModified();
2405 time_t prevw = d->bibfile_status_[fn];
2406 if (lastw != prevw) {
2407 d->bibinfo_cache_valid_ = false;
2408 d->cite_labels_valid_ = false;
2409 d->bibfile_status_[fn] = lastw;
2415 void Buffer::reloadBibInfoCache() const
2417 // use the master's cache
2418 Buffer const * const tmp = masterBuffer();
2420 tmp->reloadBibInfoCache();
2424 checkIfBibInfoCacheIsValid();
2425 if (d->bibinfo_cache_valid_)
2428 d->bibinfo_.clear();
2430 d->bibinfo_cache_valid_ = true;
2434 void Buffer::collectBibKeys() const
2436 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2437 it->collectBibKeys(it);
2441 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2443 Buffer const * tmp = masterBuffer();
2444 BiblioInfo & masterbi = (tmp == this) ?
2445 d->bibinfo_ : tmp->d->bibinfo_;
2446 masterbi.mergeBiblioInfo(bi);
2450 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2452 Buffer const * tmp = masterBuffer();
2453 BiblioInfo & masterbi = (tmp == this) ?
2454 d->bibinfo_ : tmp->d->bibinfo_;
2459 void Buffer::makeCitationLabels() const
2461 Buffer const * const master = masterBuffer();
2462 return d->bibinfo_.makeCitationLabels(*master);
2466 bool Buffer::citeLabelsValid() const
2468 return masterBuffer()->d->cite_labels_valid_;
2472 void Buffer::removeBiblioTempFiles() const
2474 // We remove files that contain LaTeX commands specific to the
2475 // particular bibliographic style being used, in order to avoid
2476 // LaTeX errors when we switch style.
2477 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2478 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2479 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2480 aux_file.removeFile();
2481 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2482 bbl_file.removeFile();
2483 // Also for the parent buffer
2484 Buffer const * const pbuf = parent();
2486 pbuf->removeBiblioTempFiles();
2490 bool Buffer::isDepClean(string const & name) const
2492 DepClean::const_iterator const it = d->dep_clean.find(name);
2493 if (it == d->dep_clean.end())
2499 void Buffer::markDepClean(string const & name)
2501 d->dep_clean[name] = true;
2505 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2508 // FIXME? if there is an Buffer LFUN that can be dispatched even
2509 // if internal, put a switch '(cmd.action)' here.
2515 switch (cmd.action()) {
2517 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2518 flag.setOnOff(isReadonly());
2521 // FIXME: There is need for a command-line import.
2522 //case LFUN_BUFFER_IMPORT:
2524 case LFUN_BUFFER_AUTO_SAVE:
2527 case LFUN_BUFFER_EXPORT_CUSTOM:
2528 // FIXME: Nothing to check here?
2531 case LFUN_BUFFER_EXPORT: {
2532 docstring const arg = cmd.argument();
2533 if (arg == "custom") {
2538 arg.empty() ? params().getDefaultOutputFormat() : to_utf8(arg);
2539 size_t pos = format.find(' ');
2540 if (pos != string::npos)
2541 format = format.substr(0, pos);
2542 enable = params().isExportable(format, false);
2544 flag.message(bformat(
2545 _("Don't know how to export to format: %1$s"), arg));
2549 case LFUN_BUFFER_CHKTEX:
2550 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2553 case LFUN_BUILD_PROGRAM:
2554 enable = params().isExportable("program", false);
2557 case LFUN_BRANCH_ACTIVATE:
2558 case LFUN_BRANCH_DEACTIVATE:
2559 case LFUN_BRANCH_MASTER_ACTIVATE:
2560 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2561 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2562 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2563 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2564 : params().branchlist();
2565 docstring const branchName = cmd.argument();
2566 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2570 case LFUN_BRANCH_ADD:
2571 case LFUN_BRANCHES_RENAME:
2572 // if no Buffer is present, then of course we won't be called!
2575 case LFUN_BUFFER_LANGUAGE:
2576 enable = !isReadonly();
2579 case LFUN_BUFFER_VIEW_CACHE:
2580 (d->preview_file_).refresh();
2581 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2584 case LFUN_CHANGES_TRACK:
2585 flag.setEnabled(true);
2586 flag.setOnOff(params().track_changes);
2589 case LFUN_CHANGES_OUTPUT:
2590 flag.setEnabled(true);
2591 flag.setOnOff(params().output_changes);
2594 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2595 flag.setOnOff(params().compressed);
2599 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2600 flag.setOnOff(params().output_sync);
2607 flag.setEnabled(enable);
2612 void Buffer::dispatch(string const & command, DispatchResult & result)
2614 return dispatch(lyxaction.lookupFunc(command), result);
2618 // NOTE We can end up here even if we have no GUI, because we are called
2619 // by LyX::exec to handled command-line requests. So we may need to check
2620 // whether we have a GUI or not. The boolean use_gui holds this information.
2621 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2624 // FIXME? if there is an Buffer LFUN that can be dispatched even
2625 // if internal, put a switch '(cmd.action())' here.
2626 dr.dispatched(false);
2629 string const argument = to_utf8(func.argument());
2630 // We'll set this back to false if need be.
2631 bool dispatched = true;
2632 undo().beginUndoGroup();
2634 switch (func.action()) {
2635 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2636 if (lyxvc().inUse()) {
2637 string log = lyxvc().toggleReadOnly();
2642 setReadonly(!isReadonly());
2645 case LFUN_BUFFER_EXPORT: {
2646 string const format =
2647 argument.empty() ? params().getDefaultOutputFormat() : argument;
2648 ExportStatus const status = doExport(format, false);
2649 dr.setError(status != ExportSuccess);
2650 if (status != ExportSuccess)
2651 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2652 from_utf8(format)));
2656 case LFUN_BUILD_PROGRAM: {
2657 ExportStatus const status = doExport("program", true);
2658 dr.setError(status != ExportSuccess);
2659 if (status != ExportSuccess)
2660 dr.setMessage(_("Error generating literate programming code."));
2664 case LFUN_BUFFER_CHKTEX:
2668 case LFUN_BUFFER_EXPORT_CUSTOM: {
2670 string command = split(argument, format_name, ' ');
2671 Format const * format = formats.getFormat(format_name);
2673 lyxerr << "Format \"" << format_name
2674 << "\" not recognized!"
2679 // The name of the file created by the conversion process
2682 // Output to filename
2683 if (format->name() == "lyx") {
2684 string const latexname = latexName(false);
2685 filename = changeExtension(latexname,
2686 format->extension());
2687 filename = addName(temppath(), filename);
2689 if (!writeFile(FileName(filename)))
2693 doExport(format_name, true, filename);
2696 // Substitute $$FName for filename
2697 if (!contains(command, "$$FName"))
2698 command = "( " + command + " ) < $$FName";
2699 command = subst(command, "$$FName", filename);
2701 // Execute the command in the background
2703 call.startscript(Systemcall::DontWait, command,
2704 filePath(), layoutPos());
2708 // FIXME: There is need for a command-line import.
2710 case LFUN_BUFFER_IMPORT:
2715 case LFUN_BUFFER_AUTO_SAVE:
2717 resetAutosaveTimers();
2720 case LFUN_BRANCH_ACTIVATE:
2721 case LFUN_BRANCH_DEACTIVATE:
2722 case LFUN_BRANCH_MASTER_ACTIVATE:
2723 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2724 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2725 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2726 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2729 docstring const branch_name = func.argument();
2730 // the case without a branch name is handled elsewhere
2731 if (branch_name.empty()) {
2735 Branch * branch = buf->params().branchlist().find(branch_name);
2737 LYXERR0("Branch " << branch_name << " does not exist.");
2739 docstring const msg =
2740 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2744 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2745 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2746 if (branch->isSelected() != activate) {
2747 buf->undo().recordUndoBufferParams(CursorData());
2748 branch->setSelected(activate);
2750 dr.screenUpdate(Update::Force);
2751 dr.forceBufferUpdate();
2756 case LFUN_BRANCH_ADD: {
2757 docstring branch_name = func.argument();
2758 if (branch_name.empty()) {
2762 BranchList & branch_list = params().branchlist();
2763 vector<docstring> const branches =
2764 getVectorFromString(branch_name, branch_list.separator());
2766 for (vector<docstring>::const_iterator it = branches.begin();
2767 it != branches.end(); ++it) {
2769 Branch * branch = branch_list.find(branch_name);
2771 LYXERR0("Branch " << branch_name << " already exists.");
2775 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2777 undo().recordUndoBufferParams(CursorData());
2778 branch_list.add(branch_name);
2779 branch = branch_list.find(branch_name);
2780 string const x11hexname = X11hexname(branch->color());
2781 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2782 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2784 dr.screenUpdate(Update::Force);
2792 case LFUN_BRANCHES_RENAME: {
2793 if (func.argument().empty())
2796 docstring const oldname = from_utf8(func.getArg(0));
2797 docstring const newname = from_utf8(func.getArg(1));
2798 InsetIterator it = inset_iterator_begin(inset());
2799 InsetIterator const end = inset_iterator_end(inset());
2800 bool success = false;
2801 for (; it != end; ++it) {
2802 if (it->lyxCode() == BRANCH_CODE) {
2803 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2804 if (ins.branch() == oldname) {
2805 undo().recordUndo(CursorData(it));
2806 ins.rename(newname);
2811 if (it->lyxCode() == INCLUDE_CODE) {
2812 // get buffer of external file
2813 InsetInclude const & ins =
2814 static_cast<InsetInclude const &>(*it);
2815 Buffer * child = ins.getChildBuffer();
2818 child->dispatch(func, dr);
2823 dr.screenUpdate(Update::Force);
2824 dr.forceBufferUpdate();
2829 case LFUN_BUFFER_VIEW_CACHE:
2830 if (!formats.view(*this, d->preview_file_,
2831 d->preview_format_))
2832 dr.setMessage(_("Error viewing the output file."));
2835 case LFUN_CHANGES_TRACK:
2836 if (params().save_transient_properties)
2837 undo().recordUndoBufferParams(CursorData());
2838 params().track_changes = !params().track_changes;
2839 if (!params().track_changes)
2840 dr.forceChangesUpdate();
2843 case LFUN_CHANGES_OUTPUT:
2844 if (params().save_transient_properties)
2845 undo().recordUndoBufferParams(CursorData());
2846 params().output_changes = !params().output_changes;
2847 if (params().output_changes) {
2848 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2849 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2850 LaTeXFeatures::isAvailable("xcolor");
2852 if (!dvipost && !xcolorulem) {
2853 Alert::warning(_("Changes not shown in LaTeX output"),
2854 _("Changes will not be highlighted in LaTeX output, "
2855 "because neither dvipost nor xcolor/ulem are installed.\n"
2856 "Please install these packages or redefine "
2857 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2858 } else if (!xcolorulem) {
2859 Alert::warning(_("Changes not shown in LaTeX output"),
2860 _("Changes will not be highlighted in LaTeX output "
2861 "when using pdflatex, because xcolor and ulem are not installed.\n"
2862 "Please install both packages or redefine "
2863 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2868 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2869 // turn compression on/off
2870 undo().recordUndoBufferParams(CursorData());
2871 params().compressed = !params().compressed;
2874 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2875 undo().recordUndoBufferParams(CursorData());
2876 params().output_sync = !params().output_sync;
2883 dr.dispatched(dispatched);
2884 undo().endUndoGroup();
2888 void Buffer::changeLanguage(Language const * from, Language const * to)
2890 LASSERT(from, return);
2891 LASSERT(to, return);
2893 for_each(par_iterator_begin(),
2895 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2899 bool Buffer::isMultiLingual() const
2901 ParConstIterator end = par_iterator_end();
2902 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2903 if (it->isMultiLingual(params()))
2910 std::set<Language const *> Buffer::getLanguages() const
2912 std::set<Language const *> languages;
2913 getLanguages(languages);
2918 void Buffer::getLanguages(std::set<Language const *> & languages) const
2920 ParConstIterator end = par_iterator_end();
2921 // add the buffer language, even if it's not actively used
2922 languages.insert(language());
2923 // iterate over the paragraphs
2924 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2925 it->getLanguages(languages);
2927 ListOfBuffers clist = getDescendents();
2928 ListOfBuffers::const_iterator cit = clist.begin();
2929 ListOfBuffers::const_iterator const cen = clist.end();
2930 for (; cit != cen; ++cit)
2931 (*cit)->getLanguages(languages);
2935 DocIterator Buffer::getParFromID(int const id) const
2937 Buffer * buf = const_cast<Buffer *>(this);
2939 // This means non-existent
2940 return doc_iterator_end(buf);
2942 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2943 if (it.paragraph().id() == id)
2946 return doc_iterator_end(buf);
2950 bool Buffer::hasParWithID(int const id) const
2952 return !getParFromID(id).atEnd();
2956 ParIterator Buffer::par_iterator_begin()
2958 return ParIterator(doc_iterator_begin(this));
2962 ParIterator Buffer::par_iterator_end()
2964 return ParIterator(doc_iterator_end(this));
2968 ParConstIterator Buffer::par_iterator_begin() const
2970 return ParConstIterator(doc_iterator_begin(this));
2974 ParConstIterator Buffer::par_iterator_end() const
2976 return ParConstIterator(doc_iterator_end(this));
2980 Language const * Buffer::language() const
2982 return params().language;
2986 docstring const Buffer::B_(string const & l10n) const
2988 return params().B_(l10n);
2992 bool Buffer::isClean() const
2994 return d->lyx_clean;
2998 bool Buffer::isExternallyModified(CheckMethod method) const
3000 LASSERT(d->filename.exists(), return false);
3001 // if method == timestamp, check timestamp before checksum
3002 return (method == checksum_method
3003 || d->timestamp_ != d->filename.lastModified())
3004 && d->checksum_ != d->filename.checksum();
3008 void Buffer::saveCheckSum() const
3010 FileName const & file = d->filename;
3013 if (file.exists()) {
3014 d->timestamp_ = file.lastModified();
3015 d->checksum_ = file.checksum();
3017 // in the case of save to a new file.
3024 void Buffer::markClean() const
3026 if (!d->lyx_clean) {
3027 d->lyx_clean = true;
3030 // if the .lyx file has been saved, we don't need an
3032 d->bak_clean = true;
3033 d->undo_.markDirty();
3037 void Buffer::setUnnamed(bool flag)
3043 bool Buffer::isUnnamed() const
3050 /// Don't check unnamed, here: isInternal() is used in
3051 /// newBuffer(), where the unnamed flag has not been set by anyone
3052 /// yet. Also, for an internal buffer, there should be no need for
3053 /// retrieving fileName() nor for checking if it is unnamed or not.
3054 bool Buffer::isInternal() const
3056 return d->internal_buffer;
3060 void Buffer::setInternal(bool flag)
3062 d->internal_buffer = flag;
3066 void Buffer::markDirty()
3069 d->lyx_clean = false;
3072 d->bak_clean = false;
3074 DepClean::iterator it = d->dep_clean.begin();
3075 DepClean::const_iterator const end = d->dep_clean.end();
3077 for (; it != end; ++it)
3082 FileName Buffer::fileName() const
3088 string Buffer::absFileName() const
3090 return d->filename.absFileName();
3094 string Buffer::filePath() const
3096 string const abs = d->filename.onlyPath().absFileName();
3099 int last = abs.length() - 1;
3101 return abs[last] == '/' ? abs : abs + '/';
3105 DocFileName Buffer::getReferencedFileName(string const & fn) const
3108 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3109 result.set(fn, filePath());
3111 // filePath() ends with a path separator
3112 FileName const test(filePath() + fn);
3114 result.set(fn, filePath());
3116 result.set(fn, params().origin);
3123 string const Buffer::prepareFileNameForLaTeX(string const & name,
3124 string const & ext, bool nice) const
3126 string const fname = makeAbsPath(name, filePath()).absFileName();
3127 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3133 return to_utf8(makeRelPath(from_utf8(fname),
3134 from_utf8(masterBuffer()->filePath())));
3138 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3139 FileNamePairList const bibfilelist,
3140 bool const add_extension) const
3142 // If we are processing the LaTeX file in a temp directory then
3143 // copy the .bib databases to this temp directory, mangling their
3144 // names in the process. Store this mangled name in the list of
3146 // (We need to do all this because BibTeX *really*, *really*
3147 // can't handle "files with spaces" and Windows users tend to
3148 // use such filenames.)
3149 // Otherwise, store the (maybe absolute) path to the original,
3150 // unmangled database name.
3152 vector<docstring> res;
3154 // determine the export format
3155 string const tex_format = flavor2format(runparams.flavor);
3157 // check for spaces in paths
3158 bool found_space = false;
3160 FileNamePairList::const_iterator it = bibfilelist.begin();
3161 FileNamePairList::const_iterator en = bibfilelist.end();
3162 for (; it != en; ++it) {
3163 string utf8input = to_utf8(it->first);
3165 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3166 FileName const try_in_file =
3167 makeAbsPath(database + ".bib", filePath());
3168 bool const not_from_texmf = try_in_file.isReadableFile();
3170 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3172 // mangledFileName() needs the extension
3173 DocFileName const in_file = DocFileName(try_in_file);
3174 database = removeExtension(in_file.mangledFileName());
3175 FileName const out_file = makeAbsPath(database + ".bib",
3176 masterBuffer()->temppath());
3177 bool const success = in_file.copyTo(out_file);
3179 LYXERR0("Failed to copy '" << in_file
3180 << "' to '" << out_file << "'");
3182 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3183 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3184 if (!isValidLaTeXFileName(database)) {
3185 frontend::Alert::warning(_("Invalid filename"),
3186 _("The following filename will cause troubles "
3187 "when running the exported file through LaTeX: ") +
3188 from_utf8(database));
3190 if (!isValidDVIFileName(database)) {
3191 frontend::Alert::warning(_("Problematic filename for DVI"),
3192 _("The following filename can cause troubles "
3193 "when running the exported file through LaTeX "
3194 "and opening the resulting DVI: ") +
3195 from_utf8(database), true);
3203 docstring const path = from_utf8(latex_path(database));
3205 if (contains(path, ' '))
3208 if (find(res.begin(), res.end(), path) == res.end())
3209 res.push_back(path);
3212 // Check if there are spaces in the path and warn BibTeX users, if so.
3213 // (biber can cope with such paths)
3214 if (!prefixIs(runparams.bibtex_command, "biber")) {
3215 // Post this warning only once.
3216 static bool warned_about_spaces = false;
3217 if (!warned_about_spaces &&
3218 runparams.nice && found_space) {
3219 warned_about_spaces = true;
3220 Alert::warning(_("Export Warning!"),
3221 _("There are spaces in the paths to your BibTeX databases.\n"
3222 "BibTeX will be unable to find them."));
3231 string Buffer::layoutPos() const
3233 return d->layout_position;
3237 void Buffer::setLayoutPos(string const & path)
3240 d->layout_position.clear();
3244 LATTEST(FileName::isAbsolute(path));
3246 d->layout_position =
3247 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3249 if (d->layout_position.empty())
3250 d->layout_position = ".";
3254 bool Buffer::isReadonly() const
3256 return d->read_only;
3260 void Buffer::setParent(Buffer const * buffer)
3262 // Avoids recursive include.
3263 d->setParent(buffer == this ? 0 : buffer);
3268 Buffer const * Buffer::parent() const
3274 ListOfBuffers Buffer::allRelatives() const
3276 ListOfBuffers lb = masterBuffer()->getDescendents();
3277 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3282 Buffer const * Buffer::masterBuffer() const
3284 // FIXME Should be make sure we are not in some kind
3285 // of recursive include? A -> B -> A will crash this.
3286 Buffer const * const pbuf = d->parent();
3290 return pbuf->masterBuffer();
3294 bool Buffer::isChild(Buffer * child) const
3296 return d->children_positions.find(child) != d->children_positions.end();
3300 DocIterator Buffer::firstChildPosition(Buffer const * child)
3302 Impl::BufferPositionMap::iterator it;
3303 it = d->children_positions.find(child);
3304 if (it == d->children_positions.end())
3305 return DocIterator(this);
3310 bool Buffer::hasChildren() const
3312 return !d->children_positions.empty();
3316 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3318 // loop over children
3319 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3320 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3321 for (; it != end; ++it) {
3322 Buffer * child = const_cast<Buffer *>(it->first);
3324 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3325 if (bit != clist.end())
3327 clist.push_back(child);
3329 // there might be grandchildren
3330 child->collectChildren(clist, true);
3335 ListOfBuffers Buffer::getChildren() const
3338 collectChildren(v, false);
3339 // Make sure we have not included ourselves.
3340 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3341 if (bit != v.end()) {
3342 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3349 ListOfBuffers Buffer::getDescendents() const
3352 collectChildren(v, true);
3353 // Make sure we have not included ourselves.
3354 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3355 if (bit != v.end()) {
3356 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3363 template<typename M>
3364 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3369 typename M::const_iterator it = m.lower_bound(x);
3370 if (it == m.begin())
3378 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3379 DocIterator const & pos) const
3381 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3383 // if paragraphs have no macro context set, pos will be empty
3387 // we haven't found anything yet
3388 DocIterator bestPos = owner_->par_iterator_begin();
3389 MacroData const * bestData = 0;
3391 // find macro definitions for name
3392 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3393 if (nameIt != macros.end()) {
3394 // find last definition in front of pos or at pos itself
3395 PositionScopeMacroMap::const_iterator it
3396 = greatest_below(nameIt->second, pos);
3397 if (it != nameIt->second.end()) {
3399 // scope ends behind pos?
3400 if (pos < it->second.scope) {
3401 // Looks good, remember this. If there
3402 // is no external macro behind this,
3403 // we found the right one already.
3404 bestPos = it->first;
3405 bestData = &it->second.macro;
3409 // try previous macro if there is one
3410 if (it == nameIt->second.begin())
3417 // find macros in included files
3418 PositionScopeBufferMap::const_iterator it
3419 = greatest_below(position_to_children, pos);
3420 if (it == position_to_children.end())
3421 // no children before
3425 // do we know something better (i.e. later) already?
3426 if (it->first < bestPos )
3429 // scope ends behind pos?
3430 if (pos < it->second.scope
3431 && (cloned_buffer_ ||
3432 theBufferList().isLoaded(it->second.buffer))) {
3433 // look for macro in external file
3435 MacroData const * data
3436 = it->second.buffer->getMacro(name, false);
3439 bestPos = it->first;
3445 // try previous file if there is one
3446 if (it == position_to_children.begin())
3451 // return the best macro we have found
3456 MacroData const * Buffer::getMacro(docstring const & name,
3457 DocIterator const & pos, bool global) const
3462 // query buffer macros
3463 MacroData const * data = d->getBufferMacro(name, pos);
3467 // If there is a master buffer, query that
3468 Buffer const * const pbuf = d->parent();
3470 d->macro_lock = true;
3471 MacroData const * macro = pbuf->getMacro(
3472 name, *this, false);
3473 d->macro_lock = false;
3479 data = MacroTable::globalMacros().get(name);
3488 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3490 // set scope end behind the last paragraph
3491 DocIterator scope = par_iterator_begin();
3492 scope.pit() = scope.lastpit() + 1;
3494 return getMacro(name, scope, global);
3498 MacroData const * Buffer::getMacro(docstring const & name,
3499 Buffer const & child, bool global) const
3501 // look where the child buffer is included first
3502 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3503 if (it == d->children_positions.end())
3506 // check for macros at the inclusion position
3507 return getMacro(name, it->second, global);
3511 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3513 pit_type const lastpit = it.lastpit();
3515 // look for macros in each paragraph
3516 while (it.pit() <= lastpit) {
3517 Paragraph & par = it.paragraph();
3519 // iterate over the insets of the current paragraph
3520 InsetList const & insets = par.insetList();
3521 InsetList::const_iterator iit = insets.begin();
3522 InsetList::const_iterator end = insets.end();
3523 for (; iit != end; ++iit) {
3524 it.pos() = iit->pos;
3526 // is it a nested text inset?
3527 if (iit->inset->asInsetText()) {
3528 // Inset needs its own scope?
3529 InsetText const * itext = iit->inset->asInsetText();
3530 bool newScope = itext->isMacroScope();
3532 // scope which ends just behind the inset
3533 DocIterator insetScope = it;
3536 // collect macros in inset
3537 it.push_back(CursorSlice(*iit->inset));
3538 updateMacros(it, newScope ? insetScope : scope);
3543 if (iit->inset->asInsetTabular()) {
3544 CursorSlice slice(*iit->inset);
3545 size_t const numcells = slice.nargs();
3546 for (; slice.idx() < numcells; slice.forwardIdx()) {
3547 it.push_back(slice);
3548 updateMacros(it, scope);
3554 // is it an external file?
3555 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3556 // get buffer of external file
3557 InsetInclude const & inset =
3558 static_cast<InsetInclude const &>(*iit->inset);
3560 Buffer * child = inset.getChildBuffer();
3565 // register its position, but only when it is
3566 // included first in the buffer
3567 if (children_positions.find(child) ==
3568 children_positions.end())
3569 children_positions[child] = it;
3571 // register child with its scope
3572 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3576 InsetMath * im = iit->inset->asInsetMath();
3577 if (doing_export && im) {
3578 InsetMathHull * hull = im->asHullInset();
3580 hull->recordLocation(it);
3583 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3587 MathMacroTemplate & macroTemplate =
3588 *iit->inset->asInsetMath()->asMacroTemplate();
3589 MacroContext mc(owner_, it);
3590 macroTemplate.updateToContext(mc);
3593 bool valid = macroTemplate.validMacro();
3594 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3595 // then the BufferView's cursor will be invalid in
3596 // some cases which leads to crashes.
3601 // FIXME (Abdel), I don't understand why we pass 'it' here
3602 // instead of 'macroTemplate' defined above... is this correct?
3603 macros[macroTemplate.name()][it] =
3604 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3614 void Buffer::updateMacros() const
3619 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3621 // start with empty table
3623 d->children_positions.clear();
3624 d->position_to_children.clear();
3626 // Iterate over buffer, starting with first paragraph
3627 // The scope must be bigger than any lookup DocIterator
3628 // later. For the global lookup, lastpit+1 is used, hence
3629 // we use lastpit+2 here.
3630 DocIterator it = par_iterator_begin();
3631 DocIterator outerScope = it;
3632 outerScope.pit() = outerScope.lastpit() + 2;
3633 d->updateMacros(it, outerScope);
3637 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3639 InsetIterator it = inset_iterator_begin(inset());
3640 InsetIterator const end = inset_iterator_end(inset());
3641 for (; it != end; ++it) {
3642 if (it->lyxCode() == BRANCH_CODE) {
3643 InsetBranch & br = static_cast<InsetBranch &>(*it);
3644 docstring const name = br.branch();
3645 if (!from_master && !params().branchlist().find(name))
3646 result.push_back(name);
3647 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3648 result.push_back(name);
3651 if (it->lyxCode() == INCLUDE_CODE) {
3652 // get buffer of external file
3653 InsetInclude const & ins =
3654 static_cast<InsetInclude const &>(*it);
3655 Buffer * child = ins.getChildBuffer();
3658 child->getUsedBranches(result, true);
3661 // remove duplicates
3666 void Buffer::updateMacroInstances(UpdateType utype) const
3668 LYXERR(Debug::MACROS, "updateMacroInstances for "
3669 << d->filename.onlyFileName());
3670 DocIterator it = doc_iterator_begin(this);
3672 DocIterator const end = doc_iterator_end(this);
3673 for (; it != end; it.forwardInset()) {
3674 // look for MathData cells in InsetMathNest insets
3675 InsetMath * minset = it.nextInset()->asInsetMath();
3679 // update macro in all cells of the InsetMathNest
3680 DocIterator::idx_type n = minset->nargs();
3681 MacroContext mc = MacroContext(this, it);
3682 for (DocIterator::idx_type i = 0; i < n; ++i) {
3683 MathData & data = minset->cell(i);
3684 data.updateMacros(0, mc, utype, 0);
3690 void Buffer::listMacroNames(MacroNameSet & macros) const
3695 d->macro_lock = true;
3697 // loop over macro names
3698 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3699 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3700 for (; nameIt != nameEnd; ++nameIt)
3701 macros.insert(nameIt->first);
3703 // loop over children
3704 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3705 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3706 for (; it != end; ++it)
3707 it->first->listMacroNames(macros);
3710 Buffer const * const pbuf = d->parent();
3712 pbuf->listMacroNames(macros);
3714 d->macro_lock = false;
3718 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3720 Buffer const * const pbuf = d->parent();
3725 pbuf->listMacroNames(names);
3728 MacroNameSet::iterator it = names.begin();
3729 MacroNameSet::iterator end = names.end();
3730 for (; it != end; ++it) {
3732 MacroData const * data =
3733 pbuf->getMacro(*it, *this, false);
3735 macros.insert(data);
3737 // we cannot access the original MathMacroTemplate anymore
3738 // here to calls validate method. So we do its work here manually.
3739 // FIXME: somehow make the template accessible here.
3740 if (data->optionals() > 0)
3741 features.require("xargs");
3747 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3750 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3752 RefCache::iterator it = d->ref_cache_.find(label);
3753 if (it != d->ref_cache_.end())
3754 return it->second.second;
3756 static InsetLabel const * dummy_il = 0;
3757 static References const dummy_refs = References();
3758 it = d->ref_cache_.insert(
3759 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3760 return it->second.second;
3764 Buffer::References const & Buffer::references(docstring const & label) const
3766 return const_cast<Buffer *>(this)->getReferenceCache(label);
3770 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3772 References & refs = getReferenceCache(label);
3773 refs.push_back(make_pair(inset, it));
3777 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3779 masterBuffer()->d->ref_cache_[label].first = il;
3783 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3785 return masterBuffer()->d->ref_cache_[label].first;
3789 void Buffer::clearReferenceCache() const
3792 d->ref_cache_.clear();
3796 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3798 //FIXME: This does not work for child documents yet.
3799 reloadBibInfoCache();
3801 // Check if the label 'from' appears more than once
3802 BiblioInfo const & keys = masterBibInfo();
3803 BiblioInfo::const_iterator bit = keys.begin();
3804 BiblioInfo::const_iterator bend = keys.end();
3805 vector<docstring> labels;
3807 for (; bit != bend; ++bit)
3809 labels.push_back(bit->first);
3811 if (count(labels.begin(), labels.end(), from) > 1)
3814 string const paramName = "key";
3815 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3816 if (it->lyxCode() != CITE_CODE)
3818 InsetCommand * inset = it->asInsetCommand();
3819 docstring const oldValue = inset->getParam(paramName);
3820 if (oldValue == from)
3821 inset->setParam(paramName, to);
3825 // returns NULL if id-to-row conversion is unsupported
3826 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3827 pit_type par_begin, pit_type par_end,
3828 OutputWhat output, bool master) const
3830 unique_ptr<TexRow> texrow;
3831 OutputParams runparams(¶ms().encoding());
3832 runparams.nice = true;
3833 runparams.flavor = params().getOutputFlavor(format);
3834 runparams.linelen = lyxrc.plaintext_linelen;
3835 // No side effect of file copying and image conversion
3836 runparams.dryrun = true;
3838 if (output == CurrentParagraph) {
3839 runparams.par_begin = par_begin;
3840 runparams.par_end = par_end;
3841 if (par_begin + 1 == par_end) {
3843 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3847 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3848 convert<docstring>(par_begin),
3849 convert<docstring>(par_end - 1))
3852 // output paragraphs
3853 if (runparams.flavor == OutputParams::LYX) {
3854 Paragraph const & par = text().paragraphs()[par_begin];
3856 depth_type dt = par.getDepth();
3857 par.write(ods, params(), dt);
3858 os << from_utf8(ods.str());
3859 } else if (runparams.flavor == OutputParams::HTML) {
3861 setMathFlavor(runparams);
3862 xhtmlParagraphs(text(), *this, xs, runparams);
3863 } else if (runparams.flavor == OutputParams::TEXT) {
3865 // FIXME Handles only one paragraph, unlike the others.
3866 // Probably should have some routine with a signature like them.
3867 writePlaintextParagraph(*this,
3868 text().paragraphs()[par_begin], os, runparams, dummy);
3869 } else if (params().isDocBook()) {
3870 docbookParagraphs(text(), *this, os, runparams);
3872 // If we are previewing a paragraph, even if this is the
3873 // child of some other buffer, let's cut the link here,
3874 // so that no concurring settings from the master
3875 // (e.g. branch state) interfere (see #8101).
3877 d->ignore_parent = true;
3878 // We need to validate the Buffer params' features here
3879 // in order to know if we should output polyglossia
3880 // macros (instead of babel macros)
3881 LaTeXFeatures features(*this, params(), runparams);
3883 runparams.use_polyglossia = features.usePolyglossia();
3884 // latex or literate
3887 ots.texrow().newlines(2);
3889 latexParagraphs(*this, text(), ots, runparams);
3890 texrow = ots.releaseTexRow();
3892 // Restore the parenthood
3894 d->ignore_parent = false;
3898 if (output == FullSource)
3899 os << _("Preview source code");
3900 else if (output == OnlyPreamble)
3901 os << _("Preview preamble");
3902 else if (output == OnlyBody)
3903 os << _("Preview body");
3905 if (runparams.flavor == OutputParams::LYX) {
3907 if (output == FullSource)
3909 else if (output == OnlyPreamble)
3910 params().writeFile(ods, this);
3911 else if (output == OnlyBody)
3913 os << from_utf8(ods.str());
3914 } else if (runparams.flavor == OutputParams::HTML) {
3915 writeLyXHTMLSource(os, runparams, output);
3916 } else if (runparams.flavor == OutputParams::TEXT) {
3917 if (output == OnlyPreamble) {
3918 os << "% "<< _("Plain text does not have a preamble.");
3920 writePlaintextFile(*this, os, runparams);
3921 } else if (params().isDocBook()) {
3922 writeDocBookSource(os, absFileName(), runparams, output);
3924 // latex or literate
3927 ots.texrow().newlines(2);
3929 runparams.is_child = true;
3930 writeLaTeXSource(ots, string(), runparams, output);
3931 texrow = ots.releaseTexRow();
3938 ErrorList & Buffer::errorList(string const & type) const
3940 return d->errorLists[type];
3944 void Buffer::updateTocItem(std::string const & type,
3945 DocIterator const & dit) const
3948 d->gui_->updateTocItem(type, dit);
3952 void Buffer::structureChanged() const
3955 d->gui_->structureChanged();
3959 void Buffer::errors(string const & err, bool from_master) const
3962 d->gui_->errors(err, from_master);
3966 void Buffer::message(docstring const & msg) const
3969 d->gui_->message(msg);
3973 void Buffer::setBusy(bool on) const
3976 d->gui_->setBusy(on);
3980 void Buffer::updateTitles() const
3983 d->wa_->updateTitles();
3987 void Buffer::resetAutosaveTimers() const
3990 d->gui_->resetAutosaveTimers();
3994 bool Buffer::hasGuiDelegate() const
4000 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4009 class AutoSaveBuffer : public ForkedProcess {
4012 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4013 : buffer_(buffer), fname_(fname) {}
4015 virtual shared_ptr<ForkedProcess> clone() const
4017 return make_shared<AutoSaveBuffer>(*this);
4022 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4023 from_utf8(fname_.absFileName())));
4024 return run(DontWait);
4028 virtual int generateChild();
4030 Buffer const & buffer_;
4035 int AutoSaveBuffer::generateChild()
4037 #if defined(__APPLE__)
4038 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4039 * We should use something else like threads.
4041 * Since I do not know how to determine at run time what is the OS X
4042 * version, I just disable forking altogether for now (JMarc)
4044 pid_t const pid = -1;
4046 // tmp_ret will be located (usually) in /tmp
4047 // will that be a problem?
4048 // Note that this calls ForkedCalls::fork(), so it's
4049 // ok cross-platform.
4050 pid_t const pid = fork();
4051 // If you want to debug the autosave
4052 // you should set pid to -1, and comment out the fork.
4053 if (pid != 0 && pid != -1)
4057 // pid = -1 signifies that lyx was unable
4058 // to fork. But we will do the save
4060 bool failed = false;
4061 TempFile tempfile("lyxautoXXXXXX.lyx");
4062 tempfile.setAutoRemove(false);
4063 FileName const tmp_ret = tempfile.name();
4064 if (!tmp_ret.empty()) {
4065 if (!buffer_.writeFile(tmp_ret))
4067 else if (!tmp_ret.moveTo(fname_))
4073 // failed to write/rename tmp_ret so try writing direct
4074 if (!buffer_.writeFile(fname_)) {
4075 // It is dangerous to do this in the child,
4076 // but safe in the parent, so...
4077 if (pid == -1) // emit message signal.
4078 buffer_.message(_("Autosave failed!"));
4082 if (pid == 0) // we are the child so...
4091 FileName Buffer::getEmergencyFileName() const
4093 return FileName(d->filename.absFileName() + ".emergency");
4097 FileName Buffer::getAutosaveFileName() const
4099 // if the document is unnamed try to save in the backup dir, else
4100 // in the default document path, and as a last try in the filePath,
4101 // which will most often be the temporary directory
4104 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4105 : lyxrc.backupdir_path;
4106 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4109 string const fname = "#" + d->filename.onlyFileName() + "#";
4111 return makeAbsPath(fname, fpath);
4115 void Buffer::removeAutosaveFile() const
4117 FileName const f = getAutosaveFileName();
4123 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4125 FileName const newauto = getAutosaveFileName();
4127 if (newauto != oldauto && oldauto.exists())
4128 if (!oldauto.moveTo(newauto))
4129 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4133 bool Buffer::autoSave() const
4135 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4136 if (buf->d->bak_clean || isReadonly())
4139 message(_("Autosaving current document..."));
4140 buf->d->bak_clean = true;
4142 FileName const fname = getAutosaveFileName();
4143 LASSERT(d->cloned_buffer_, return false);
4145 // If this buffer is cloned, we assume that
4146 // we are running in a separate thread already.
4147 TempFile tempfile("lyxautoXXXXXX.lyx");
4148 tempfile.setAutoRemove(false);
4149 FileName const tmp_ret = tempfile.name();
4150 if (!tmp_ret.empty()) {
4152 // assume successful write of tmp_ret
4153 if (tmp_ret.moveTo(fname))
4156 // failed to write/rename tmp_ret so try writing direct
4157 return writeFile(fname);
4161 void Buffer::setExportStatus(bool e) const
4163 d->doing_export = e;
4164 ListOfBuffers clist = getDescendents();
4165 ListOfBuffers::const_iterator cit = clist.begin();
4166 ListOfBuffers::const_iterator const cen = clist.end();
4167 for (; cit != cen; ++cit)
4168 (*cit)->d->doing_export = e;
4172 bool Buffer::isExporting() const
4174 return d->doing_export;
4178 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4182 return doExport(target, put_in_tempdir, result_file);
4185 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4186 string & result_file) const
4188 bool const update_unincluded =
4189 params().maintain_unincluded_children
4190 && !params().getIncludedChildren().empty();
4192 // (1) export with all included children (omit \includeonly)
4193 if (update_unincluded) {
4194 ExportStatus const status =
4195 doExport(target, put_in_tempdir, true, result_file);
4196 if (status != ExportSuccess)
4199 // (2) export with included children only
4200 return doExport(target, put_in_tempdir, false, result_file);
4204 void Buffer::setMathFlavor(OutputParams & op) const
4206 switch (params().html_math_output) {
4207 case BufferParams::MathML:
4208 op.math_flavor = OutputParams::MathAsMathML;
4210 case BufferParams::HTML:
4211 op.math_flavor = OutputParams::MathAsHTML;
4213 case BufferParams::Images:
4214 op.math_flavor = OutputParams::MathAsImages;
4216 case BufferParams::LaTeX:
4217 op.math_flavor = OutputParams::MathAsLaTeX;
4223 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4224 bool includeall, string & result_file) const
4226 LYXERR(Debug::FILES, "target=" << target);
4227 OutputParams runparams(¶ms().encoding());
4228 string format = target;
4229 string dest_filename;
4230 size_t pos = target.find(' ');
4231 if (pos != string::npos) {
4232 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4233 format = target.substr(0, pos);
4234 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4235 FileName(dest_filename).onlyPath().createPath();
4236 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4238 MarkAsExporting exporting(this);
4239 string backend_format;
4240 runparams.flavor = OutputParams::LATEX;
4241 runparams.linelen = lyxrc.plaintext_linelen;
4242 runparams.includeall = includeall;
4243 vector<string> backs = params().backends();
4244 Converters converters = theConverters();
4245 bool need_nice_file = false;
4246 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4247 // Get shortest path to format
4248 converters.buildGraph();
4249 Graph::EdgePath path;
4250 for (vector<string>::const_iterator it = backs.begin();
4251 it != backs.end(); ++it) {
4252 Graph::EdgePath p = converters.getPath(*it, format);
4253 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4254 backend_format = *it;
4259 if (!put_in_tempdir) {
4260 // Only show this alert if this is an export to a non-temporary
4261 // file (not for previewing).
4262 Alert::error(_("Couldn't export file"), bformat(
4263 _("No information for exporting the format %1$s."),
4264 formats.prettyName(format)));
4266 return ExportNoPathToFormat;
4268 runparams.flavor = converters.getFlavor(path, this);
4269 Graph::EdgePath::const_iterator it = path.begin();
4270 Graph::EdgePath::const_iterator en = path.end();
4271 for (; it != en; ++it)
4272 if (theConverters().get(*it).nice()) {
4273 need_nice_file = true;
4278 backend_format = format;
4279 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4280 // FIXME: Don't hardcode format names here, but use a flag
4281 if (backend_format == "pdflatex")
4282 runparams.flavor = OutputParams::PDFLATEX;
4283 else if (backend_format == "luatex")
4284 runparams.flavor = OutputParams::LUATEX;
4285 else if (backend_format == "dviluatex")
4286 runparams.flavor = OutputParams::DVILUATEX;
4287 else if (backend_format == "xetex")
4288 runparams.flavor = OutputParams::XETEX;
4291 string filename = latexName(false);
4292 filename = addName(temppath(), filename);
4293 filename = changeExtension(filename,
4294 formats.extension(backend_format));
4295 LYXERR(Debug::FILES, "filename=" << filename);
4297 // Plain text backend
4298 if (backend_format == "text") {
4299 runparams.flavor = OutputParams::TEXT;
4300 writePlaintextFile(*this, FileName(filename), runparams);
4303 else if (backend_format == "xhtml") {
4304 runparams.flavor = OutputParams::HTML;
4305 setMathFlavor(runparams);
4306 makeLyXHTMLFile(FileName(filename), runparams);
4307 } else if (backend_format == "lyx")
4308 writeFile(FileName(filename));
4310 else if (params().isDocBook()) {
4311 runparams.nice = !put_in_tempdir;
4312 makeDocBookFile(FileName(filename), runparams);
4315 else if (backend_format == format || need_nice_file) {
4316 runparams.nice = true;
4317 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4318 if (d->cloned_buffer_)
4319 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4322 } else if (!lyxrc.tex_allows_spaces
4323 && contains(filePath(), ' ')) {
4324 Alert::error(_("File name error"),
4325 _("The directory path to the document cannot contain spaces."));
4326 return ExportTexPathHasSpaces;
4328 runparams.nice = false;
4329 bool const success = makeLaTeXFile(
4330 FileName(filename), filePath(), runparams);
4331 if (d->cloned_buffer_)
4332 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4337 string const error_type = (format == "program")
4338 ? "Build" : params().bufferFormat();
4339 ErrorList & error_list = d->errorLists[error_type];
4340 string const ext = formats.extension(format);
4341 FileName const tmp_result_file(changeExtension(filename, ext));
4342 bool const success = converters.convert(this, FileName(filename),
4343 tmp_result_file, FileName(absFileName()), backend_format, format,
4346 // Emit the signal to show the error list or copy it back to the
4347 // cloned Buffer so that it can be emitted afterwards.
4348 if (format != backend_format) {
4349 if (runparams.silent)
4351 else if (d->cloned_buffer_)
4352 d->cloned_buffer_->d->errorLists[error_type] =
4353 d->errorLists[error_type];
4356 // also to the children, in case of master-buffer-view
4357 ListOfBuffers clist = getDescendents();
4358 ListOfBuffers::const_iterator cit = clist.begin();
4359 ListOfBuffers::const_iterator const cen = clist.end();
4360 for (; cit != cen; ++cit) {
4361 if (runparams.silent)
4362 (*cit)->d->errorLists[error_type].clear();
4363 else if (d->cloned_buffer_) {
4364 // Enable reverse search by copying back the
4365 // texrow object to the cloned buffer.
4366 // FIXME: this is not thread safe.
4367 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4368 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4369 (*cit)->d->errorLists[error_type];
4371 (*cit)->errors(error_type, true);
4375 if (d->cloned_buffer_) {
4376 // Enable reverse dvi or pdf to work by copying back the texrow
4377 // object to the cloned buffer.
4378 // FIXME: There is a possibility of concurrent access to texrow
4379 // here from the main GUI thread that should be securized.
4380 d->cloned_buffer_->d->texrow = d->texrow;
4381 string const error_type = params().bufferFormat();
4382 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4386 if (put_in_tempdir) {
4387 result_file = tmp_result_file.absFileName();
4388 return success ? ExportSuccess : ExportConverterError;
4391 if (dest_filename.empty())
4392 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4394 result_file = dest_filename;
4395 // We need to copy referenced files (e. g. included graphics
4396 // if format == "dvi") to the result dir.
4397 vector<ExportedFile> const files =
4398 runparams.exportdata->externalFiles(format);
4399 string const dest = runparams.export_folder.empty() ?
4400 onlyPath(result_file) : runparams.export_folder;
4401 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4402 : force_overwrite == ALL_FILES;
4403 CopyStatus status = use_force ? FORCE : SUCCESS;
4405 vector<ExportedFile>::const_iterator it = files.begin();
4406 vector<ExportedFile>::const_iterator const en = files.end();
4407 for (; it != en && status != CANCEL; ++it) {
4408 string const fmt = formats.getFormatFromFile(it->sourceName);
4409 string fixedName = it->exportName;
4410 if (!runparams.export_folder.empty()) {
4411 // Relative pathnames starting with ../ will be sanitized
4412 // if exporting to a different folder
4413 while (fixedName.substr(0, 3) == "../")
4414 fixedName = fixedName.substr(3, fixedName.length() - 3);
4416 FileName fixedFileName = makeAbsPath(fixedName, dest);
4417 fixedFileName.onlyPath().createPath();
4418 status = copyFile(fmt, it->sourceName,
4420 it->exportName, status == FORCE,
4421 runparams.export_folder.empty());
4424 if (status == CANCEL) {
4425 message(_("Document export cancelled."));
4426 return ExportCancel;
4429 if (tmp_result_file.exists()) {
4430 // Finally copy the main file
4431 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4432 : force_overwrite != NO_FILES;
4433 if (status == SUCCESS && use_force)
4435 status = copyFile(format, tmp_result_file,
4436 FileName(result_file), result_file,
4438 if (status == CANCEL) {
4439 message(_("Document export cancelled."));
4440 return ExportCancel;
4442 message(bformat(_("Document exported as %1$s "
4444 formats.prettyName(format),
4445 makeDisplayPath(result_file)));
4448 // This must be a dummy converter like fax (bug 1888)
4449 message(bformat(_("Document exported as %1$s"),
4450 formats.prettyName(format)));
4453 return success ? ExportSuccess : ExportConverterError;
4457 Buffer::ExportStatus Buffer::preview(string const & format) const
4459 bool const update_unincluded =
4460 params().maintain_unincluded_children
4461 && !params().getIncludedChildren().empty();
4462 return preview(format, update_unincluded);
4466 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4468 MarkAsExporting exporting(this);
4470 // (1) export with all included children (omit \includeonly)
4472 ExportStatus const status = doExport(format, true, true, result_file);
4473 if (status != ExportSuccess)
4476 // (2) export with included children only
4477 ExportStatus const status = doExport(format, true, false, result_file);
4478 FileName const previewFile(result_file);
4480 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4481 theimpl->preview_file_ = previewFile;
4482 theimpl->preview_format_ = format;
4483 theimpl->preview_error_ = (status != ExportSuccess);
4485 if (status != ExportSuccess)
4488 if (previewFile.exists())
4489 return formats.view(*this, previewFile, format) ?
4490 PreviewSuccess : PreviewError;
4492 // Successful export but no output file?
4493 // Probably a bug in error detection.
4494 LATTEST(status != ExportSuccess);
4499 Buffer::ReadStatus Buffer::extractFromVC()
4501 bool const found = LyXVC::file_not_found_hook(d->filename);
4503 return ReadFileNotFound;
4504 if (!d->filename.isReadableFile())
4510 Buffer::ReadStatus Buffer::loadEmergency()
4512 FileName const emergencyFile = getEmergencyFileName();
4513 if (!emergencyFile.exists()
4514 || emergencyFile.lastModified() <= d->filename.lastModified())
4515 return ReadFileNotFound;
4517 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4518 docstring const text = bformat(_("An emergency save of the document "
4519 "%1$s exists.\n\nRecover emergency save?"), file);
4521 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4522 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4528 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4529 bool const success = (ret_llf == ReadSuccess);
4532 Alert::warning(_("File is read-only"),
4533 bformat(_("An emergency file is successfully loaded, "
4534 "but the original file %1$s is marked read-only. "
4535 "Please make sure to save the document as a different "
4536 "file."), from_utf8(d->filename.absFileName())));
4539 lyxvc().file_found_hook(d->filename);
4540 str = _("Document was successfully recovered.");
4542 str = _("Document was NOT successfully recovered.");
4543 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4544 makeDisplayPath(emergencyFile.absFileName()));
4546 int const del_emerg =
4547 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4548 _("&Remove"), _("&Keep"));
4549 if (del_emerg == 0) {
4550 emergencyFile.removeFile();
4552 Alert::warning(_("Emergency file deleted"),
4553 _("Do not forget to save your file now!"), true);
4555 return success ? ReadSuccess : ReadEmergencyFailure;
4558 int const del_emerg =
4559 Alert::prompt(_("Delete emergency file?"),
4560 _("Remove emergency file now?"), 1, 1,
4561 _("&Remove"), _("&Keep"));
4563 emergencyFile.removeFile();
4564 return ReadOriginal;
4574 Buffer::ReadStatus Buffer::loadAutosave()
4576 // Now check if autosave file is newer.
4577 FileName const autosaveFile = getAutosaveFileName();
4578 if (!autosaveFile.exists()
4579 || autosaveFile.lastModified() <= d->filename.lastModified())
4580 return ReadFileNotFound;
4582 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4583 docstring const text = bformat(_("The backup of the document %1$s "
4584 "is newer.\n\nLoad the backup instead?"), file);
4585 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4586 _("&Load backup"), _("Load &original"), _("&Cancel"));
4591 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4592 // the file is not saved if we load the autosave file.
4593 if (ret_llf == ReadSuccess) {
4595 Alert::warning(_("File is read-only"),
4596 bformat(_("A backup file is successfully loaded, "
4597 "but the original file %1$s is marked read-only. "
4598 "Please make sure to save the document as a "
4600 from_utf8(d->filename.absFileName())));
4603 lyxvc().file_found_hook(d->filename);
4606 return ReadAutosaveFailure;
4609 // Here we delete the autosave
4610 autosaveFile.removeFile();
4611 return ReadOriginal;
4619 Buffer::ReadStatus Buffer::loadLyXFile()
4621 if (!d->filename.isReadableFile()) {
4622 ReadStatus const ret_rvc = extractFromVC();
4623 if (ret_rvc != ReadSuccess)
4627 ReadStatus const ret_re = loadEmergency();
4628 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4631 ReadStatus const ret_ra = loadAutosave();
4632 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4635 return loadThisLyXFile(d->filename);
4639 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4641 return readFile(fn);
4645 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4647 for (auto const & err : terr) {
4648 TexRow::TextEntry start, end = TexRow::text_none;
4649 int errorRow = err.error_in_line;
4650 Buffer const * buf = 0;
4652 if (err.child_name.empty())
4653 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4655 // The error occurred in a child
4656 for (Buffer const * child : getDescendents()) {
4657 string const child_name =
4658 DocFileName(changeExtension(child->absFileName(), "tex")).
4660 if (err.child_name != child_name)
4662 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4663 if (!TexRow::isNone(start)) {
4664 buf = d->cloned_buffer_
4665 ? child->d->cloned_buffer_->d->owner_
4672 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4678 void Buffer::setBuffersForInsets() const
4680 inset().setBuffer(const_cast<Buffer &>(*this));
4684 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4686 LBUFERR(!text().paragraphs().empty());
4688 // Use the master text class also for child documents
4689 Buffer const * const master = masterBuffer();
4690 DocumentClass const & textclass = master->params().documentClass();
4692 // do this only if we are the top-level Buffer
4693 if (master == this) {
4694 textclass.counters().reset(from_ascii("bibitem"));
4695 reloadBibInfoCache();
4698 // keep the buffers to be children in this set. If the call from the
4699 // master comes back we can see which of them were actually seen (i.e.
4700 // via an InsetInclude). The remaining ones in the set need still be updated.
4701 static std::set<Buffer const *> bufToUpdate;
4702 if (scope == UpdateMaster) {
4703 // If this is a child document start with the master
4704 if (master != this) {
4705 bufToUpdate.insert(this);
4706 master->updateBuffer(UpdateMaster, utype);
4707 // If the master buffer has no gui associated with it, then the TocModel is
4708 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4709 // (bug 5699). The same happens if the master buffer is open in a different
4710 // window. This test catches both possibilities.
4711 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4712 // There remains a problem here: If there is another child open in yet a third
4713 // window, that TOC is not updated. So some more general solution is needed at
4715 if (master->d->gui_ != d->gui_)
4718 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4719 if (bufToUpdate.find(this) == bufToUpdate.end())
4723 // start over the counters in the master
4724 textclass.counters().reset();
4727 // update will be done below for this buffer
4728 bufToUpdate.erase(this);
4730 // update all caches
4731 clearReferenceCache();
4733 setChangesPresent(false);
4735 Buffer & cbuf = const_cast<Buffer &>(*this);
4738 ParIterator parit = cbuf.par_iterator_begin();
4739 updateBuffer(parit, utype);
4742 /// Update the tocBackend for any buffer. The outliner uses the master's,
4743 /// and the navigation menu uses the child's.
4744 cbuf.tocBackend().update(true, utype);
4749 d->bibinfo_cache_valid_ = true;
4750 d->cite_labels_valid_ = true;
4751 if (scope == UpdateMaster)
4752 cbuf.structureChanged();
4756 static depth_type getDepth(DocIterator const & it)
4758 depth_type depth = 0;
4759 for (size_t i = 0 ; i < it.depth() ; ++i)
4760 if (!it[i].inset().inMathed())
4761 depth += it[i].paragraph().getDepth() + 1;
4762 // remove 1 since the outer inset does not count
4763 // we should have at least one non-math inset, so
4764 // depth should nevery be 0. but maybe it is worth
4765 // marking this, just in case.
4767 // coverity[INTEGER_OVERFLOW]
4771 static depth_type getItemDepth(ParIterator const & it)
4773 Paragraph const & par = *it;
4774 LabelType const labeltype = par.layout().labeltype;
4776 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4779 // this will hold the lowest depth encountered up to now.
4780 depth_type min_depth = getDepth(it);
4781 ParIterator prev_it = it;
4784 --prev_it.top().pit();
4786 // start of nested inset: go to outer par
4788 if (prev_it.empty()) {
4789 // start of document: nothing to do
4794 // We search for the first paragraph with same label
4795 // that is not more deeply nested.
4796 Paragraph & prev_par = *prev_it;
4797 depth_type const prev_depth = getDepth(prev_it);
4798 if (labeltype == prev_par.layout().labeltype) {
4799 if (prev_depth < min_depth)
4800 return prev_par.itemdepth + 1;
4801 if (prev_depth == min_depth)
4802 return prev_par.itemdepth;
4804 min_depth = min(min_depth, prev_depth);
4805 // small optimization: if we are at depth 0, we won't
4806 // find anything else
4807 if (prev_depth == 0)
4813 static bool needEnumCounterReset(ParIterator const & it)
4815 Paragraph const & par = *it;
4816 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4817 depth_type const cur_depth = par.getDepth();
4818 ParIterator prev_it = it;
4819 while (prev_it.pit()) {
4820 --prev_it.top().pit();
4821 Paragraph const & prev_par = *prev_it;
4822 if (prev_par.getDepth() <= cur_depth)
4823 return prev_par.layout().name() != par.layout().name();
4825 // start of nested inset: reset
4830 // set the label of a paragraph. This includes the counters.
4831 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4833 BufferParams const & bp = owner_->masterBuffer()->params();
4834 DocumentClass const & textclass = bp.documentClass();
4835 Paragraph & par = it.paragraph();
4836 Layout const & layout = par.layout();
4837 Counters & counters = textclass.counters();
4839 if (par.params().startOfAppendix()) {
4840 // We want to reset the counter corresponding to toplevel sectioning
4841 Layout const & lay = textclass.getTOCLayout();
4842 docstring const cnt = lay.counter;
4844 counters.reset(cnt);
4845 counters.appendix(true);
4847 par.params().appendix(counters.appendix());
4849 // Compute the item depth of the paragraph
4850 par.itemdepth = getItemDepth(it);
4852 if (layout.margintype == MARGIN_MANUAL) {
4853 if (par.params().labelWidthString().empty())
4854 par.params().labelWidthString(par.expandLabel(layout, bp));
4855 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4856 // we do not need to do anything here, since the empty case is
4857 // handled during export.
4859 par.params().labelWidthString(docstring());
4862 switch(layout.labeltype) {
4863 case LABEL_ITEMIZE: {
4864 // At some point of time we should do something more
4865 // clever here, like:
4866 // par.params().labelString(
4867 // bp.user_defined_bullet(par.itemdepth).getText());
4868 // for now, use a simple hardcoded label
4869 docstring itemlabel;
4870 switch (par.itemdepth) {
4872 itemlabel = char_type(0x2022);
4875 itemlabel = char_type(0x2013);
4878 itemlabel = char_type(0x2217);
4881 itemlabel = char_type(0x2219); // or 0x00b7
4884 par.params().labelString(itemlabel);
4888 case LABEL_ENUMERATE: {
4889 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4891 switch (par.itemdepth) {
4900 enumcounter += "iv";
4903 // not a valid enumdepth...
4907 // Increase the master counter?
4908 if (layout.stepmastercounter && needEnumCounterReset(it))
4909 counters.stepMaster(enumcounter, utype);
4911 // Maybe we have to reset the enumeration counter.
4912 if (!layout.resumecounter && needEnumCounterReset(it))
4913 counters.reset(enumcounter);
4914 counters.step(enumcounter, utype);
4916 string const & lang = par.getParLanguage(bp)->code();
4917 par.params().labelString(counters.theCounter(enumcounter, lang));
4922 case LABEL_SENSITIVE: {
4923 string const & type = counters.current_float();
4924 docstring full_label;
4926 full_label = owner_->B_("Senseless!!! ");
4928 docstring name = owner_->B_(textclass.floats().getType(type).name());
4929 if (counters.hasCounter(from_utf8(type))) {
4930 string const & lang = par.getParLanguage(bp)->code();
4931 counters.step(from_utf8(type), utype);
4932 full_label = bformat(from_ascii("%1$s %2$s:"),
4934 counters.theCounter(from_utf8(type), lang));
4936 full_label = bformat(from_ascii("%1$s #:"), name);
4938 par.params().labelString(full_label);
4942 case LABEL_NO_LABEL:
4943 par.params().labelString(docstring());
4947 case LABEL_CENTERED:
4948 case LABEL_STATIC: {
4949 docstring const & lcounter = layout.counter;
4950 if (!lcounter.empty()) {
4951 if (layout.toclevel <= bp.secnumdepth
4952 && (layout.latextype != LATEX_ENVIRONMENT
4953 || it.text()->isFirstInSequence(it.pit()))) {
4954 if (counters.hasCounter(lcounter))
4955 counters.step(lcounter, utype);
4956 par.params().labelString(par.expandLabel(layout, bp));
4958 par.params().labelString(docstring());
4960 par.params().labelString(par.expandLabel(layout, bp));
4966 par.params().labelString(par.expandLabel(layout, bp));
4971 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4973 // LASSERT: Is it safe to continue here, or should we just return?
4974 LASSERT(parit.pit() == 0, /**/);
4976 // Set the position of the text in the buffer to be able
4977 // to resolve macros in it.
4978 parit.text()->setMacrocontextPosition(parit);
4980 depth_type maxdepth = 0;
4981 pit_type const lastpit = parit.lastpit();
4982 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4983 // reduce depth if necessary
4984 if (parit->params().depth() > maxdepth) {
4985 /** FIXME: this function is const, but
4986 * nevertheless it modifies the buffer. To be
4987 * cleaner, one should modify the buffer in
4988 * another function, which is actually
4989 * non-const. This would however be costly in
4990 * terms of code duplication.
4992 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4993 parit->params().depth(maxdepth);
4995 maxdepth = parit->getMaxDepthAfter();
4997 if (utype == OutputUpdate) {
4998 // track the active counters
4999 // we have to do this for the master buffer, since the local
5000 // buffer isn't tracking anything.
5001 masterBuffer()->params().documentClass().counters().
5002 setActiveLayout(parit->layout());
5005 // set the counter for this paragraph
5006 d->setLabel(parit, utype);
5008 // update change-tracking flag
5009 parit->addChangesToBuffer(*this);
5012 InsetList::const_iterator iit = parit->insetList().begin();
5013 InsetList::const_iterator end = parit->insetList().end();
5014 for (; iit != end; ++iit) {
5015 parit.pos() = iit->pos;
5016 iit->inset->updateBuffer(parit, utype);
5022 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5023 WordLangTuple & word_lang, docstring_list & suggestions) const
5027 suggestions.clear();
5028 word_lang = WordLangTuple();
5029 bool const to_end = to.empty();
5030 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5031 // OK, we start from here.
5032 for (; from != end; from.forwardPos()) {
5033 // This skips all insets with spell check disabled.
5034 while (!from.allowSpellCheck()) {
5038 // If from is at the end of the document (which is possible
5039 // when "from" was changed above) LyX will crash later otherwise.
5040 if (from.atEnd() || (!to_end && from >= end))
5043 from.paragraph().spellCheck();
5044 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5045 if (SpellChecker::misspelled(res)) {
5049 // Do not increase progress when from == to, otherwise the word
5050 // count will be wrong.
5060 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5062 bool inword = false;
5067 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5068 if (!dit.inTexted()) {
5073 Paragraph const & par = dit.paragraph();
5074 pos_type const pos = dit.pos();
5076 // Copied and adapted from isWordSeparator() in Paragraph
5077 if (pos == dit.lastpos()) {
5080 Inset const * ins = par.getInset(pos);
5081 if (ins && skipNoOutput && !ins->producesOutput()) {
5084 // stop if end of range was skipped
5085 if (!to.atEnd() && dit >= to)
5088 } else if (!par.isDeleted(pos)) {
5089 if (par.isWordSeparator(pos))
5095 if (ins && ins->isLetter())
5097 else if (ins && ins->isSpace())
5100 char_type const c = par.getChar(pos);
5101 if (isPrintableNonspace(c))
5103 else if (isSpace(c))
5113 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5115 d->updateStatistics(from, to, skipNoOutput);
5119 int Buffer::wordCount() const
5121 return d->wordCount();
5125 int Buffer::charCount(bool with_blanks) const
5127 return d->charCount(with_blanks);
5131 Buffer::ReadStatus Buffer::reload()
5134 // c.f. bug http://www.lyx.org/trac/ticket/6587
5135 removeAutosaveFile();
5136 // e.g., read-only status could have changed due to version control
5137 d->filename.refresh();
5138 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5140 // clear parent. this will get reset if need be.
5142 ReadStatus const status = loadLyXFile();
5143 if (status == ReadSuccess) {
5148 message(bformat(_("Document %1$s reloaded."), disp_fn));
5151 message(bformat(_("Could not reload document %1$s."), disp_fn));
5161 bool Buffer::saveAs(FileName const & fn)
5163 FileName const old_name = fileName();
5164 FileName const old_auto = getAutosaveFileName();
5165 bool const old_unnamed = isUnnamed();
5166 bool success = true;
5167 d->old_position = filePath();
5174 // bring the autosave file with us, just in case.
5175 moveAutosaveFile(old_auto);
5176 // validate version control data and
5177 // correct buffer title
5178 lyxvc().file_found_hook(fileName());
5180 // the file has now been saved to the new location.
5181 // we need to check that the locations of child buffers
5183 checkChildBuffers();
5184 checkMasterBuffer();
5187 // reset the old filename and unnamed state
5188 setFileName(old_name);
5189 setUnnamed(old_unnamed);
5193 d->old_position.clear();
5198 void Buffer::checkChildBuffers()
5200 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5201 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5202 for (; it != en; ++it) {
5203 DocIterator dit = it->second;
5204 Buffer * cbuf = const_cast<Buffer *>(it->first);
5205 if (!cbuf || !theBufferList().isLoaded(cbuf))
5207 Inset * inset = dit.nextInset();
5208 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5209 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5210 docstring const & incfile = inset_inc->getParam("filename");
5211 string oldloc = cbuf->absFileName();
5212 string newloc = makeAbsPath(to_utf8(incfile),
5213 onlyPath(absFileName())).absFileName();
5214 if (oldloc == newloc)
5216 // the location of the child file is incorrect.
5218 inset_inc->setChildBuffer(0);
5220 // invalidate cache of children
5221 d->children_positions.clear();
5222 d->position_to_children.clear();
5226 // If a child has been saved under a different name/path, it might have been
5227 // orphaned. Therefore the master needs to be reset (bug 8161).
5228 void Buffer::checkMasterBuffer()
5230 Buffer const * const master = masterBuffer();
5234 // necessary to re-register the child (bug 5873)
5235 // FIXME: clean up updateMacros (here, only
5236 // child registering is needed).
5237 master->updateMacros();
5238 // (re)set master as master buffer, but only
5239 // if we are a real child
5240 if (master->isChild(this))
5247 string Buffer::includedFilePath(string const & name, string const & ext) const
5249 if (d->old_position.empty() ||
5250 equivalent(FileName(d->old_position), FileName(filePath())))
5253 bool isabsolute = FileName::isAbsolute(name);
5254 // both old_position and filePath() end with a path separator
5255 string absname = isabsolute ? name : d->old_position + name;
5257 // if old_position is set to origin, we need to do the equivalent of
5258 // getReferencedFileName() (see readDocument())
5259 if (!isabsolute && d->old_position == params().origin) {
5260 FileName const test(addExtension(filePath() + name, ext));
5262 absname = filePath() + name;
5265 if (!FileName(addExtension(absname, ext)).exists())
5269 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5271 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5272 from_utf8(filePath())));
5276 void Buffer::setChangesPresent(bool b) const
5278 d->tracked_changes_present_ = b;
5282 bool Buffer::areChangesPresent() const
5284 return d->tracked_changes_present_;
5288 void Buffer::updateChangesPresent() const
5290 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5291 setChangesPresent(false);
5292 ParConstIterator it = par_iterator_begin();
5293 ParConstIterator const end = par_iterator_end();
5294 for (; !areChangesPresent() && it != end; ++it)
5295 it->addChangesToBuffer(*this);