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), parent_buffer(0),
427 word_count_(0), char_count_(0), blank_count_(0)
429 if (!cloned_buffer_) {
430 temppath = createBufferTmpDir();
431 lyxvc.setBuffer(owner_);
433 wa_ = new frontend::WorkAreaManager;
436 temppath = cloned_buffer_->d->temppath;
437 file_fully_loaded = true;
438 params = cloned_buffer_->d->params;
439 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
440 bibinfo_ = cloned_buffer_->d->bibinfo_;
441 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
442 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
443 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
444 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
445 unnamed = cloned_buffer_->d->unnamed;
446 internal_buffer = cloned_buffer_->d->internal_buffer;
447 layout_position = cloned_buffer_->d->layout_position;
448 preview_file_ = cloned_buffer_->d->preview_file_;
449 preview_format_ = cloned_buffer_->d->preview_format_;
450 preview_error_ = cloned_buffer_->d->preview_error_;
451 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
455 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
456 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
458 LYXERR(Debug::INFO, "Buffer::Buffer()");
460 d->inset = new InsetText(*cloned_buffer->d->inset);
461 d->inset->setBuffer(*this);
462 // FIXME: optimize this loop somewhat, maybe by creating a new
463 // general recursive Inset::setId().
464 DocIterator it = doc_iterator_begin(this);
465 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
466 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
467 it.paragraph().setId(cloned_it.paragraph().id());
469 d->inset = new InsetText(this);
470 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
476 LYXERR(Debug::INFO, "Buffer::~Buffer()");
477 // here the buffer should take care that it is
478 // saved properly, before it goes into the void.
480 // GuiView already destroyed
484 // No need to do additional cleanups for internal buffer.
490 // this is in case of recursive includes: we won't try to delete
491 // ourselves as a child.
492 d->clone_list_->erase(this);
493 // loop over children
494 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
495 Impl::BufferPositionMap::iterator end = d->children_positions.end();
496 for (; it != end; ++it) {
497 Buffer * child = const_cast<Buffer *>(it->first);
498 if (d->clone_list_->erase(child))
501 // if we're the master buffer, then we should get rid of the list
504 // If this is not empty, we have leaked something. Worse, one of the
505 // children still has a reference to this list. But we will try to
506 // continue, rather than shut down.
507 LATTEST(d->clone_list_->empty());
508 list<CloneList *>::iterator it =
509 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
510 if (it == cloned_buffers.end()) {
511 // We will leak in this case, but it is safe to continue.
514 cloned_buffers.erase(it);
515 delete d->clone_list_;
517 // FIXME Do we really need to do this right before we delete d?
518 // clear references to children in macro tables
519 d->children_positions.clear();
520 d->position_to_children.clear();
522 // loop over children
523 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
524 Impl::BufferPositionMap::iterator end = d->children_positions.end();
525 for (; it != end; ++it) {
526 Buffer * child = const_cast<Buffer *>(it->first);
527 if (theBufferList().isLoaded(child)) {
528 if (theBufferList().isOthersChild(this, child))
531 theBufferList().release(child);
536 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
537 msg += emergencyWrite();
538 Alert::warning(_("Attempting to close changed document!"), msg);
541 // FIXME Do we really need to do this right before we delete d?
542 // clear references to children in macro tables
543 d->children_positions.clear();
544 d->position_to_children.clear();
546 if (!d->temppath.destroyDirectory()) {
547 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
548 from_utf8(d->temppath.absFileName())));
557 Buffer * Buffer::cloneFromMaster() const
560 cloned_buffers.push_back(new CloneList);
561 CloneList * clones = cloned_buffers.back();
563 masterBuffer()->cloneWithChildren(bufmap, clones);
565 // make sure we got cloned
566 BufferMap::const_iterator bit = bufmap.find(this);
567 LASSERT(bit != bufmap.end(), return 0);
568 Buffer * cloned_buffer = bit->second;
570 return cloned_buffer;
574 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
576 // have we already been cloned?
577 if (bufmap.find(this) != bufmap.end())
580 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
582 // The clone needs its own DocumentClass, since running updateBuffer() will
583 // modify it, and we would otherwise be sharing it with the original Buffer.
584 buffer_clone->params().makeDocumentClass(true);
586 cap::switchBetweenClasses(
587 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
588 static_cast<InsetText &>(buffer_clone->inset()), el);
590 bufmap[this] = buffer_clone;
591 clones->insert(buffer_clone);
592 buffer_clone->d->clone_list_ = clones;
593 buffer_clone->d->macro_lock = true;
594 buffer_clone->d->children_positions.clear();
596 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
597 // math macro caches need to be rethought and simplified.
598 // I am not sure wether we should handle Buffer cloning here or in BufferList.
599 // Right now BufferList knows nothing about buffer clones.
600 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
601 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
602 for (; it != end; ++it) {
603 DocIterator dit = it->first.clone(buffer_clone);
604 dit.setBuffer(buffer_clone);
605 Buffer * child = const_cast<Buffer *>(it->second.buffer);
607 child->cloneWithChildren(bufmap, clones);
608 BufferMap::iterator const bit = bufmap.find(child);
609 LASSERT(bit != bufmap.end(), continue);
610 Buffer * child_clone = bit->second;
612 Inset * inset = dit.nextInset();
613 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
614 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
615 inset_inc->setChildBuffer(child_clone);
616 child_clone->d->setParent(buffer_clone);
617 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
618 buffer_clone->setChild(dit, child_clone);
620 buffer_clone->d->macro_lock = false;
625 Buffer * Buffer::cloneBufferOnly() const {
626 cloned_buffers.push_back(new CloneList);
627 CloneList * clones = cloned_buffers.back();
628 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
630 // The clone needs its own DocumentClass, since running updateBuffer() will
631 // modify it, and we would otherwise be sharing it with the original Buffer.
632 buffer_clone->params().makeDocumentClass(true);
634 cap::switchBetweenClasses(
635 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
636 static_cast<InsetText &>(buffer_clone->inset()), el);
638 clones->insert(buffer_clone);
639 buffer_clone->d->clone_list_ = clones;
641 // we won't be cloning the children
642 buffer_clone->d->children_positions.clear();
647 bool Buffer::isClone() const
649 return d->cloned_buffer_;
653 void Buffer::changed(bool update_metrics) const
656 d->wa_->redrawAll(update_metrics);
660 frontend::WorkAreaManager & Buffer::workAreaManager() const
667 Text & Buffer::text() const
669 return d->inset->text();
673 Inset & Buffer::inset() const
679 BufferParams & Buffer::params()
685 BufferParams const & Buffer::params() const
691 BufferParams const & Buffer::masterParams() const
693 if (masterBuffer() == this)
696 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
697 // Copy child authors to the params. We need those pointers.
698 AuthorList const & child_authors = params().authors();
699 AuthorList::Authors::const_iterator it = child_authors.begin();
700 for (; it != child_authors.end(); ++it)
701 mparams.authors().record(*it);
706 double Buffer::fontScalingFactor() const
708 return isExporting() ? 75.0 * params().html_math_img_scale
709 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
713 ParagraphList & Buffer::paragraphs()
715 return text().paragraphs();
719 ParagraphList const & Buffer::paragraphs() const
721 return text().paragraphs();
725 LyXVC & Buffer::lyxvc()
731 LyXVC const & Buffer::lyxvc() const
737 string const Buffer::temppath() const
739 return d->temppath.absFileName();
743 TexRow & Buffer::texrow()
749 TexRow const & Buffer::texrow() const
755 TocBackend & Buffer::tocBackend() const
757 return d->toc_backend;
761 Undo & Buffer::undo()
767 void Buffer::setChild(DocIterator const & dit, Buffer * child)
769 d->children_positions[child] = dit;
773 string Buffer::latexName(bool const no_path) const
775 FileName latex_name =
776 makeLatexName(d->exportFileName());
777 return no_path ? latex_name.onlyFileName()
778 : latex_name.absFileName();
782 FileName Buffer::Impl::exportFileName() const
784 docstring const branch_suffix =
785 params.branchlist().getFileNameSuffix();
786 if (branch_suffix.empty())
789 string const name = filename.onlyFileNameWithoutExt()
790 + to_utf8(branch_suffix);
791 FileName res(filename.onlyPath().absFileName() + "/" + name);
792 res.changeExtension(filename.extension());
798 string Buffer::logName(LogType * type) const
800 string const filename = latexName(false);
802 if (filename.empty()) {
808 string const path = temppath();
810 FileName const fname(addName(temppath(),
811 onlyFileName(changeExtension(filename,
814 // FIXME: how do we know this is the name of the build log?
815 FileName const bname(
816 addName(path, onlyFileName(
817 changeExtension(filename,
818 formats.extension(params().bufferFormat()) + ".out"))));
820 // Also consider the master buffer log file
821 FileName masterfname = fname;
822 LogType mtype = latexlog;
823 if (masterBuffer() != this) {
824 string const mlogfile = masterBuffer()->logName(&mtype);
825 masterfname = FileName(mlogfile);
828 // If no Latex log or Build log is newer, show Build log
829 if (bname.exists() &&
830 ((!fname.exists() && !masterfname.exists())
831 || (fname.lastModified() < bname.lastModified()
832 && masterfname.lastModified() < bname.lastModified()))) {
833 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
836 return bname.absFileName();
837 // If we have a newer master file log or only a master log, show this
838 } else if (fname != masterfname
839 && (!fname.exists() && (masterfname.exists()
840 || fname.lastModified() < masterfname.lastModified()))) {
841 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
844 return masterfname.absFileName();
846 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
849 return fname.absFileName();
853 void Buffer::setReadonly(bool const flag)
855 if (d->read_only != flag) {
862 void Buffer::setFileName(FileName const & fname)
864 bool const changed = fname != d->filename;
867 lyxvc().file_found_hook(fname);
868 setReadonly(d->filename.isReadOnly());
874 int Buffer::readHeader(Lexer & lex)
876 int unknown_tokens = 0;
878 int begin_header_line = -1;
880 // Initialize parameters that may be/go lacking in header:
881 params().branchlist().clear();
882 params().preamble.erase();
883 params().options.erase();
884 params().master.erase();
885 params().float_placement.erase();
886 params().paperwidth.erase();
887 params().paperheight.erase();
888 params().leftmargin.erase();
889 params().rightmargin.erase();
890 params().topmargin.erase();
891 params().bottommargin.erase();
892 params().headheight.erase();
893 params().headsep.erase();
894 params().footskip.erase();
895 params().columnsep.erase();
896 params().fonts_cjk.erase();
897 params().listings_params.clear();
898 params().clearLayoutModules();
899 params().clearRemovedModules();
900 params().clearIncludedChildren();
901 params().pdfoptions().clear();
902 params().indiceslist().clear();
903 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
904 params().isbackgroundcolor = false;
905 params().fontcolor = RGBColor(0, 0, 0);
906 params().isfontcolor = false;
907 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
908 params().boxbgcolor = RGBColor(0xFF, 0, 0);
909 params().html_latex_start.clear();
910 params().html_latex_end.clear();
911 params().html_math_img_scale = 1.0;
912 params().output_sync_macro.erase();
913 params().setLocalLayout(docstring(), false);
914 params().setLocalLayout(docstring(), true);
915 params().biblio_opts.erase();
916 params().biblatex_bibstyle.erase();
917 params().biblatex_citestyle.erase();
918 params().multibib.erase();
920 for (int i = 0; i < 4; ++i) {
921 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
922 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
925 ErrorList & errorList = d->errorLists["Parse"];
934 if (token == "\\end_header")
938 if (token == "\\begin_header") {
939 begin_header_line = line;
943 LYXERR(Debug::PARSER, "Handling document header token: `"
946 string const result =
947 params().readToken(lex, token, d->filename.onlyPath());
948 if (!result.empty()) {
949 if (token == "\\textclass") {
950 d->layout_position = result;
953 docstring const s = bformat(_("Unknown token: "
957 errorList.push_back(ErrorItem(_("Document header error"), s));
961 if (begin_header_line) {
962 docstring const s = _("\\begin_header is missing");
963 errorList.push_back(ErrorItem(_("Document header error"), s));
966 params().makeDocumentClass();
968 return unknown_tokens;
973 // changed to be public and have one parameter
974 // Returns true if "\end_document" is not read (Asger)
975 bool Buffer::readDocument(Lexer & lex)
977 ErrorList & errorList = d->errorLists["Parse"];
980 // remove dummy empty par
981 paragraphs().clear();
983 if (!lex.checkFor("\\begin_document")) {
984 docstring const s = _("\\begin_document is missing");
985 errorList.push_back(ErrorItem(_("Document header error"), s));
990 if (params().output_changes) {
991 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
992 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
993 LaTeXFeatures::isAvailable("xcolor");
995 if (!dvipost && !xcolorulem) {
996 Alert::warning(_("Changes not shown in LaTeX output"),
997 _("Changes will not be highlighted in LaTeX output, "
998 "because neither dvipost nor xcolor/ulem are installed.\n"
999 "Please install these packages or redefine "
1000 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1001 } else if (!xcolorulem) {
1002 Alert::warning(_("Changes not shown in LaTeX output"),
1003 _("Changes will not be highlighted in LaTeX output "
1004 "when using pdflatex, because xcolor and ulem are not installed.\n"
1005 "Please install both packages or redefine "
1006 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1010 if (!parent() && !params().master.empty()) {
1011 FileName const master_file = makeAbsPath(params().master,
1012 onlyPath(absFileName()));
1013 if (isLyXFileName(master_file.absFileName())) {
1015 checkAndLoadLyXFile(master_file, true);
1017 // necessary e.g. after a reload
1018 // to re-register the child (bug 5873)
1019 // FIXME: clean up updateMacros (here, only
1020 // child registering is needed).
1021 master->updateMacros();
1022 // set master as master buffer, but only
1023 // if we are a real child
1024 if (master->isChild(this))
1026 // if the master is not fully loaded
1027 // it is probably just loading this
1028 // child. No warning needed then.
1029 else if (master->isFullyLoaded())
1030 LYXERR0("The master '"
1032 << "' assigned to this document ("
1034 << ") does not include "
1035 "this document. Ignoring the master assignment.");
1040 // assure we have a default index
1041 params().indiceslist().addDefault(B_("Index"));
1044 if (FileName::isAbsolute(params().origin))
1045 d->old_position = params().origin;
1047 d->old_position = filePath();
1048 bool const res = text().read(lex, errorList, d->inset);
1049 d->old_position.clear();
1051 // inform parent buffer about local macros
1053 Buffer const * pbuf = parent();
1054 UserMacroSet::const_iterator cit = usermacros.begin();
1055 UserMacroSet::const_iterator end = usermacros.end();
1056 for (; cit != end; ++cit)
1057 pbuf->usermacros.insert(*cit);
1061 updateMacroInstances(InternalUpdate);
1066 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1068 Format const * fmt = formats.getFormat(format);
1071 // It is important to use the correct extension here, since some
1072 // converters create a wrong output file otherwise (e.g. html2latex)
1073 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1074 FileName const name(tempfile.name());
1075 ofdocstream os(name.toFilesystemEncoding().c_str());
1076 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1077 bool const success = !(os << contents).fail();
1080 bool converted = false;
1082 params().compressed = false;
1084 // remove dummy empty par
1085 paragraphs().clear();
1087 converted = importFile(format, name, errorList);
1096 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1098 if (!theConverters().isReachable(format, "lyx"))
1101 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1102 FileName const lyx(tempfile.name());
1103 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1104 return readFile(lyx) == ReadSuccess;
1110 bool Buffer::readString(string const & s)
1112 params().compressed = false;
1115 istringstream is(s);
1117 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1118 FileName const fn = tempfile.name();
1121 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1123 if (success && file_format != LYX_FORMAT) {
1124 // We need to call lyx2lyx, so write the input to a file
1125 ofstream os(fn.toFilesystemEncoding().c_str());
1128 // lyxvc in readFile
1129 if (readFile(fn) != ReadSuccess)
1133 if (readDocument(lex))
1139 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1143 if (!lex.setFile(fname)) {
1144 Alert::error(_("File Not Found"),
1145 bformat(_("Unable to open file `%1$s'."),
1146 from_utf8(fn.absFileName())));
1147 return ReadFileNotFound;
1151 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1152 if (ret_plf != ReadSuccess)
1155 if (file_format != LYX_FORMAT) {
1157 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1158 if (ret_clf != ReadSuccess)
1160 ret_clf = readFile(tmpFile);
1161 if (ret_clf == ReadSuccess) {
1162 d->file_format = file_format;
1163 d->need_format_backup = true;
1168 // FIXME: InsetInfo needs to know whether the file is under VCS
1169 // during the parse process, so this has to be done before.
1170 lyxvc().file_found_hook(d->filename);
1172 if (readDocument(lex)) {
1173 Alert::error(_("Document format failure"),
1174 bformat(_("%1$s ended unexpectedly, which means"
1175 " that it is probably corrupted."),
1176 from_utf8(fn.absFileName())));
1177 return ReadDocumentFailure;
1180 d->file_fully_loaded = true;
1181 d->read_only = !d->filename.isWritable();
1182 params().compressed = formats.isZippedFile(d->filename);
1188 bool Buffer::isFullyLoaded() const
1190 return d->file_fully_loaded;
1194 void Buffer::setFullyLoaded(bool value)
1196 d->file_fully_loaded = value;
1200 bool Buffer::lastPreviewError() const
1202 return d->preview_error_;
1206 PreviewLoader * Buffer::loader() const
1208 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1210 if (!d->preview_loader_)
1211 d->preview_loader_ = new PreviewLoader(*this);
1212 return d->preview_loader_;
1216 void Buffer::removePreviews() const
1218 delete d->preview_loader_;
1219 d->preview_loader_ = 0;
1223 void Buffer::updatePreviews() const
1225 PreviewLoader * ploader = loader();
1229 InsetIterator it = inset_iterator_begin(*d->inset);
1230 InsetIterator const end = inset_iterator_end(*d->inset);
1231 for (; it != end; ++it)
1232 it->addPreview(it, *ploader);
1234 ploader->startLoading();
1238 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1239 FileName const & fn, int & file_format) const
1241 if(!lex.checkFor("\\lyxformat")) {
1242 Alert::error(_("Document format failure"),
1243 bformat(_("%1$s is not a readable LyX document."),
1244 from_utf8(fn.absFileName())));
1245 return ReadNoLyXFormat;
1251 // LyX formats 217 and earlier were written as 2.17. This corresponds
1252 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1253 // these cases. See also: www.lyx.org/trac/changeset/1313.
1254 size_t dot = tmp_format.find_first_of(".,");
1255 if (dot != string::npos)
1256 tmp_format.erase(dot, 1);
1258 file_format = convert<int>(tmp_format);
1263 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1264 FileName & tmpfile, int from_format)
1266 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1267 tempfile.setAutoRemove(false);
1268 tmpfile = tempfile.name();
1269 if(tmpfile.empty()) {
1270 Alert::error(_("Conversion failed"),
1271 bformat(_("%1$s is from a different"
1272 " version of LyX, but a temporary"
1273 " file for converting it could"
1274 " not be created."),
1275 from_utf8(fn.absFileName())));
1276 return LyX2LyXNoTempFile;
1279 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1280 if (lyx2lyx.empty()) {
1281 Alert::error(_("Conversion script not found"),
1282 bformat(_("%1$s is from a different"
1283 " version of LyX, but the"
1284 " conversion script lyx2lyx"
1285 " could not be found."),
1286 from_utf8(fn.absFileName())));
1287 return LyX2LyXNotFound;
1291 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1292 ostringstream command;
1293 command << os::python()
1294 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1295 << " -t " << convert<string>(LYX_FORMAT)
1296 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1297 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1298 string const command_str = command.str();
1300 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1302 cmd_ret const ret = runCommand(command_str);
1303 if (ret.first != 0) {
1304 if (from_format < LYX_FORMAT) {
1305 Alert::error(_("Conversion script failed"),
1306 bformat(_("%1$s is from an older version"
1307 " of LyX and the lyx2lyx script"
1308 " failed to convert it."),
1309 from_utf8(fn.absFileName())));
1310 return LyX2LyXOlderFormat;
1312 Alert::error(_("Conversion script failed"),
1313 bformat(_("%1$s is from a newer version"
1314 " of LyX and the lyx2lyx script"
1315 " failed to convert it."),
1316 from_utf8(fn.absFileName())));
1317 return LyX2LyXNewerFormat;
1324 FileName Buffer::getBackupName() const {
1325 FileName const & fn = fileName();
1326 string const fname = fn.onlyFileNameWithoutExt();
1327 string const fext = fn.extension() + "~";
1328 string const fpath = lyxrc.backupdir_path.empty() ?
1329 fn.onlyPath().absFileName() :
1330 lyxrc.backupdir_path;
1331 string const fform = convert<string>(d->file_format);
1332 string const backname = fname + "-lyxformat-" + fform;
1333 FileName backup(addName(fpath, addExtension(backname, fext)));
1335 // limit recursion, just in case
1337 unsigned long orig_checksum = 0;
1338 while (backup.exists() && v < 100) {
1339 if (orig_checksum == 0)
1340 orig_checksum = fn.checksum();
1341 unsigned long new_checksum = backup.checksum();
1342 if (orig_checksum == new_checksum) {
1343 LYXERR(Debug::FILES, "Not backing up " << fn <<
1344 "since " << backup << "has the same checksum.");
1345 // a bit of a hack, but we have to check this anyway
1346 // below, and setting this is simpler than introducing
1347 // a special boolean for this purpose.
1351 string const newbackname = backname + "-" + convert<string>(v);
1352 backup.set(addName(fpath, addExtension(newbackname, fext)));
1355 return v < 100 ? backup : FileName();
1359 // Should probably be moved to somewhere else: BufferView? GuiView?
1360 bool Buffer::save() const
1362 docstring const file = makeDisplayPath(absFileName(), 20);
1363 d->filename.refresh();
1365 // check the read-only status before moving the file as a backup
1366 if (d->filename.exists()) {
1367 bool const read_only = !d->filename.isWritable();
1369 Alert::warning(_("File is read-only"),
1370 bformat(_("The file %1$s cannot be written because it "
1371 "is marked as read-only."), file));
1376 // ask if the disk file has been externally modified (use checksum method)
1377 if (fileName().exists() && isExternallyModified(checksum_method)) {
1379 bformat(_("Document %1$s has been externally modified. "
1380 "Are you sure you want to overwrite this file?"), file);
1381 int const ret = Alert::prompt(_("Overwrite modified file?"),
1382 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1387 // We don't need autosaves in the immediate future. (Asger)
1388 resetAutosaveTimers();
1390 // if the file does not yet exist, none of the backup activity
1391 // that follows is necessary
1392 if (!fileName().exists()) {
1393 if (!writeFile(fileName()))
1399 // we first write the file to a new name, then move it to its
1400 // proper location once that has been done successfully. that
1401 // way we preserve the original file if something goes wrong.
1402 string const justname = fileName().onlyFileNameWithoutExt();
1403 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1404 justname + "-XXXXXX.lyx");
1405 bool const symlink = fileName().isSymLink();
1407 tempfile->setAutoRemove(false);
1409 FileName savefile(tempfile->name());
1410 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1411 if (!writeFile(savefile))
1414 // we will set this to false if we fail
1415 bool made_backup = true;
1417 FileName backupName;
1418 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1420 if (d->need_format_backup)
1421 backupName = getBackupName();
1423 // If we for some reason failed to find a backup name in case of
1424 // a format change, this will still set one. It's the best we can
1426 if (backupName.empty()) {
1427 backupName.set(fileName().absFileName() + "~");
1428 if (!lyxrc.backupdir_path.empty()) {
1429 string const mangledName =
1430 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1431 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1435 LYXERR(Debug::FILES, "Backing up original file to " <<
1436 backupName.absFileName());
1437 // Except file is symlink do not copy because of #6587.
1438 // Hard links have bad luck.
1439 made_backup = symlink ?
1440 fileName().copyTo(backupName):
1441 fileName().moveTo(backupName);
1444 Alert::error(_("Backup failure"),
1445 bformat(_("Cannot create backup file %1$s.\n"
1446 "Please check whether the directory exists and is writable."),
1447 from_utf8(backupName.absFileName())));
1448 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1449 } else if (d->need_format_backup) {
1450 // the original file has been backed up successfully, so we
1451 // will not need to do that again
1452 d->need_format_backup = false;
1456 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1457 // Only do this if tempfile is not in autoremove mode
1460 // If we have no symlink, we can simply rename the temp file.
1461 // Otherwise, we need to copy it so the symlink stays intact.
1462 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1463 savefile.moveTo(fileName()))
1465 // saveCheckSum() was already called by writeFile(), but the
1466 // time stamp is invalidated by copying/moving
1469 if (d->file_format != LYX_FORMAT)
1470 // the file associated with this buffer is now in the current format
1471 d->file_format = LYX_FORMAT;
1474 // else we saved the file, but failed to move it to the right location.
1476 if (needBackup && made_backup && !symlink) {
1477 // the original file was moved to some new location, so it will look
1478 // to the user as if it was deleted. (see bug #9234.) we could try
1479 // to restore it, but that would basically mean trying to do again
1480 // what we just failed to do. better to leave things as they are.
1481 Alert::error(_("Write failure"),
1482 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1483 "But LyX could not move it to:\n %2$s.\n"
1484 "Your original file has been backed up to:\n %3$s"),
1485 from_utf8(savefile.absFileName()),
1486 from_utf8(fileName().absFileName()),
1487 from_utf8(backupName.absFileName())));
1489 // either we did not try to make a backup, or else we tried and failed,
1490 // or else the original file was a symlink, in which case it was copied,
1491 // not moved. so the original file is intact.
1492 Alert::error(_("Write failure"),
1493 bformat(_("Cannot move saved file to:\n %1$s.\n"
1494 "But the file has successfully been saved as:\n %2$s."),
1495 from_utf8(fileName().absFileName()),
1496 from_utf8(savefile.absFileName())));
1502 bool Buffer::writeFile(FileName const & fname) const
1504 if (d->read_only && fname == d->filename)
1507 bool retval = false;
1509 docstring const str = bformat(_("Saving document %1$s..."),
1510 makeDisplayPath(fname.absFileName()));
1513 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1515 if (params().compressed) {
1516 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1517 retval = ofs && write(ofs);
1519 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1520 retval = ofs && write(ofs);
1524 message(str + _(" could not write file!"));
1529 // removeAutosaveFile();
1532 message(str + _(" done."));
1538 docstring Buffer::emergencyWrite()
1540 // No need to save if the buffer has not changed.
1544 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1546 docstring user_message = bformat(
1547 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1549 // We try to save three places:
1550 // 1) Same place as document. Unless it is an unnamed doc.
1552 string s = absFileName();
1555 if (writeFile(FileName(s))) {
1557 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1558 return user_message;
1560 user_message += " " + _("Save failed! Trying again...\n");
1564 // 2) In HOME directory.
1565 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1567 lyxerr << ' ' << s << endl;
1568 if (writeFile(FileName(s))) {
1570 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1571 return user_message;
1574 user_message += " " + _("Save failed! Trying yet again...\n");
1576 // 3) In "/tmp" directory.
1577 // MakeAbsPath to prepend the current
1578 // drive letter on OS/2
1579 s = addName(package().temp_dir().absFileName(), absFileName());
1581 lyxerr << ' ' << s << endl;
1582 if (writeFile(FileName(s))) {
1584 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1585 return user_message;
1588 user_message += " " + _("Save failed! Bummer. Document is lost.");
1591 return user_message;
1595 bool Buffer::write(ostream & ofs) const
1598 // Use the standard "C" locale for file output.
1599 ofs.imbue(locale::classic());
1602 // The top of the file should not be written by params().
1604 // write out a comment in the top of the file
1605 // Important: Keep the version formatting in sync with lyx2lyx and
1606 // tex2lyx (bug 7951)
1607 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1608 << " created this file. For more info see http://www.lyx.org/\n"
1609 << "\\lyxformat " << LYX_FORMAT << "\n"
1610 << "\\begin_document\n";
1612 /// For each author, set 'used' to true if there is a change
1613 /// by this author in the document; otherwise set it to 'false'.
1614 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1615 AuthorList::Authors::const_iterator a_end = params().authors().end();
1616 for (; a_it != a_end; ++a_it)
1617 a_it->setUsed(false);
1619 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1620 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1621 for ( ; it != end; ++it)
1622 it->checkAuthors(params().authors());
1624 // now write out the buffer parameters.
1625 ofs << "\\begin_header\n";
1626 params().writeFile(ofs, this);
1627 ofs << "\\end_header\n";
1630 ofs << "\n\\begin_body\n";
1632 ofs << "\n\\end_body\n";
1634 // Write marker that shows file is complete
1635 ofs << "\\end_document" << endl;
1637 // Shouldn't really be needed....
1640 // how to check if close went ok?
1641 // Following is an attempt... (BE 20001011)
1643 // good() returns false if any error occurred, including some
1644 // formatting error.
1645 // bad() returns true if something bad happened in the buffer,
1646 // which should include file system full errors.
1651 lyxerr << "File was not closed properly." << endl;
1658 bool Buffer::makeLaTeXFile(FileName const & fname,
1659 string const & original_path,
1660 OutputParams const & runparams_in,
1661 OutputWhat output) const
1663 OutputParams runparams = runparams_in;
1665 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1666 // Check here, because the "flavor" is not known in BufferParams::encoding()
1667 // (power users can override this safety measure selecting "utf8-plain").
1668 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1669 && (runparams.encoding->name() != "utf8-plain"))
1670 runparams.encoding = encodings.fromLyXName("ascii");
1672 string const encoding = runparams.encoding->iconvName();
1673 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1676 try { ofs.reset(encoding); }
1677 catch (iconv_codecvt_facet_exception const & e) {
1678 lyxerr << "Caught iconv exception: " << e.what() << endl;
1679 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1680 "verify that the support software for your encoding (%1$s) is "
1681 "properly installed"), from_ascii(encoding)));
1684 if (!openFileWrite(ofs, fname))
1687 ErrorList & errorList = d->errorLists["Export"];
1689 bool failed_export = false;
1692 // make sure we are ready to export
1693 // this needs to be done before we validate
1694 // FIXME Do we need to do this all the time? I.e., in children
1695 // of a master we are exporting?
1697 updateMacroInstances(OutputUpdate);
1700 writeLaTeXSource(os, original_path, runparams, output);
1702 catch (EncodingException const & e) {
1703 docstring const failed(1, e.failed_char);
1705 oss << "0x" << hex << e.failed_char << dec;
1706 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1707 " (code point %2$s)"),
1708 failed, from_utf8(oss.str()));
1709 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1710 "representable in the chosen encoding.\n"
1711 "Changing the document encoding to utf8 could help."),
1712 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1713 failed_export = true;
1715 catch (iconv_codecvt_facet_exception const & e) {
1716 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1718 failed_export = true;
1720 catch (exception const & e) {
1721 errorList.push_back(ErrorItem(_("conversion failed"),
1723 failed_export = true;
1726 lyxerr << "Caught some really weird exception..." << endl;
1730 d->texrow = move(os.texrow());
1734 failed_export = true;
1735 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1738 if (runparams_in.silent)
1742 return !failed_export;
1746 void Buffer::writeLaTeXSource(otexstream & os,
1747 string const & original_path,
1748 OutputParams const & runparams_in,
1749 OutputWhat output) const
1751 // The child documents, if any, shall be already loaded at this point.
1753 OutputParams runparams = runparams_in;
1755 // XeTeX with TeX fonts is only safe with ASCII encoding,
1756 // Check here, because the "flavor" is not known in BufferParams::encoding()
1757 // (power users can override this safety measure selecting "utf8-plain").
1758 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1759 && (runparams.encoding->name() != "utf8-plain"))
1760 runparams.encoding = encodings.fromLyXName("ascii");
1761 // FIXME: when only the current paragraph is shown, this is ignored
1762 // (or not reached) and characters encodable in the current
1763 // encoding are not converted to ASCII-representation.
1765 // If we are compiling a file standalone, even if this is the
1766 // child of some other buffer, let's cut the link here, so the
1767 // file is really independent and no concurring settings from
1768 // the master (e.g. branch state) interfere (see #8100).
1769 if (!runparams.is_child)
1770 d->ignore_parent = true;
1772 // Classify the unicode characters appearing in math insets
1773 BufferEncodings::initUnicodeMath(*this);
1775 // validate the buffer.
1776 LYXERR(Debug::LATEX, " Validating buffer...");
1777 LaTeXFeatures features(*this, params(), runparams);
1779 // This is only set once per document (in master)
1780 if (!runparams.is_child)
1781 runparams.use_polyglossia = features.usePolyglossia();
1782 LYXERR(Debug::LATEX, " Buffer validation done.");
1784 bool const output_preamble =
1785 output == FullSource || output == OnlyPreamble;
1786 bool const output_body =
1787 output == FullSource || output == OnlyBody;
1789 // The starting paragraph of the coming rows is the
1790 // first paragraph of the document. (Asger)
1791 if (output_preamble && runparams.nice) {
1792 os << "%% LyX " << lyx_version << " created this file. "
1793 "For more info, see http://www.lyx.org/.\n"
1794 "%% Do not edit unless you really know what "
1797 LYXERR(Debug::INFO, "lyx document header finished");
1799 // There are a few differences between nice LaTeX and usual files:
1800 // usual files have \batchmode and special input@path to allow
1801 // inclusion of figures specified by an explicitly relative path
1802 // (i.e., a path starting with './' or '../') with either \input or
1803 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1804 // input@path is set when the actual parameter original_path is set.
1805 // This is done for usual tex-file, but not for nice-latex-file.
1806 // (Matthias 250696)
1807 // Note that input@path is only needed for something the user does
1808 // in the preamble, included .tex files or ERT, files included by
1809 // LyX work without it.
1810 if (output_preamble) {
1811 if (!runparams.nice) {
1812 // code for usual, NOT nice-latex-file
1813 os << "\\batchmode\n"; // changed from \nonstopmode
1815 if (!original_path.empty()) {
1817 // We don't know the encoding of inputpath
1818 docstring const inputpath = from_utf8(original_path);
1819 docstring uncodable_glyphs;
1820 Encoding const * const enc = runparams.encoding;
1822 for (size_t n = 0; n < inputpath.size(); ++n) {
1823 if (!enc->encodable(inputpath[n])) {
1824 docstring const glyph(1, inputpath[n]);
1825 LYXERR0("Uncodable character '"
1827 << "' in input path!");
1828 uncodable_glyphs += glyph;
1833 // warn user if we found uncodable glyphs.
1834 if (!uncodable_glyphs.empty()) {
1835 frontend::Alert::warning(
1836 _("Uncodable character in file path"),
1838 _("The path of your document\n"
1840 "contains glyphs that are unknown "
1841 "in the current document encoding "
1842 "(namely %2$s). This may result in "
1843 "incomplete output, unless "
1844 "TEXINPUTS contains the document "
1845 "directory and you don't use "
1846 "explicitly relative paths (i.e., "
1847 "paths starting with './' or "
1848 "'../') in the preamble or in ERT."
1849 "\n\nIn case of problems, choose "
1850 "an appropriate document encoding\n"
1851 "(such as utf8) or change the "
1853 inputpath, uncodable_glyphs));
1856 support::latex_path(original_path);
1857 if (contains(docdir, '#')) {
1858 docdir = subst(docdir, "#", "\\#");
1859 os << "\\catcode`\\#=11"
1860 "\\def\\#{#}\\catcode`\\#=6\n";
1862 if (contains(docdir, '%')) {
1863 docdir = subst(docdir, "%", "\\%");
1864 os << "\\catcode`\\%=11"
1865 "\\def\\%{%}\\catcode`\\%=14\n";
1867 os << "\\makeatletter\n"
1868 << "\\def\\input@path{{"
1870 << "\\makeatother\n";
1874 // get parent macros (if this buffer has a parent) which will be
1875 // written at the document begin further down.
1876 MacroSet parentMacros;
1877 listParentMacros(parentMacros, features);
1879 // Write the preamble
1880 runparams.use_babel = params().writeLaTeX(os, features,
1881 d->filename.onlyPath());
1883 // Biblatex bibliographies are loaded here
1884 if (params().useBiblatex()) {
1885 vector<docstring> const bibfiles =
1886 prepareBibFilePaths(runparams, getBibfilesCache(), true);
1887 for (docstring const & file: bibfiles)
1888 os << "\\addbibresource{" << file << "}\n";
1891 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1892 && !features.hasOnlyPolyglossiaLanguages()) {
1895 vector<string> bll = features.getBabelExclusiveLanguages();
1896 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1899 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1904 blangs = bll.size() > 1 ?
1905 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1906 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1910 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1915 plangs = pll.size() > 1 ?
1916 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1917 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1918 if (!blangs.empty())
1922 frontend::Alert::warning(
1923 _("Incompatible Languages!"),
1925 _("You cannot use the following languages "
1926 "together in one LaTeX document because "
1927 "they require conflicting language packages:\n"
1932 // Japanese might be required only in some children of a document,
1933 // but once required, we must keep use_japanese true.
1934 runparams.use_japanese |= features.isRequired("japanese");
1937 // Restore the parenthood if needed
1938 if (!runparams.is_child)
1939 d->ignore_parent = false;
1944 // mark the beginning of the body to separate it from InPreamble insets
1945 os.texrow().start(TexRow::beginDocument());
1946 os << "\\begin{document}\n";
1948 // mark the start of a new paragraph by simulating a newline,
1949 // so that os.afterParbreak() returns true at document start
1952 // output the parent macros
1953 MacroSet::iterator it = parentMacros.begin();
1954 MacroSet::iterator end = parentMacros.end();
1955 for (; it != end; ++it) {
1956 int num_lines = (*it)->write(os.os(), true);
1957 os.texrow().newlines(num_lines);
1960 } // output_preamble
1962 LYXERR(Debug::INFO, "preamble finished, now the body.");
1965 latexParagraphs(*this, text(), os, runparams);
1967 // Restore the parenthood if needed
1968 if (!runparams.is_child)
1969 d->ignore_parent = false;
1971 // add this just in case after all the paragraphs
1974 if (output_preamble) {
1975 os << "\\end{document}\n";
1976 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1978 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1980 runparams_in.encoding = runparams.encoding;
1982 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1983 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1987 void Buffer::makeDocBookFile(FileName const & fname,
1988 OutputParams const & runparams,
1989 OutputWhat output) const
1991 LYXERR(Debug::LATEX, "makeDocBookFile...");
1994 if (!openFileWrite(ofs, fname))
1997 // make sure we are ready to export
1998 // this needs to be done before we validate
2000 updateMacroInstances(OutputUpdate);
2002 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2006 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2010 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2011 OutputParams const & runparams,
2012 OutputWhat output) const
2014 LaTeXFeatures features(*this, params(), runparams);
2019 DocumentClass const & tclass = params().documentClass();
2020 string const & top_element = tclass.latexname();
2022 bool const output_preamble =
2023 output == FullSource || output == OnlyPreamble;
2024 bool const output_body =
2025 output == FullSource || output == OnlyBody;
2027 if (output_preamble) {
2028 if (runparams.flavor == OutputParams::XML)
2029 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2032 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2035 if (! tclass.class_header().empty())
2036 os << from_ascii(tclass.class_header());
2037 else if (runparams.flavor == OutputParams::XML)
2038 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2039 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2041 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2043 docstring preamble = params().preamble;
2044 if (runparams.flavor != OutputParams::XML ) {
2045 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2046 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2047 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2048 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2051 string const name = runparams.nice
2052 ? changeExtension(absFileName(), ".sgml") : fname;
2053 preamble += features.getIncludedFiles(name);
2054 preamble += features.getLyXSGMLEntities();
2056 if (!preamble.empty()) {
2057 os << "\n [ " << preamble << " ]";
2063 string top = top_element;
2065 if (runparams.flavor == OutputParams::XML)
2066 top += params().language->code();
2068 top += params().language->code().substr(0, 2);
2071 if (!params().options.empty()) {
2073 top += params().options;
2076 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2077 << " file was created by LyX " << lyx_version
2078 << "\n See http://www.lyx.org/ for more information -->\n";
2080 params().documentClass().counters().reset();
2082 sgml::openTag(os, top);
2084 docbookParagraphs(text(), *this, os, runparams);
2085 sgml::closeTag(os, top_element);
2090 void Buffer::makeLyXHTMLFile(FileName const & fname,
2091 OutputParams const & runparams) const
2093 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2096 if (!openFileWrite(ofs, fname))
2099 // make sure we are ready to export
2100 // this has to be done before we validate
2101 updateBuffer(UpdateMaster, OutputUpdate);
2102 updateMacroInstances(OutputUpdate);
2104 writeLyXHTMLSource(ofs, runparams, FullSource);
2108 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2112 void Buffer::writeLyXHTMLSource(odocstream & os,
2113 OutputParams const & runparams,
2114 OutputWhat output) const
2116 LaTeXFeatures features(*this, params(), runparams);
2118 d->bibinfo_.makeCitationLabels(*this);
2120 bool const output_preamble =
2121 output == FullSource || output == OnlyPreamble;
2122 bool const output_body =
2123 output == FullSource || output == OnlyBody || output == IncludedFile;
2125 if (output_preamble) {
2126 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2127 << "<!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"
2128 // FIXME Language should be set properly.
2129 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2131 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2132 // FIXME Presumably need to set this right
2133 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2135 docstring const & doctitle = features.htmlTitle();
2137 << (doctitle.empty() ?
2138 from_ascii("LyX Document") :
2139 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2142 docstring styles = features.getTClassHTMLPreamble();
2143 if (!styles.empty())
2144 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2146 styles = features.getPreambleSnippets().str;
2147 if (!styles.empty())
2148 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2150 // we will collect CSS information in a stream, and then output it
2151 // either here, as part of the header, or else in a separate file.
2152 odocstringstream css;
2153 styles = features.getCSSSnippets();
2154 if (!styles.empty())
2155 css << "/* LyX Provided Styles */\n" << styles << '\n';
2157 styles = features.getTClassHTMLStyles();
2158 if (!styles.empty())
2159 css << "/* Layout-provided Styles */\n" << styles << '\n';
2161 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2162 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2163 if (needfg || needbg) {
2164 css << "\nbody {\n";
2167 << from_ascii(X11hexname(params().fontcolor))
2170 css << " background-color: "
2171 << from_ascii(X11hexname(params().backgroundcolor))
2176 docstring const dstyles = css.str();
2177 if (!dstyles.empty()) {
2178 bool written = false;
2179 if (params().html_css_as_file) {
2180 // open a file for CSS info
2182 string const fcssname = addName(temppath(), "docstyle.css");
2183 FileName const fcssfile = FileName(fcssname);
2184 if (openFileWrite(ocss, fcssfile)) {
2188 // write link to header
2189 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2191 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2194 // we are here if the CSS is supposed to be written to the header
2195 // or if we failed to write it to an external file.
2197 os << "<style type='text/css'>\n"
2206 bool const output_body_tag = (output != IncludedFile);
2207 if (output_body_tag)
2208 os << "<body dir=\"auto\">\n";
2210 if (output != IncludedFile)
2211 // if we're an included file, the counters are in the master.
2212 params().documentClass().counters().reset();
2213 xhtmlParagraphs(text(), *this, xs, runparams);
2214 if (output_body_tag)
2218 if (output_preamble)
2223 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2224 // Other flags: -wall -v0 -x
2225 int Buffer::runChktex()
2229 // get LaTeX-Filename
2230 FileName const path(temppath());
2231 string const name = addName(path.absFileName(), latexName());
2232 string const org_path = filePath();
2234 PathChanger p(path); // path to LaTeX file
2235 message(_("Running chktex..."));
2237 // Generate the LaTeX file if neccessary
2238 OutputParams runparams(¶ms().encoding());
2239 runparams.flavor = OutputParams::LATEX;
2240 runparams.nice = false;
2241 runparams.linelen = lyxrc.plaintext_linelen;
2242 makeLaTeXFile(FileName(name), org_path, runparams);
2245 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2246 int const res = chktex.run(terr); // run chktex
2249 Alert::error(_("chktex failure"),
2250 _("Could not run chktex successfully."));
2252 ErrorList & errlist = d->errorLists["ChkTeX"];
2254 bufferErrors(terr, errlist);
2259 if (runparams.silent)
2260 d->errorLists["ChkTeX"].clear();
2268 void Buffer::validate(LaTeXFeatures & features) const
2270 // Validate the buffer params, but not for included
2271 // files, since they also use the parent buffer's
2273 if (!features.runparams().is_child)
2274 params().validate(features);
2276 for (Paragraph const & p : paragraphs())
2277 p.validate(features);
2279 if (lyxerr.debugging(Debug::LATEX)) {
2280 features.showStruct();
2285 void Buffer::getLabelList(vector<docstring> & list) const
2287 // If this is a child document, use the master's list instead.
2289 masterBuffer()->getLabelList(list);
2294 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2295 Toc::const_iterator toc_it = toc->begin();
2296 Toc::const_iterator end = toc->end();
2297 for (; toc_it != end; ++toc_it) {
2298 if (toc_it->depth() == 0)
2299 list.push_back(toc_it->str());
2304 void Buffer::updateBibfilesCache(UpdateScope scope) const
2306 // FIXME This is probably unnecssary, given where we call this.
2307 // If this is a child document, use the parent's cache instead.
2308 if (parent() && scope != UpdateChildOnly) {
2309 masterBuffer()->updateBibfilesCache();
2313 d->bibfiles_cache_.clear();
2314 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2315 if (it->lyxCode() == BIBTEX_CODE) {
2316 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2317 support::FileNamePairList const bibfiles = inset.getBibFiles();
2318 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2321 } else if (it->lyxCode() == INCLUDE_CODE) {
2322 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2323 Buffer const * const incbuf = inset.getChildBuffer();
2326 support::FileNamePairList const & bibfiles =
2327 incbuf->getBibfilesCache(UpdateChildOnly);
2328 if (!bibfiles.empty()) {
2329 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2335 d->bibfile_cache_valid_ = true;
2336 d->bibinfo_cache_valid_ = false;
2337 d->cite_labels_valid_ = false;
2341 void Buffer::invalidateBibinfoCache() const
2343 d->bibinfo_cache_valid_ = false;
2344 d->cite_labels_valid_ = false;
2345 // also invalidate the cache for the parent buffer
2346 Buffer const * const pbuf = d->parent();
2348 pbuf->invalidateBibinfoCache();
2352 void Buffer::invalidateBibfileCache() const
2354 d->bibfile_cache_valid_ = false;
2355 d->bibinfo_cache_valid_ = false;
2356 d->cite_labels_valid_ = false;
2357 // also invalidate the cache for the parent buffer
2358 Buffer const * const pbuf = d->parent();
2360 pbuf->invalidateBibfileCache();
2364 support::FileNamePairList const & Buffer::getBibfilesCache(UpdateScope scope) const
2366 // FIXME This is probably unnecessary, given where we call this.
2367 // If this is a child document, use the master's cache instead.
2368 Buffer const * const pbuf = masterBuffer();
2369 if (pbuf != this && scope != UpdateChildOnly)
2370 return pbuf->getBibfilesCache();
2372 if (!d->bibfile_cache_valid_)
2373 this->updateBibfilesCache(scope);
2375 return d->bibfiles_cache_;
2379 BiblioInfo const & Buffer::masterBibInfo() const
2381 Buffer const * const tmp = masterBuffer();
2383 return tmp->masterBibInfo();
2388 void Buffer::checkIfBibInfoCacheIsValid() const
2390 // use the master's cache
2391 Buffer const * const tmp = masterBuffer();
2393 tmp->checkIfBibInfoCacheIsValid();
2397 // compare the cached timestamps with the actual ones.
2398 FileNamePairList const & bibfiles_cache = getBibfilesCache();
2399 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2400 FileNamePairList::const_iterator en = bibfiles_cache.end();
2401 for (; ei != en; ++ ei) {
2402 FileName const fn = ei->second;
2403 time_t lastw = fn.lastModified();
2404 time_t prevw = d->bibfile_status_[fn];
2405 if (lastw != prevw) {
2406 d->bibinfo_cache_valid_ = false;
2407 d->cite_labels_valid_ = false;
2408 d->bibfile_status_[fn] = lastw;
2414 void Buffer::reloadBibInfoCache() const
2416 // use the master's cache
2417 Buffer const * const tmp = masterBuffer();
2419 tmp->reloadBibInfoCache();
2423 checkIfBibInfoCacheIsValid();
2424 if (d->bibinfo_cache_valid_)
2427 d->bibinfo_.clear();
2429 d->bibinfo_cache_valid_ = true;
2433 void Buffer::collectBibKeys() const
2435 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2436 it->collectBibKeys(it);
2440 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2442 Buffer const * tmp = masterBuffer();
2443 BiblioInfo & masterbi = (tmp == this) ?
2444 d->bibinfo_ : tmp->d->bibinfo_;
2445 masterbi.mergeBiblioInfo(bi);
2449 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2451 Buffer const * tmp = masterBuffer();
2452 BiblioInfo & masterbi = (tmp == this) ?
2453 d->bibinfo_ : tmp->d->bibinfo_;
2458 void Buffer::makeCitationLabels() const
2460 Buffer const * const master = masterBuffer();
2461 return d->bibinfo_.makeCitationLabels(*master);
2465 bool Buffer::citeLabelsValid() const
2467 return masterBuffer()->d->cite_labels_valid_;
2471 void Buffer::removeBiblioTempFiles() const
2473 // We remove files that contain LaTeX commands specific to the
2474 // particular bibliographic style being used, in order to avoid
2475 // LaTeX errors when we switch style.
2476 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2477 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2478 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2479 aux_file.removeFile();
2480 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2481 bbl_file.removeFile();
2482 // Also for the parent buffer
2483 Buffer const * const pbuf = parent();
2485 pbuf->removeBiblioTempFiles();
2489 bool Buffer::isDepClean(string const & name) const
2491 DepClean::const_iterator const it = d->dep_clean.find(name);
2492 if (it == d->dep_clean.end())
2498 void Buffer::markDepClean(string const & name)
2500 d->dep_clean[name] = true;
2504 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2507 // FIXME? if there is an Buffer LFUN that can be dispatched even
2508 // if internal, put a switch '(cmd.action)' here.
2514 switch (cmd.action()) {
2516 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2517 flag.setOnOff(isReadonly());
2520 // FIXME: There is need for a command-line import.
2521 //case LFUN_BUFFER_IMPORT:
2523 case LFUN_BUFFER_AUTO_SAVE:
2526 case LFUN_BUFFER_EXPORT_CUSTOM:
2527 // FIXME: Nothing to check here?
2530 case LFUN_BUFFER_EXPORT: {
2531 docstring const arg = cmd.argument();
2532 if (arg == "custom") {
2537 arg.empty() ? params().getDefaultOutputFormat() : to_utf8(arg);
2538 size_t pos = format.find(' ');
2539 if (pos != string::npos)
2540 format = format.substr(0, pos);
2541 enable = params().isExportable(format, false);
2543 flag.message(bformat(
2544 _("Don't know how to export to format: %1$s"), arg));
2548 case LFUN_BUFFER_CHKTEX:
2549 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2552 case LFUN_BUILD_PROGRAM:
2553 enable = params().isExportable("program", false);
2556 case LFUN_BRANCH_ACTIVATE:
2557 case LFUN_BRANCH_DEACTIVATE:
2558 case LFUN_BRANCH_MASTER_ACTIVATE:
2559 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2560 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2561 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2562 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2563 : params().branchlist();
2564 docstring const branchName = cmd.argument();
2565 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2569 case LFUN_BRANCH_ADD:
2570 case LFUN_BRANCHES_RENAME:
2571 // if no Buffer is present, then of course we won't be called!
2574 case LFUN_BUFFER_LANGUAGE:
2575 enable = !isReadonly();
2578 case LFUN_BUFFER_VIEW_CACHE:
2579 (d->preview_file_).refresh();
2580 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2583 case LFUN_CHANGES_TRACK:
2584 flag.setEnabled(true);
2585 flag.setOnOff(params().track_changes);
2588 case LFUN_CHANGES_OUTPUT:
2589 flag.setEnabled(true);
2590 flag.setOnOff(params().output_changes);
2593 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2594 flag.setOnOff(params().compressed);
2598 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2599 flag.setOnOff(params().output_sync);
2606 flag.setEnabled(enable);
2611 void Buffer::dispatch(string const & command, DispatchResult & result)
2613 return dispatch(lyxaction.lookupFunc(command), result);
2617 // NOTE We can end up here even if we have no GUI, because we are called
2618 // by LyX::exec to handled command-line requests. So we may need to check
2619 // whether we have a GUI or not. The boolean use_gui holds this information.
2620 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2623 // FIXME? if there is an Buffer LFUN that can be dispatched even
2624 // if internal, put a switch '(cmd.action())' here.
2625 dr.dispatched(false);
2628 string const argument = to_utf8(func.argument());
2629 // We'll set this back to false if need be.
2630 bool dispatched = true;
2631 undo().beginUndoGroup();
2633 switch (func.action()) {
2634 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2635 if (lyxvc().inUse()) {
2636 string log = lyxvc().toggleReadOnly();
2641 setReadonly(!isReadonly());
2644 case LFUN_BUFFER_EXPORT: {
2645 string const format =
2646 argument.empty() ? params().getDefaultOutputFormat() : argument;
2647 ExportStatus const status = doExport(format, false);
2648 dr.setError(status != ExportSuccess);
2649 if (status != ExportSuccess)
2650 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2651 from_utf8(format)));
2655 case LFUN_BUILD_PROGRAM: {
2656 ExportStatus const status = doExport("program", true);
2657 dr.setError(status != ExportSuccess);
2658 if (status != ExportSuccess)
2659 dr.setMessage(_("Error generating literate programming code."));
2663 case LFUN_BUFFER_CHKTEX:
2667 case LFUN_BUFFER_EXPORT_CUSTOM: {
2669 string command = split(argument, format_name, ' ');
2670 Format const * format = formats.getFormat(format_name);
2672 lyxerr << "Format \"" << format_name
2673 << "\" not recognized!"
2678 // The name of the file created by the conversion process
2681 // Output to filename
2682 if (format->name() == "lyx") {
2683 string const latexname = latexName(false);
2684 filename = changeExtension(latexname,
2685 format->extension());
2686 filename = addName(temppath(), filename);
2688 if (!writeFile(FileName(filename)))
2692 doExport(format_name, true, filename);
2695 // Substitute $$FName for filename
2696 if (!contains(command, "$$FName"))
2697 command = "( " + command + " ) < $$FName";
2698 command = subst(command, "$$FName", filename);
2700 // Execute the command in the background
2702 call.startscript(Systemcall::DontWait, command,
2703 filePath(), layoutPos());
2707 // FIXME: There is need for a command-line import.
2709 case LFUN_BUFFER_IMPORT:
2714 case LFUN_BUFFER_AUTO_SAVE:
2716 resetAutosaveTimers();
2719 case LFUN_BRANCH_ACTIVATE:
2720 case LFUN_BRANCH_DEACTIVATE:
2721 case LFUN_BRANCH_MASTER_ACTIVATE:
2722 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2723 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2724 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2725 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2728 docstring const branch_name = func.argument();
2729 // the case without a branch name is handled elsewhere
2730 if (branch_name.empty()) {
2734 Branch * branch = buf->params().branchlist().find(branch_name);
2736 LYXERR0("Branch " << branch_name << " does not exist.");
2738 docstring const msg =
2739 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2743 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2744 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2745 if (branch->isSelected() != activate) {
2746 buf->undo().recordUndoBufferParams(CursorData());
2747 branch->setSelected(activate);
2749 dr.screenUpdate(Update::Force);
2750 dr.forceBufferUpdate();
2755 case LFUN_BRANCH_ADD: {
2756 docstring branch_name = func.argument();
2757 if (branch_name.empty()) {
2761 BranchList & branch_list = params().branchlist();
2762 vector<docstring> const branches =
2763 getVectorFromString(branch_name, branch_list.separator());
2765 for (vector<docstring>::const_iterator it = branches.begin();
2766 it != branches.end(); ++it) {
2768 Branch * branch = branch_list.find(branch_name);
2770 LYXERR0("Branch " << branch_name << " already exists.");
2774 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2776 undo().recordUndoBufferParams(CursorData());
2777 branch_list.add(branch_name);
2778 branch = branch_list.find(branch_name);
2779 string const x11hexname = X11hexname(branch->color());
2780 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2781 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2783 dr.screenUpdate(Update::Force);
2791 case LFUN_BRANCHES_RENAME: {
2792 if (func.argument().empty())
2795 docstring const oldname = from_utf8(func.getArg(0));
2796 docstring const newname = from_utf8(func.getArg(1));
2797 InsetIterator it = inset_iterator_begin(inset());
2798 InsetIterator const end = inset_iterator_end(inset());
2799 bool success = false;
2800 for (; it != end; ++it) {
2801 if (it->lyxCode() == BRANCH_CODE) {
2802 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2803 if (ins.branch() == oldname) {
2804 undo().recordUndo(CursorData(it));
2805 ins.rename(newname);
2810 if (it->lyxCode() == INCLUDE_CODE) {
2811 // get buffer of external file
2812 InsetInclude const & ins =
2813 static_cast<InsetInclude const &>(*it);
2814 Buffer * child = ins.getChildBuffer();
2817 child->dispatch(func, dr);
2822 dr.screenUpdate(Update::Force);
2823 dr.forceBufferUpdate();
2828 case LFUN_BUFFER_VIEW_CACHE:
2829 if (!formats.view(*this, d->preview_file_,
2830 d->preview_format_))
2831 dr.setMessage(_("Error viewing the output file."));
2834 case LFUN_CHANGES_TRACK:
2835 if (params().save_transient_properties)
2836 undo().recordUndoBufferParams(CursorData());
2837 params().track_changes = !params().track_changes;
2838 if (!params().track_changes)
2839 dr.forceChangesUpdate();
2842 case LFUN_CHANGES_OUTPUT:
2843 if (params().save_transient_properties)
2844 undo().recordUndoBufferParams(CursorData());
2845 params().output_changes = !params().output_changes;
2846 if (params().output_changes) {
2847 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2848 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2849 LaTeXFeatures::isAvailable("xcolor");
2851 if (!dvipost && !xcolorulem) {
2852 Alert::warning(_("Changes not shown in LaTeX output"),
2853 _("Changes will not be highlighted in LaTeX output, "
2854 "because neither dvipost nor xcolor/ulem are installed.\n"
2855 "Please install these packages or redefine "
2856 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2857 } else if (!xcolorulem) {
2858 Alert::warning(_("Changes not shown in LaTeX output"),
2859 _("Changes will not be highlighted in LaTeX output "
2860 "when using pdflatex, because xcolor and ulem are not installed.\n"
2861 "Please install both packages or redefine "
2862 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2867 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2868 // turn compression on/off
2869 undo().recordUndoBufferParams(CursorData());
2870 params().compressed = !params().compressed;
2873 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2874 undo().recordUndoBufferParams(CursorData());
2875 params().output_sync = !params().output_sync;
2882 dr.dispatched(dispatched);
2883 undo().endUndoGroup();
2887 void Buffer::changeLanguage(Language const * from, Language const * to)
2889 LASSERT(from, return);
2890 LASSERT(to, return);
2892 for_each(par_iterator_begin(),
2894 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2898 bool Buffer::isMultiLingual() const
2900 ParConstIterator end = par_iterator_end();
2901 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2902 if (it->isMultiLingual(params()))
2909 std::set<Language const *> Buffer::getLanguages() const
2911 std::set<Language const *> languages;
2912 getLanguages(languages);
2917 void Buffer::getLanguages(std::set<Language const *> & languages) const
2919 ParConstIterator end = par_iterator_end();
2920 // add the buffer language, even if it's not actively used
2921 languages.insert(language());
2922 // iterate over the paragraphs
2923 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2924 it->getLanguages(languages);
2926 ListOfBuffers clist = getDescendents();
2927 ListOfBuffers::const_iterator cit = clist.begin();
2928 ListOfBuffers::const_iterator const cen = clist.end();
2929 for (; cit != cen; ++cit)
2930 (*cit)->getLanguages(languages);
2934 DocIterator Buffer::getParFromID(int const id) const
2936 Buffer * buf = const_cast<Buffer *>(this);
2938 // This means non-existent
2939 return doc_iterator_end(buf);
2941 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2942 if (it.paragraph().id() == id)
2945 return doc_iterator_end(buf);
2949 bool Buffer::hasParWithID(int const id) const
2951 return !getParFromID(id).atEnd();
2955 ParIterator Buffer::par_iterator_begin()
2957 return ParIterator(doc_iterator_begin(this));
2961 ParIterator Buffer::par_iterator_end()
2963 return ParIterator(doc_iterator_end(this));
2967 ParConstIterator Buffer::par_iterator_begin() const
2969 return ParConstIterator(doc_iterator_begin(this));
2973 ParConstIterator Buffer::par_iterator_end() const
2975 return ParConstIterator(doc_iterator_end(this));
2979 Language const * Buffer::language() const
2981 return params().language;
2985 docstring const Buffer::B_(string const & l10n) const
2987 return params().B_(l10n);
2991 bool Buffer::isClean() const
2993 return d->lyx_clean;
2997 bool Buffer::isExternallyModified(CheckMethod method) const
2999 LASSERT(d->filename.exists(), return false);
3000 // if method == timestamp, check timestamp before checksum
3001 return (method == checksum_method
3002 || d->timestamp_ != d->filename.lastModified())
3003 && d->checksum_ != d->filename.checksum();
3007 void Buffer::saveCheckSum() const
3009 FileName const & file = d->filename;
3012 if (file.exists()) {
3013 d->timestamp_ = file.lastModified();
3014 d->checksum_ = file.checksum();
3016 // in the case of save to a new file.
3023 void Buffer::markClean() const
3025 if (!d->lyx_clean) {
3026 d->lyx_clean = true;
3029 // if the .lyx file has been saved, we don't need an
3031 d->bak_clean = true;
3032 d->undo_.markDirty();
3036 void Buffer::setUnnamed(bool flag)
3042 bool Buffer::isUnnamed() const
3049 /// Don't check unnamed, here: isInternal() is used in
3050 /// newBuffer(), where the unnamed flag has not been set by anyone
3051 /// yet. Also, for an internal buffer, there should be no need for
3052 /// retrieving fileName() nor for checking if it is unnamed or not.
3053 bool Buffer::isInternal() const
3055 return d->internal_buffer;
3059 void Buffer::setInternal(bool flag)
3061 d->internal_buffer = flag;
3065 void Buffer::markDirty()
3068 d->lyx_clean = false;
3071 d->bak_clean = false;
3073 DepClean::iterator it = d->dep_clean.begin();
3074 DepClean::const_iterator const end = d->dep_clean.end();
3076 for (; it != end; ++it)
3081 FileName Buffer::fileName() const
3087 string Buffer::absFileName() const
3089 return d->filename.absFileName();
3093 string Buffer::filePath() const
3095 string const abs = d->filename.onlyPath().absFileName();
3098 int last = abs.length() - 1;
3100 return abs[last] == '/' ? abs : abs + '/';
3104 DocFileName Buffer::getReferencedFileName(string const & fn) const
3107 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3108 result.set(fn, filePath());
3110 // filePath() ends with a path separator
3111 FileName const test(filePath() + fn);
3113 result.set(fn, filePath());
3115 result.set(fn, params().origin);
3122 string const Buffer::prepareFileNameForLaTeX(string const & name,
3123 string const & ext, bool nice) const
3125 string const fname = makeAbsPath(name, filePath()).absFileName();
3126 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3132 return to_utf8(makeRelPath(from_utf8(fname),
3133 from_utf8(masterBuffer()->filePath())));
3137 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3138 FileNamePairList const bibfilelist,
3139 bool const add_extension) const
3141 // If we are processing the LaTeX file in a temp directory then
3142 // copy the .bib databases to this temp directory, mangling their
3143 // names in the process. Store this mangled name in the list of
3145 // (We need to do all this because BibTeX *really*, *really*
3146 // can't handle "files with spaces" and Windows users tend to
3147 // use such filenames.)
3148 // Otherwise, store the (maybe absolute) path to the original,
3149 // unmangled database name.
3151 vector<docstring> res;
3153 // determine the export format
3154 string const tex_format = flavor2format(runparams.flavor);
3156 // check for spaces in paths
3157 bool found_space = false;
3159 FileNamePairList::const_iterator it = bibfilelist.begin();
3160 FileNamePairList::const_iterator en = bibfilelist.end();
3161 for (; it != en; ++it) {
3162 string utf8input = to_utf8(it->first);
3164 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3165 FileName const try_in_file =
3166 makeAbsPath(database + ".bib", filePath());
3167 bool const not_from_texmf = try_in_file.isReadableFile();
3169 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3171 // mangledFileName() needs the extension
3172 DocFileName const in_file = DocFileName(try_in_file);
3173 database = removeExtension(in_file.mangledFileName());
3174 FileName const out_file = makeAbsPath(database + ".bib",
3175 masterBuffer()->temppath());
3176 bool const success = in_file.copyTo(out_file);
3178 LYXERR0("Failed to copy '" << in_file
3179 << "' to '" << out_file << "'");
3181 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3182 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3183 if (!isValidLaTeXFileName(database)) {
3184 frontend::Alert::warning(_("Invalid filename"),
3185 _("The following filename will cause troubles "
3186 "when running the exported file through LaTeX: ") +
3187 from_utf8(database));
3189 if (!isValidDVIFileName(database)) {
3190 frontend::Alert::warning(_("Problematic filename for DVI"),
3191 _("The following filename can cause troubles "
3192 "when running the exported file through LaTeX "
3193 "and opening the resulting DVI: ") +
3194 from_utf8(database), true);
3202 docstring const path = from_utf8(latex_path(database));
3204 if (contains(path, ' '))
3207 if (find(res.begin(), res.end(), path) == res.end())
3208 res.push_back(path);
3211 // Check if there are spaces in the path and warn BibTeX users, if so.
3212 // (biber can cope with such paths)
3213 if (!prefixIs(runparams.bibtex_command, "biber")) {
3214 // Post this warning only once.
3215 static bool warned_about_spaces = false;
3216 if (!warned_about_spaces &&
3217 runparams.nice && found_space) {
3218 warned_about_spaces = true;
3219 Alert::warning(_("Export Warning!"),
3220 _("There are spaces in the paths to your BibTeX databases.\n"
3221 "BibTeX will be unable to find them."));
3230 string Buffer::layoutPos() const
3232 return d->layout_position;
3236 void Buffer::setLayoutPos(string const & path)
3239 d->layout_position.clear();
3243 LATTEST(FileName::isAbsolute(path));
3245 d->layout_position =
3246 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3248 if (d->layout_position.empty())
3249 d->layout_position = ".";
3253 bool Buffer::isReadonly() const
3255 return d->read_only;
3259 void Buffer::setParent(Buffer const * buffer)
3261 // Avoids recursive include.
3262 d->setParent(buffer == this ? 0 : buffer);
3267 Buffer const * Buffer::parent() const
3273 ListOfBuffers Buffer::allRelatives() const
3275 ListOfBuffers lb = masterBuffer()->getDescendents();
3276 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3281 Buffer const * Buffer::masterBuffer() const
3283 // FIXME Should be make sure we are not in some kind
3284 // of recursive include? A -> B -> A will crash this.
3285 Buffer const * const pbuf = d->parent();
3289 return pbuf->masterBuffer();
3293 bool Buffer::isChild(Buffer * child) const
3295 return d->children_positions.find(child) != d->children_positions.end();
3299 DocIterator Buffer::firstChildPosition(Buffer const * child)
3301 Impl::BufferPositionMap::iterator it;
3302 it = d->children_positions.find(child);
3303 if (it == d->children_positions.end())
3304 return DocIterator(this);
3309 bool Buffer::hasChildren() const
3311 return !d->children_positions.empty();
3315 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3317 // loop over children
3318 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3319 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3320 for (; it != end; ++it) {
3321 Buffer * child = const_cast<Buffer *>(it->first);
3323 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3324 if (bit != clist.end())
3326 clist.push_back(child);
3328 // there might be grandchildren
3329 child->collectChildren(clist, true);
3334 ListOfBuffers Buffer::getChildren() const
3337 collectChildren(v, false);
3338 // Make sure we have not included ourselves.
3339 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3340 if (bit != v.end()) {
3341 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3348 ListOfBuffers Buffer::getDescendents() const
3351 collectChildren(v, true);
3352 // Make sure we have not included ourselves.
3353 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3354 if (bit != v.end()) {
3355 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3362 template<typename M>
3363 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3368 typename M::const_iterator it = m.lower_bound(x);
3369 if (it == m.begin())
3377 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3378 DocIterator const & pos) const
3380 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3382 // if paragraphs have no macro context set, pos will be empty
3386 // we haven't found anything yet
3387 DocIterator bestPos = owner_->par_iterator_begin();
3388 MacroData const * bestData = 0;
3390 // find macro definitions for name
3391 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3392 if (nameIt != macros.end()) {
3393 // find last definition in front of pos or at pos itself
3394 PositionScopeMacroMap::const_iterator it
3395 = greatest_below(nameIt->second, pos);
3396 if (it != nameIt->second.end()) {
3398 // scope ends behind pos?
3399 if (pos < it->second.scope) {
3400 // Looks good, remember this. If there
3401 // is no external macro behind this,
3402 // we found the right one already.
3403 bestPos = it->first;
3404 bestData = &it->second.macro;
3408 // try previous macro if there is one
3409 if (it == nameIt->second.begin())
3416 // find macros in included files
3417 PositionScopeBufferMap::const_iterator it
3418 = greatest_below(position_to_children, pos);
3419 if (it == position_to_children.end())
3420 // no children before
3424 // do we know something better (i.e. later) already?
3425 if (it->first < bestPos )
3428 // scope ends behind pos?
3429 if (pos < it->second.scope
3430 && (cloned_buffer_ ||
3431 theBufferList().isLoaded(it->second.buffer))) {
3432 // look for macro in external file
3434 MacroData const * data
3435 = it->second.buffer->getMacro(name, false);
3438 bestPos = it->first;
3444 // try previous file if there is one
3445 if (it == position_to_children.begin())
3450 // return the best macro we have found
3455 MacroData const * Buffer::getMacro(docstring const & name,
3456 DocIterator const & pos, bool global) const
3461 // query buffer macros
3462 MacroData const * data = d->getBufferMacro(name, pos);
3466 // If there is a master buffer, query that
3467 Buffer const * const pbuf = d->parent();
3469 d->macro_lock = true;
3470 MacroData const * macro = pbuf->getMacro(
3471 name, *this, false);
3472 d->macro_lock = false;
3478 data = MacroTable::globalMacros().get(name);
3487 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3489 // set scope end behind the last paragraph
3490 DocIterator scope = par_iterator_begin();
3491 scope.pit() = scope.lastpit() + 1;
3493 return getMacro(name, scope, global);
3497 MacroData const * Buffer::getMacro(docstring const & name,
3498 Buffer const & child, bool global) const
3500 // look where the child buffer is included first
3501 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3502 if (it == d->children_positions.end())
3505 // check for macros at the inclusion position
3506 return getMacro(name, it->second, global);
3510 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3512 pit_type const lastpit = it.lastpit();
3514 // look for macros in each paragraph
3515 while (it.pit() <= lastpit) {
3516 Paragraph & par = it.paragraph();
3518 // iterate over the insets of the current paragraph
3519 InsetList const & insets = par.insetList();
3520 InsetList::const_iterator iit = insets.begin();
3521 InsetList::const_iterator end = insets.end();
3522 for (; iit != end; ++iit) {
3523 it.pos() = iit->pos;
3525 // is it a nested text inset?
3526 if (iit->inset->asInsetText()) {
3527 // Inset needs its own scope?
3528 InsetText const * itext = iit->inset->asInsetText();
3529 bool newScope = itext->isMacroScope();
3531 // scope which ends just behind the inset
3532 DocIterator insetScope = it;
3535 // collect macros in inset
3536 it.push_back(CursorSlice(*iit->inset));
3537 updateMacros(it, newScope ? insetScope : scope);
3542 if (iit->inset->asInsetTabular()) {
3543 CursorSlice slice(*iit->inset);
3544 size_t const numcells = slice.nargs();
3545 for (; slice.idx() < numcells; slice.forwardIdx()) {
3546 it.push_back(slice);
3547 updateMacros(it, scope);
3553 // is it an external file?
3554 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3555 // get buffer of external file
3556 InsetInclude const & inset =
3557 static_cast<InsetInclude const &>(*iit->inset);
3559 Buffer * child = inset.getChildBuffer();
3564 // register its position, but only when it is
3565 // included first in the buffer
3566 if (children_positions.find(child) ==
3567 children_positions.end())
3568 children_positions[child] = it;
3570 // register child with its scope
3571 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3575 InsetMath * im = iit->inset->asInsetMath();
3576 if (doing_export && im) {
3577 InsetMathHull * hull = im->asHullInset();
3579 hull->recordLocation(it);
3582 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3586 MathMacroTemplate & macroTemplate =
3587 *iit->inset->asInsetMath()->asMacroTemplate();
3588 MacroContext mc(owner_, it);
3589 macroTemplate.updateToContext(mc);
3592 bool valid = macroTemplate.validMacro();
3593 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3594 // then the BufferView's cursor will be invalid in
3595 // some cases which leads to crashes.
3600 // FIXME (Abdel), I don't understand why we pass 'it' here
3601 // instead of 'macroTemplate' defined above... is this correct?
3602 macros[macroTemplate.name()][it] =
3603 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3613 void Buffer::updateMacros() const
3618 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3620 // start with empty table
3622 d->children_positions.clear();
3623 d->position_to_children.clear();
3625 // Iterate over buffer, starting with first paragraph
3626 // The scope must be bigger than any lookup DocIterator
3627 // later. For the global lookup, lastpit+1 is used, hence
3628 // we use lastpit+2 here.
3629 DocIterator it = par_iterator_begin();
3630 DocIterator outerScope = it;
3631 outerScope.pit() = outerScope.lastpit() + 2;
3632 d->updateMacros(it, outerScope);
3636 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3638 InsetIterator it = inset_iterator_begin(inset());
3639 InsetIterator const end = inset_iterator_end(inset());
3640 for (; it != end; ++it) {
3641 if (it->lyxCode() == BRANCH_CODE) {
3642 InsetBranch & br = static_cast<InsetBranch &>(*it);
3643 docstring const name = br.branch();
3644 if (!from_master && !params().branchlist().find(name))
3645 result.push_back(name);
3646 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3647 result.push_back(name);
3650 if (it->lyxCode() == INCLUDE_CODE) {
3651 // get buffer of external file
3652 InsetInclude const & ins =
3653 static_cast<InsetInclude const &>(*it);
3654 Buffer * child = ins.getChildBuffer();
3657 child->getUsedBranches(result, true);
3660 // remove duplicates
3665 void Buffer::updateMacroInstances(UpdateType utype) const
3667 LYXERR(Debug::MACROS, "updateMacroInstances for "
3668 << d->filename.onlyFileName());
3669 DocIterator it = doc_iterator_begin(this);
3671 DocIterator const end = doc_iterator_end(this);
3672 for (; it != end; it.forwardInset()) {
3673 // look for MathData cells in InsetMathNest insets
3674 InsetMath * minset = it.nextInset()->asInsetMath();
3678 // update macro in all cells of the InsetMathNest
3679 DocIterator::idx_type n = minset->nargs();
3680 MacroContext mc = MacroContext(this, it);
3681 for (DocIterator::idx_type i = 0; i < n; ++i) {
3682 MathData & data = minset->cell(i);
3683 data.updateMacros(0, mc, utype, 0);
3689 void Buffer::listMacroNames(MacroNameSet & macros) const
3694 d->macro_lock = true;
3696 // loop over macro names
3697 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3698 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3699 for (; nameIt != nameEnd; ++nameIt)
3700 macros.insert(nameIt->first);
3702 // loop over children
3703 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3704 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3705 for (; it != end; ++it)
3706 it->first->listMacroNames(macros);
3709 Buffer const * const pbuf = d->parent();
3711 pbuf->listMacroNames(macros);
3713 d->macro_lock = false;
3717 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3719 Buffer const * const pbuf = d->parent();
3724 pbuf->listMacroNames(names);
3727 MacroNameSet::iterator it = names.begin();
3728 MacroNameSet::iterator end = names.end();
3729 for (; it != end; ++it) {
3731 MacroData const * data =
3732 pbuf->getMacro(*it, *this, false);
3734 macros.insert(data);
3736 // we cannot access the original MathMacroTemplate anymore
3737 // here to calls validate method. So we do its work here manually.
3738 // FIXME: somehow make the template accessible here.
3739 if (data->optionals() > 0)
3740 features.require("xargs");
3746 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3749 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3751 RefCache::iterator it = d->ref_cache_.find(label);
3752 if (it != d->ref_cache_.end())
3753 return it->second.second;
3755 static InsetLabel const * dummy_il = 0;
3756 static References const dummy_refs = References();
3757 it = d->ref_cache_.insert(
3758 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3759 return it->second.second;
3763 Buffer::References const & Buffer::references(docstring const & label) const
3765 return const_cast<Buffer *>(this)->getReferenceCache(label);
3769 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3771 References & refs = getReferenceCache(label);
3772 refs.push_back(make_pair(inset, it));
3776 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3778 masterBuffer()->d->ref_cache_[label].first = il;
3782 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3784 return masterBuffer()->d->ref_cache_[label].first;
3788 void Buffer::clearReferenceCache() const
3791 d->ref_cache_.clear();
3795 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3797 //FIXME: This does not work for child documents yet.
3798 reloadBibInfoCache();
3800 // Check if the label 'from' appears more than once
3801 BiblioInfo const & keys = masterBibInfo();
3802 BiblioInfo::const_iterator bit = keys.begin();
3803 BiblioInfo::const_iterator bend = keys.end();
3804 vector<docstring> labels;
3806 for (; bit != bend; ++bit)
3808 labels.push_back(bit->first);
3810 if (count(labels.begin(), labels.end(), from) > 1)
3813 string const paramName = "key";
3814 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3815 if (it->lyxCode() != CITE_CODE)
3817 InsetCommand * inset = it->asInsetCommand();
3818 docstring const oldValue = inset->getParam(paramName);
3819 if (oldValue == from)
3820 inset->setParam(paramName, to);
3824 // returns NULL if id-to-row conversion is unsupported
3825 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3826 pit_type par_begin, pit_type par_end,
3827 OutputWhat output, bool master) const
3829 unique_ptr<TexRow> texrow;
3830 OutputParams runparams(¶ms().encoding());
3831 runparams.nice = true;
3832 runparams.flavor = params().getOutputFlavor(format);
3833 runparams.linelen = lyxrc.plaintext_linelen;
3834 // No side effect of file copying and image conversion
3835 runparams.dryrun = true;
3837 if (output == CurrentParagraph) {
3838 runparams.par_begin = par_begin;
3839 runparams.par_end = par_end;
3840 if (par_begin + 1 == par_end) {
3842 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3846 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3847 convert<docstring>(par_begin),
3848 convert<docstring>(par_end - 1))
3851 // output paragraphs
3852 if (runparams.flavor == OutputParams::LYX) {
3853 Paragraph const & par = text().paragraphs()[par_begin];
3855 depth_type dt = par.getDepth();
3856 par.write(ods, params(), dt);
3857 os << from_utf8(ods.str());
3858 } else if (runparams.flavor == OutputParams::HTML) {
3860 setMathFlavor(runparams);
3861 xhtmlParagraphs(text(), *this, xs, runparams);
3862 } else if (runparams.flavor == OutputParams::TEXT) {
3864 // FIXME Handles only one paragraph, unlike the others.
3865 // Probably should have some routine with a signature like them.
3866 writePlaintextParagraph(*this,
3867 text().paragraphs()[par_begin], os, runparams, dummy);
3868 } else if (params().isDocBook()) {
3869 docbookParagraphs(text(), *this, os, runparams);
3871 // If we are previewing a paragraph, even if this is the
3872 // child of some other buffer, let's cut the link here,
3873 // so that no concurring settings from the master
3874 // (e.g. branch state) interfere (see #8101).
3876 d->ignore_parent = true;
3877 // We need to validate the Buffer params' features here
3878 // in order to know if we should output polyglossia
3879 // macros (instead of babel macros)
3880 LaTeXFeatures features(*this, params(), runparams);
3882 runparams.use_polyglossia = features.usePolyglossia();
3883 // latex or literate
3886 ots.texrow().newlines(2);
3888 latexParagraphs(*this, text(), ots, runparams);
3889 texrow = ots.releaseTexRow();
3891 // Restore the parenthood
3893 d->ignore_parent = false;
3897 if (output == FullSource)
3898 os << _("Preview source code");
3899 else if (output == OnlyPreamble)
3900 os << _("Preview preamble");
3901 else if (output == OnlyBody)
3902 os << _("Preview body");
3904 if (runparams.flavor == OutputParams::LYX) {
3906 if (output == FullSource)
3908 else if (output == OnlyPreamble)
3909 params().writeFile(ods, this);
3910 else if (output == OnlyBody)
3912 os << from_utf8(ods.str());
3913 } else if (runparams.flavor == OutputParams::HTML) {
3914 writeLyXHTMLSource(os, runparams, output);
3915 } else if (runparams.flavor == OutputParams::TEXT) {
3916 if (output == OnlyPreamble) {
3917 os << "% "<< _("Plain text does not have a preamble.");
3919 writePlaintextFile(*this, os, runparams);
3920 } else if (params().isDocBook()) {
3921 writeDocBookSource(os, absFileName(), runparams, output);
3923 // latex or literate
3926 ots.texrow().newlines(2);
3928 runparams.is_child = true;
3929 writeLaTeXSource(ots, string(), runparams, output);
3930 texrow = ots.releaseTexRow();
3937 ErrorList & Buffer::errorList(string const & type) const
3939 return d->errorLists[type];
3943 void Buffer::updateTocItem(std::string const & type,
3944 DocIterator const & dit) const
3947 d->gui_->updateTocItem(type, dit);
3951 void Buffer::structureChanged() const
3954 d->gui_->structureChanged();
3958 void Buffer::errors(string const & err, bool from_master) const
3961 d->gui_->errors(err, from_master);
3965 void Buffer::message(docstring const & msg) const
3968 d->gui_->message(msg);
3972 void Buffer::setBusy(bool on) const
3975 d->gui_->setBusy(on);
3979 void Buffer::updateTitles() const
3982 d->wa_->updateTitles();
3986 void Buffer::resetAutosaveTimers() const
3989 d->gui_->resetAutosaveTimers();
3993 bool Buffer::hasGuiDelegate() const
3999 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4008 class AutoSaveBuffer : public ForkedProcess {
4011 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4012 : buffer_(buffer), fname_(fname) {}
4014 virtual shared_ptr<ForkedProcess> clone() const
4016 return make_shared<AutoSaveBuffer>(*this);
4021 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4022 from_utf8(fname_.absFileName())));
4023 return run(DontWait);
4027 virtual int generateChild();
4029 Buffer const & buffer_;
4034 int AutoSaveBuffer::generateChild()
4036 #if defined(__APPLE__)
4037 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4038 * We should use something else like threads.
4040 * Since I do not know how to determine at run time what is the OS X
4041 * version, I just disable forking altogether for now (JMarc)
4043 pid_t const pid = -1;
4045 // tmp_ret will be located (usually) in /tmp
4046 // will that be a problem?
4047 // Note that this calls ForkedCalls::fork(), so it's
4048 // ok cross-platform.
4049 pid_t const pid = fork();
4050 // If you want to debug the autosave
4051 // you should set pid to -1, and comment out the fork.
4052 if (pid != 0 && pid != -1)
4056 // pid = -1 signifies that lyx was unable
4057 // to fork. But we will do the save
4059 bool failed = false;
4060 TempFile tempfile("lyxautoXXXXXX.lyx");
4061 tempfile.setAutoRemove(false);
4062 FileName const tmp_ret = tempfile.name();
4063 if (!tmp_ret.empty()) {
4064 if (!buffer_.writeFile(tmp_ret))
4066 else if (!tmp_ret.moveTo(fname_))
4072 // failed to write/rename tmp_ret so try writing direct
4073 if (!buffer_.writeFile(fname_)) {
4074 // It is dangerous to do this in the child,
4075 // but safe in the parent, so...
4076 if (pid == -1) // emit message signal.
4077 buffer_.message(_("Autosave failed!"));
4081 if (pid == 0) // we are the child so...
4090 FileName Buffer::getEmergencyFileName() const
4092 return FileName(d->filename.absFileName() + ".emergency");
4096 FileName Buffer::getAutosaveFileName() const
4098 // if the document is unnamed try to save in the backup dir, else
4099 // in the default document path, and as a last try in the filePath,
4100 // which will most often be the temporary directory
4103 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4104 : lyxrc.backupdir_path;
4105 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4108 string const fname = "#" + d->filename.onlyFileName() + "#";
4110 return makeAbsPath(fname, fpath);
4114 void Buffer::removeAutosaveFile() const
4116 FileName const f = getAutosaveFileName();
4122 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4124 FileName const newauto = getAutosaveFileName();
4126 if (newauto != oldauto && oldauto.exists())
4127 if (!oldauto.moveTo(newauto))
4128 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4132 bool Buffer::autoSave() const
4134 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4135 if (buf->d->bak_clean || isReadonly())
4138 message(_("Autosaving current document..."));
4139 buf->d->bak_clean = true;
4141 FileName const fname = getAutosaveFileName();
4142 LASSERT(d->cloned_buffer_, return false);
4144 // If this buffer is cloned, we assume that
4145 // we are running in a separate thread already.
4146 TempFile tempfile("lyxautoXXXXXX.lyx");
4147 tempfile.setAutoRemove(false);
4148 FileName const tmp_ret = tempfile.name();
4149 if (!tmp_ret.empty()) {
4151 // assume successful write of tmp_ret
4152 if (tmp_ret.moveTo(fname))
4155 // failed to write/rename tmp_ret so try writing direct
4156 return writeFile(fname);
4160 void Buffer::setExportStatus(bool e) const
4162 d->doing_export = e;
4163 ListOfBuffers clist = getDescendents();
4164 ListOfBuffers::const_iterator cit = clist.begin();
4165 ListOfBuffers::const_iterator const cen = clist.end();
4166 for (; cit != cen; ++cit)
4167 (*cit)->d->doing_export = e;
4171 bool Buffer::isExporting() const
4173 return d->doing_export;
4177 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4181 return doExport(target, put_in_tempdir, result_file);
4184 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4185 string & result_file) const
4187 bool const update_unincluded =
4188 params().maintain_unincluded_children
4189 && !params().getIncludedChildren().empty();
4191 // (1) export with all included children (omit \includeonly)
4192 if (update_unincluded) {
4193 ExportStatus const status =
4194 doExport(target, put_in_tempdir, true, result_file);
4195 if (status != ExportSuccess)
4198 // (2) export with included children only
4199 return doExport(target, put_in_tempdir, false, result_file);
4203 void Buffer::setMathFlavor(OutputParams & op) const
4205 switch (params().html_math_output) {
4206 case BufferParams::MathML:
4207 op.math_flavor = OutputParams::MathAsMathML;
4209 case BufferParams::HTML:
4210 op.math_flavor = OutputParams::MathAsHTML;
4212 case BufferParams::Images:
4213 op.math_flavor = OutputParams::MathAsImages;
4215 case BufferParams::LaTeX:
4216 op.math_flavor = OutputParams::MathAsLaTeX;
4222 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4223 bool includeall, string & result_file) const
4225 LYXERR(Debug::FILES, "target=" << target);
4226 OutputParams runparams(¶ms().encoding());
4227 string format = target;
4228 string dest_filename;
4229 size_t pos = target.find(' ');
4230 if (pos != string::npos) {
4231 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4232 format = target.substr(0, pos);
4233 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4234 FileName(dest_filename).onlyPath().createPath();
4235 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4237 MarkAsExporting exporting(this);
4238 string backend_format;
4239 runparams.flavor = OutputParams::LATEX;
4240 runparams.linelen = lyxrc.plaintext_linelen;
4241 runparams.includeall = includeall;
4242 vector<string> backs = params().backends();
4243 Converters converters = theConverters();
4244 bool need_nice_file = false;
4245 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4246 // Get shortest path to format
4247 converters.buildGraph();
4248 Graph::EdgePath path;
4249 for (vector<string>::const_iterator it = backs.begin();
4250 it != backs.end(); ++it) {
4251 Graph::EdgePath p = converters.getPath(*it, format);
4252 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4253 backend_format = *it;
4258 if (!put_in_tempdir) {
4259 // Only show this alert if this is an export to a non-temporary
4260 // file (not for previewing).
4261 Alert::error(_("Couldn't export file"), bformat(
4262 _("No information for exporting the format %1$s."),
4263 formats.prettyName(format)));
4265 return ExportNoPathToFormat;
4267 runparams.flavor = converters.getFlavor(path, this);
4268 Graph::EdgePath::const_iterator it = path.begin();
4269 Graph::EdgePath::const_iterator en = path.end();
4270 for (; it != en; ++it)
4271 if (theConverters().get(*it).nice()) {
4272 need_nice_file = true;
4277 backend_format = format;
4278 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4279 // FIXME: Don't hardcode format names here, but use a flag
4280 if (backend_format == "pdflatex")
4281 runparams.flavor = OutputParams::PDFLATEX;
4282 else if (backend_format == "luatex")
4283 runparams.flavor = OutputParams::LUATEX;
4284 else if (backend_format == "dviluatex")
4285 runparams.flavor = OutputParams::DVILUATEX;
4286 else if (backend_format == "xetex")
4287 runparams.flavor = OutputParams::XETEX;
4290 string filename = latexName(false);
4291 filename = addName(temppath(), filename);
4292 filename = changeExtension(filename,
4293 formats.extension(backend_format));
4294 LYXERR(Debug::FILES, "filename=" << filename);
4296 // Plain text backend
4297 if (backend_format == "text") {
4298 runparams.flavor = OutputParams::TEXT;
4299 writePlaintextFile(*this, FileName(filename), runparams);
4302 else if (backend_format == "xhtml") {
4303 runparams.flavor = OutputParams::HTML;
4304 setMathFlavor(runparams);
4305 makeLyXHTMLFile(FileName(filename), runparams);
4306 } else if (backend_format == "lyx")
4307 writeFile(FileName(filename));
4309 else if (params().isDocBook()) {
4310 runparams.nice = !put_in_tempdir;
4311 makeDocBookFile(FileName(filename), runparams);
4314 else if (backend_format == format || need_nice_file) {
4315 runparams.nice = true;
4316 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4317 if (d->cloned_buffer_)
4318 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4321 } else if (!lyxrc.tex_allows_spaces
4322 && contains(filePath(), ' ')) {
4323 Alert::error(_("File name error"),
4324 _("The directory path to the document cannot contain spaces."));
4325 return ExportTexPathHasSpaces;
4327 runparams.nice = false;
4328 bool const success = makeLaTeXFile(
4329 FileName(filename), filePath(), runparams);
4330 if (d->cloned_buffer_)
4331 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4336 string const error_type = (format == "program")
4337 ? "Build" : params().bufferFormat();
4338 ErrorList & error_list = d->errorLists[error_type];
4339 string const ext = formats.extension(format);
4340 FileName const tmp_result_file(changeExtension(filename, ext));
4341 bool const success = converters.convert(this, FileName(filename),
4342 tmp_result_file, FileName(absFileName()), backend_format, format,
4345 // Emit the signal to show the error list or copy it back to the
4346 // cloned Buffer so that it can be emitted afterwards.
4347 if (format != backend_format) {
4348 if (runparams.silent)
4350 else if (d->cloned_buffer_)
4351 d->cloned_buffer_->d->errorLists[error_type] =
4352 d->errorLists[error_type];
4355 // also to the children, in case of master-buffer-view
4356 ListOfBuffers clist = getDescendents();
4357 ListOfBuffers::const_iterator cit = clist.begin();
4358 ListOfBuffers::const_iterator const cen = clist.end();
4359 for (; cit != cen; ++cit) {
4360 if (runparams.silent)
4361 (*cit)->d->errorLists[error_type].clear();
4362 else if (d->cloned_buffer_) {
4363 // Enable reverse search by copying back the
4364 // texrow object to the cloned buffer.
4365 // FIXME: this is not thread safe.
4366 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4367 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4368 (*cit)->d->errorLists[error_type];
4370 (*cit)->errors(error_type, true);
4374 if (d->cloned_buffer_) {
4375 // Enable reverse dvi or pdf to work by copying back the texrow
4376 // object to the cloned buffer.
4377 // FIXME: There is a possibility of concurrent access to texrow
4378 // here from the main GUI thread that should be securized.
4379 d->cloned_buffer_->d->texrow = d->texrow;
4380 string const error_type = params().bufferFormat();
4381 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4385 if (put_in_tempdir) {
4386 result_file = tmp_result_file.absFileName();
4387 return success ? ExportSuccess : ExportConverterError;
4390 if (dest_filename.empty())
4391 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4393 result_file = dest_filename;
4394 // We need to copy referenced files (e. g. included graphics
4395 // if format == "dvi") to the result dir.
4396 vector<ExportedFile> const files =
4397 runparams.exportdata->externalFiles(format);
4398 string const dest = runparams.export_folder.empty() ?
4399 onlyPath(result_file) : runparams.export_folder;
4400 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4401 : force_overwrite == ALL_FILES;
4402 CopyStatus status = use_force ? FORCE : SUCCESS;
4404 vector<ExportedFile>::const_iterator it = files.begin();
4405 vector<ExportedFile>::const_iterator const en = files.end();
4406 for (; it != en && status != CANCEL; ++it) {
4407 string const fmt = formats.getFormatFromFile(it->sourceName);
4408 string fixedName = it->exportName;
4409 if (!runparams.export_folder.empty()) {
4410 // Relative pathnames starting with ../ will be sanitized
4411 // if exporting to a different folder
4412 while (fixedName.substr(0, 3) == "../")
4413 fixedName = fixedName.substr(3, fixedName.length() - 3);
4415 FileName fixedFileName = makeAbsPath(fixedName, dest);
4416 fixedFileName.onlyPath().createPath();
4417 status = copyFile(fmt, it->sourceName,
4419 it->exportName, status == FORCE,
4420 runparams.export_folder.empty());
4423 if (status == CANCEL) {
4424 message(_("Document export cancelled."));
4425 return ExportCancel;
4428 if (tmp_result_file.exists()) {
4429 // Finally copy the main file
4430 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4431 : force_overwrite != NO_FILES;
4432 if (status == SUCCESS && use_force)
4434 status = copyFile(format, tmp_result_file,
4435 FileName(result_file), result_file,
4437 if (status == CANCEL) {
4438 message(_("Document export cancelled."));
4439 return ExportCancel;
4441 message(bformat(_("Document exported as %1$s "
4443 formats.prettyName(format),
4444 makeDisplayPath(result_file)));
4447 // This must be a dummy converter like fax (bug 1888)
4448 message(bformat(_("Document exported as %1$s"),
4449 formats.prettyName(format)));
4452 return success ? ExportSuccess : ExportConverterError;
4456 Buffer::ExportStatus Buffer::preview(string const & format) const
4458 bool const update_unincluded =
4459 params().maintain_unincluded_children
4460 && !params().getIncludedChildren().empty();
4461 return preview(format, update_unincluded);
4465 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4467 MarkAsExporting exporting(this);
4469 // (1) export with all included children (omit \includeonly)
4471 ExportStatus const status = doExport(format, true, true, result_file);
4472 if (status != ExportSuccess)
4475 // (2) export with included children only
4476 ExportStatus const status = doExport(format, true, false, result_file);
4477 FileName const previewFile(result_file);
4479 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4480 theimpl->preview_file_ = previewFile;
4481 theimpl->preview_format_ = format;
4482 theimpl->preview_error_ = (status != ExportSuccess);
4484 if (status != ExportSuccess)
4487 if (previewFile.exists())
4488 return formats.view(*this, previewFile, format) ?
4489 PreviewSuccess : PreviewError;
4491 // Successful export but no output file?
4492 // Probably a bug in error detection.
4493 LATTEST(status != ExportSuccess);
4498 Buffer::ReadStatus Buffer::extractFromVC()
4500 bool const found = LyXVC::file_not_found_hook(d->filename);
4502 return ReadFileNotFound;
4503 if (!d->filename.isReadableFile())
4509 Buffer::ReadStatus Buffer::loadEmergency()
4511 FileName const emergencyFile = getEmergencyFileName();
4512 if (!emergencyFile.exists()
4513 || emergencyFile.lastModified() <= d->filename.lastModified())
4514 return ReadFileNotFound;
4516 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4517 docstring const text = bformat(_("An emergency save of the document "
4518 "%1$s exists.\n\nRecover emergency save?"), file);
4520 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4521 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4527 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4528 bool const success = (ret_llf == ReadSuccess);
4531 Alert::warning(_("File is read-only"),
4532 bformat(_("An emergency file is successfully loaded, "
4533 "but the original file %1$s is marked read-only. "
4534 "Please make sure to save the document as a different "
4535 "file."), from_utf8(d->filename.absFileName())));
4538 lyxvc().file_found_hook(d->filename);
4539 str = _("Document was successfully recovered.");
4541 str = _("Document was NOT successfully recovered.");
4542 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4543 makeDisplayPath(emergencyFile.absFileName()));
4545 int const del_emerg =
4546 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4547 _("&Remove"), _("&Keep"));
4548 if (del_emerg == 0) {
4549 emergencyFile.removeFile();
4551 Alert::warning(_("Emergency file deleted"),
4552 _("Do not forget to save your file now!"), true);
4554 return success ? ReadSuccess : ReadEmergencyFailure;
4557 int const del_emerg =
4558 Alert::prompt(_("Delete emergency file?"),
4559 _("Remove emergency file now?"), 1, 1,
4560 _("&Remove"), _("&Keep"));
4562 emergencyFile.removeFile();
4563 return ReadOriginal;
4573 Buffer::ReadStatus Buffer::loadAutosave()
4575 // Now check if autosave file is newer.
4576 FileName const autosaveFile = getAutosaveFileName();
4577 if (!autosaveFile.exists()
4578 || autosaveFile.lastModified() <= d->filename.lastModified())
4579 return ReadFileNotFound;
4581 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4582 docstring const text = bformat(_("The backup of the document %1$s "
4583 "is newer.\n\nLoad the backup instead?"), file);
4584 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4585 _("&Load backup"), _("Load &original"), _("&Cancel"));
4590 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4591 // the file is not saved if we load the autosave file.
4592 if (ret_llf == ReadSuccess) {
4594 Alert::warning(_("File is read-only"),
4595 bformat(_("A backup file is successfully loaded, "
4596 "but the original file %1$s is marked read-only. "
4597 "Please make sure to save the document as a "
4599 from_utf8(d->filename.absFileName())));
4602 lyxvc().file_found_hook(d->filename);
4605 return ReadAutosaveFailure;
4608 // Here we delete the autosave
4609 autosaveFile.removeFile();
4610 return ReadOriginal;
4618 Buffer::ReadStatus Buffer::loadLyXFile()
4620 if (!d->filename.isReadableFile()) {
4621 ReadStatus const ret_rvc = extractFromVC();
4622 if (ret_rvc != ReadSuccess)
4626 ReadStatus const ret_re = loadEmergency();
4627 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4630 ReadStatus const ret_ra = loadAutosave();
4631 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4634 return loadThisLyXFile(d->filename);
4638 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4640 return readFile(fn);
4644 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4646 for (auto const & err : terr) {
4647 TexRow::TextEntry start, end = TexRow::text_none;
4648 int errorRow = err.error_in_line;
4649 Buffer const * buf = 0;
4651 if (err.child_name.empty())
4652 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4654 // The error occurred in a child
4655 for (Buffer const * child : getDescendents()) {
4656 string const child_name =
4657 DocFileName(changeExtension(child->absFileName(), "tex")).
4659 if (err.child_name != child_name)
4661 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4662 if (!TexRow::isNone(start)) {
4663 buf = d->cloned_buffer_
4664 ? child->d->cloned_buffer_->d->owner_
4671 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4677 void Buffer::setBuffersForInsets() const
4679 inset().setBuffer(const_cast<Buffer &>(*this));
4683 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4685 LBUFERR(!text().paragraphs().empty());
4687 // Use the master text class also for child documents
4688 Buffer const * const master = masterBuffer();
4689 DocumentClass const & textclass = master->params().documentClass();
4691 // do this only if we are the top-level Buffer
4692 if (master == this) {
4693 textclass.counters().reset(from_ascii("bibitem"));
4694 reloadBibInfoCache();
4697 // keep the buffers to be children in this set. If the call from the
4698 // master comes back we can see which of them were actually seen (i.e.
4699 // via an InsetInclude). The remaining ones in the set need still be updated.
4700 static std::set<Buffer const *> bufToUpdate;
4701 if (scope == UpdateMaster) {
4702 // If this is a child document start with the master
4703 if (master != this) {
4704 bufToUpdate.insert(this);
4705 master->updateBuffer(UpdateMaster, utype);
4706 // If the master buffer has no gui associated with it, then the TocModel is
4707 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4708 // (bug 5699). The same happens if the master buffer is open in a different
4709 // window. This test catches both possibilities.
4710 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4711 // There remains a problem here: If there is another child open in yet a third
4712 // window, that TOC is not updated. So some more general solution is needed at
4714 if (master->d->gui_ != d->gui_)
4717 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4718 if (bufToUpdate.find(this) == bufToUpdate.end())
4722 // start over the counters in the master
4723 textclass.counters().reset();
4726 // update will be done below for this buffer
4727 bufToUpdate.erase(this);
4729 // update all caches
4730 clearReferenceCache();
4732 setChangesPresent(false);
4734 Buffer & cbuf = const_cast<Buffer &>(*this);
4737 ParIterator parit = cbuf.par_iterator_begin();
4738 updateBuffer(parit, utype);
4741 /// Update the tocBackend for any buffer. The outliner uses the master's,
4742 /// and the navigation menu uses the child's.
4743 cbuf.tocBackend().update(true, utype);
4748 d->bibinfo_cache_valid_ = true;
4749 d->cite_labels_valid_ = true;
4750 if (scope == UpdateMaster)
4751 cbuf.structureChanged();
4755 static depth_type getDepth(DocIterator const & it)
4757 depth_type depth = 0;
4758 for (size_t i = 0 ; i < it.depth() ; ++i)
4759 if (!it[i].inset().inMathed())
4760 depth += it[i].paragraph().getDepth() + 1;
4761 // remove 1 since the outer inset does not count
4762 // we should have at least one non-math inset, so
4763 // depth should nevery be 0. but maybe it is worth
4764 // marking this, just in case.
4766 // coverity[INTEGER_OVERFLOW]
4770 static depth_type getItemDepth(ParIterator const & it)
4772 Paragraph const & par = *it;
4773 LabelType const labeltype = par.layout().labeltype;
4775 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4778 // this will hold the lowest depth encountered up to now.
4779 depth_type min_depth = getDepth(it);
4780 ParIterator prev_it = it;
4783 --prev_it.top().pit();
4785 // start of nested inset: go to outer par
4787 if (prev_it.empty()) {
4788 // start of document: nothing to do
4793 // We search for the first paragraph with same label
4794 // that is not more deeply nested.
4795 Paragraph & prev_par = *prev_it;
4796 depth_type const prev_depth = getDepth(prev_it);
4797 if (labeltype == prev_par.layout().labeltype) {
4798 if (prev_depth < min_depth)
4799 return prev_par.itemdepth + 1;
4800 if (prev_depth == min_depth)
4801 return prev_par.itemdepth;
4803 min_depth = min(min_depth, prev_depth);
4804 // small optimization: if we are at depth 0, we won't
4805 // find anything else
4806 if (prev_depth == 0)
4812 static bool needEnumCounterReset(ParIterator const & it)
4814 Paragraph const & par = *it;
4815 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4816 depth_type const cur_depth = par.getDepth();
4817 ParIterator prev_it = it;
4818 while (prev_it.pit()) {
4819 --prev_it.top().pit();
4820 Paragraph const & prev_par = *prev_it;
4821 if (prev_par.getDepth() <= cur_depth)
4822 return prev_par.layout().name() != par.layout().name();
4824 // start of nested inset: reset
4829 // set the label of a paragraph. This includes the counters.
4830 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4832 BufferParams const & bp = owner_->masterBuffer()->params();
4833 DocumentClass const & textclass = bp.documentClass();
4834 Paragraph & par = it.paragraph();
4835 Layout const & layout = par.layout();
4836 Counters & counters = textclass.counters();
4838 if (par.params().startOfAppendix()) {
4839 // We want to reset the counter corresponding to toplevel sectioning
4840 Layout const & lay = textclass.getTOCLayout();
4841 docstring const cnt = lay.counter;
4843 counters.reset(cnt);
4844 counters.appendix(true);
4846 par.params().appendix(counters.appendix());
4848 // Compute the item depth of the paragraph
4849 par.itemdepth = getItemDepth(it);
4851 if (layout.margintype == MARGIN_MANUAL) {
4852 if (par.params().labelWidthString().empty())
4853 par.params().labelWidthString(par.expandLabel(layout, bp));
4854 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4855 // we do not need to do anything here, since the empty case is
4856 // handled during export.
4858 par.params().labelWidthString(docstring());
4861 switch(layout.labeltype) {
4862 case LABEL_ITEMIZE: {
4863 // At some point of time we should do something more
4864 // clever here, like:
4865 // par.params().labelString(
4866 // bp.user_defined_bullet(par.itemdepth).getText());
4867 // for now, use a simple hardcoded label
4868 docstring itemlabel;
4869 switch (par.itemdepth) {
4871 itemlabel = char_type(0x2022);
4874 itemlabel = char_type(0x2013);
4877 itemlabel = char_type(0x2217);
4880 itemlabel = char_type(0x2219); // or 0x00b7
4883 par.params().labelString(itemlabel);
4887 case LABEL_ENUMERATE: {
4888 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4890 switch (par.itemdepth) {
4899 enumcounter += "iv";
4902 // not a valid enumdepth...
4906 // Increase the master counter?
4907 if (layout.stepmastercounter && needEnumCounterReset(it))
4908 counters.stepMaster(enumcounter, utype);
4910 // Maybe we have to reset the enumeration counter.
4911 if (!layout.resumecounter && needEnumCounterReset(it))
4912 counters.reset(enumcounter);
4913 counters.step(enumcounter, utype);
4915 string const & lang = par.getParLanguage(bp)->code();
4916 par.params().labelString(counters.theCounter(enumcounter, lang));
4921 case LABEL_SENSITIVE: {
4922 string const & type = counters.current_float();
4923 docstring full_label;
4925 full_label = owner_->B_("Senseless!!! ");
4927 docstring name = owner_->B_(textclass.floats().getType(type).name());
4928 if (counters.hasCounter(from_utf8(type))) {
4929 string const & lang = par.getParLanguage(bp)->code();
4930 counters.step(from_utf8(type), utype);
4931 full_label = bformat(from_ascii("%1$s %2$s:"),
4933 counters.theCounter(from_utf8(type), lang));
4935 full_label = bformat(from_ascii("%1$s #:"), name);
4937 par.params().labelString(full_label);
4941 case LABEL_NO_LABEL:
4942 par.params().labelString(docstring());
4946 case LABEL_CENTERED:
4947 case LABEL_STATIC: {
4948 docstring const & lcounter = layout.counter;
4949 if (!lcounter.empty()) {
4950 if (layout.toclevel <= bp.secnumdepth
4951 && (layout.latextype != LATEX_ENVIRONMENT
4952 || it.text()->isFirstInSequence(it.pit()))) {
4953 if (counters.hasCounter(lcounter))
4954 counters.step(lcounter, utype);
4955 par.params().labelString(par.expandLabel(layout, bp));
4957 par.params().labelString(docstring());
4959 par.params().labelString(par.expandLabel(layout, bp));
4965 par.params().labelString(par.expandLabel(layout, bp));
4970 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4972 // LASSERT: Is it safe to continue here, or should we just return?
4973 LASSERT(parit.pit() == 0, /**/);
4975 // Set the position of the text in the buffer to be able
4976 // to resolve macros in it.
4977 parit.text()->setMacrocontextPosition(parit);
4979 depth_type maxdepth = 0;
4980 pit_type const lastpit = parit.lastpit();
4981 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4982 // reduce depth if necessary
4983 if (parit->params().depth() > maxdepth) {
4984 /** FIXME: this function is const, but
4985 * nevertheless it modifies the buffer. To be
4986 * cleaner, one should modify the buffer in
4987 * another function, which is actually
4988 * non-const. This would however be costly in
4989 * terms of code duplication.
4991 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4992 parit->params().depth(maxdepth);
4994 maxdepth = parit->getMaxDepthAfter();
4996 if (utype == OutputUpdate) {
4997 // track the active counters
4998 // we have to do this for the master buffer, since the local
4999 // buffer isn't tracking anything.
5000 masterBuffer()->params().documentClass().counters().
5001 setActiveLayout(parit->layout());
5004 // set the counter for this paragraph
5005 d->setLabel(parit, utype);
5007 // update change-tracking flag
5008 parit->addChangesToBuffer(*this);
5011 InsetList::const_iterator iit = parit->insetList().begin();
5012 InsetList::const_iterator end = parit->insetList().end();
5013 for (; iit != end; ++iit) {
5014 parit.pos() = iit->pos;
5015 iit->inset->updateBuffer(parit, utype);
5021 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5022 WordLangTuple & word_lang, docstring_list & suggestions) const
5026 suggestions.clear();
5027 word_lang = WordLangTuple();
5028 bool const to_end = to.empty();
5029 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5030 // OK, we start from here.
5031 for (; from != end; from.forwardPos()) {
5032 // This skips all insets with spell check disabled.
5033 while (!from.allowSpellCheck()) {
5037 // If from is at the end of the document (which is possible
5038 // when "from" was changed above) LyX will crash later otherwise.
5039 if (from.atEnd() || (!to_end && from >= end))
5042 from.paragraph().spellCheck();
5043 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5044 if (SpellChecker::misspelled(res)) {
5048 // Do not increase progress when from == to, otherwise the word
5049 // count will be wrong.
5059 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5061 bool inword = false;
5066 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5067 if (!dit.inTexted()) {
5072 Paragraph const & par = dit.paragraph();
5073 pos_type const pos = dit.pos();
5075 // Copied and adapted from isWordSeparator() in Paragraph
5076 if (pos == dit.lastpos()) {
5079 Inset const * ins = par.getInset(pos);
5080 if (ins && skipNoOutput && !ins->producesOutput()) {
5083 // stop if end of range was skipped
5084 if (!to.atEnd() && dit >= to)
5087 } else if (!par.isDeleted(pos)) {
5088 if (par.isWordSeparator(pos))
5094 if (ins && ins->isLetter())
5096 else if (ins && ins->isSpace())
5099 char_type const c = par.getChar(pos);
5100 if (isPrintableNonspace(c))
5102 else if (isSpace(c))
5112 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5114 d->updateStatistics(from, to, skipNoOutput);
5118 int Buffer::wordCount() const
5120 return d->wordCount();
5124 int Buffer::charCount(bool with_blanks) const
5126 return d->charCount(with_blanks);
5130 Buffer::ReadStatus Buffer::reload()
5133 // c.f. bug http://www.lyx.org/trac/ticket/6587
5134 removeAutosaveFile();
5135 // e.g., read-only status could have changed due to version control
5136 d->filename.refresh();
5137 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5139 // clear parent. this will get reset if need be.
5141 ReadStatus const status = loadLyXFile();
5142 if (status == ReadSuccess) {
5147 message(bformat(_("Document %1$s reloaded."), disp_fn));
5150 message(bformat(_("Could not reload document %1$s."), disp_fn));
5160 bool Buffer::saveAs(FileName const & fn)
5162 FileName const old_name = fileName();
5163 FileName const old_auto = getAutosaveFileName();
5164 bool const old_unnamed = isUnnamed();
5165 bool success = true;
5166 d->old_position = filePath();
5173 // bring the autosave file with us, just in case.
5174 moveAutosaveFile(old_auto);
5175 // validate version control data and
5176 // correct buffer title
5177 lyxvc().file_found_hook(fileName());
5179 // the file has now been saved to the new location.
5180 // we need to check that the locations of child buffers
5182 checkChildBuffers();
5183 checkMasterBuffer();
5186 // reset the old filename and unnamed state
5187 setFileName(old_name);
5188 setUnnamed(old_unnamed);
5192 d->old_position.clear();
5197 void Buffer::checkChildBuffers()
5199 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5200 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5201 for (; it != en; ++it) {
5202 DocIterator dit = it->second;
5203 Buffer * cbuf = const_cast<Buffer *>(it->first);
5204 if (!cbuf || !theBufferList().isLoaded(cbuf))
5206 Inset * inset = dit.nextInset();
5207 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5208 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5209 docstring const & incfile = inset_inc->getParam("filename");
5210 string oldloc = cbuf->absFileName();
5211 string newloc = makeAbsPath(to_utf8(incfile),
5212 onlyPath(absFileName())).absFileName();
5213 if (oldloc == newloc)
5215 // the location of the child file is incorrect.
5217 inset_inc->setChildBuffer(0);
5219 // invalidate cache of children
5220 d->children_positions.clear();
5221 d->position_to_children.clear();
5225 // If a child has been saved under a different name/path, it might have been
5226 // orphaned. Therefore the master needs to be reset (bug 8161).
5227 void Buffer::checkMasterBuffer()
5229 Buffer const * const master = masterBuffer();
5233 // necessary to re-register the child (bug 5873)
5234 // FIXME: clean up updateMacros (here, only
5235 // child registering is needed).
5236 master->updateMacros();
5237 // (re)set master as master buffer, but only
5238 // if we are a real child
5239 if (master->isChild(this))
5246 string Buffer::includedFilePath(string const & name, string const & ext) const
5248 if (d->old_position.empty() ||
5249 equivalent(FileName(d->old_position), FileName(filePath())))
5252 bool isabsolute = FileName::isAbsolute(name);
5253 // both old_position and filePath() end with a path separator
5254 string absname = isabsolute ? name : d->old_position + name;
5256 // if old_position is set to origin, we need to do the equivalent of
5257 // getReferencedFileName() (see readDocument())
5258 if (!isabsolute && d->old_position == params().origin) {
5259 FileName const test(addExtension(filePath() + name, ext));
5261 absname = filePath() + name;
5264 if (!FileName(addExtension(absname, ext)).exists())
5268 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5270 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5271 from_utf8(filePath())));
5275 void Buffer::setChangesPresent(bool b) const
5277 d->tracked_changes_present_ = b;
5281 bool Buffer::areChangesPresent() const
5283 return d->tracked_changes_present_;
5287 void Buffer::updateChangesPresent() const
5289 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5290 setChangesPresent(false);
5291 ParConstIterator it = par_iterator_begin();
5292 ParConstIterator const end = par_iterator_end();
5293 for (; !areChangesPresent() && it != end; ++it)
5294 it->addChangesToBuffer(*this);