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/FileMonitor.h"
95 #include "support/FileName.h"
96 #include "support/FileNameList.h"
97 #include "support/filetools.h"
98 #include "support/ForkedCalls.h"
99 #include "support/gettext.h"
100 #include "support/gzstream.h"
101 #include "support/lstrings.h"
102 #include "support/lyxalgo.h"
103 #include "support/mutex.h"
104 #include "support/os.h"
105 #include "support/Package.h"
106 #include "support/PathChanger.h"
107 #include "support/Systemcall.h"
108 #include "support/TempFile.h"
109 #include "support/textutils.h"
110 #include "support/types.h"
112 #include "support/bind.h"
124 using namespace lyx::support;
125 using namespace lyx::graphics;
129 namespace Alert = frontend::Alert;
130 namespace os = support::os;
134 int const LYX_FORMAT = LYX_FORMAT_LYX;
136 typedef map<string, bool> DepClean;
137 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
142 // A storehouse for the cloned buffers.
143 list<CloneList *> cloned_buffers;
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
153 delete preview_loader_;
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this an unnamed file (New...)?
195 /// is this an internal bufffer?
196 bool internal_buffer;
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
210 /// original format of loaded file
213 /// if the file was originally loaded from an older format, do
214 /// we need to back it up still?
215 bool need_format_backup;
217 /// Ignore the parent (e.g. when exporting a child standalone)?
221 mutable TocBackend toc_backend;
226 ScopeMacro(DocIterator const & s, MacroData const & m)
227 : scope(s), macro(m) {}
231 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
232 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
233 /// map from the macro name to the position map,
234 /// which maps the macro definition position to the scope and the MacroData.
235 NamePositionScopeMacroMap macros;
236 /// This seem to change the way Buffer::getMacro() works
237 mutable bool macro_lock;
239 /// positions of child buffers in the buffer
240 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
242 ScopeBuffer() : buffer(0) {}
243 ScopeBuffer(DocIterator const & s, Buffer const * b)
244 : scope(s), buffer(b) {}
246 Buffer const * buffer;
248 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
249 /// position of children buffers in this buffer
250 BufferPositionMap children_positions;
251 /// map from children inclusion positions to their scope and their buffer
252 PositionScopeBufferMap position_to_children;
254 /// Contains the old buffer filePath() while saving-as, or the
255 /// directory where the document was last saved while loading.
258 /** Keeps track of the path of local layout files.
259 * If possible, it is always relative to the buffer path.
260 * Empty for layouts in system or user directory.
262 string layout_position;
264 /// Container for all sort of Buffer dependant errors.
265 map<string, ErrorList> errorLists;
267 /// checksum used to test if the file has been externally modified. Used to
268 /// double check whether the file had been externally modified when saving.
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_;
379 // Make sure the file monitor monitors the good file.
380 void refreshFileMonitor();
382 /// has it been notified of an external modification?
383 bool isExternallyModified() const { return externally_modified_; }
385 /// Notify or clear of external modification
386 void fileExternallyModified(bool modified) const;
388 /// Block notifications of external modifications
389 FileMonitorBlocker blockFileMonitor() { return file_monitor_->block(10); }
392 /// So we can force access via the accessors.
393 mutable Buffer const * parent_buffer;
399 /// has been externally modified? Can be reset by the user.
400 mutable bool externally_modified_;
402 FileMonitorPtr file_monitor_;
406 /// Creates the per buffer temporary directory
407 static FileName createBufferTmpDir()
409 // FIXME This would be the ideal application for a TempDir class (like
410 // TempFile but for directories)
415 Mutex::Locker locker(&mutex);
416 counter = convert<string>(count++);
418 // We are in our own directory. Why bother to mangle name?
419 // In fact I wrote this code to circumvent a problematic behaviour
420 // (bug?) of EMX mkstemp().
421 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
424 if (!tmpfl.createDirectory(0777)) {
425 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
426 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
427 from_utf8(tmpfl.absFileName())));
433 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
434 Buffer const * cloned_buffer)
435 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
436 internal_buffer(false), read_only(readonly_), filename(file),
437 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
438 ignore_parent(false), toc_backend(owner), macro_lock(false),
439 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
440 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
441 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
442 clone_list_(0), doing_export(false),
443 tracked_changes_present_(0), parent_buffer(0),
444 word_count_(0), char_count_(0), blank_count_(0),
445 externally_modified_(false)
447 refreshFileMonitor();
448 if (!cloned_buffer_) {
449 temppath = createBufferTmpDir();
450 lyxvc.setBuffer(owner_);
452 wa_ = new frontend::WorkAreaManager;
455 temppath = cloned_buffer_->d->temppath;
456 file_fully_loaded = true;
457 params = cloned_buffer_->d->params;
458 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
459 bibinfo_ = cloned_buffer_->d->bibinfo_;
460 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
461 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
462 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
463 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
464 unnamed = cloned_buffer_->d->unnamed;
465 internal_buffer = cloned_buffer_->d->internal_buffer;
466 layout_position = cloned_buffer_->d->layout_position;
467 preview_file_ = cloned_buffer_->d->preview_file_;
468 preview_format_ = cloned_buffer_->d->preview_format_;
469 preview_error_ = cloned_buffer_->d->preview_error_;
470 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
474 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
475 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
477 LYXERR(Debug::INFO, "Buffer::Buffer()");
479 d->inset = new InsetText(*cloned_buffer->d->inset);
480 d->inset->setBuffer(*this);
481 // FIXME: optimize this loop somewhat, maybe by creating a new
482 // general recursive Inset::setId().
483 DocIterator it = doc_iterator_begin(this);
484 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
485 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
486 it.paragraph().setId(cloned_it.paragraph().id());
488 d->inset = new InsetText(this);
489 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
495 LYXERR(Debug::INFO, "Buffer::~Buffer()");
496 // here the buffer should take care that it is
497 // saved properly, before it goes into the void.
499 // GuiView already destroyed
503 // No need to do additional cleanups for internal buffer.
509 // this is in case of recursive includes: we won't try to delete
510 // ourselves as a child.
511 d->clone_list_->erase(this);
512 // loop over children
513 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
514 Impl::BufferPositionMap::iterator end = d->children_positions.end();
515 for (; it != end; ++it) {
516 Buffer * child = const_cast<Buffer *>(it->first);
517 if (d->clone_list_->erase(child))
520 // if we're the master buffer, then we should get rid of the list
523 // If this is not empty, we have leaked something. Worse, one of the
524 // children still has a reference to this list. But we will try to
525 // continue, rather than shut down.
526 LATTEST(d->clone_list_->empty());
527 list<CloneList *>::iterator it =
528 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
529 if (it == cloned_buffers.end()) {
530 // We will leak in this case, but it is safe to continue.
533 cloned_buffers.erase(it);
534 delete d->clone_list_;
536 // FIXME Do we really need to do this right before we delete d?
537 // clear references to children in macro tables
538 d->children_positions.clear();
539 d->position_to_children.clear();
541 // loop over children
542 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
543 Impl::BufferPositionMap::iterator end = d->children_positions.end();
544 for (; it != end; ++it) {
545 Buffer * child = const_cast<Buffer *>(it->first);
546 if (theBufferList().isLoaded(child)) {
547 if (theBufferList().isOthersChild(this, child))
550 theBufferList().release(child);
555 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
557 msg += emergencyWrite();
559 msg += " " + _("Save failed! Document is lost.");
561 Alert::warning(_("Attempting to close changed document!"), msg);
564 // FIXME Do we really need to do this right before we delete d?
565 // clear references to children in macro tables
566 d->children_positions.clear();
567 d->position_to_children.clear();
569 if (!d->temppath.destroyDirectory()) {
570 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
571 from_utf8(d->temppath.absFileName())));
580 Buffer * Buffer::cloneFromMaster() const
583 cloned_buffers.push_back(new CloneList);
584 CloneList * clones = cloned_buffers.back();
586 masterBuffer()->cloneWithChildren(bufmap, clones);
588 // make sure we got cloned
589 BufferMap::const_iterator bit = bufmap.find(this);
590 LASSERT(bit != bufmap.end(), return 0);
591 Buffer * cloned_buffer = bit->second;
593 return cloned_buffer;
597 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
599 // have we already been cloned?
600 if (bufmap.find(this) != bufmap.end())
603 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
605 // The clone needs its own DocumentClass, since running updateBuffer() will
606 // modify it, and we would otherwise be sharing it with the original Buffer.
607 buffer_clone->params().makeDocumentClass(true);
609 cap::switchBetweenClasses(
610 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
611 static_cast<InsetText &>(buffer_clone->inset()), el);
613 bufmap[this] = buffer_clone;
614 clones->insert(buffer_clone);
615 buffer_clone->d->clone_list_ = clones;
616 buffer_clone->d->macro_lock = true;
617 buffer_clone->d->children_positions.clear();
619 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
620 // math macro caches need to be rethought and simplified.
621 // I am not sure wether we should handle Buffer cloning here or in BufferList.
622 // Right now BufferList knows nothing about buffer clones.
623 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
624 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
625 for (; it != end; ++it) {
626 DocIterator dit = it->first.clone(buffer_clone);
627 dit.setBuffer(buffer_clone);
628 Buffer * child = const_cast<Buffer *>(it->second.buffer);
630 child->cloneWithChildren(bufmap, clones);
631 BufferMap::iterator const bit = bufmap.find(child);
632 LASSERT(bit != bufmap.end(), continue);
633 Buffer * child_clone = bit->second;
635 Inset * inset = dit.nextInset();
636 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
637 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
638 inset_inc->setChildBuffer(child_clone);
639 child_clone->d->setParent(buffer_clone);
640 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
641 buffer_clone->setChild(dit, child_clone);
643 buffer_clone->d->macro_lock = false;
648 Buffer * Buffer::cloneBufferOnly() const {
649 cloned_buffers.push_back(new CloneList);
650 CloneList * clones = cloned_buffers.back();
651 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
653 // The clone needs its own DocumentClass, since running updateBuffer() will
654 // modify it, and we would otherwise be sharing it with the original Buffer.
655 buffer_clone->params().makeDocumentClass(true);
657 cap::switchBetweenClasses(
658 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
659 static_cast<InsetText &>(buffer_clone->inset()), el);
661 clones->insert(buffer_clone);
662 buffer_clone->d->clone_list_ = clones;
664 // we won't be cloning the children
665 buffer_clone->d->children_positions.clear();
670 bool Buffer::isClone() const
672 return d->cloned_buffer_;
676 void Buffer::changed(bool update_metrics) const
679 d->wa_->redrawAll(update_metrics);
683 frontend::WorkAreaManager & Buffer::workAreaManager() const
690 Text & Buffer::text() const
692 return d->inset->text();
696 Inset & Buffer::inset() const
702 BufferParams & Buffer::params()
708 BufferParams const & Buffer::params() const
714 BufferParams const & Buffer::masterParams() const
716 if (masterBuffer() == this)
719 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
720 // Copy child authors to the params. We need those pointers.
721 AuthorList const & child_authors = params().authors();
722 AuthorList::Authors::const_iterator it = child_authors.begin();
723 for (; it != child_authors.end(); ++it)
724 mparams.authors().record(*it);
729 double Buffer::fontScalingFactor() const
731 return isExporting() ? 75.0 * params().html_math_img_scale
732 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
736 ParagraphList & Buffer::paragraphs()
738 return text().paragraphs();
742 ParagraphList const & Buffer::paragraphs() const
744 return text().paragraphs();
748 LyXVC & Buffer::lyxvc()
754 LyXVC const & Buffer::lyxvc() const
760 string const Buffer::temppath() const
762 return d->temppath.absFileName();
766 TexRow & Buffer::texrow()
772 TexRow const & Buffer::texrow() const
778 TocBackend & Buffer::tocBackend() const
780 return d->toc_backend;
784 Undo & Buffer::undo()
790 void Buffer::setChild(DocIterator const & dit, Buffer * child)
792 d->children_positions[child] = dit;
796 string Buffer::latexName(bool const no_path) const
798 FileName latex_name =
799 makeLatexName(d->exportFileName());
800 return no_path ? latex_name.onlyFileName()
801 : latex_name.absFileName();
805 FileName Buffer::Impl::exportFileName() const
807 docstring const branch_suffix =
808 params.branchlist().getFileNameSuffix();
809 if (branch_suffix.empty())
812 string const name = filename.onlyFileNameWithoutExt()
813 + to_utf8(branch_suffix);
814 FileName res(filename.onlyPath().absFileName() + "/" + name);
815 res.changeExtension(filename.extension());
821 string Buffer::logName(LogType * type) const
823 string const filename = latexName(false);
825 if (filename.empty()) {
831 string const path = temppath();
833 FileName const fname(addName(temppath(),
834 onlyFileName(changeExtension(filename,
837 // FIXME: how do we know this is the name of the build log?
838 FileName const bname(
839 addName(path, onlyFileName(
840 changeExtension(filename,
841 theFormats().extension(params().bufferFormat()) + ".out"))));
843 // Also consider the master buffer log file
844 FileName masterfname = fname;
845 LogType mtype = latexlog;
846 if (masterBuffer() != this) {
847 string const mlogfile = masterBuffer()->logName(&mtype);
848 masterfname = FileName(mlogfile);
851 // If no Latex log or Build log is newer, show Build log
852 if (bname.exists() &&
853 ((!fname.exists() && !masterfname.exists())
854 || (fname.lastModified() < bname.lastModified()
855 && masterfname.lastModified() < bname.lastModified()))) {
856 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
859 return bname.absFileName();
860 // If we have a newer master file log or only a master log, show this
861 } else if (fname != masterfname
862 && (!fname.exists() && (masterfname.exists()
863 || fname.lastModified() < masterfname.lastModified()))) {
864 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
867 return masterfname.absFileName();
869 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
872 return fname.absFileName();
876 void Buffer::setReadonly(bool const flag)
878 if (d->read_only != flag) {
885 void Buffer::setFileName(FileName const & fname)
887 bool const changed = fname != d->filename;
889 d->refreshFileMonitor();
891 lyxvc().file_found_hook(fname);
892 setReadonly(d->filename.isReadOnly());
898 int Buffer::readHeader(Lexer & lex)
900 int unknown_tokens = 0;
902 int begin_header_line = -1;
904 // Initialize parameters that may be/go lacking in header:
905 params().branchlist().clear();
906 params().preamble.erase();
907 params().options.erase();
908 params().master.erase();
909 params().float_placement.erase();
910 params().paperwidth.erase();
911 params().paperheight.erase();
912 params().leftmargin.erase();
913 params().rightmargin.erase();
914 params().topmargin.erase();
915 params().bottommargin.erase();
916 params().headheight.erase();
917 params().headsep.erase();
918 params().footskip.erase();
919 params().columnsep.erase();
920 params().fonts_cjk.erase();
921 params().listings_params.clear();
922 params().clearLayoutModules();
923 params().clearRemovedModules();
924 params().clearIncludedChildren();
925 params().pdfoptions().clear();
926 params().indiceslist().clear();
927 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
928 params().isbackgroundcolor = false;
929 params().fontcolor = RGBColor(0, 0, 0);
930 params().isfontcolor = false;
931 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
932 params().boxbgcolor = RGBColor(0xFF, 0, 0);
933 params().html_latex_start.clear();
934 params().html_latex_end.clear();
935 params().html_math_img_scale = 1.0;
936 params().output_sync_macro.erase();
937 params().setLocalLayout(docstring(), false);
938 params().setLocalLayout(docstring(), true);
939 params().biblio_opts.erase();
940 params().biblatex_bibstyle.erase();
941 params().biblatex_citestyle.erase();
942 params().multibib.erase();
944 for (int i = 0; i < 4; ++i) {
945 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
946 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
949 ErrorList & errorList = d->errorLists["Parse"];
958 if (token == "\\end_header")
962 if (token == "\\begin_header") {
963 begin_header_line = line;
967 LYXERR(Debug::PARSER, "Handling document header token: `"
970 string const result =
971 params().readToken(lex, token, d->filename.onlyPath());
972 if (!result.empty()) {
973 if (token == "\\textclass") {
974 d->layout_position = result;
977 docstring const s = bformat(_("Unknown token: "
981 errorList.push_back(ErrorItem(_("Document header error"), s));
985 if (begin_header_line) {
986 docstring const s = _("\\begin_header is missing");
987 errorList.push_back(ErrorItem(_("Document header error"), s));
990 params().makeDocumentClass();
992 return unknown_tokens;
997 // changed to be public and have one parameter
998 // Returns true if "\end_document" is not read (Asger)
999 bool Buffer::readDocument(Lexer & lex)
1001 ErrorList & errorList = d->errorLists["Parse"];
1004 // remove dummy empty par
1005 paragraphs().clear();
1007 if (!lex.checkFor("\\begin_document")) {
1008 docstring const s = _("\\begin_document is missing");
1009 errorList.push_back(ErrorItem(_("Document header error"), s));
1014 if (params().output_changes) {
1015 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1016 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1017 LaTeXFeatures::isAvailable("xcolor");
1019 if (!dvipost && !xcolorulem) {
1020 Alert::warning(_("Changes not shown in LaTeX output"),
1021 _("Changes will not be highlighted in LaTeX output, "
1022 "because neither dvipost nor xcolor/ulem are installed.\n"
1023 "Please install these packages or redefine "
1024 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1025 } else if (!xcolorulem) {
1026 Alert::warning(_("Changes not shown in LaTeX output"),
1027 _("Changes will not be highlighted in LaTeX output "
1028 "when using pdflatex, because xcolor and ulem are not installed.\n"
1029 "Please install both packages or redefine "
1030 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1034 if (!parent() && !params().master.empty()) {
1035 FileName const master_file = makeAbsPath(params().master,
1036 onlyPath(absFileName()));
1037 if (isLyXFileName(master_file.absFileName())) {
1039 checkAndLoadLyXFile(master_file, true);
1041 // necessary e.g. after a reload
1042 // to re-register the child (bug 5873)
1043 // FIXME: clean up updateMacros (here, only
1044 // child registering is needed).
1045 master->updateMacros();
1046 // set master as master buffer, but only
1047 // if we are a real child
1048 if (master->isChild(this))
1050 // if the master is not fully loaded
1051 // it is probably just loading this
1052 // child. No warning needed then.
1053 else if (master->isFullyLoaded())
1054 LYXERR0("The master '"
1056 << "' assigned to this document ("
1058 << ") does not include "
1059 "this document. Ignoring the master assignment.");
1064 // assure we have a default index
1065 params().indiceslist().addDefault(B_("Index"));
1068 if (FileName::isAbsolute(params().origin))
1069 d->old_position = params().origin;
1071 d->old_position = filePath();
1072 bool const res = text().read(lex, errorList, d->inset);
1073 d->old_position.clear();
1075 // inform parent buffer about local macros
1077 Buffer const * pbuf = parent();
1078 UserMacroSet::const_iterator cit = usermacros.begin();
1079 UserMacroSet::const_iterator end = usermacros.end();
1080 for (; cit != end; ++cit)
1081 pbuf->usermacros.insert(*cit);
1085 updateMacroInstances(InternalUpdate);
1090 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1092 Format const * fmt = theFormats().getFormat(format);
1095 // It is important to use the correct extension here, since some
1096 // converters create a wrong output file otherwise (e.g. html2latex)
1097 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1098 FileName const name(tempfile.name());
1099 ofdocstream os(name.toFilesystemEncoding().c_str());
1100 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1101 bool const success = !(os << contents).fail();
1104 bool converted = false;
1106 params().compressed = false;
1108 // remove dummy empty par
1109 paragraphs().clear();
1111 converted = importFile(format, name, errorList);
1120 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1122 if (!theConverters().isReachable(format, "lyx"))
1125 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1126 FileName const lyx(tempfile.name());
1127 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1128 return readFile(lyx) == ReadSuccess;
1134 bool Buffer::readString(string const & s)
1136 params().compressed = false;
1139 istringstream is(s);
1141 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1142 FileName const fn = tempfile.name();
1145 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1147 if (success && file_format != LYX_FORMAT) {
1148 // We need to call lyx2lyx, so write the input to a file
1149 ofstream os(fn.toFilesystemEncoding().c_str());
1152 // lyxvc in readFile
1153 if (readFile(fn) != ReadSuccess)
1157 if (readDocument(lex))
1163 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1167 if (!lex.setFile(fname)) {
1168 Alert::error(_("File Not Found"),
1169 bformat(_("Unable to open file `%1$s'."),
1170 from_utf8(fn.absFileName())));
1171 return ReadFileNotFound;
1175 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1176 if (ret_plf != ReadSuccess)
1179 if (file_format != LYX_FORMAT) {
1181 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1182 if (ret_clf != ReadSuccess)
1184 ret_clf = readFile(tmpFile);
1185 if (ret_clf == ReadSuccess) {
1186 d->file_format = file_format;
1187 d->need_format_backup = true;
1192 // FIXME: InsetInfo needs to know whether the file is under VCS
1193 // during the parse process, so this has to be done before.
1194 lyxvc().file_found_hook(d->filename);
1196 if (readDocument(lex)) {
1197 Alert::error(_("Document format failure"),
1198 bformat(_("%1$s ended unexpectedly, which means"
1199 " that it is probably corrupted."),
1200 from_utf8(fn.absFileName())));
1201 return ReadDocumentFailure;
1204 d->file_fully_loaded = true;
1205 d->read_only = !d->filename.isWritable();
1206 params().compressed = theFormats().isZippedFile(d->filename);
1212 bool Buffer::isFullyLoaded() const
1214 return d->file_fully_loaded;
1218 void Buffer::setFullyLoaded(bool value)
1220 d->file_fully_loaded = value;
1224 bool Buffer::lastPreviewError() const
1226 return d->preview_error_;
1230 PreviewLoader * Buffer::loader() const
1232 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1234 if (!d->preview_loader_)
1235 d->preview_loader_ = new PreviewLoader(*this);
1236 return d->preview_loader_;
1240 void Buffer::removePreviews() const
1242 delete d->preview_loader_;
1243 d->preview_loader_ = 0;
1247 void Buffer::updatePreviews() const
1249 PreviewLoader * ploader = loader();
1253 InsetIterator it = inset_iterator_begin(*d->inset);
1254 InsetIterator const end = inset_iterator_end(*d->inset);
1255 for (; it != end; ++it)
1256 it->addPreview(it, *ploader);
1258 ploader->startLoading();
1262 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1263 FileName const & fn, int & file_format) const
1265 if(!lex.checkFor("\\lyxformat")) {
1266 Alert::error(_("Document format failure"),
1267 bformat(_("%1$s is not a readable LyX document."),
1268 from_utf8(fn.absFileName())));
1269 return ReadNoLyXFormat;
1275 // LyX formats 217 and earlier were written as 2.17. This corresponds
1276 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1277 // these cases. See also: www.lyx.org/trac/changeset/1313.
1278 size_t dot = tmp_format.find_first_of(".,");
1279 if (dot != string::npos)
1280 tmp_format.erase(dot, 1);
1282 file_format = convert<int>(tmp_format);
1287 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1288 FileName & tmpfile, int from_format)
1290 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1291 tempfile.setAutoRemove(false);
1292 tmpfile = tempfile.name();
1293 if(tmpfile.empty()) {
1294 Alert::error(_("Conversion failed"),
1295 bformat(_("%1$s is from a different"
1296 " version of LyX, but a temporary"
1297 " file for converting it could"
1298 " not be created."),
1299 from_utf8(fn.absFileName())));
1300 return LyX2LyXNoTempFile;
1303 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1304 if (lyx2lyx.empty()) {
1305 Alert::error(_("Conversion script not found"),
1306 bformat(_("%1$s is from a different"
1307 " version of LyX, but the"
1308 " conversion script lyx2lyx"
1309 " could not be found."),
1310 from_utf8(fn.absFileName())));
1311 return LyX2LyXNotFound;
1315 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1316 ostringstream command;
1317 command << os::python()
1318 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1319 << " -t " << convert<string>(LYX_FORMAT)
1320 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1321 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1322 string const command_str = command.str();
1324 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1326 cmd_ret const ret = runCommand(command_str);
1327 if (ret.first != 0) {
1328 if (from_format < LYX_FORMAT) {
1329 Alert::error(_("Conversion script failed"),
1330 bformat(_("%1$s is from an older version"
1331 " of LyX and the lyx2lyx script"
1332 " failed to convert it."),
1333 from_utf8(fn.absFileName())));
1334 return LyX2LyXOlderFormat;
1336 Alert::error(_("Conversion script failed"),
1337 bformat(_("%1$s is from a newer version"
1338 " of LyX and the lyx2lyx script"
1339 " failed to convert it."),
1340 from_utf8(fn.absFileName())));
1341 return LyX2LyXNewerFormat;
1348 FileName Buffer::getBackupName() const {
1349 FileName const & fn = fileName();
1350 string const fname = fn.onlyFileNameWithoutExt();
1351 string const fext = fn.extension() + "~";
1352 string const fpath = lyxrc.backupdir_path.empty() ?
1353 fn.onlyPath().absFileName() :
1354 lyxrc.backupdir_path;
1355 string const fform = convert<string>(d->file_format);
1356 string const backname = fname + "-lyxformat-" + fform;
1357 FileName backup(addName(fpath, addExtension(backname, fext)));
1359 // limit recursion, just in case
1361 unsigned long orig_checksum = 0;
1362 while (backup.exists() && v < 100) {
1363 if (orig_checksum == 0)
1364 orig_checksum = fn.checksum();
1365 unsigned long new_checksum = backup.checksum();
1366 if (orig_checksum == new_checksum) {
1367 LYXERR(Debug::FILES, "Not backing up " << fn <<
1368 "since " << backup << "has the same checksum.");
1369 // a bit of a hack, but we have to check this anyway
1370 // below, and setting this is simpler than introducing
1371 // a special boolean for this purpose.
1375 string const newbackname = backname + "-" + convert<string>(v);
1376 backup.set(addName(fpath, addExtension(newbackname, fext)));
1379 return v < 100 ? backup : FileName();
1383 // Should probably be moved to somewhere else: BufferView? GuiView?
1384 bool Buffer::save() const
1386 FileMonitorBlocker block = d->blockFileMonitor();
1387 docstring const file = makeDisplayPath(absFileName(), 20);
1388 d->filename.refresh();
1390 // check the read-only status before moving the file as a backup
1391 if (d->filename.exists()) {
1392 bool const read_only = !d->filename.isWritable();
1394 Alert::warning(_("File is read-only"),
1395 bformat(_("The file %1$s cannot be written because it "
1396 "is marked as read-only."), file));
1401 // ask if the disk file has been externally modified (use checksum method)
1402 if (fileName().exists() && isChecksumModified()) {
1404 bformat(_("Document %1$s has been externally modified. "
1405 "Are you sure you want to overwrite this file?"), file);
1406 int const ret = Alert::prompt(_("Overwrite modified file?"),
1407 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1412 // We don't need autosaves in the immediate future. (Asger)
1413 resetAutosaveTimers();
1415 // if the file does not yet exist, none of the backup activity
1416 // that follows is necessary
1417 if (!fileName().exists()) {
1418 if (!writeFile(fileName()))
1424 // we first write the file to a new name, then move it to its
1425 // proper location once that has been done successfully. that
1426 // way we preserve the original file if something goes wrong.
1427 string const justname = fileName().onlyFileNameWithoutExt();
1428 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1429 justname + "-XXXXXX.lyx");
1430 bool const symlink = fileName().isSymLink();
1432 tempfile->setAutoRemove(false);
1434 FileName savefile(tempfile->name());
1435 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1436 if (!writeFile(savefile))
1439 // we will set this to false if we fail
1440 bool made_backup = true;
1442 FileName backupName;
1443 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1445 if (d->need_format_backup)
1446 backupName = getBackupName();
1448 // If we for some reason failed to find a backup name in case of
1449 // a format change, this will still set one. It's the best we can
1451 if (backupName.empty()) {
1452 backupName.set(fileName().absFileName() + "~");
1453 if (!lyxrc.backupdir_path.empty()) {
1454 string const mangledName =
1455 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1456 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1460 LYXERR(Debug::FILES, "Backing up original file to " <<
1461 backupName.absFileName());
1462 // Except file is symlink do not copy because of #6587.
1463 // Hard links have bad luck.
1464 made_backup = symlink ?
1465 fileName().copyTo(backupName):
1466 fileName().moveTo(backupName);
1469 Alert::error(_("Backup failure"),
1470 bformat(_("Cannot create backup file %1$s.\n"
1471 "Please check whether the directory exists and is writable."),
1472 from_utf8(backupName.absFileName())));
1473 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1474 } else if (d->need_format_backup) {
1475 // the original file has been backed up successfully, so we
1476 // will not need to do that again
1477 d->need_format_backup = false;
1481 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1482 // Only do this if tempfile is not in autoremove mode
1485 // If we have no symlink, we can simply rename the temp file.
1486 // Otherwise, we need to copy it so the symlink stays intact.
1487 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1488 savefile.moveTo(fileName()))
1490 // saveCheckSum() was already called by writeFile(), but the
1491 // time stamp is invalidated by copying/moving
1494 if (d->file_format != LYX_FORMAT)
1495 // the file associated with this buffer is now in the current format
1496 d->file_format = LYX_FORMAT;
1499 // else we saved the file, but failed to move it to the right location.
1501 if (needBackup && made_backup && !symlink) {
1502 // the original file was moved to some new location, so it will look
1503 // to the user as if it was deleted. (see bug #9234.) we could try
1504 // to restore it, but that would basically mean trying to do again
1505 // what we just failed to do. better to leave things as they are.
1506 Alert::error(_("Write failure"),
1507 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1508 "But LyX could not move it to:\n %2$s.\n"
1509 "Your original file has been backed up to:\n %3$s"),
1510 from_utf8(savefile.absFileName()),
1511 from_utf8(fileName().absFileName()),
1512 from_utf8(backupName.absFileName())));
1514 // either we did not try to make a backup, or else we tried and failed,
1515 // or else the original file was a symlink, in which case it was copied,
1516 // not moved. so the original file is intact.
1517 Alert::error(_("Write failure"),
1518 bformat(_("Cannot move saved file to:\n %1$s.\n"
1519 "But the file has successfully been saved as:\n %2$s."),
1520 from_utf8(fileName().absFileName()),
1521 from_utf8(savefile.absFileName())));
1527 bool Buffer::writeFile(FileName const & fname) const
1529 if (d->read_only && fname == d->filename)
1532 bool retval = false;
1534 docstring const str = bformat(_("Saving document %1$s..."),
1535 makeDisplayPath(fname.absFileName()));
1538 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1540 if (params().compressed) {
1541 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1542 retval = ofs && write(ofs);
1544 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1545 retval = ofs && write(ofs);
1549 message(str + _(" could not write file!"));
1554 // removeAutosaveFile();
1557 message(str + _(" done."));
1563 docstring Buffer::emergencyWrite()
1565 // No need to save if the buffer has not changed.
1569 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1571 docstring user_message = bformat(
1572 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1574 // We try to save three places:
1575 // 1) Same place as document. Unless it is an unnamed doc.
1577 string s = absFileName();
1580 if (writeFile(FileName(s))) {
1582 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1583 return user_message;
1585 user_message += " " + _("Save failed! Trying again...\n");
1589 // 2) In HOME directory.
1590 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1592 lyxerr << ' ' << s << endl;
1593 if (writeFile(FileName(s))) {
1595 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1596 return user_message;
1599 user_message += " " + _("Save failed! Trying yet again...\n");
1601 // 3) In "/tmp" directory.
1602 // MakeAbsPath to prepend the current
1603 // drive letter on OS/2
1604 s = addName(package().temp_dir().absFileName(), absFileName());
1606 lyxerr << ' ' << s << endl;
1607 if (writeFile(FileName(s))) {
1609 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1610 return user_message;
1613 user_message += " " + _("Save failed! Document is lost.");
1616 return user_message;
1620 bool Buffer::write(ostream & ofs) const
1623 // Use the standard "C" locale for file output.
1624 ofs.imbue(locale::classic());
1627 // The top of the file should not be written by params().
1629 // write out a comment in the top of the file
1630 // Important: Keep the version formatting in sync with lyx2lyx and
1631 // tex2lyx (bug 7951)
1632 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1633 << " created this file. For more info see http://www.lyx.org/\n"
1634 << "\\lyxformat " << LYX_FORMAT << "\n"
1635 << "\\begin_document\n";
1637 /// For each author, set 'used' to true if there is a change
1638 /// by this author in the document; otherwise set it to 'false'.
1639 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1640 AuthorList::Authors::const_iterator a_end = params().authors().end();
1641 for (; a_it != a_end; ++a_it)
1642 a_it->setUsed(false);
1644 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1645 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1646 for ( ; it != end; ++it)
1647 it->checkAuthors(params().authors());
1649 // now write out the buffer parameters.
1650 ofs << "\\begin_header\n";
1651 params().writeFile(ofs, this);
1652 ofs << "\\end_header\n";
1655 ofs << "\n\\begin_body\n";
1657 ofs << "\n\\end_body\n";
1659 // Write marker that shows file is complete
1660 ofs << "\\end_document" << endl;
1662 // Shouldn't really be needed....
1665 // how to check if close went ok?
1666 // Following is an attempt... (BE 20001011)
1668 // good() returns false if any error occurred, including some
1669 // formatting error.
1670 // bad() returns true if something bad happened in the buffer,
1671 // which should include file system full errors.
1676 lyxerr << "File was not closed properly." << endl;
1683 bool Buffer::makeLaTeXFile(FileName const & fname,
1684 string const & original_path,
1685 OutputParams const & runparams_in,
1686 OutputWhat output) const
1688 OutputParams runparams = runparams_in;
1690 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1691 // Check here, because the "flavor" is not known in BufferParams::encoding()
1692 // (power users can override this safety measure selecting "utf8-plain").
1693 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1694 && (runparams.encoding->name() != "utf8-plain"))
1695 runparams.encoding = encodings.fromLyXName("ascii");
1697 string const encoding = runparams.encoding->iconvName();
1698 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1701 try { ofs.reset(encoding); }
1702 catch (iconv_codecvt_facet_exception const & e) {
1703 lyxerr << "Caught iconv exception: " << e.what() << endl;
1704 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1705 "verify that the support software for your encoding (%1$s) is "
1706 "properly installed"), from_ascii(encoding)));
1709 if (!openFileWrite(ofs, fname))
1712 ErrorList & errorList = d->errorLists["Export"];
1714 bool failed_export = false;
1717 // make sure we are ready to export
1718 // this needs to be done before we validate
1719 // FIXME Do we need to do this all the time? I.e., in children
1720 // of a master we are exporting?
1722 updateMacroInstances(OutputUpdate);
1725 writeLaTeXSource(os, original_path, runparams, output);
1727 catch (EncodingException const & e) {
1728 docstring const failed(1, e.failed_char);
1730 oss << "0x" << hex << e.failed_char << dec;
1731 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1732 " (code point %2$s)"),
1733 failed, from_utf8(oss.str()));
1734 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1735 "representable in the chosen encoding.\n"
1736 "Changing the document encoding to utf8 could help."),
1737 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1738 failed_export = true;
1740 catch (iconv_codecvt_facet_exception const & e) {
1741 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1743 failed_export = true;
1745 catch (exception const & e) {
1746 errorList.push_back(ErrorItem(_("conversion failed"),
1748 lyxerr << e.what() << endl;
1749 failed_export = true;
1752 lyxerr << "Caught some really weird exception..." << endl;
1756 d->texrow = move(os.texrow());
1760 failed_export = true;
1761 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1764 if (runparams_in.silent)
1768 return !failed_export;
1772 void Buffer::writeLaTeXSource(otexstream & os,
1773 string const & original_path,
1774 OutputParams const & runparams_in,
1775 OutputWhat output) const
1777 // The child documents, if any, shall be already loaded at this point.
1779 OutputParams runparams = runparams_in;
1781 // XeTeX with TeX fonts is only safe with ASCII encoding,
1782 // Check here, because the "flavor" is not known in BufferParams::encoding()
1783 // (power users can override this safety measure selecting "utf8-plain").
1784 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1785 && (runparams.encoding->name() != "utf8-plain"))
1786 runparams.encoding = encodings.fromLyXName("ascii");
1787 // FIXME: when only the current paragraph is shown, this is ignored
1788 // (or not reached) and characters encodable in the current
1789 // encoding are not converted to ASCII-representation.
1791 // If we are compiling a file standalone, even if this is the
1792 // child of some other buffer, let's cut the link here, so the
1793 // file is really independent and no concurring settings from
1794 // the master (e.g. branch state) interfere (see #8100).
1795 if (!runparams.is_child)
1796 d->ignore_parent = true;
1798 // Classify the unicode characters appearing in math insets
1799 BufferEncodings::initUnicodeMath(*this);
1801 // validate the buffer.
1802 LYXERR(Debug::LATEX, " Validating buffer...");
1803 LaTeXFeatures features(*this, params(), runparams);
1805 // This is only set once per document (in master)
1806 if (!runparams.is_child)
1807 runparams.use_polyglossia = features.usePolyglossia();
1808 LYXERR(Debug::LATEX, " Buffer validation done.");
1810 bool const output_preamble =
1811 output == FullSource || output == OnlyPreamble;
1812 bool const output_body =
1813 output == FullSource || output == OnlyBody;
1815 // The starting paragraph of the coming rows is the
1816 // first paragraph of the document. (Asger)
1817 if (output_preamble && runparams.nice) {
1818 os << "%% LyX " << lyx_version << " created this file. "
1819 "For more info, see http://www.lyx.org/.\n"
1820 "%% Do not edit unless you really know what "
1823 LYXERR(Debug::INFO, "lyx document header finished");
1825 // There are a few differences between nice LaTeX and usual files:
1826 // usual files have \batchmode and special input@path to allow
1827 // inclusion of figures specified by an explicitly relative path
1828 // (i.e., a path starting with './' or '../') with either \input or
1829 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1830 // input@path is set when the actual parameter original_path is set.
1831 // This is done for usual tex-file, but not for nice-latex-file.
1832 // (Matthias 250696)
1833 // Note that input@path is only needed for something the user does
1834 // in the preamble, included .tex files or ERT, files included by
1835 // LyX work without it.
1836 if (output_preamble) {
1837 if (!runparams.nice) {
1838 // code for usual, NOT nice-latex-file
1839 os << "\\batchmode\n"; // changed from \nonstopmode
1841 if (!original_path.empty()) {
1843 // We don't know the encoding of inputpath
1844 docstring const inputpath = from_utf8(original_path);
1845 docstring uncodable_glyphs;
1846 Encoding const * const enc = runparams.encoding;
1848 for (size_t n = 0; n < inputpath.size(); ++n) {
1849 if (!enc->encodable(inputpath[n])) {
1850 docstring const glyph(1, inputpath[n]);
1851 LYXERR0("Uncodable character '"
1853 << "' in input path!");
1854 uncodable_glyphs += glyph;
1859 // warn user if we found uncodable glyphs.
1860 if (!uncodable_glyphs.empty()) {
1861 frontend::Alert::warning(
1862 _("Uncodable character in file path"),
1864 _("The path of your document\n"
1866 "contains glyphs that are unknown "
1867 "in the current document encoding "
1868 "(namely %2$s). This may result in "
1869 "incomplete output, unless "
1870 "TEXINPUTS contains the document "
1871 "directory and you don't use "
1872 "explicitly relative paths (i.e., "
1873 "paths starting with './' or "
1874 "'../') in the preamble or in ERT."
1875 "\n\nIn case of problems, choose "
1876 "an appropriate document encoding\n"
1877 "(such as utf8) or change the "
1879 inputpath, uncodable_glyphs));
1882 support::latex_path(original_path);
1883 if (contains(docdir, '#')) {
1884 docdir = subst(docdir, "#", "\\#");
1885 os << "\\catcode`\\#=11"
1886 "\\def\\#{#}\\catcode`\\#=6\n";
1888 if (contains(docdir, '%')) {
1889 docdir = subst(docdir, "%", "\\%");
1890 os << "\\catcode`\\%=11"
1891 "\\def\\%{%}\\catcode`\\%=14\n";
1893 os << "\\makeatletter\n"
1894 << "\\def\\input@path{{"
1896 << "\\makeatother\n";
1900 // get parent macros (if this buffer has a parent) which will be
1901 // written at the document begin further down.
1902 MacroSet parentMacros;
1903 listParentMacros(parentMacros, features);
1905 // Write the preamble
1906 runparams.use_babel = params().writeLaTeX(os, features,
1907 d->filename.onlyPath());
1909 // Biblatex bibliographies are loaded here
1910 if (params().useBiblatex()) {
1911 vector<docstring> const bibfiles =
1912 prepareBibFilePaths(runparams, getBibfilesCache(), true);
1913 for (docstring const & file: bibfiles)
1914 os << "\\addbibresource{" << file << "}\n";
1917 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1918 && !features.hasOnlyPolyglossiaLanguages()) {
1921 vector<string> bll = features.getBabelExclusiveLanguages();
1922 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1925 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1930 blangs = bll.size() > 1 ?
1931 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1932 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1936 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1941 plangs = pll.size() > 1 ?
1942 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1943 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1944 if (!blangs.empty())
1948 frontend::Alert::warning(
1949 _("Incompatible Languages!"),
1951 _("You cannot use the following languages "
1952 "together in one LaTeX document because "
1953 "they require conflicting language packages:\n"
1958 // Japanese might be required only in some children of a document,
1959 // but once required, we must keep use_japanese true.
1960 runparams.use_japanese |= features.isRequired("japanese");
1963 // Restore the parenthood if needed
1964 if (!runparams.is_child)
1965 d->ignore_parent = false;
1970 // mark the beginning of the body to separate it from InPreamble insets
1971 os.texrow().start(TexRow::beginDocument());
1972 os << "\\begin{document}\n";
1974 // mark the start of a new paragraph by simulating a newline,
1975 // so that os.afterParbreak() returns true at document start
1978 // output the parent macros
1979 MacroSet::iterator it = parentMacros.begin();
1980 MacroSet::iterator end = parentMacros.end();
1981 for (; it != end; ++it) {
1982 int num_lines = (*it)->write(os.os(), true);
1983 os.texrow().newlines(num_lines);
1986 } // output_preamble
1988 LYXERR(Debug::INFO, "preamble finished, now the body.");
1991 latexParagraphs(*this, text(), os, runparams);
1993 // Restore the parenthood if needed
1994 if (!runparams.is_child)
1995 d->ignore_parent = false;
1997 // add this just in case after all the paragraphs
2000 if (output_preamble) {
2001 os << "\\end{document}\n";
2002 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2004 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2006 runparams_in.encoding = runparams.encoding;
2008 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2009 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2013 void Buffer::makeDocBookFile(FileName const & fname,
2014 OutputParams const & runparams,
2015 OutputWhat output) const
2017 LYXERR(Debug::LATEX, "makeDocBookFile...");
2020 if (!openFileWrite(ofs, fname))
2023 // make sure we are ready to export
2024 // this needs to be done before we validate
2026 updateMacroInstances(OutputUpdate);
2028 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2032 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2036 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2037 OutputParams const & runparams,
2038 OutputWhat output) const
2040 LaTeXFeatures features(*this, params(), runparams);
2045 DocumentClass const & tclass = params().documentClass();
2046 string const & top_element = tclass.latexname();
2048 bool const output_preamble =
2049 output == FullSource || output == OnlyPreamble;
2050 bool const output_body =
2051 output == FullSource || output == OnlyBody;
2053 if (output_preamble) {
2054 if (runparams.flavor == OutputParams::XML)
2055 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2058 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2061 if (! tclass.class_header().empty())
2062 os << from_ascii(tclass.class_header());
2063 else if (runparams.flavor == OutputParams::XML)
2064 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2065 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2067 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2069 docstring preamble = params().preamble;
2070 if (runparams.flavor != OutputParams::XML ) {
2071 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2072 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2073 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2074 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2077 string const name = runparams.nice
2078 ? changeExtension(absFileName(), ".sgml") : fname;
2079 preamble += features.getIncludedFiles(name);
2080 preamble += features.getLyXSGMLEntities();
2082 if (!preamble.empty()) {
2083 os << "\n [ " << preamble << " ]";
2089 string top = top_element;
2091 if (runparams.flavor == OutputParams::XML)
2092 top += params().language->code();
2094 top += params().language->code().substr(0, 2);
2097 if (!params().options.empty()) {
2099 top += params().options;
2102 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2103 << " file was created by LyX " << lyx_version
2104 << "\n See http://www.lyx.org/ for more information -->\n";
2106 params().documentClass().counters().reset();
2108 sgml::openTag(os, top);
2110 docbookParagraphs(text(), *this, os, runparams);
2111 sgml::closeTag(os, top_element);
2116 void Buffer::makeLyXHTMLFile(FileName const & fname,
2117 OutputParams const & runparams) const
2119 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2122 if (!openFileWrite(ofs, fname))
2125 // make sure we are ready to export
2126 // this has to be done before we validate
2127 updateBuffer(UpdateMaster, OutputUpdate);
2128 updateMacroInstances(OutputUpdate);
2130 writeLyXHTMLSource(ofs, runparams, FullSource);
2134 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2138 void Buffer::writeLyXHTMLSource(odocstream & os,
2139 OutputParams const & runparams,
2140 OutputWhat output) const
2142 LaTeXFeatures features(*this, params(), runparams);
2144 d->bibinfo_.makeCitationLabels(*this);
2146 bool const output_preamble =
2147 output == FullSource || output == OnlyPreamble;
2148 bool const output_body =
2149 output == FullSource || output == OnlyBody || output == IncludedFile;
2151 if (output_preamble) {
2152 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2153 << "<!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"
2154 // FIXME Language should be set properly.
2155 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2157 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2158 // FIXME Presumably need to set this right
2159 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2161 docstring const & doctitle = features.htmlTitle();
2163 << (doctitle.empty() ?
2164 from_ascii("LyX Document") :
2165 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2168 docstring styles = features.getTClassHTMLPreamble();
2169 if (!styles.empty())
2170 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2172 styles = features.getPreambleSnippets().str;
2173 if (!styles.empty())
2174 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2176 // we will collect CSS information in a stream, and then output it
2177 // either here, as part of the header, or else in a separate file.
2178 odocstringstream css;
2179 styles = features.getCSSSnippets();
2180 if (!styles.empty())
2181 css << "/* LyX Provided Styles */\n" << styles << '\n';
2183 styles = features.getTClassHTMLStyles();
2184 if (!styles.empty())
2185 css << "/* Layout-provided Styles */\n" << styles << '\n';
2187 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2188 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2189 if (needfg || needbg) {
2190 css << "\nbody {\n";
2193 << from_ascii(X11hexname(params().fontcolor))
2196 css << " background-color: "
2197 << from_ascii(X11hexname(params().backgroundcolor))
2202 docstring const dstyles = css.str();
2203 if (!dstyles.empty()) {
2204 bool written = false;
2205 if (params().html_css_as_file) {
2206 // open a file for CSS info
2208 string const fcssname = addName(temppath(), "docstyle.css");
2209 FileName const fcssfile = FileName(fcssname);
2210 if (openFileWrite(ocss, fcssfile)) {
2214 // write link to header
2215 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2217 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2220 // we are here if the CSS is supposed to be written to the header
2221 // or if we failed to write it to an external file.
2223 os << "<style type='text/css'>\n"
2232 bool const output_body_tag = (output != IncludedFile);
2233 if (output_body_tag)
2234 os << "<body dir=\"auto\">\n";
2236 if (output != IncludedFile)
2237 // if we're an included file, the counters are in the master.
2238 params().documentClass().counters().reset();
2239 xhtmlParagraphs(text(), *this, xs, runparams);
2240 if (output_body_tag)
2244 if (output_preamble)
2249 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2250 // Other flags: -wall -v0 -x
2251 int Buffer::runChktex()
2255 // get LaTeX-Filename
2256 FileName const path(temppath());
2257 string const name = addName(path.absFileName(), latexName());
2258 string const org_path = filePath();
2260 PathChanger p(path); // path to LaTeX file
2261 message(_("Running chktex..."));
2263 // Generate the LaTeX file if neccessary
2264 OutputParams runparams(¶ms().encoding());
2265 runparams.flavor = OutputParams::LATEX;
2266 runparams.nice = false;
2267 runparams.linelen = lyxrc.plaintext_linelen;
2268 makeLaTeXFile(FileName(name), org_path, runparams);
2271 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2272 int const res = chktex.run(terr); // run chktex
2275 Alert::error(_("chktex failure"),
2276 _("Could not run chktex successfully."));
2278 ErrorList & errlist = d->errorLists["ChkTeX"];
2280 bufferErrors(terr, errlist);
2285 if (runparams.silent)
2286 d->errorLists["ChkTeX"].clear();
2294 void Buffer::validate(LaTeXFeatures & features) const
2296 // Validate the buffer params, but not for included
2297 // files, since they also use the parent buffer's
2299 if (!features.runparams().is_child)
2300 params().validate(features);
2302 for (Paragraph const & p : paragraphs())
2303 p.validate(features);
2305 if (lyxerr.debugging(Debug::LATEX)) {
2306 features.showStruct();
2311 void Buffer::getLabelList(vector<docstring> & list) const
2313 // If this is a child document, use the master's list instead.
2315 masterBuffer()->getLabelList(list);
2320 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2321 Toc::const_iterator toc_it = toc->begin();
2322 Toc::const_iterator end = toc->end();
2323 for (; toc_it != end; ++toc_it) {
2324 if (toc_it->depth() == 0)
2325 list.push_back(toc_it->str());
2330 void Buffer::updateBibfilesCache(UpdateScope scope) const
2332 // FIXME This is probably unnecssary, given where we call this.
2333 // If this is a child document, use the parent's cache instead.
2334 if (parent() && scope != UpdateChildOnly) {
2335 masterBuffer()->updateBibfilesCache();
2339 d->bibfiles_cache_.clear();
2340 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2341 if (it->lyxCode() == BIBTEX_CODE) {
2342 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2343 support::FileNamePairList const bibfiles = inset.getBibFiles();
2344 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2347 } else if (it->lyxCode() == INCLUDE_CODE) {
2348 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2349 Buffer const * const incbuf = inset.getChildBuffer();
2352 support::FileNamePairList const & bibfiles =
2353 incbuf->getBibfilesCache(UpdateChildOnly);
2354 if (!bibfiles.empty()) {
2355 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2361 d->bibfile_cache_valid_ = true;
2362 d->bibinfo_cache_valid_ = false;
2363 d->cite_labels_valid_ = false;
2367 void Buffer::invalidateBibinfoCache() const
2369 d->bibinfo_cache_valid_ = false;
2370 d->cite_labels_valid_ = false;
2371 // also invalidate the cache for the parent buffer
2372 Buffer const * const pbuf = d->parent();
2374 pbuf->invalidateBibinfoCache();
2378 void Buffer::invalidateBibfileCache() const
2380 d->bibfile_cache_valid_ = false;
2381 d->bibinfo_cache_valid_ = false;
2382 d->cite_labels_valid_ = false;
2383 // also invalidate the cache for the parent buffer
2384 Buffer const * const pbuf = d->parent();
2386 pbuf->invalidateBibfileCache();
2390 support::FileNamePairList const & Buffer::getBibfilesCache(UpdateScope scope) const
2392 // FIXME This is probably unnecessary, given where we call this.
2393 // If this is a child document, use the master's cache instead.
2394 Buffer const * const pbuf = masterBuffer();
2395 if (pbuf != this && scope != UpdateChildOnly)
2396 return pbuf->getBibfilesCache();
2398 if (!d->bibfile_cache_valid_)
2399 this->updateBibfilesCache(scope);
2401 return d->bibfiles_cache_;
2405 BiblioInfo const & Buffer::masterBibInfo() const
2407 Buffer const * const tmp = masterBuffer();
2409 return tmp->masterBibInfo();
2414 void Buffer::checkIfBibInfoCacheIsValid() const
2416 // use the master's cache
2417 Buffer const * const tmp = masterBuffer();
2419 tmp->checkIfBibInfoCacheIsValid();
2423 // compare the cached timestamps with the actual ones.
2424 FileNamePairList const & bibfiles_cache = getBibfilesCache();
2425 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2426 FileNamePairList::const_iterator en = bibfiles_cache.end();
2427 for (; ei != en; ++ ei) {
2428 FileName const fn = ei->second;
2429 time_t lastw = fn.lastModified();
2430 time_t prevw = d->bibfile_status_[fn];
2431 if (lastw != prevw) {
2432 d->bibinfo_cache_valid_ = false;
2433 d->cite_labels_valid_ = false;
2434 d->bibfile_status_[fn] = lastw;
2440 void Buffer::reloadBibInfoCache() const
2442 // use the master's cache
2443 Buffer const * const tmp = masterBuffer();
2445 tmp->reloadBibInfoCache();
2449 checkIfBibInfoCacheIsValid();
2450 if (d->bibinfo_cache_valid_)
2453 d->bibinfo_.clear();
2455 d->bibinfo_cache_valid_ = true;
2459 void Buffer::collectBibKeys() const
2461 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2462 it->collectBibKeys(it);
2466 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2468 Buffer const * tmp = masterBuffer();
2469 BiblioInfo & masterbi = (tmp == this) ?
2470 d->bibinfo_ : tmp->d->bibinfo_;
2471 masterbi.mergeBiblioInfo(bi);
2475 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2477 Buffer const * tmp = masterBuffer();
2478 BiblioInfo & masterbi = (tmp == this) ?
2479 d->bibinfo_ : tmp->d->bibinfo_;
2484 void Buffer::makeCitationLabels() const
2486 Buffer const * const master = masterBuffer();
2487 return d->bibinfo_.makeCitationLabels(*master);
2491 bool Buffer::citeLabelsValid() const
2493 return masterBuffer()->d->cite_labels_valid_;
2497 void Buffer::removeBiblioTempFiles() const
2499 // We remove files that contain LaTeX commands specific to the
2500 // particular bibliographic style being used, in order to avoid
2501 // LaTeX errors when we switch style.
2502 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2503 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2504 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2505 aux_file.removeFile();
2506 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2507 bbl_file.removeFile();
2508 // Also for the parent buffer
2509 Buffer const * const pbuf = parent();
2511 pbuf->removeBiblioTempFiles();
2515 bool Buffer::isDepClean(string const & name) const
2517 DepClean::const_iterator const it = d->dep_clean.find(name);
2518 if (it == d->dep_clean.end())
2524 void Buffer::markDepClean(string const & name)
2526 d->dep_clean[name] = true;
2530 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2533 // FIXME? if there is an Buffer LFUN that can be dispatched even
2534 // if internal, put a switch '(cmd.action)' here.
2540 switch (cmd.action()) {
2542 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2543 flag.setOnOff(hasReadonlyFlag());
2546 // FIXME: There is need for a command-line import.
2547 //case LFUN_BUFFER_IMPORT:
2549 case LFUN_BUFFER_AUTO_SAVE:
2552 case LFUN_BUFFER_EXPORT_CUSTOM:
2553 // FIXME: Nothing to check here?
2556 case LFUN_BUFFER_EXPORT: {
2557 docstring const arg = cmd.argument();
2558 if (arg == "custom") {
2562 string format = (arg.empty() || arg == "default") ?
2563 params().getDefaultOutputFormat() : to_utf8(arg);
2564 size_t pos = format.find(' ');
2565 if (pos != string::npos)
2566 format = format.substr(0, pos);
2567 enable = params().isExportable(format, false);
2569 flag.message(bformat(
2570 _("Don't know how to export to format: %1$s"), arg));
2574 case LFUN_BUFFER_CHKTEX:
2575 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2578 case LFUN_BUILD_PROGRAM:
2579 enable = params().isExportable("program", false);
2582 case LFUN_BRANCH_ACTIVATE:
2583 case LFUN_BRANCH_DEACTIVATE:
2584 case LFUN_BRANCH_MASTER_ACTIVATE:
2585 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2586 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2587 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2588 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2589 : params().branchlist();
2590 docstring const branchName = cmd.argument();
2591 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2595 case LFUN_BRANCH_ADD:
2596 case LFUN_BRANCHES_RENAME:
2597 // if no Buffer is present, then of course we won't be called!
2600 case LFUN_BUFFER_LANGUAGE:
2601 enable = !isReadonly();
2604 case LFUN_BUFFER_VIEW_CACHE:
2605 (d->preview_file_).refresh();
2606 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2609 case LFUN_CHANGES_TRACK:
2610 flag.setEnabled(true);
2611 flag.setOnOff(params().track_changes);
2614 case LFUN_CHANGES_OUTPUT:
2615 flag.setEnabled(true);
2616 flag.setOnOff(params().output_changes);
2619 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2620 flag.setOnOff(params().compressed);
2624 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2625 flag.setOnOff(params().output_sync);
2632 flag.setEnabled(enable);
2637 void Buffer::dispatch(string const & command, DispatchResult & result)
2639 return dispatch(lyxaction.lookupFunc(command), result);
2643 // NOTE We can end up here even if we have no GUI, because we are called
2644 // by LyX::exec to handled command-line requests. So we may need to check
2645 // whether we have a GUI or not. The boolean use_gui holds this information.
2646 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2649 // FIXME? if there is an Buffer LFUN that can be dispatched even
2650 // if internal, put a switch '(cmd.action())' here.
2651 dr.dispatched(false);
2654 string const argument = to_utf8(func.argument());
2655 // We'll set this back to false if need be.
2656 bool dispatched = true;
2657 undo().beginUndoGroup();
2659 switch (func.action()) {
2660 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2661 if (lyxvc().inUse()) {
2662 string log = lyxvc().toggleReadOnly();
2667 setReadonly(!hasReadonlyFlag());
2670 case LFUN_BUFFER_EXPORT: {
2671 string const format = (argument.empty() || argument == "default") ?
2672 params().getDefaultOutputFormat() : argument;
2673 ExportStatus const status = doExport(format, false);
2674 dr.setError(status != ExportSuccess);
2675 if (status != ExportSuccess)
2676 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2677 from_utf8(format)));
2681 case LFUN_BUILD_PROGRAM: {
2682 ExportStatus const status = doExport("program", true);
2683 dr.setError(status != ExportSuccess);
2684 if (status != ExportSuccess)
2685 dr.setMessage(_("Error generating literate programming code."));
2689 case LFUN_BUFFER_CHKTEX:
2693 case LFUN_BUFFER_EXPORT_CUSTOM: {
2695 string command = split(argument, format_name, ' ');
2696 Format const * format = theFormats().getFormat(format_name);
2698 lyxerr << "Format \"" << format_name
2699 << "\" not recognized!"
2704 // The name of the file created by the conversion process
2707 // Output to filename
2708 if (format->name() == "lyx") {
2709 string const latexname = latexName(false);
2710 filename = changeExtension(latexname,
2711 format->extension());
2712 filename = addName(temppath(), filename);
2714 if (!writeFile(FileName(filename)))
2718 doExport(format_name, true, filename);
2721 // Substitute $$FName for filename
2722 if (!contains(command, "$$FName"))
2723 command = "( " + command + " ) < $$FName";
2724 command = subst(command, "$$FName", filename);
2726 // Execute the command in the background
2728 call.startscript(Systemcall::DontWait, command,
2729 filePath(), layoutPos());
2733 // FIXME: There is need for a command-line import.
2735 case LFUN_BUFFER_IMPORT:
2740 case LFUN_BUFFER_AUTO_SAVE:
2742 resetAutosaveTimers();
2745 case LFUN_BRANCH_ACTIVATE:
2746 case LFUN_BRANCH_DEACTIVATE:
2747 case LFUN_BRANCH_MASTER_ACTIVATE:
2748 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2749 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2750 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2751 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2754 docstring const branch_name = func.argument();
2755 // the case without a branch name is handled elsewhere
2756 if (branch_name.empty()) {
2760 Branch * branch = buf->params().branchlist().find(branch_name);
2762 LYXERR0("Branch " << branch_name << " does not exist.");
2764 docstring const msg =
2765 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2769 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2770 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2771 if (branch->isSelected() != activate) {
2772 buf->undo().recordUndoBufferParams(CursorData());
2773 branch->setSelected(activate);
2775 dr.screenUpdate(Update::Force);
2776 dr.forceBufferUpdate();
2781 case LFUN_BRANCH_ADD: {
2782 docstring branch_name = func.argument();
2783 if (branch_name.empty()) {
2787 BranchList & branch_list = params().branchlist();
2788 vector<docstring> const branches =
2789 getVectorFromString(branch_name, branch_list.separator());
2791 for (vector<docstring>::const_iterator it = branches.begin();
2792 it != branches.end(); ++it) {
2794 Branch * branch = branch_list.find(branch_name);
2796 LYXERR0("Branch " << branch_name << " already exists.");
2800 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2802 undo().recordUndoBufferParams(CursorData());
2803 branch_list.add(branch_name);
2804 branch = branch_list.find(branch_name);
2805 string const x11hexname = X11hexname(branch->color());
2806 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2807 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2809 dr.screenUpdate(Update::Force);
2817 case LFUN_BRANCHES_RENAME: {
2818 if (func.argument().empty())
2821 docstring const oldname = from_utf8(func.getArg(0));
2822 docstring const newname = from_utf8(func.getArg(1));
2823 InsetIterator it = inset_iterator_begin(inset());
2824 InsetIterator const end = inset_iterator_end(inset());
2825 bool success = false;
2826 for (; it != end; ++it) {
2827 if (it->lyxCode() == BRANCH_CODE) {
2828 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2829 if (ins.branch() == oldname) {
2830 undo().recordUndo(CursorData(it));
2831 ins.rename(newname);
2836 if (it->lyxCode() == INCLUDE_CODE) {
2837 // get buffer of external file
2838 InsetInclude const & ins =
2839 static_cast<InsetInclude const &>(*it);
2840 Buffer * child = ins.getChildBuffer();
2843 child->dispatch(func, dr);
2848 dr.screenUpdate(Update::Force);
2849 dr.forceBufferUpdate();
2854 case LFUN_BUFFER_VIEW_CACHE:
2855 if (!theFormats().view(*this, d->preview_file_,
2856 d->preview_format_))
2857 dr.setMessage(_("Error viewing the output file."));
2860 case LFUN_CHANGES_TRACK:
2861 if (params().save_transient_properties)
2862 undo().recordUndoBufferParams(CursorData());
2863 params().track_changes = !params().track_changes;
2864 if (!params().track_changes)
2865 dr.forceChangesUpdate();
2868 case LFUN_CHANGES_OUTPUT:
2869 if (params().save_transient_properties)
2870 undo().recordUndoBufferParams(CursorData());
2871 params().output_changes = !params().output_changes;
2872 if (params().output_changes) {
2873 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2874 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2875 LaTeXFeatures::isAvailable("xcolor");
2877 if (!dvipost && !xcolorulem) {
2878 Alert::warning(_("Changes not shown in LaTeX output"),
2879 _("Changes will not be highlighted in LaTeX output, "
2880 "because neither dvipost nor xcolor/ulem are installed.\n"
2881 "Please install these packages or redefine "
2882 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2883 } else if (!xcolorulem) {
2884 Alert::warning(_("Changes not shown in LaTeX output"),
2885 _("Changes will not be highlighted in LaTeX output "
2886 "when using pdflatex, because xcolor and ulem are not installed.\n"
2887 "Please install both packages or redefine "
2888 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2893 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2894 // turn compression on/off
2895 undo().recordUndoBufferParams(CursorData());
2896 params().compressed = !params().compressed;
2899 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2900 undo().recordUndoBufferParams(CursorData());
2901 params().output_sync = !params().output_sync;
2908 dr.dispatched(dispatched);
2909 undo().endUndoGroup();
2913 void Buffer::changeLanguage(Language const * from, Language const * to)
2915 LASSERT(from, return);
2916 LASSERT(to, return);
2918 for_each(par_iterator_begin(),
2920 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2924 bool Buffer::isMultiLingual() const
2926 ParConstIterator end = par_iterator_end();
2927 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2928 if (it->isMultiLingual(params()))
2935 std::set<Language const *> Buffer::getLanguages() const
2937 std::set<Language const *> languages;
2938 getLanguages(languages);
2943 void Buffer::getLanguages(std::set<Language const *> & languages) const
2945 ParConstIterator end = par_iterator_end();
2946 // add the buffer language, even if it's not actively used
2947 languages.insert(language());
2948 // iterate over the paragraphs
2949 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2950 it->getLanguages(languages);
2952 ListOfBuffers clist = getDescendents();
2953 ListOfBuffers::const_iterator cit = clist.begin();
2954 ListOfBuffers::const_iterator const cen = clist.end();
2955 for (; cit != cen; ++cit)
2956 (*cit)->getLanguages(languages);
2960 DocIterator Buffer::getParFromID(int const id) const
2962 Buffer * buf = const_cast<Buffer *>(this);
2964 // This means non-existent
2965 return doc_iterator_end(buf);
2967 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2968 if (it.paragraph().id() == id)
2971 return doc_iterator_end(buf);
2975 bool Buffer::hasParWithID(int const id) const
2977 return !getParFromID(id).atEnd();
2981 ParIterator Buffer::par_iterator_begin()
2983 return ParIterator(doc_iterator_begin(this));
2987 ParIterator Buffer::par_iterator_end()
2989 return ParIterator(doc_iterator_end(this));
2993 ParConstIterator Buffer::par_iterator_begin() const
2995 return ParConstIterator(doc_iterator_begin(this));
2999 ParConstIterator Buffer::par_iterator_end() const
3001 return ParConstIterator(doc_iterator_end(this));
3005 Language const * Buffer::language() const
3007 return params().language;
3011 docstring const Buffer::B_(string const & l10n) const
3013 return params().B_(l10n);
3017 bool Buffer::isClean() const
3019 return d->lyx_clean;
3023 bool Buffer::isChecksumModified() const
3025 LASSERT(d->filename.exists(), return false);
3026 return d->checksum_ != d->filename.checksum();
3030 void Buffer::saveCheckSum() const
3032 FileName const & file = d->filename;
3034 d->checksum_ = file.exists() ? file.checksum()
3035 : 0; // in the case of save to a new file.
3039 void Buffer::markClean() const
3041 if (!d->lyx_clean) {
3042 d->lyx_clean = true;
3045 // if the .lyx file has been saved, we don't need an
3047 d->bak_clean = true;
3048 d->undo_.markDirty();
3049 clearExternalModification();
3053 void Buffer::setUnnamed(bool flag)
3059 bool Buffer::isUnnamed() const
3066 /// Don't check unnamed, here: isInternal() is used in
3067 /// newBuffer(), where the unnamed flag has not been set by anyone
3068 /// yet. Also, for an internal buffer, there should be no need for
3069 /// retrieving fileName() nor for checking if it is unnamed or not.
3070 bool Buffer::isInternal() const
3072 return d->internal_buffer;
3076 void Buffer::setInternal(bool flag)
3078 d->internal_buffer = flag;
3082 void Buffer::markDirty()
3085 d->lyx_clean = false;
3088 d->bak_clean = false;
3090 DepClean::iterator it = d->dep_clean.begin();
3091 DepClean::const_iterator const end = d->dep_clean.end();
3093 for (; it != end; ++it)
3098 FileName Buffer::fileName() const
3104 string Buffer::absFileName() const
3106 return d->filename.absFileName();
3110 string Buffer::filePath() const
3112 string const abs = d->filename.onlyPath().absFileName();
3115 int last = abs.length() - 1;
3117 return abs[last] == '/' ? abs : abs + '/';
3121 DocFileName Buffer::getReferencedFileName(string const & fn) const
3124 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3125 result.set(fn, filePath());
3127 // filePath() ends with a path separator
3128 FileName const test(filePath() + fn);
3130 result.set(fn, filePath());
3132 result.set(fn, params().origin);
3139 string const Buffer::prepareFileNameForLaTeX(string const & name,
3140 string const & ext, bool nice) const
3142 string const fname = makeAbsPath(name, filePath()).absFileName();
3143 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3149 return to_utf8(makeRelPath(from_utf8(fname),
3150 from_utf8(masterBuffer()->filePath())));
3154 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3155 FileNamePairList const bibfilelist,
3156 bool const add_extension) const
3158 // If we are processing the LaTeX file in a temp directory then
3159 // copy the .bib databases to this temp directory, mangling their
3160 // names in the process. Store this mangled name in the list of
3162 // (We need to do all this because BibTeX *really*, *really*
3163 // can't handle "files with spaces" and Windows users tend to
3164 // use such filenames.)
3165 // Otherwise, store the (maybe absolute) path to the original,
3166 // unmangled database name.
3168 vector<docstring> res;
3170 // determine the export format
3171 string const tex_format = flavor2format(runparams.flavor);
3173 // check for spaces in paths
3174 bool found_space = false;
3176 FileNamePairList::const_iterator it = bibfilelist.begin();
3177 FileNamePairList::const_iterator en = bibfilelist.end();
3178 for (; it != en; ++it) {
3179 string utf8input = to_utf8(it->first);
3181 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3182 FileName const try_in_file =
3183 makeAbsPath(database + ".bib", filePath());
3184 bool const not_from_texmf = try_in_file.isReadableFile();
3186 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3188 // mangledFileName() needs the extension
3189 DocFileName const in_file = DocFileName(try_in_file);
3190 database = removeExtension(in_file.mangledFileName());
3191 FileName const out_file = makeAbsPath(database + ".bib",
3192 masterBuffer()->temppath());
3193 bool const success = in_file.copyTo(out_file);
3195 LYXERR0("Failed to copy '" << in_file
3196 << "' to '" << out_file << "'");
3198 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3199 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3200 if (!isValidLaTeXFileName(database)) {
3201 frontend::Alert::warning(_("Invalid filename"),
3202 _("The following filename will cause troubles "
3203 "when running the exported file through LaTeX: ") +
3204 from_utf8(database));
3206 if (!isValidDVIFileName(database)) {
3207 frontend::Alert::warning(_("Problematic filename for DVI"),
3208 _("The following filename can cause troubles "
3209 "when running the exported file through LaTeX "
3210 "and opening the resulting DVI: ") +
3211 from_utf8(database), true);
3219 docstring const path = from_utf8(latex_path(database));
3221 if (contains(path, ' '))
3224 if (find(res.begin(), res.end(), path) == res.end())
3225 res.push_back(path);
3228 // Check if there are spaces in the path and warn BibTeX users, if so.
3229 // (biber can cope with such paths)
3230 if (!prefixIs(runparams.bibtex_command, "biber")) {
3231 // Post this warning only once.
3232 static bool warned_about_spaces = false;
3233 if (!warned_about_spaces &&
3234 runparams.nice && found_space) {
3235 warned_about_spaces = true;
3236 Alert::warning(_("Export Warning!"),
3237 _("There are spaces in the paths to your BibTeX databases.\n"
3238 "BibTeX will be unable to find them."));
3247 string Buffer::layoutPos() const
3249 return d->layout_position;
3253 void Buffer::setLayoutPos(string const & path)
3256 d->layout_position.clear();
3260 LATTEST(FileName::isAbsolute(path));
3262 d->layout_position =
3263 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3265 if (d->layout_position.empty())
3266 d->layout_position = ".";
3270 bool Buffer::hasReadonlyFlag() const
3272 return d->read_only;
3276 bool Buffer::isReadonly() const
3278 return hasReadonlyFlag() || notifiesExternalModification();
3282 void Buffer::setParent(Buffer const * buffer)
3284 // Avoids recursive include.
3285 d->setParent(buffer == this ? 0 : buffer);
3290 Buffer const * Buffer::parent() const
3296 ListOfBuffers Buffer::allRelatives() const
3298 ListOfBuffers lb = masterBuffer()->getDescendents();
3299 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3304 Buffer const * Buffer::masterBuffer() const
3306 // FIXME Should be make sure we are not in some kind
3307 // of recursive include? A -> B -> A will crash this.
3308 Buffer const * const pbuf = d->parent();
3312 return pbuf->masterBuffer();
3316 bool Buffer::isChild(Buffer * child) const
3318 return d->children_positions.find(child) != d->children_positions.end();
3322 DocIterator Buffer::firstChildPosition(Buffer const * child)
3324 Impl::BufferPositionMap::iterator it;
3325 it = d->children_positions.find(child);
3326 if (it == d->children_positions.end())
3327 return DocIterator(this);
3332 bool Buffer::hasChildren() const
3334 return !d->children_positions.empty();
3338 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3340 // loop over children
3341 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3342 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3343 for (; it != end; ++it) {
3344 Buffer * child = const_cast<Buffer *>(it->first);
3346 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3347 if (bit != clist.end())
3349 clist.push_back(child);
3351 // there might be grandchildren
3352 child->collectChildren(clist, true);
3357 ListOfBuffers Buffer::getChildren() const
3360 collectChildren(v, false);
3361 // Make sure we have not included ourselves.
3362 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3363 if (bit != v.end()) {
3364 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3371 ListOfBuffers Buffer::getDescendents() const
3374 collectChildren(v, true);
3375 // Make sure we have not included ourselves.
3376 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3377 if (bit != v.end()) {
3378 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3385 template<typename M>
3386 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3391 typename M::const_iterator it = m.lower_bound(x);
3392 if (it == m.begin())
3400 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3401 DocIterator const & pos) const
3403 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3405 // if paragraphs have no macro context set, pos will be empty
3409 // we haven't found anything yet
3410 DocIterator bestPos = owner_->par_iterator_begin();
3411 MacroData const * bestData = 0;
3413 // find macro definitions for name
3414 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3415 if (nameIt != macros.end()) {
3416 // find last definition in front of pos or at pos itself
3417 PositionScopeMacroMap::const_iterator it
3418 = greatest_below(nameIt->second, pos);
3419 if (it != nameIt->second.end()) {
3421 // scope ends behind pos?
3422 if (pos < it->second.scope) {
3423 // Looks good, remember this. If there
3424 // is no external macro behind this,
3425 // we found the right one already.
3426 bestPos = it->first;
3427 bestData = &it->second.macro;
3431 // try previous macro if there is one
3432 if (it == nameIt->second.begin())
3439 // find macros in included files
3440 PositionScopeBufferMap::const_iterator it
3441 = greatest_below(position_to_children, pos);
3442 if (it == position_to_children.end())
3443 // no children before
3447 // do we know something better (i.e. later) already?
3448 if (it->first < bestPos )
3451 // scope ends behind pos?
3452 if (pos < it->second.scope
3453 && (cloned_buffer_ ||
3454 theBufferList().isLoaded(it->second.buffer))) {
3455 // look for macro in external file
3457 MacroData const * data
3458 = it->second.buffer->getMacro(name, false);
3461 bestPos = it->first;
3467 // try previous file if there is one
3468 if (it == position_to_children.begin())
3473 // return the best macro we have found
3478 MacroData const * Buffer::getMacro(docstring const & name,
3479 DocIterator const & pos, bool global) const
3484 // query buffer macros
3485 MacroData const * data = d->getBufferMacro(name, pos);
3489 // If there is a master buffer, query that
3490 Buffer const * const pbuf = d->parent();
3492 d->macro_lock = true;
3493 MacroData const * macro = pbuf->getMacro(
3494 name, *this, false);
3495 d->macro_lock = false;
3501 data = MacroTable::globalMacros().get(name);
3510 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3512 // set scope end behind the last paragraph
3513 DocIterator scope = par_iterator_begin();
3514 scope.pit() = scope.lastpit() + 1;
3516 return getMacro(name, scope, global);
3520 MacroData const * Buffer::getMacro(docstring const & name,
3521 Buffer const & child, bool global) const
3523 // look where the child buffer is included first
3524 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3525 if (it == d->children_positions.end())
3528 // check for macros at the inclusion position
3529 return getMacro(name, it->second, global);
3533 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3535 pit_type const lastpit = it.lastpit();
3537 // look for macros in each paragraph
3538 while (it.pit() <= lastpit) {
3539 Paragraph & par = it.paragraph();
3541 // iterate over the insets of the current paragraph
3542 InsetList const & insets = par.insetList();
3543 InsetList::const_iterator iit = insets.begin();
3544 InsetList::const_iterator end = insets.end();
3545 for (; iit != end; ++iit) {
3546 it.pos() = iit->pos;
3548 // is it a nested text inset?
3549 if (iit->inset->asInsetText()) {
3550 // Inset needs its own scope?
3551 InsetText const * itext = iit->inset->asInsetText();
3552 bool newScope = itext->isMacroScope();
3554 // scope which ends just behind the inset
3555 DocIterator insetScope = it;
3558 // collect macros in inset
3559 it.push_back(CursorSlice(*iit->inset));
3560 updateMacros(it, newScope ? insetScope : scope);
3565 if (iit->inset->asInsetTabular()) {
3566 CursorSlice slice(*iit->inset);
3567 size_t const numcells = slice.nargs();
3568 for (; slice.idx() < numcells; slice.forwardIdx()) {
3569 it.push_back(slice);
3570 updateMacros(it, scope);
3576 // is it an external file?
3577 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3578 // get buffer of external file
3579 InsetInclude const & inset =
3580 static_cast<InsetInclude const &>(*iit->inset);
3582 Buffer * child = inset.getChildBuffer();
3587 // register its position, but only when it is
3588 // included first in the buffer
3589 if (children_positions.find(child) ==
3590 children_positions.end())
3591 children_positions[child] = it;
3593 // register child with its scope
3594 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3598 InsetMath * im = iit->inset->asInsetMath();
3599 if (doing_export && im) {
3600 InsetMathHull * hull = im->asHullInset();
3602 hull->recordLocation(it);
3605 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3609 MathMacroTemplate & macroTemplate =
3610 *iit->inset->asInsetMath()->asMacroTemplate();
3611 MacroContext mc(owner_, it);
3612 macroTemplate.updateToContext(mc);
3615 bool valid = macroTemplate.validMacro();
3616 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3617 // then the BufferView's cursor will be invalid in
3618 // some cases which leads to crashes.
3623 // FIXME (Abdel), I don't understand why we pass 'it' here
3624 // instead of 'macroTemplate' defined above... is this correct?
3625 macros[macroTemplate.name()][it] =
3626 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3636 void Buffer::updateMacros() const
3641 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3643 // start with empty table
3645 d->children_positions.clear();
3646 d->position_to_children.clear();
3648 // Iterate over buffer, starting with first paragraph
3649 // The scope must be bigger than any lookup DocIterator
3650 // later. For the global lookup, lastpit+1 is used, hence
3651 // we use lastpit+2 here.
3652 DocIterator it = par_iterator_begin();
3653 DocIterator outerScope = it;
3654 outerScope.pit() = outerScope.lastpit() + 2;
3655 d->updateMacros(it, outerScope);
3659 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3661 InsetIterator it = inset_iterator_begin(inset());
3662 InsetIterator const end = inset_iterator_end(inset());
3663 for (; it != end; ++it) {
3664 if (it->lyxCode() == BRANCH_CODE) {
3665 InsetBranch & br = static_cast<InsetBranch &>(*it);
3666 docstring const name = br.branch();
3667 if (!from_master && !params().branchlist().find(name))
3668 result.push_back(name);
3669 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3670 result.push_back(name);
3673 if (it->lyxCode() == INCLUDE_CODE) {
3674 // get buffer of external file
3675 InsetInclude const & ins =
3676 static_cast<InsetInclude const &>(*it);
3677 Buffer * child = ins.getChildBuffer();
3680 child->getUsedBranches(result, true);
3683 // remove duplicates
3688 void Buffer::updateMacroInstances(UpdateType utype) const
3690 LYXERR(Debug::MACROS, "updateMacroInstances for "
3691 << d->filename.onlyFileName());
3692 DocIterator it = doc_iterator_begin(this);
3694 DocIterator const end = doc_iterator_end(this);
3695 for (; it != end; it.forwardInset()) {
3696 // look for MathData cells in InsetMathNest insets
3697 InsetMath * minset = it.nextInset()->asInsetMath();
3701 // update macro in all cells of the InsetMathNest
3702 DocIterator::idx_type n = minset->nargs();
3703 MacroContext mc = MacroContext(this, it);
3704 for (DocIterator::idx_type i = 0; i < n; ++i) {
3705 MathData & data = minset->cell(i);
3706 data.updateMacros(0, mc, utype, 0);
3712 void Buffer::listMacroNames(MacroNameSet & macros) const
3717 d->macro_lock = true;
3719 // loop over macro names
3720 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3721 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3722 for (; nameIt != nameEnd; ++nameIt)
3723 macros.insert(nameIt->first);
3725 // loop over children
3726 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3727 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3728 for (; it != end; ++it)
3729 it->first->listMacroNames(macros);
3732 Buffer const * const pbuf = d->parent();
3734 pbuf->listMacroNames(macros);
3736 d->macro_lock = false;
3740 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3742 Buffer const * const pbuf = d->parent();
3747 pbuf->listMacroNames(names);
3750 MacroNameSet::iterator it = names.begin();
3751 MacroNameSet::iterator end = names.end();
3752 for (; it != end; ++it) {
3754 MacroData const * data =
3755 pbuf->getMacro(*it, *this, false);
3757 macros.insert(data);
3759 // we cannot access the original MathMacroTemplate anymore
3760 // here to calls validate method. So we do its work here manually.
3761 // FIXME: somehow make the template accessible here.
3762 if (data->optionals() > 0)
3763 features.require("xargs");
3769 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3772 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3774 RefCache::iterator it = d->ref_cache_.find(label);
3775 if (it != d->ref_cache_.end())
3776 return it->second.second;
3778 static InsetLabel const * dummy_il = 0;
3779 static References const dummy_refs = References();
3780 it = d->ref_cache_.insert(
3781 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3782 return it->second.second;
3786 Buffer::References const & Buffer::references(docstring const & label) const
3788 return const_cast<Buffer *>(this)->getReferenceCache(label);
3792 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3794 References & refs = getReferenceCache(label);
3795 refs.push_back(make_pair(inset, it));
3799 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3801 masterBuffer()->d->ref_cache_[label].first = il;
3805 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3807 return masterBuffer()->d->ref_cache_[label].first;
3811 void Buffer::clearReferenceCache() const
3814 d->ref_cache_.clear();
3818 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3820 //FIXME: This does not work for child documents yet.
3821 reloadBibInfoCache();
3823 // Check if the label 'from' appears more than once
3824 BiblioInfo const & keys = masterBibInfo();
3825 BiblioInfo::const_iterator bit = keys.begin();
3826 BiblioInfo::const_iterator bend = keys.end();
3827 vector<docstring> labels;
3829 for (; bit != bend; ++bit)
3831 labels.push_back(bit->first);
3833 if (count(labels.begin(), labels.end(), from) > 1)
3836 string const paramName = "key";
3837 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3838 if (it->lyxCode() != CITE_CODE)
3840 InsetCommand * inset = it->asInsetCommand();
3841 docstring const oldValue = inset->getParam(paramName);
3842 if (oldValue == from)
3843 inset->setParam(paramName, to);
3847 // returns NULL if id-to-row conversion is unsupported
3848 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3849 pit_type par_begin, pit_type par_end,
3850 OutputWhat output, bool master) const
3852 unique_ptr<TexRow> texrow;
3853 OutputParams runparams(¶ms().encoding());
3854 runparams.nice = true;
3855 runparams.flavor = params().getOutputFlavor(format);
3856 runparams.linelen = lyxrc.plaintext_linelen;
3857 // No side effect of file copying and image conversion
3858 runparams.dryrun = true;
3860 if (output == CurrentParagraph) {
3861 runparams.par_begin = par_begin;
3862 runparams.par_end = par_end;
3863 if (par_begin + 1 == par_end) {
3865 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3869 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3870 convert<docstring>(par_begin),
3871 convert<docstring>(par_end - 1))
3874 // output paragraphs
3875 if (runparams.flavor == OutputParams::LYX) {
3876 Paragraph const & par = text().paragraphs()[par_begin];
3878 depth_type dt = par.getDepth();
3879 par.write(ods, params(), dt);
3880 os << from_utf8(ods.str());
3881 } else if (runparams.flavor == OutputParams::HTML) {
3883 setMathFlavor(runparams);
3884 xhtmlParagraphs(text(), *this, xs, runparams);
3885 } else if (runparams.flavor == OutputParams::TEXT) {
3887 // FIXME Handles only one paragraph, unlike the others.
3888 // Probably should have some routine with a signature like them.
3889 writePlaintextParagraph(*this,
3890 text().paragraphs()[par_begin], os, runparams, dummy);
3891 } else if (params().isDocBook()) {
3892 docbookParagraphs(text(), *this, os, runparams);
3894 // If we are previewing a paragraph, even if this is the
3895 // child of some other buffer, let's cut the link here,
3896 // so that no concurring settings from the master
3897 // (e.g. branch state) interfere (see #8101).
3899 d->ignore_parent = true;
3900 // We need to validate the Buffer params' features here
3901 // in order to know if we should output polyglossia
3902 // macros (instead of babel macros)
3903 LaTeXFeatures features(*this, params(), runparams);
3905 runparams.use_polyglossia = features.usePolyglossia();
3906 // latex or literate
3909 ots.texrow().newlines(2);
3911 latexParagraphs(*this, text(), ots, runparams);
3912 texrow = ots.releaseTexRow();
3914 // Restore the parenthood
3916 d->ignore_parent = false;
3920 if (output == FullSource)
3921 os << _("Preview source code");
3922 else if (output == OnlyPreamble)
3923 os << _("Preview preamble");
3924 else if (output == OnlyBody)
3925 os << _("Preview body");
3927 if (runparams.flavor == OutputParams::LYX) {
3929 if (output == FullSource)
3931 else if (output == OnlyPreamble)
3932 params().writeFile(ods, this);
3933 else if (output == OnlyBody)
3935 os << from_utf8(ods.str());
3936 } else if (runparams.flavor == OutputParams::HTML) {
3937 writeLyXHTMLSource(os, runparams, output);
3938 } else if (runparams.flavor == OutputParams::TEXT) {
3939 if (output == OnlyPreamble) {
3940 os << "% "<< _("Plain text does not have a preamble.");
3942 writePlaintextFile(*this, os, runparams);
3943 } else if (params().isDocBook()) {
3944 writeDocBookSource(os, absFileName(), runparams, output);
3946 // latex or literate
3949 ots.texrow().newlines(2);
3951 runparams.is_child = true;
3953 writeLaTeXSource(ots, string(), runparams, output);
3954 texrow = ots.releaseTexRow();
3961 ErrorList & Buffer::errorList(string const & type) const
3963 return d->errorLists[type];
3967 void Buffer::updateTocItem(std::string const & type,
3968 DocIterator const & dit) const
3971 d->gui_->updateTocItem(type, dit);
3975 void Buffer::structureChanged() const
3978 d->gui_->structureChanged();
3982 void Buffer::errors(string const & err, bool from_master) const
3985 d->gui_->errors(err, from_master);
3989 void Buffer::message(docstring const & msg) const
3992 d->gui_->message(msg);
3996 void Buffer::setBusy(bool on) const
3999 d->gui_->setBusy(on);
4003 void Buffer::updateTitles() const
4006 d->wa_->updateTitles();
4010 void Buffer::resetAutosaveTimers() const
4013 d->gui_->resetAutosaveTimers();
4017 bool Buffer::hasGuiDelegate() const
4023 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4032 class AutoSaveBuffer : public ForkedProcess {
4035 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4036 : buffer_(buffer), fname_(fname) {}
4038 virtual shared_ptr<ForkedProcess> clone() const
4040 return make_shared<AutoSaveBuffer>(*this);
4045 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4046 from_utf8(fname_.absFileName())));
4047 return run(DontWait);
4051 virtual int generateChild();
4053 Buffer const & buffer_;
4058 int AutoSaveBuffer::generateChild()
4060 #if defined(__APPLE__)
4061 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4062 * We should use something else like threads.
4064 * Since I do not know how to determine at run time what is the OS X
4065 * version, I just disable forking altogether for now (JMarc)
4067 pid_t const pid = -1;
4069 // tmp_ret will be located (usually) in /tmp
4070 // will that be a problem?
4071 // Note that this calls ForkedCalls::fork(), so it's
4072 // ok cross-platform.
4073 pid_t const pid = fork();
4074 // If you want to debug the autosave
4075 // you should set pid to -1, and comment out the fork.
4076 if (pid != 0 && pid != -1)
4080 // pid = -1 signifies that lyx was unable
4081 // to fork. But we will do the save
4083 bool failed = false;
4084 TempFile tempfile("lyxautoXXXXXX.lyx");
4085 tempfile.setAutoRemove(false);
4086 FileName const tmp_ret = tempfile.name();
4087 if (!tmp_ret.empty()) {
4088 if (!buffer_.writeFile(tmp_ret))
4090 else if (!tmp_ret.moveTo(fname_))
4096 // failed to write/rename tmp_ret so try writing direct
4097 if (!buffer_.writeFile(fname_)) {
4098 // It is dangerous to do this in the child,
4099 // but safe in the parent, so...
4100 if (pid == -1) // emit message signal.
4101 buffer_.message(_("Autosave failed!"));
4105 if (pid == 0) // we are the child so...
4114 FileName Buffer::getEmergencyFileName() const
4116 return FileName(d->filename.absFileName() + ".emergency");
4120 FileName Buffer::getAutosaveFileName() const
4122 // if the document is unnamed try to save in the backup dir, else
4123 // in the default document path, and as a last try in the filePath,
4124 // which will most often be the temporary directory
4127 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4128 : lyxrc.backupdir_path;
4129 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4132 string const fname = "#" + d->filename.onlyFileName() + "#";
4134 return makeAbsPath(fname, fpath);
4138 void Buffer::removeAutosaveFile() const
4140 FileName const f = getAutosaveFileName();
4146 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4148 FileName const newauto = getAutosaveFileName();
4150 if (newauto != oldauto && oldauto.exists())
4151 if (!oldauto.moveTo(newauto))
4152 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4156 bool Buffer::autoSave() const
4158 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4159 if (buf->d->bak_clean || hasReadonlyFlag())
4162 message(_("Autosaving current document..."));
4163 buf->d->bak_clean = true;
4165 FileName const fname = getAutosaveFileName();
4166 LASSERT(d->cloned_buffer_, return false);
4168 // If this buffer is cloned, we assume that
4169 // we are running in a separate thread already.
4170 TempFile tempfile("lyxautoXXXXXX.lyx");
4171 tempfile.setAutoRemove(false);
4172 FileName const tmp_ret = tempfile.name();
4173 if (!tmp_ret.empty()) {
4175 // assume successful write of tmp_ret
4176 if (tmp_ret.moveTo(fname))
4179 // failed to write/rename tmp_ret so try writing direct
4180 return writeFile(fname);
4184 void Buffer::setExportStatus(bool e) const
4186 d->doing_export = e;
4187 ListOfBuffers clist = getDescendents();
4188 ListOfBuffers::const_iterator cit = clist.begin();
4189 ListOfBuffers::const_iterator const cen = clist.end();
4190 for (; cit != cen; ++cit)
4191 (*cit)->d->doing_export = e;
4195 bool Buffer::isExporting() const
4197 return d->doing_export;
4201 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4205 return doExport(target, put_in_tempdir, result_file);
4208 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4209 string & result_file) const
4211 bool const update_unincluded =
4212 params().maintain_unincluded_children
4213 && !params().getIncludedChildren().empty();
4215 // (1) export with all included children (omit \includeonly)
4216 if (update_unincluded) {
4217 ExportStatus const status =
4218 doExport(target, put_in_tempdir, true, result_file);
4219 if (status != ExportSuccess)
4222 // (2) export with included children only
4223 return doExport(target, put_in_tempdir, false, result_file);
4227 void Buffer::setMathFlavor(OutputParams & op) const
4229 switch (params().html_math_output) {
4230 case BufferParams::MathML:
4231 op.math_flavor = OutputParams::MathAsMathML;
4233 case BufferParams::HTML:
4234 op.math_flavor = OutputParams::MathAsHTML;
4236 case BufferParams::Images:
4237 op.math_flavor = OutputParams::MathAsImages;
4239 case BufferParams::LaTeX:
4240 op.math_flavor = OutputParams::MathAsLaTeX;
4246 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4247 bool includeall, string & result_file) const
4249 LYXERR(Debug::FILES, "target=" << target);
4250 OutputParams runparams(¶ms().encoding());
4251 string format = target;
4252 string dest_filename;
4253 size_t pos = target.find(' ');
4254 if (pos != string::npos) {
4255 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4256 format = target.substr(0, pos);
4257 if (format == "default")
4258 format = params().getDefaultOutputFormat();
4259 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4260 FileName(dest_filename).onlyPath().createPath();
4261 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4263 MarkAsExporting exporting(this);
4264 string backend_format;
4265 runparams.flavor = OutputParams::LATEX;
4266 runparams.linelen = lyxrc.plaintext_linelen;
4267 runparams.includeall = includeall;
4268 vector<string> backs = params().backends();
4269 Converters converters = theConverters();
4270 bool need_nice_file = false;
4271 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4272 // Get shortest path to format
4273 converters.buildGraph();
4274 Graph::EdgePath path;
4275 for (vector<string>::const_iterator it = backs.begin();
4276 it != backs.end(); ++it) {
4277 Graph::EdgePath p = converters.getPath(*it, format);
4278 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4279 backend_format = *it;
4284 if (!put_in_tempdir) {
4285 // Only show this alert if this is an export to a non-temporary
4286 // file (not for previewing).
4287 Alert::error(_("Couldn't export file"), bformat(
4288 _("No information for exporting the format %1$s."),
4289 theFormats().prettyName(format)));
4291 return ExportNoPathToFormat;
4293 runparams.flavor = converters.getFlavor(path, this);
4294 Graph::EdgePath::const_iterator it = path.begin();
4295 Graph::EdgePath::const_iterator en = path.end();
4296 for (; it != en; ++it)
4297 if (theConverters().get(*it).nice()) {
4298 need_nice_file = true;
4303 backend_format = format;
4304 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4305 // FIXME: Don't hardcode format names here, but use a flag
4306 if (backend_format == "pdflatex")
4307 runparams.flavor = OutputParams::PDFLATEX;
4308 else if (backend_format == "luatex")
4309 runparams.flavor = OutputParams::LUATEX;
4310 else if (backend_format == "dviluatex")
4311 runparams.flavor = OutputParams::DVILUATEX;
4312 else if (backend_format == "xetex")
4313 runparams.flavor = OutputParams::XETEX;
4316 string filename = latexName(false);
4317 filename = addName(temppath(), filename);
4318 filename = changeExtension(filename,
4319 theFormats().extension(backend_format));
4320 LYXERR(Debug::FILES, "filename=" << filename);
4322 // Plain text backend
4323 if (backend_format == "text") {
4324 runparams.flavor = OutputParams::TEXT;
4325 writePlaintextFile(*this, FileName(filename), runparams);
4328 else if (backend_format == "xhtml") {
4329 runparams.flavor = OutputParams::HTML;
4330 setMathFlavor(runparams);
4331 makeLyXHTMLFile(FileName(filename), runparams);
4332 } else if (backend_format == "lyx")
4333 writeFile(FileName(filename));
4335 else if (params().isDocBook()) {
4336 runparams.nice = !put_in_tempdir;
4337 makeDocBookFile(FileName(filename), runparams);
4340 else if (backend_format == format || need_nice_file) {
4341 runparams.nice = true;
4342 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4343 if (d->cloned_buffer_)
4344 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4347 } else if (!lyxrc.tex_allows_spaces
4348 && contains(filePath(), ' ')) {
4349 Alert::error(_("File name error"),
4350 _("The directory path to the document cannot contain spaces."));
4351 return ExportTexPathHasSpaces;
4353 runparams.nice = false;
4354 bool const success = makeLaTeXFile(
4355 FileName(filename), filePath(), runparams);
4356 if (d->cloned_buffer_)
4357 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4362 string const error_type = (format == "program")
4363 ? "Build" : params().bufferFormat();
4364 ErrorList & error_list = d->errorLists[error_type];
4365 string const ext = theFormats().extension(format);
4366 FileName const tmp_result_file(changeExtension(filename, ext));
4367 bool const success = converters.convert(this, FileName(filename),
4368 tmp_result_file, FileName(absFileName()), backend_format, format,
4371 // Emit the signal to show the error list or copy it back to the
4372 // cloned Buffer so that it can be emitted afterwards.
4373 if (format != backend_format) {
4374 if (runparams.silent)
4376 else if (d->cloned_buffer_)
4377 d->cloned_buffer_->d->errorLists[error_type] =
4378 d->errorLists[error_type];
4381 // also to the children, in case of master-buffer-view
4382 ListOfBuffers clist = getDescendents();
4383 ListOfBuffers::const_iterator cit = clist.begin();
4384 ListOfBuffers::const_iterator const cen = clist.end();
4385 for (; cit != cen; ++cit) {
4386 if (runparams.silent)
4387 (*cit)->d->errorLists[error_type].clear();
4388 else if (d->cloned_buffer_) {
4389 // Enable reverse search by copying back the
4390 // texrow object to the cloned buffer.
4391 // FIXME: this is not thread safe.
4392 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4393 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4394 (*cit)->d->errorLists[error_type];
4396 (*cit)->errors(error_type, true);
4400 if (d->cloned_buffer_) {
4401 // Enable reverse dvi or pdf to work by copying back the texrow
4402 // object to the cloned buffer.
4403 // FIXME: There is a possibility of concurrent access to texrow
4404 // here from the main GUI thread that should be securized.
4405 d->cloned_buffer_->d->texrow = d->texrow;
4406 string const error_type = params().bufferFormat();
4407 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4411 if (put_in_tempdir) {
4412 result_file = tmp_result_file.absFileName();
4413 return success ? ExportSuccess : ExportConverterError;
4416 if (dest_filename.empty())
4417 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4419 result_file = dest_filename;
4420 // We need to copy referenced files (e. g. included graphics
4421 // if format == "dvi") to the result dir.
4422 vector<ExportedFile> const files =
4423 runparams.exportdata->externalFiles(format);
4424 string const dest = runparams.export_folder.empty() ?
4425 onlyPath(result_file) : runparams.export_folder;
4426 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4427 : force_overwrite == ALL_FILES;
4428 CopyStatus status = use_force ? FORCE : SUCCESS;
4430 vector<ExportedFile>::const_iterator it = files.begin();
4431 vector<ExportedFile>::const_iterator const en = files.end();
4432 for (; it != en && status != CANCEL; ++it) {
4433 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4434 string fixedName = it->exportName;
4435 if (!runparams.export_folder.empty()) {
4436 // Relative pathnames starting with ../ will be sanitized
4437 // if exporting to a different folder
4438 while (fixedName.substr(0, 3) == "../")
4439 fixedName = fixedName.substr(3, fixedName.length() - 3);
4441 FileName fixedFileName = makeAbsPath(fixedName, dest);
4442 fixedFileName.onlyPath().createPath();
4443 status = copyFile(fmt, it->sourceName,
4445 it->exportName, status == FORCE,
4446 runparams.export_folder.empty());
4449 if (status == CANCEL) {
4450 message(_("Document export cancelled."));
4451 return ExportCancel;
4454 if (tmp_result_file.exists()) {
4455 // Finally copy the main file
4456 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4457 : force_overwrite != NO_FILES;
4458 if (status == SUCCESS && use_force)
4460 status = copyFile(format, tmp_result_file,
4461 FileName(result_file), result_file,
4463 if (status == CANCEL) {
4464 message(_("Document export cancelled."));
4465 return ExportCancel;
4467 message(bformat(_("Document exported as %1$s "
4469 theFormats().prettyName(format),
4470 makeDisplayPath(result_file)));
4473 // This must be a dummy converter like fax (bug 1888)
4474 message(bformat(_("Document exported as %1$s"),
4475 theFormats().prettyName(format)));
4478 return success ? ExportSuccess : ExportConverterError;
4482 Buffer::ExportStatus Buffer::preview(string const & format) const
4484 bool const update_unincluded =
4485 params().maintain_unincluded_children
4486 && !params().getIncludedChildren().empty();
4487 return preview(format, update_unincluded);
4491 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4493 MarkAsExporting exporting(this);
4495 // (1) export with all included children (omit \includeonly)
4497 ExportStatus const status = doExport(format, true, true, result_file);
4498 if (status != ExportSuccess)
4501 // (2) export with included children only
4502 ExportStatus const status = doExport(format, true, false, result_file);
4503 FileName const previewFile(result_file);
4505 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4506 theimpl->preview_file_ = previewFile;
4507 theimpl->preview_format_ = format;
4508 theimpl->preview_error_ = (status != ExportSuccess);
4510 if (status != ExportSuccess)
4513 if (previewFile.exists())
4514 return theFormats().view(*this, previewFile, format) ?
4515 PreviewSuccess : PreviewError;
4517 // Successful export but no output file?
4518 // Probably a bug in error detection.
4519 LATTEST(status != ExportSuccess);
4524 Buffer::ReadStatus Buffer::extractFromVC()
4526 bool const found = LyXVC::file_not_found_hook(d->filename);
4528 return ReadFileNotFound;
4529 if (!d->filename.isReadableFile())
4535 Buffer::ReadStatus Buffer::loadEmergency()
4537 FileName const emergencyFile = getEmergencyFileName();
4538 if (!emergencyFile.exists()
4539 || emergencyFile.lastModified() <= d->filename.lastModified())
4540 return ReadFileNotFound;
4542 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4543 docstring const text = bformat(_("An emergency save of the document "
4544 "%1$s exists.\n\nRecover emergency save?"), file);
4546 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4547 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4553 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4554 bool const success = (ret_llf == ReadSuccess);
4556 if (hasReadonlyFlag()) {
4557 Alert::warning(_("File is read-only"),
4558 bformat(_("An emergency file is successfully loaded, "
4559 "but the original file %1$s is marked read-only. "
4560 "Please make sure to save the document as a different "
4561 "file."), from_utf8(d->filename.absFileName())));
4564 lyxvc().file_found_hook(d->filename);
4565 str = _("Document was successfully recovered.");
4567 str = _("Document was NOT successfully recovered.");
4568 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4569 makeDisplayPath(emergencyFile.absFileName()));
4571 int const del_emerg =
4572 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4573 _("&Remove"), _("&Keep"));
4574 if (del_emerg == 0) {
4575 emergencyFile.removeFile();
4577 Alert::warning(_("Emergency file deleted"),
4578 _("Do not forget to save your file now!"), true);
4580 return success ? ReadSuccess : ReadEmergencyFailure;
4583 int const del_emerg =
4584 Alert::prompt(_("Delete emergency file?"),
4585 _("Remove emergency file now?"), 1, 1,
4586 _("&Remove"), _("&Keep"));
4588 emergencyFile.removeFile();
4589 return ReadOriginal;
4599 Buffer::ReadStatus Buffer::loadAutosave()
4601 // Now check if autosave file is newer.
4602 FileName const autosaveFile = getAutosaveFileName();
4603 if (!autosaveFile.exists()
4604 || autosaveFile.lastModified() <= d->filename.lastModified())
4605 return ReadFileNotFound;
4607 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4608 docstring const text = bformat(_("The backup of the document %1$s "
4609 "is newer.\n\nLoad the backup instead?"), file);
4610 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4611 _("&Load backup"), _("Load &original"), _("&Cancel"));
4616 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4617 // the file is not saved if we load the autosave file.
4618 if (ret_llf == ReadSuccess) {
4619 if (hasReadonlyFlag()) {
4620 Alert::warning(_("File is read-only"),
4621 bformat(_("A backup file is successfully loaded, "
4622 "but the original file %1$s is marked read-only. "
4623 "Please make sure to save the document as a "
4625 from_utf8(d->filename.absFileName())));
4628 lyxvc().file_found_hook(d->filename);
4631 return ReadAutosaveFailure;
4634 // Here we delete the autosave
4635 autosaveFile.removeFile();
4636 return ReadOriginal;
4644 Buffer::ReadStatus Buffer::loadLyXFile()
4646 if (!d->filename.isReadableFile()) {
4647 ReadStatus const ret_rvc = extractFromVC();
4648 if (ret_rvc != ReadSuccess)
4652 ReadStatus const ret_re = loadEmergency();
4653 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4656 ReadStatus const ret_ra = loadAutosave();
4657 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4660 return loadThisLyXFile(d->filename);
4664 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4666 return readFile(fn);
4670 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4672 for (auto const & err : terr) {
4673 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4674 int errorRow = err.error_in_line;
4675 Buffer const * buf = 0;
4677 if (err.child_name.empty())
4678 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4680 // The error occurred in a child
4681 for (Buffer const * child : getDescendents()) {
4682 string const child_name =
4683 DocFileName(changeExtension(child->absFileName(), "tex")).
4685 if (err.child_name != child_name)
4687 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4688 if (!TexRow::isNone(start)) {
4689 buf = d->cloned_buffer_
4690 ? child->d->cloned_buffer_->d->owner_
4697 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4703 void Buffer::setBuffersForInsets() const
4705 inset().setBuffer(const_cast<Buffer &>(*this));
4709 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4711 LBUFERR(!text().paragraphs().empty());
4713 // Use the master text class also for child documents
4714 Buffer const * const master = masterBuffer();
4715 DocumentClass const & textclass = master->params().documentClass();
4717 // do this only if we are the top-level Buffer
4718 if (master == this) {
4719 textclass.counters().reset(from_ascii("bibitem"));
4720 reloadBibInfoCache();
4723 // keep the buffers to be children in this set. If the call from the
4724 // master comes back we can see which of them were actually seen (i.e.
4725 // via an InsetInclude). The remaining ones in the set need still be updated.
4726 static std::set<Buffer const *> bufToUpdate;
4727 if (scope == UpdateMaster) {
4728 // If this is a child document start with the master
4729 if (master != this) {
4730 bufToUpdate.insert(this);
4731 master->updateBuffer(UpdateMaster, utype);
4732 // If the master buffer has no gui associated with it, then the TocModel is
4733 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4734 // (bug 5699). The same happens if the master buffer is open in a different
4735 // window. This test catches both possibilities.
4736 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4737 // There remains a problem here: If there is another child open in yet a third
4738 // window, that TOC is not updated. So some more general solution is needed at
4740 if (master->d->gui_ != d->gui_)
4743 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4744 if (bufToUpdate.find(this) == bufToUpdate.end())
4748 // start over the counters in the master
4749 textclass.counters().reset();
4752 // update will be done below for this buffer
4753 bufToUpdate.erase(this);
4755 // update all caches
4756 clearReferenceCache();
4758 setChangesPresent(false);
4760 Buffer & cbuf = const_cast<Buffer &>(*this);
4763 ParIterator parit = cbuf.par_iterator_begin();
4764 updateBuffer(parit, utype);
4767 /// Update the tocBackend for any buffer. The outliner uses the master's,
4768 /// and the navigation menu uses the child's.
4769 cbuf.tocBackend().update(true, utype);
4774 d->bibinfo_cache_valid_ = true;
4775 d->cite_labels_valid_ = true;
4776 if (scope == UpdateMaster)
4777 cbuf.structureChanged();
4781 static depth_type getDepth(DocIterator const & it)
4783 depth_type depth = 0;
4784 for (size_t i = 0 ; i < it.depth() ; ++i)
4785 if (!it[i].inset().inMathed())
4786 depth += it[i].paragraph().getDepth() + 1;
4787 // remove 1 since the outer inset does not count
4788 // we should have at least one non-math inset, so
4789 // depth should nevery be 0. but maybe it is worth
4790 // marking this, just in case.
4792 // coverity[INTEGER_OVERFLOW]
4796 static depth_type getItemDepth(ParIterator const & it)
4798 Paragraph const & par = *it;
4799 LabelType const labeltype = par.layout().labeltype;
4801 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4804 // this will hold the lowest depth encountered up to now.
4805 depth_type min_depth = getDepth(it);
4806 ParIterator prev_it = it;
4809 --prev_it.top().pit();
4811 // start of nested inset: go to outer par
4813 if (prev_it.empty()) {
4814 // start of document: nothing to do
4819 // We search for the first paragraph with same label
4820 // that is not more deeply nested.
4821 Paragraph & prev_par = *prev_it;
4822 depth_type const prev_depth = getDepth(prev_it);
4823 if (labeltype == prev_par.layout().labeltype) {
4824 if (prev_depth < min_depth)
4825 return prev_par.itemdepth + 1;
4826 if (prev_depth == min_depth)
4827 return prev_par.itemdepth;
4829 min_depth = min(min_depth, prev_depth);
4830 // small optimization: if we are at depth 0, we won't
4831 // find anything else
4832 if (prev_depth == 0)
4838 static bool needEnumCounterReset(ParIterator const & it)
4840 Paragraph const & par = *it;
4841 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4842 depth_type const cur_depth = par.getDepth();
4843 ParIterator prev_it = it;
4844 while (prev_it.pit()) {
4845 --prev_it.top().pit();
4846 Paragraph const & prev_par = *prev_it;
4847 if (prev_par.getDepth() <= cur_depth)
4848 return prev_par.layout().name() != par.layout().name();
4850 // start of nested inset: reset
4855 // set the label of a paragraph. This includes the counters.
4856 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4858 BufferParams const & bp = owner_->masterBuffer()->params();
4859 DocumentClass const & textclass = bp.documentClass();
4860 Paragraph & par = it.paragraph();
4861 Layout const & layout = par.layout();
4862 Counters & counters = textclass.counters();
4864 if (par.params().startOfAppendix()) {
4865 // We want to reset the counter corresponding to toplevel sectioning
4866 Layout const & lay = textclass.getTOCLayout();
4867 docstring const cnt = lay.counter;
4869 counters.reset(cnt);
4870 counters.appendix(true);
4872 par.params().appendix(counters.appendix());
4874 // Compute the item depth of the paragraph
4875 par.itemdepth = getItemDepth(it);
4877 if (layout.margintype == MARGIN_MANUAL) {
4878 if (par.params().labelWidthString().empty())
4879 par.params().labelWidthString(par.expandLabel(layout, bp));
4880 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4881 // we do not need to do anything here, since the empty case is
4882 // handled during export.
4884 par.params().labelWidthString(docstring());
4887 switch(layout.labeltype) {
4888 case LABEL_ITEMIZE: {
4889 // At some point of time we should do something more
4890 // clever here, like:
4891 // par.params().labelString(
4892 // bp.user_defined_bullet(par.itemdepth).getText());
4893 // for now, use a simple hardcoded label
4894 docstring itemlabel;
4895 switch (par.itemdepth) {
4897 itemlabel = char_type(0x2022);
4900 itemlabel = char_type(0x2013);
4903 itemlabel = char_type(0x2217);
4906 itemlabel = char_type(0x2219); // or 0x00b7
4909 par.params().labelString(itemlabel);
4913 case LABEL_ENUMERATE: {
4914 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4916 switch (par.itemdepth) {
4925 enumcounter += "iv";
4928 // not a valid enumdepth...
4932 // Increase the master counter?
4933 if (layout.stepmastercounter && needEnumCounterReset(it))
4934 counters.stepMaster(enumcounter, utype);
4936 // Maybe we have to reset the enumeration counter.
4937 if (!layout.resumecounter && needEnumCounterReset(it))
4938 counters.reset(enumcounter);
4939 counters.step(enumcounter, utype);
4941 string const & lang = par.getParLanguage(bp)->code();
4942 par.params().labelString(counters.theCounter(enumcounter, lang));
4947 case LABEL_SENSITIVE: {
4948 string const & type = counters.current_float();
4949 docstring full_label;
4951 full_label = owner_->B_("Senseless!!! ");
4953 docstring name = owner_->B_(textclass.floats().getType(type).name());
4954 if (counters.hasCounter(from_utf8(type))) {
4955 string const & lang = par.getParLanguage(bp)->code();
4956 counters.step(from_utf8(type), utype);
4957 full_label = bformat(from_ascii("%1$s %2$s:"),
4959 counters.theCounter(from_utf8(type), lang));
4961 full_label = bformat(from_ascii("%1$s #:"), name);
4963 par.params().labelString(full_label);
4967 case LABEL_NO_LABEL:
4968 par.params().labelString(docstring());
4972 case LABEL_CENTERED:
4973 case LABEL_STATIC: {
4974 docstring const & lcounter = layout.counter;
4975 if (!lcounter.empty()) {
4976 if (layout.toclevel <= bp.secnumdepth
4977 && (layout.latextype != LATEX_ENVIRONMENT
4978 || it.text()->isFirstInSequence(it.pit()))) {
4979 if (counters.hasCounter(lcounter))
4980 counters.step(lcounter, utype);
4981 par.params().labelString(par.expandLabel(layout, bp));
4983 par.params().labelString(docstring());
4985 par.params().labelString(par.expandLabel(layout, bp));
4991 par.params().labelString(par.expandLabel(layout, bp));
4996 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4998 // LASSERT: Is it safe to continue here, or should we just return?
4999 LASSERT(parit.pit() == 0, /**/);
5001 // Set the position of the text in the buffer to be able
5002 // to resolve macros in it.
5003 parit.text()->setMacrocontextPosition(parit);
5005 depth_type maxdepth = 0;
5006 pit_type const lastpit = parit.lastpit();
5007 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5008 // reduce depth if necessary
5009 if (parit->params().depth() > maxdepth) {
5010 /** FIXME: this function is const, but
5011 * nevertheless it modifies the buffer. To be
5012 * cleaner, one should modify the buffer in
5013 * another function, which is actually
5014 * non-const. This would however be costly in
5015 * terms of code duplication.
5017 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5018 parit->params().depth(maxdepth);
5020 maxdepth = parit->getMaxDepthAfter();
5022 if (utype == OutputUpdate) {
5023 // track the active counters
5024 // we have to do this for the master buffer, since the local
5025 // buffer isn't tracking anything.
5026 masterBuffer()->params().documentClass().counters().
5027 setActiveLayout(parit->layout());
5030 // set the counter for this paragraph
5031 d->setLabel(parit, utype);
5033 // update change-tracking flag
5034 parit->addChangesToBuffer(*this);
5037 InsetList::const_iterator iit = parit->insetList().begin();
5038 InsetList::const_iterator end = parit->insetList().end();
5039 for (; iit != end; ++iit) {
5040 parit.pos() = iit->pos;
5041 iit->inset->updateBuffer(parit, utype);
5047 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5048 WordLangTuple & word_lang, docstring_list & suggestions) const
5052 suggestions.clear();
5053 word_lang = WordLangTuple();
5054 bool const to_end = to.empty();
5055 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5056 // OK, we start from here.
5057 for (; from != end; from.forwardPos()) {
5058 // This skips all insets with spell check disabled.
5059 while (!from.allowSpellCheck()) {
5063 // If from is at the end of the document (which is possible
5064 // when "from" was changed above) LyX will crash later otherwise.
5065 if (from.atEnd() || (!to_end && from >= end))
5068 from.paragraph().spellCheck();
5069 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5070 if (SpellChecker::misspelled(res)) {
5074 // Do not increase progress when from == to, otherwise the word
5075 // count will be wrong.
5085 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5087 bool inword = false;
5092 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5093 if (!dit.inTexted()) {
5098 Paragraph const & par = dit.paragraph();
5099 pos_type const pos = dit.pos();
5101 // Copied and adapted from isWordSeparator() in Paragraph
5102 if (pos == dit.lastpos()) {
5105 Inset const * ins = par.getInset(pos);
5106 if (ins && skipNoOutput && !ins->producesOutput()) {
5109 // stop if end of range was skipped
5110 if (!to.atEnd() && dit >= to)
5113 } else if (!par.isDeleted(pos)) {
5114 if (par.isWordSeparator(pos))
5120 if (ins && ins->isLetter())
5122 else if (ins && ins->isSpace())
5125 char_type const c = par.getChar(pos);
5126 if (isPrintableNonspace(c))
5128 else if (isSpace(c))
5138 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5140 d->updateStatistics(from, to, skipNoOutput);
5144 int Buffer::wordCount() const
5146 return d->wordCount();
5150 int Buffer::charCount(bool with_blanks) const
5152 return d->charCount(with_blanks);
5156 Buffer::ReadStatus Buffer::reload()
5159 // c.f. bug http://www.lyx.org/trac/ticket/6587
5160 removeAutosaveFile();
5161 // e.g., read-only status could have changed due to version control
5162 d->filename.refresh();
5163 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5165 // clear parent. this will get reset if need be.
5167 ReadStatus const status = loadLyXFile();
5168 if (status == ReadSuccess) {
5173 message(bformat(_("Document %1$s reloaded."), disp_fn));
5176 message(bformat(_("Could not reload document %1$s."), disp_fn));
5186 bool Buffer::saveAs(FileName const & fn)
5188 FileName const old_name = fileName();
5189 FileName const old_auto = getAutosaveFileName();
5190 bool const old_unnamed = isUnnamed();
5191 bool success = true;
5192 d->old_position = filePath();
5199 // bring the autosave file with us, just in case.
5200 moveAutosaveFile(old_auto);
5201 // validate version control data and
5202 // correct buffer title
5203 lyxvc().file_found_hook(fileName());
5205 // the file has now been saved to the new location.
5206 // we need to check that the locations of child buffers
5208 checkChildBuffers();
5209 checkMasterBuffer();
5212 // reset the old filename and unnamed state
5213 setFileName(old_name);
5214 setUnnamed(old_unnamed);
5218 d->old_position.clear();
5223 void Buffer::checkChildBuffers()
5225 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5226 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5227 for (; it != en; ++it) {
5228 DocIterator dit = it->second;
5229 Buffer * cbuf = const_cast<Buffer *>(it->first);
5230 if (!cbuf || !theBufferList().isLoaded(cbuf))
5232 Inset * inset = dit.nextInset();
5233 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5234 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5235 docstring const & incfile = inset_inc->getParam("filename");
5236 string oldloc = cbuf->absFileName();
5237 string newloc = makeAbsPath(to_utf8(incfile),
5238 onlyPath(absFileName())).absFileName();
5239 if (oldloc == newloc)
5241 // the location of the child file is incorrect.
5243 inset_inc->setChildBuffer(0);
5245 // invalidate cache of children
5246 d->children_positions.clear();
5247 d->position_to_children.clear();
5251 // If a child has been saved under a different name/path, it might have been
5252 // orphaned. Therefore the master needs to be reset (bug 8161).
5253 void Buffer::checkMasterBuffer()
5255 Buffer const * const master = masterBuffer();
5259 // necessary to re-register the child (bug 5873)
5260 // FIXME: clean up updateMacros (here, only
5261 // child registering is needed).
5262 master->updateMacros();
5263 // (re)set master as master buffer, but only
5264 // if we are a real child
5265 if (master->isChild(this))
5272 string Buffer::includedFilePath(string const & name, string const & ext) const
5274 if (d->old_position.empty() ||
5275 equivalent(FileName(d->old_position), FileName(filePath())))
5278 bool isabsolute = FileName::isAbsolute(name);
5279 // both old_position and filePath() end with a path separator
5280 string absname = isabsolute ? name : d->old_position + name;
5282 // if old_position is set to origin, we need to do the equivalent of
5283 // getReferencedFileName() (see readDocument())
5284 if (!isabsolute && d->old_position == params().origin) {
5285 FileName const test(addExtension(filePath() + name, ext));
5287 absname = filePath() + name;
5290 if (!FileName(addExtension(absname, ext)).exists())
5294 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5296 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5297 from_utf8(filePath())));
5301 void Buffer::setChangesPresent(bool b) const
5303 d->tracked_changes_present_ = b;
5307 bool Buffer::areChangesPresent() const
5309 return d->tracked_changes_present_;
5313 void Buffer::updateChangesPresent() const
5315 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5316 setChangesPresent(false);
5317 ParConstIterator it = par_iterator_begin();
5318 ParConstIterator const end = par_iterator_end();
5319 for (; !areChangesPresent() && it != end; ++it)
5320 it->addChangesToBuffer(*this);
5324 void Buffer::Impl::refreshFileMonitor()
5326 if (file_monitor_ && file_monitor_->filename() == filename.absFileName())
5327 return file_monitor_->refresh();
5329 // The previous file monitor is invalid
5330 // This also destroys the previous file monitor and all its connections
5331 file_monitor_ = FileSystemWatcher::monitor(filename);
5332 fileExternallyModified(false);
5333 // file_monitor_ will be destroyed with *this, so it is not going to call a
5334 // destroyed object method.
5335 file_monitor_->connect([this](){ fileExternallyModified(true); });
5339 void Buffer::Impl::fileExternallyModified(bool modified) const
5342 lyx_clean = bak_clean = false;
5343 externally_modified_ = modified;
5345 wa_->updateTitles();
5349 bool Buffer::notifiesExternalModification() const
5351 return d->isExternallyModified();
5355 void Buffer::clearExternalModification() const
5357 d->fileExternallyModified(false);