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 /// timestamp and checksum used to test if the file has been externally
268 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
270 unsigned long checksum_;
273 frontend::WorkAreaManager * wa_;
275 frontend::GuiBufferDelegate * gui_;
280 /// A cache for the bibfiles (including bibfiles of loaded child
281 /// documents), needed for appropriate update of natbib labels.
282 mutable support::FileNamePairList bibfiles_cache_;
284 // FIXME The caching mechanism could be improved. At present, we have a
285 // cache for each Buffer, that caches all the bibliography info for that
286 // Buffer. A more efficient solution would be to have a global cache per
287 // file, and then to construct the Buffer's bibinfo from that.
288 /// A cache for bibliography info
289 mutable BiblioInfo bibinfo_;
290 /// whether the bibinfo cache is valid
291 mutable bool bibinfo_cache_valid_;
292 /// whether the bibfile cache is valid
293 mutable bool bibfile_cache_valid_;
294 /// Cache of timestamps of .bib files
295 map<FileName, time_t> bibfile_status_;
296 /// Indicates whether the bibinfo has changed since the last time
297 /// we ran updateBuffer(), i.e., whether citation labels may need
299 mutable bool cite_labels_valid_;
301 /// These two hold the file name and format, written to by
302 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
303 FileName preview_file_;
304 string preview_format_;
305 /// If there was an error when previewing, on the next preview we do
306 /// a fresh compile (e.g. in case the user installed a package that
310 mutable RefCache ref_cache_;
312 /// our Text that should be wrapped in an InsetText
316 PreviewLoader * preview_loader_;
318 /// This is here to force the test to be done whenever parent_buffer
320 Buffer const * parent() const
322 // ignore_parent temporarily "orphans" a buffer
323 // (e.g. if a child is compiled standalone)
326 // if parent_buffer is not loaded, then it has been unloaded,
327 // which means that parent_buffer is an invalid pointer. So we
328 // set it to null in that case.
329 // however, the BufferList doesn't know about cloned buffers, so
330 // they will always be regarded as unloaded. in that case, we hope
332 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
334 return parent_buffer;
338 void setParent(Buffer const * pb)
340 if (parent_buffer == pb)
343 if (!cloned_buffer_ && parent_buffer && pb)
344 LYXERR0("Warning: a buffer should not have two parents!");
346 if (!cloned_buffer_ && parent_buffer) {
347 parent_buffer->invalidateBibfileCache();
348 parent_buffer->invalidateBibinfoCache();
352 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
353 /// This one is useful for preview detached in a thread.
354 Buffer const * cloned_buffer_;
356 CloneList * clone_list_;
357 /// are we in the process of exporting this buffer?
358 mutable bool doing_export;
360 /// compute statistics
361 /// \p from initial position
362 /// \p to points to the end position
363 void updateStatistics(DocIterator & from, DocIterator & to,
364 bool skipNoOutput = true);
365 /// statistics accessor functions
366 int wordCount() const
370 int charCount(bool with_blanks) const
373 + (with_blanks ? blank_count_ : 0);
376 // does the buffer contain tracked changes? (if so, we automatically
377 // display the review toolbar, for instance)
378 mutable bool tracked_changes_present_;
380 // Make sure the file monitor monitors the good file.
381 void refreshFileMonitor();
383 /// has it been notified of an external modification?
384 bool isExternallyModified() const { return externally_modified_; }
386 /// Notify or clear of external modification
387 void fileExternallyModified(bool modified) const;
389 /// Block notifications of external modifications
390 FileMonitorBlocker blockFileMonitor() { return file_monitor_->block(10); }
393 /// So we can force access via the accessors.
394 mutable Buffer const * parent_buffer;
400 /// has been externally modified? Can be reset by the user.
401 mutable bool externally_modified_;
403 FileMonitorPtr file_monitor_;
407 /// Creates the per buffer temporary directory
408 static FileName createBufferTmpDir()
410 // FIXME This would be the ideal application for a TempDir class (like
411 // TempFile but for directories)
416 Mutex::Locker locker(&mutex);
417 counter = convert<string>(count++);
419 // We are in our own directory. Why bother to mangle name?
420 // In fact I wrote this code to circumvent a problematic behaviour
421 // (bug?) of EMX mkstemp().
422 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
425 if (!tmpfl.createDirectory(0777)) {
426 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
427 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
428 from_utf8(tmpfl.absFileName())));
434 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
435 Buffer const * cloned_buffer)
436 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
437 internal_buffer(false), read_only(readonly_), filename(file),
438 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
439 ignore_parent(false), toc_backend(owner), macro_lock(false), timestamp_(0),
440 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
441 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
442 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
443 clone_list_(0), doing_export(false),
444 tracked_changes_present_(0), parent_buffer(0),
445 word_count_(0), char_count_(0), blank_count_(0),
446 externally_modified_(false)
448 refreshFileMonitor();
449 if (!cloned_buffer_) {
450 temppath = createBufferTmpDir();
451 lyxvc.setBuffer(owner_);
453 wa_ = new frontend::WorkAreaManager;
456 temppath = cloned_buffer_->d->temppath;
457 file_fully_loaded = true;
458 params = cloned_buffer_->d->params;
459 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
460 bibinfo_ = cloned_buffer_->d->bibinfo_;
461 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
462 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
463 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
464 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
465 unnamed = cloned_buffer_->d->unnamed;
466 internal_buffer = cloned_buffer_->d->internal_buffer;
467 layout_position = cloned_buffer_->d->layout_position;
468 preview_file_ = cloned_buffer_->d->preview_file_;
469 preview_format_ = cloned_buffer_->d->preview_format_;
470 preview_error_ = cloned_buffer_->d->preview_error_;
471 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
475 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
476 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
478 LYXERR(Debug::INFO, "Buffer::Buffer()");
480 d->inset = new InsetText(*cloned_buffer->d->inset);
481 d->inset->setBuffer(*this);
482 // FIXME: optimize this loop somewhat, maybe by creating a new
483 // general recursive Inset::setId().
484 DocIterator it = doc_iterator_begin(this);
485 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
486 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
487 it.paragraph().setId(cloned_it.paragraph().id());
489 d->inset = new InsetText(this);
490 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
496 LYXERR(Debug::INFO, "Buffer::~Buffer()");
497 // here the buffer should take care that it is
498 // saved properly, before it goes into the void.
500 // GuiView already destroyed
504 // No need to do additional cleanups for internal buffer.
510 // this is in case of recursive includes: we won't try to delete
511 // ourselves as a child.
512 d->clone_list_->erase(this);
513 // loop over children
514 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
515 Impl::BufferPositionMap::iterator end = d->children_positions.end();
516 for (; it != end; ++it) {
517 Buffer * child = const_cast<Buffer *>(it->first);
518 if (d->clone_list_->erase(child))
521 // if we're the master buffer, then we should get rid of the list
524 // If this is not empty, we have leaked something. Worse, one of the
525 // children still has a reference to this list. But we will try to
526 // continue, rather than shut down.
527 LATTEST(d->clone_list_->empty());
528 list<CloneList *>::iterator it =
529 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
530 if (it == cloned_buffers.end()) {
531 // We will leak in this case, but it is safe to continue.
534 cloned_buffers.erase(it);
535 delete d->clone_list_;
537 // FIXME Do we really need to do this right before we delete d?
538 // clear references to children in macro tables
539 d->children_positions.clear();
540 d->position_to_children.clear();
542 // loop over children
543 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
544 Impl::BufferPositionMap::iterator end = d->children_positions.end();
545 for (; it != end; ++it) {
546 Buffer * child = const_cast<Buffer *>(it->first);
547 if (theBufferList().isLoaded(child)) {
548 if (theBufferList().isOthersChild(this, child))
551 theBufferList().release(child);
556 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
557 msg += emergencyWrite();
558 Alert::warning(_("Attempting to close changed document!"), msg);
561 // FIXME Do we really need to do this right before we delete d?
562 // clear references to children in macro tables
563 d->children_positions.clear();
564 d->position_to_children.clear();
566 if (!d->temppath.destroyDirectory()) {
567 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
568 from_utf8(d->temppath.absFileName())));
577 Buffer * Buffer::cloneFromMaster() const
580 cloned_buffers.push_back(new CloneList);
581 CloneList * clones = cloned_buffers.back();
583 masterBuffer()->cloneWithChildren(bufmap, clones);
585 // make sure we got cloned
586 BufferMap::const_iterator bit = bufmap.find(this);
587 LASSERT(bit != bufmap.end(), return 0);
588 Buffer * cloned_buffer = bit->second;
590 return cloned_buffer;
594 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
596 // have we already been cloned?
597 if (bufmap.find(this) != bufmap.end())
600 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
602 // The clone needs its own DocumentClass, since running updateBuffer() will
603 // modify it, and we would otherwise be sharing it with the original Buffer.
604 buffer_clone->params().makeDocumentClass(true);
606 cap::switchBetweenClasses(
607 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
608 static_cast<InsetText &>(buffer_clone->inset()), el);
610 bufmap[this] = buffer_clone;
611 clones->insert(buffer_clone);
612 buffer_clone->d->clone_list_ = clones;
613 buffer_clone->d->macro_lock = true;
614 buffer_clone->d->children_positions.clear();
616 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
617 // math macro caches need to be rethought and simplified.
618 // I am not sure wether we should handle Buffer cloning here or in BufferList.
619 // Right now BufferList knows nothing about buffer clones.
620 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
621 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
622 for (; it != end; ++it) {
623 DocIterator dit = it->first.clone(buffer_clone);
624 dit.setBuffer(buffer_clone);
625 Buffer * child = const_cast<Buffer *>(it->second.buffer);
627 child->cloneWithChildren(bufmap, clones);
628 BufferMap::iterator const bit = bufmap.find(child);
629 LASSERT(bit != bufmap.end(), continue);
630 Buffer * child_clone = bit->second;
632 Inset * inset = dit.nextInset();
633 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
634 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
635 inset_inc->setChildBuffer(child_clone);
636 child_clone->d->setParent(buffer_clone);
637 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
638 buffer_clone->setChild(dit, child_clone);
640 buffer_clone->d->macro_lock = false;
645 Buffer * Buffer::cloneBufferOnly() const {
646 cloned_buffers.push_back(new CloneList);
647 CloneList * clones = cloned_buffers.back();
648 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
650 // The clone needs its own DocumentClass, since running updateBuffer() will
651 // modify it, and we would otherwise be sharing it with the original Buffer.
652 buffer_clone->params().makeDocumentClass(true);
654 cap::switchBetweenClasses(
655 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
656 static_cast<InsetText &>(buffer_clone->inset()), el);
658 clones->insert(buffer_clone);
659 buffer_clone->d->clone_list_ = clones;
661 // we won't be cloning the children
662 buffer_clone->d->children_positions.clear();
667 bool Buffer::isClone() const
669 return d->cloned_buffer_;
673 void Buffer::changed(bool update_metrics) const
676 d->wa_->redrawAll(update_metrics);
680 frontend::WorkAreaManager & Buffer::workAreaManager() const
687 Text & Buffer::text() const
689 return d->inset->text();
693 Inset & Buffer::inset() const
699 BufferParams & Buffer::params()
705 BufferParams const & Buffer::params() const
711 BufferParams const & Buffer::masterParams() const
713 if (masterBuffer() == this)
716 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
717 // Copy child authors to the params. We need those pointers.
718 AuthorList const & child_authors = params().authors();
719 AuthorList::Authors::const_iterator it = child_authors.begin();
720 for (; it != child_authors.end(); ++it)
721 mparams.authors().record(*it);
726 double Buffer::fontScalingFactor() const
728 return isExporting() ? 75.0 * params().html_math_img_scale
729 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
733 ParagraphList & Buffer::paragraphs()
735 return text().paragraphs();
739 ParagraphList const & Buffer::paragraphs() const
741 return text().paragraphs();
745 LyXVC & Buffer::lyxvc()
751 LyXVC const & Buffer::lyxvc() const
757 string const Buffer::temppath() const
759 return d->temppath.absFileName();
763 TexRow & Buffer::texrow()
769 TexRow const & Buffer::texrow() const
775 TocBackend & Buffer::tocBackend() const
777 return d->toc_backend;
781 Undo & Buffer::undo()
787 void Buffer::setChild(DocIterator const & dit, Buffer * child)
789 d->children_positions[child] = dit;
793 string Buffer::latexName(bool const no_path) const
795 FileName latex_name =
796 makeLatexName(d->exportFileName());
797 return no_path ? latex_name.onlyFileName()
798 : latex_name.absFileName();
802 FileName Buffer::Impl::exportFileName() const
804 docstring const branch_suffix =
805 params.branchlist().getFileNameSuffix();
806 if (branch_suffix.empty())
809 string const name = filename.onlyFileNameWithoutExt()
810 + to_utf8(branch_suffix);
811 FileName res(filename.onlyPath().absFileName() + "/" + name);
812 res.changeExtension(filename.extension());
818 string Buffer::logName(LogType * type) const
820 string const filename = latexName(false);
822 if (filename.empty()) {
828 string const path = temppath();
830 FileName const fname(addName(temppath(),
831 onlyFileName(changeExtension(filename,
834 // FIXME: how do we know this is the name of the build log?
835 FileName const bname(
836 addName(path, onlyFileName(
837 changeExtension(filename,
838 formats.extension(params().bufferFormat()) + ".out"))));
840 // Also consider the master buffer log file
841 FileName masterfname = fname;
842 LogType mtype = latexlog;
843 if (masterBuffer() != this) {
844 string const mlogfile = masterBuffer()->logName(&mtype);
845 masterfname = FileName(mlogfile);
848 // If no Latex log or Build log is newer, show Build log
849 if (bname.exists() &&
850 ((!fname.exists() && !masterfname.exists())
851 || (fname.lastModified() < bname.lastModified()
852 && masterfname.lastModified() < bname.lastModified()))) {
853 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
856 return bname.absFileName();
857 // If we have a newer master file log or only a master log, show this
858 } else if (fname != masterfname
859 && (!fname.exists() && (masterfname.exists()
860 || fname.lastModified() < masterfname.lastModified()))) {
861 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
864 return masterfname.absFileName();
866 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
869 return fname.absFileName();
873 void Buffer::setReadonly(bool const flag)
875 if (d->read_only != flag) {
882 void Buffer::setFileName(FileName const & fname)
884 bool const changed = fname != d->filename;
886 d->refreshFileMonitor();
888 lyxvc().file_found_hook(fname);
889 setReadonly(d->filename.isReadOnly());
895 int Buffer::readHeader(Lexer & lex)
897 int unknown_tokens = 0;
899 int begin_header_line = -1;
901 // Initialize parameters that may be/go lacking in header:
902 params().branchlist().clear();
903 params().preamble.erase();
904 params().options.erase();
905 params().master.erase();
906 params().float_placement.erase();
907 params().paperwidth.erase();
908 params().paperheight.erase();
909 params().leftmargin.erase();
910 params().rightmargin.erase();
911 params().topmargin.erase();
912 params().bottommargin.erase();
913 params().headheight.erase();
914 params().headsep.erase();
915 params().footskip.erase();
916 params().columnsep.erase();
917 params().fonts_cjk.erase();
918 params().listings_params.clear();
919 params().clearLayoutModules();
920 params().clearRemovedModules();
921 params().clearIncludedChildren();
922 params().pdfoptions().clear();
923 params().indiceslist().clear();
924 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
925 params().isbackgroundcolor = false;
926 params().fontcolor = RGBColor(0, 0, 0);
927 params().isfontcolor = false;
928 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
929 params().boxbgcolor = RGBColor(0xFF, 0, 0);
930 params().html_latex_start.clear();
931 params().html_latex_end.clear();
932 params().html_math_img_scale = 1.0;
933 params().output_sync_macro.erase();
934 params().setLocalLayout(docstring(), false);
935 params().setLocalLayout(docstring(), true);
936 params().biblio_opts.erase();
937 params().biblatex_bibstyle.erase();
938 params().biblatex_citestyle.erase();
939 params().multibib.erase();
941 for (int i = 0; i < 4; ++i) {
942 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
943 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
946 ErrorList & errorList = d->errorLists["Parse"];
955 if (token == "\\end_header")
959 if (token == "\\begin_header") {
960 begin_header_line = line;
964 LYXERR(Debug::PARSER, "Handling document header token: `"
967 string const result =
968 params().readToken(lex, token, d->filename.onlyPath());
969 if (!result.empty()) {
970 if (token == "\\textclass") {
971 d->layout_position = result;
974 docstring const s = bformat(_("Unknown token: "
978 errorList.push_back(ErrorItem(_("Document header error"), s));
982 if (begin_header_line) {
983 docstring const s = _("\\begin_header is missing");
984 errorList.push_back(ErrorItem(_("Document header error"), s));
987 params().makeDocumentClass();
989 return unknown_tokens;
994 // changed to be public and have one parameter
995 // Returns true if "\end_document" is not read (Asger)
996 bool Buffer::readDocument(Lexer & lex)
998 ErrorList & errorList = d->errorLists["Parse"];
1001 // remove dummy empty par
1002 paragraphs().clear();
1004 if (!lex.checkFor("\\begin_document")) {
1005 docstring const s = _("\\begin_document is missing");
1006 errorList.push_back(ErrorItem(_("Document header error"), s));
1011 if (params().output_changes) {
1012 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1013 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1014 LaTeXFeatures::isAvailable("xcolor");
1016 if (!dvipost && !xcolorulem) {
1017 Alert::warning(_("Changes not shown in LaTeX output"),
1018 _("Changes will not be highlighted in LaTeX output, "
1019 "because neither dvipost nor xcolor/ulem are installed.\n"
1020 "Please install these packages or redefine "
1021 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1022 } else if (!xcolorulem) {
1023 Alert::warning(_("Changes not shown in LaTeX output"),
1024 _("Changes will not be highlighted in LaTeX output "
1025 "when using pdflatex, because xcolor and ulem are not installed.\n"
1026 "Please install both packages or redefine "
1027 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1031 if (!parent() && !params().master.empty()) {
1032 FileName const master_file = makeAbsPath(params().master,
1033 onlyPath(absFileName()));
1034 if (isLyXFileName(master_file.absFileName())) {
1036 checkAndLoadLyXFile(master_file, true);
1038 // necessary e.g. after a reload
1039 // to re-register the child (bug 5873)
1040 // FIXME: clean up updateMacros (here, only
1041 // child registering is needed).
1042 master->updateMacros();
1043 // set master as master buffer, but only
1044 // if we are a real child
1045 if (master->isChild(this))
1047 // if the master is not fully loaded
1048 // it is probably just loading this
1049 // child. No warning needed then.
1050 else if (master->isFullyLoaded())
1051 LYXERR0("The master '"
1053 << "' assigned to this document ("
1055 << ") does not include "
1056 "this document. Ignoring the master assignment.");
1061 // assure we have a default index
1062 params().indiceslist().addDefault(B_("Index"));
1065 if (FileName::isAbsolute(params().origin))
1066 d->old_position = params().origin;
1068 d->old_position = filePath();
1069 bool const res = text().read(lex, errorList, d->inset);
1070 d->old_position.clear();
1072 // inform parent buffer about local macros
1074 Buffer const * pbuf = parent();
1075 UserMacroSet::const_iterator cit = usermacros.begin();
1076 UserMacroSet::const_iterator end = usermacros.end();
1077 for (; cit != end; ++cit)
1078 pbuf->usermacros.insert(*cit);
1082 updateMacroInstances(InternalUpdate);
1087 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1089 Format const * fmt = formats.getFormat(format);
1092 // It is important to use the correct extension here, since some
1093 // converters create a wrong output file otherwise (e.g. html2latex)
1094 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1095 FileName const name(tempfile.name());
1096 ofdocstream os(name.toFilesystemEncoding().c_str());
1097 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1098 bool const success = !(os << contents).fail();
1101 bool converted = false;
1103 params().compressed = false;
1105 // remove dummy empty par
1106 paragraphs().clear();
1108 converted = importFile(format, name, errorList);
1117 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1119 if (!theConverters().isReachable(format, "lyx"))
1122 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1123 FileName const lyx(tempfile.name());
1124 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1125 return readFile(lyx) == ReadSuccess;
1131 bool Buffer::readString(string const & s)
1133 params().compressed = false;
1136 istringstream is(s);
1138 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1139 FileName const fn = tempfile.name();
1142 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1144 if (success && file_format != LYX_FORMAT) {
1145 // We need to call lyx2lyx, so write the input to a file
1146 ofstream os(fn.toFilesystemEncoding().c_str());
1149 // lyxvc in readFile
1150 if (readFile(fn) != ReadSuccess)
1154 if (readDocument(lex))
1160 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1164 if (!lex.setFile(fname)) {
1165 Alert::error(_("File Not Found"),
1166 bformat(_("Unable to open file `%1$s'."),
1167 from_utf8(fn.absFileName())));
1168 return ReadFileNotFound;
1172 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1173 if (ret_plf != ReadSuccess)
1176 if (file_format != LYX_FORMAT) {
1178 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1179 if (ret_clf != ReadSuccess)
1181 ret_clf = readFile(tmpFile);
1182 if (ret_clf == ReadSuccess) {
1183 d->file_format = file_format;
1184 d->need_format_backup = true;
1189 // FIXME: InsetInfo needs to know whether the file is under VCS
1190 // during the parse process, so this has to be done before.
1191 lyxvc().file_found_hook(d->filename);
1193 if (readDocument(lex)) {
1194 Alert::error(_("Document format failure"),
1195 bformat(_("%1$s ended unexpectedly, which means"
1196 " that it is probably corrupted."),
1197 from_utf8(fn.absFileName())));
1198 return ReadDocumentFailure;
1201 d->file_fully_loaded = true;
1202 d->read_only = !d->filename.isWritable();
1203 params().compressed = formats.isZippedFile(d->filename);
1209 bool Buffer::isFullyLoaded() const
1211 return d->file_fully_loaded;
1215 void Buffer::setFullyLoaded(bool value)
1217 d->file_fully_loaded = value;
1221 bool Buffer::lastPreviewError() const
1223 return d->preview_error_;
1227 PreviewLoader * Buffer::loader() const
1229 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1231 if (!d->preview_loader_)
1232 d->preview_loader_ = new PreviewLoader(*this);
1233 return d->preview_loader_;
1237 void Buffer::removePreviews() const
1239 delete d->preview_loader_;
1240 d->preview_loader_ = 0;
1244 void Buffer::updatePreviews() const
1246 PreviewLoader * ploader = loader();
1250 InsetIterator it = inset_iterator_begin(*d->inset);
1251 InsetIterator const end = inset_iterator_end(*d->inset);
1252 for (; it != end; ++it)
1253 it->addPreview(it, *ploader);
1255 ploader->startLoading();
1259 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1260 FileName const & fn, int & file_format) const
1262 if(!lex.checkFor("\\lyxformat")) {
1263 Alert::error(_("Document format failure"),
1264 bformat(_("%1$s is not a readable LyX document."),
1265 from_utf8(fn.absFileName())));
1266 return ReadNoLyXFormat;
1272 // LyX formats 217 and earlier were written as 2.17. This corresponds
1273 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1274 // these cases. See also: www.lyx.org/trac/changeset/1313.
1275 size_t dot = tmp_format.find_first_of(".,");
1276 if (dot != string::npos)
1277 tmp_format.erase(dot, 1);
1279 file_format = convert<int>(tmp_format);
1284 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1285 FileName & tmpfile, int from_format)
1287 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1288 tempfile.setAutoRemove(false);
1289 tmpfile = tempfile.name();
1290 if(tmpfile.empty()) {
1291 Alert::error(_("Conversion failed"),
1292 bformat(_("%1$s is from a different"
1293 " version of LyX, but a temporary"
1294 " file for converting it could"
1295 " not be created."),
1296 from_utf8(fn.absFileName())));
1297 return LyX2LyXNoTempFile;
1300 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1301 if (lyx2lyx.empty()) {
1302 Alert::error(_("Conversion script not found"),
1303 bformat(_("%1$s is from a different"
1304 " version of LyX, but the"
1305 " conversion script lyx2lyx"
1306 " could not be found."),
1307 from_utf8(fn.absFileName())));
1308 return LyX2LyXNotFound;
1312 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1313 ostringstream command;
1314 command << os::python()
1315 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1316 << " -t " << convert<string>(LYX_FORMAT)
1317 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1318 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1319 string const command_str = command.str();
1321 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1323 cmd_ret const ret = runCommand(command_str);
1324 if (ret.first != 0) {
1325 if (from_format < LYX_FORMAT) {
1326 Alert::error(_("Conversion script failed"),
1327 bformat(_("%1$s is from an older version"
1328 " of LyX and the lyx2lyx script"
1329 " failed to convert it."),
1330 from_utf8(fn.absFileName())));
1331 return LyX2LyXOlderFormat;
1333 Alert::error(_("Conversion script failed"),
1334 bformat(_("%1$s is from a newer version"
1335 " of LyX and the lyx2lyx script"
1336 " failed to convert it."),
1337 from_utf8(fn.absFileName())));
1338 return LyX2LyXNewerFormat;
1345 FileName Buffer::getBackupName() const {
1346 FileName const & fn = fileName();
1347 string const fname = fn.onlyFileNameWithoutExt();
1348 string const fext = fn.extension() + "~";
1349 string const fpath = lyxrc.backupdir_path.empty() ?
1350 fn.onlyPath().absFileName() :
1351 lyxrc.backupdir_path;
1352 string const fform = convert<string>(d->file_format);
1353 string const backname = fname + "-lyxformat-" + fform;
1354 FileName backup(addName(fpath, addExtension(backname, fext)));
1356 // limit recursion, just in case
1358 unsigned long orig_checksum = 0;
1359 while (backup.exists() && v < 100) {
1360 if (orig_checksum == 0)
1361 orig_checksum = fn.checksum();
1362 unsigned long new_checksum = backup.checksum();
1363 if (orig_checksum == new_checksum) {
1364 LYXERR(Debug::FILES, "Not backing up " << fn <<
1365 "since " << backup << "has the same checksum.");
1366 // a bit of a hack, but we have to check this anyway
1367 // below, and setting this is simpler than introducing
1368 // a special boolean for this purpose.
1372 string const newbackname = backname + "-" + convert<string>(v);
1373 backup.set(addName(fpath, addExtension(newbackname, fext)));
1376 return v < 100 ? backup : FileName();
1380 // Should probably be moved to somewhere else: BufferView? GuiView?
1381 bool Buffer::save() const
1383 FileMonitorBlocker block = d->blockFileMonitor();
1384 docstring const file = makeDisplayPath(absFileName(), 20);
1385 d->filename.refresh();
1387 // check the read-only status before moving the file as a backup
1388 if (d->filename.exists()) {
1389 bool const read_only = !d->filename.isWritable();
1391 Alert::warning(_("File is read-only"),
1392 bformat(_("The file %1$s cannot be written because it "
1393 "is marked as read-only."), file));
1398 // ask if the disk file has been externally modified (use checksum method)
1399 if (fileName().exists() && isChecksumModified()) {
1401 bformat(_("Document %1$s has been externally modified. "
1402 "Are you sure you want to overwrite this file?"), file);
1403 int const ret = Alert::prompt(_("Overwrite modified file?"),
1404 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1409 // We don't need autosaves in the immediate future. (Asger)
1410 resetAutosaveTimers();
1412 // if the file does not yet exist, none of the backup activity
1413 // that follows is necessary
1414 if (!fileName().exists()) {
1415 if (!writeFile(fileName()))
1421 // we first write the file to a new name, then move it to its
1422 // proper location once that has been done successfully. that
1423 // way we preserve the original file if something goes wrong.
1424 string const justname = fileName().onlyFileNameWithoutExt();
1425 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1426 justname + "-XXXXXX.lyx");
1427 bool const symlink = fileName().isSymLink();
1429 tempfile->setAutoRemove(false);
1431 FileName savefile(tempfile->name());
1432 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1433 if (!writeFile(savefile))
1436 // we will set this to false if we fail
1437 bool made_backup = true;
1439 FileName backupName;
1440 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1442 if (d->need_format_backup)
1443 backupName = getBackupName();
1445 // If we for some reason failed to find a backup name in case of
1446 // a format change, this will still set one. It's the best we can
1448 if (backupName.empty()) {
1449 backupName.set(fileName().absFileName() + "~");
1450 if (!lyxrc.backupdir_path.empty()) {
1451 string const mangledName =
1452 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1453 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1457 LYXERR(Debug::FILES, "Backing up original file to " <<
1458 backupName.absFileName());
1459 // Except file is symlink do not copy because of #6587.
1460 // Hard links have bad luck.
1461 made_backup = symlink ?
1462 fileName().copyTo(backupName):
1463 fileName().moveTo(backupName);
1466 Alert::error(_("Backup failure"),
1467 bformat(_("Cannot create backup file %1$s.\n"
1468 "Please check whether the directory exists and is writable."),
1469 from_utf8(backupName.absFileName())));
1470 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1471 } else if (d->need_format_backup) {
1472 // the original file has been backed up successfully, so we
1473 // will not need to do that again
1474 d->need_format_backup = false;
1478 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1479 // Only do this if tempfile is not in autoremove mode
1482 // If we have no symlink, we can simply rename the temp file.
1483 // Otherwise, we need to copy it so the symlink stays intact.
1484 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1485 savefile.moveTo(fileName()))
1487 // saveCheckSum() was already called by writeFile(), but the
1488 // time stamp is invalidated by copying/moving
1491 if (d->file_format != LYX_FORMAT)
1492 // the file associated with this buffer is now in the current format
1493 d->file_format = LYX_FORMAT;
1496 // else we saved the file, but failed to move it to the right location.
1498 if (needBackup && made_backup && !symlink) {
1499 // the original file was moved to some new location, so it will look
1500 // to the user as if it was deleted. (see bug #9234.) we could try
1501 // to restore it, but that would basically mean trying to do again
1502 // what we just failed to do. better to leave things as they are.
1503 Alert::error(_("Write failure"),
1504 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1505 "But LyX could not move it to:\n %2$s.\n"
1506 "Your original file has been backed up to:\n %3$s"),
1507 from_utf8(savefile.absFileName()),
1508 from_utf8(fileName().absFileName()),
1509 from_utf8(backupName.absFileName())));
1511 // either we did not try to make a backup, or else we tried and failed,
1512 // or else the original file was a symlink, in which case it was copied,
1513 // not moved. so the original file is intact.
1514 Alert::error(_("Write failure"),
1515 bformat(_("Cannot move saved file to:\n %1$s.\n"
1516 "But the file has successfully been saved as:\n %2$s."),
1517 from_utf8(fileName().absFileName()),
1518 from_utf8(savefile.absFileName())));
1524 bool Buffer::writeFile(FileName const & fname) const
1526 if (d->read_only && fname == d->filename)
1529 bool retval = false;
1531 docstring const str = bformat(_("Saving document %1$s..."),
1532 makeDisplayPath(fname.absFileName()));
1535 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1537 if (params().compressed) {
1538 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1539 retval = ofs && write(ofs);
1541 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1542 retval = ofs && write(ofs);
1546 message(str + _(" could not write file!"));
1551 // removeAutosaveFile();
1554 message(str + _(" done."));
1560 docstring Buffer::emergencyWrite()
1562 // No need to save if the buffer has not changed.
1566 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1568 docstring user_message = bformat(
1569 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1571 // We try to save three places:
1572 // 1) Same place as document. Unless it is an unnamed doc.
1574 string s = absFileName();
1577 if (writeFile(FileName(s))) {
1579 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1580 return user_message;
1582 user_message += " " + _("Save failed! Trying again...\n");
1586 // 2) In HOME directory.
1587 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1589 lyxerr << ' ' << s << endl;
1590 if (writeFile(FileName(s))) {
1592 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1593 return user_message;
1596 user_message += " " + _("Save failed! Trying yet again...\n");
1598 // 3) In "/tmp" directory.
1599 // MakeAbsPath to prepend the current
1600 // drive letter on OS/2
1601 s = addName(package().temp_dir().absFileName(), absFileName());
1603 lyxerr << ' ' << s << endl;
1604 if (writeFile(FileName(s))) {
1606 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1607 return user_message;
1610 user_message += " " + _("Save failed! Bummer. Document is lost.");
1613 return user_message;
1617 bool Buffer::write(ostream & ofs) const
1620 // Use the standard "C" locale for file output.
1621 ofs.imbue(locale::classic());
1624 // The top of the file should not be written by params().
1626 // write out a comment in the top of the file
1627 // Important: Keep the version formatting in sync with lyx2lyx and
1628 // tex2lyx (bug 7951)
1629 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1630 << " created this file. For more info see http://www.lyx.org/\n"
1631 << "\\lyxformat " << LYX_FORMAT << "\n"
1632 << "\\begin_document\n";
1634 /// For each author, set 'used' to true if there is a change
1635 /// by this author in the document; otherwise set it to 'false'.
1636 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1637 AuthorList::Authors::const_iterator a_end = params().authors().end();
1638 for (; a_it != a_end; ++a_it)
1639 a_it->setUsed(false);
1641 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1642 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1643 for ( ; it != end; ++it)
1644 it->checkAuthors(params().authors());
1646 // now write out the buffer parameters.
1647 ofs << "\\begin_header\n";
1648 params().writeFile(ofs, this);
1649 ofs << "\\end_header\n";
1652 ofs << "\n\\begin_body\n";
1654 ofs << "\n\\end_body\n";
1656 // Write marker that shows file is complete
1657 ofs << "\\end_document" << endl;
1659 // Shouldn't really be needed....
1662 // how to check if close went ok?
1663 // Following is an attempt... (BE 20001011)
1665 // good() returns false if any error occurred, including some
1666 // formatting error.
1667 // bad() returns true if something bad happened in the buffer,
1668 // which should include file system full errors.
1673 lyxerr << "File was not closed properly." << endl;
1680 bool Buffer::makeLaTeXFile(FileName const & fname,
1681 string const & original_path,
1682 OutputParams const & runparams_in,
1683 OutputWhat output) const
1685 OutputParams runparams = runparams_in;
1687 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1688 // Check here, because the "flavor" is not known in BufferParams::encoding()
1689 // (power users can override this safety measure selecting "utf8-plain").
1690 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1691 && (runparams.encoding->name() != "utf8-plain"))
1692 runparams.encoding = encodings.fromLyXName("ascii");
1694 string const encoding = runparams.encoding->iconvName();
1695 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1698 try { ofs.reset(encoding); }
1699 catch (iconv_codecvt_facet_exception const & e) {
1700 lyxerr << "Caught iconv exception: " << e.what() << endl;
1701 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1702 "verify that the support software for your encoding (%1$s) is "
1703 "properly installed"), from_ascii(encoding)));
1706 if (!openFileWrite(ofs, fname))
1709 ErrorList & errorList = d->errorLists["Export"];
1711 bool failed_export = false;
1714 // make sure we are ready to export
1715 // this needs to be done before we validate
1716 // FIXME Do we need to do this all the time? I.e., in children
1717 // of a master we are exporting?
1719 updateMacroInstances(OutputUpdate);
1722 writeLaTeXSource(os, original_path, runparams, output);
1724 catch (EncodingException const & e) {
1725 docstring const failed(1, e.failed_char);
1727 oss << "0x" << hex << e.failed_char << dec;
1728 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1729 " (code point %2$s)"),
1730 failed, from_utf8(oss.str()));
1731 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1732 "representable in the chosen encoding.\n"
1733 "Changing the document encoding to utf8 could help."),
1734 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1735 failed_export = true;
1737 catch (iconv_codecvt_facet_exception const & e) {
1738 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1740 failed_export = true;
1742 catch (exception const & e) {
1743 errorList.push_back(ErrorItem(_("conversion failed"),
1745 failed_export = true;
1748 lyxerr << "Caught some really weird exception..." << endl;
1752 d->texrow = move(os.texrow());
1756 failed_export = true;
1757 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1760 if (runparams_in.silent)
1764 return !failed_export;
1768 void Buffer::writeLaTeXSource(otexstream & os,
1769 string const & original_path,
1770 OutputParams const & runparams_in,
1771 OutputWhat output) const
1773 // The child documents, if any, shall be already loaded at this point.
1775 OutputParams runparams = runparams_in;
1777 // XeTeX with TeX fonts is only safe with ASCII encoding,
1778 // Check here, because the "flavor" is not known in BufferParams::encoding()
1779 // (power users can override this safety measure selecting "utf8-plain").
1780 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1781 && (runparams.encoding->name() != "utf8-plain"))
1782 runparams.encoding = encodings.fromLyXName("ascii");
1783 // FIXME: when only the current paragraph is shown, this is ignored
1784 // (or not reached) and characters encodable in the current
1785 // encoding are not converted to ASCII-representation.
1787 // If we are compiling a file standalone, even if this is the
1788 // child of some other buffer, let's cut the link here, so the
1789 // file is really independent and no concurring settings from
1790 // the master (e.g. branch state) interfere (see #8100).
1791 if (!runparams.is_child)
1792 d->ignore_parent = true;
1794 // Classify the unicode characters appearing in math insets
1795 BufferEncodings::initUnicodeMath(*this);
1797 // validate the buffer.
1798 LYXERR(Debug::LATEX, " Validating buffer...");
1799 LaTeXFeatures features(*this, params(), runparams);
1801 // This is only set once per document (in master)
1802 if (!runparams.is_child)
1803 runparams.use_polyglossia = features.usePolyglossia();
1804 LYXERR(Debug::LATEX, " Buffer validation done.");
1806 bool const output_preamble =
1807 output == FullSource || output == OnlyPreamble;
1808 bool const output_body =
1809 output == FullSource || output == OnlyBody;
1811 // The starting paragraph of the coming rows is the
1812 // first paragraph of the document. (Asger)
1813 if (output_preamble && runparams.nice) {
1814 os << "%% LyX " << lyx_version << " created this file. "
1815 "For more info, see http://www.lyx.org/.\n"
1816 "%% Do not edit unless you really know what "
1819 LYXERR(Debug::INFO, "lyx document header finished");
1821 // There are a few differences between nice LaTeX and usual files:
1822 // usual files have \batchmode and special input@path to allow
1823 // inclusion of figures specified by an explicitly relative path
1824 // (i.e., a path starting with './' or '../') with either \input or
1825 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1826 // input@path is set when the actual parameter original_path is set.
1827 // This is done for usual tex-file, but not for nice-latex-file.
1828 // (Matthias 250696)
1829 // Note that input@path is only needed for something the user does
1830 // in the preamble, included .tex files or ERT, files included by
1831 // LyX work without it.
1832 if (output_preamble) {
1833 if (!runparams.nice) {
1834 // code for usual, NOT nice-latex-file
1835 os << "\\batchmode\n"; // changed from \nonstopmode
1837 if (!original_path.empty()) {
1839 // We don't know the encoding of inputpath
1840 docstring const inputpath = from_utf8(original_path);
1841 docstring uncodable_glyphs;
1842 Encoding const * const enc = runparams.encoding;
1844 for (size_t n = 0; n < inputpath.size(); ++n) {
1845 if (!enc->encodable(inputpath[n])) {
1846 docstring const glyph(1, inputpath[n]);
1847 LYXERR0("Uncodable character '"
1849 << "' in input path!");
1850 uncodable_glyphs += glyph;
1855 // warn user if we found uncodable glyphs.
1856 if (!uncodable_glyphs.empty()) {
1857 frontend::Alert::warning(
1858 _("Uncodable character in file path"),
1860 _("The path of your document\n"
1862 "contains glyphs that are unknown "
1863 "in the current document encoding "
1864 "(namely %2$s). This may result in "
1865 "incomplete output, unless "
1866 "TEXINPUTS contains the document "
1867 "directory and you don't use "
1868 "explicitly relative paths (i.e., "
1869 "paths starting with './' or "
1870 "'../') in the preamble or in ERT."
1871 "\n\nIn case of problems, choose "
1872 "an appropriate document encoding\n"
1873 "(such as utf8) or change the "
1875 inputpath, uncodable_glyphs));
1878 support::latex_path(original_path);
1879 if (contains(docdir, '#')) {
1880 docdir = subst(docdir, "#", "\\#");
1881 os << "\\catcode`\\#=11"
1882 "\\def\\#{#}\\catcode`\\#=6\n";
1884 if (contains(docdir, '%')) {
1885 docdir = subst(docdir, "%", "\\%");
1886 os << "\\catcode`\\%=11"
1887 "\\def\\%{%}\\catcode`\\%=14\n";
1889 os << "\\makeatletter\n"
1890 << "\\def\\input@path{{"
1892 << "\\makeatother\n";
1896 // get parent macros (if this buffer has a parent) which will be
1897 // written at the document begin further down.
1898 MacroSet parentMacros;
1899 listParentMacros(parentMacros, features);
1901 // Write the preamble
1902 runparams.use_babel = params().writeLaTeX(os, features,
1903 d->filename.onlyPath());
1905 // Biblatex bibliographies are loaded here
1906 if (params().useBiblatex()) {
1907 vector<docstring> const bibfiles =
1908 prepareBibFilePaths(runparams, getBibfilesCache(), true);
1909 for (docstring const & file: bibfiles)
1910 os << "\\addbibresource{" << file << "}\n";
1913 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1914 && !features.hasOnlyPolyglossiaLanguages()) {
1917 vector<string> bll = features.getBabelExclusiveLanguages();
1918 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1921 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1926 blangs = bll.size() > 1 ?
1927 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1928 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1932 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1937 plangs = pll.size() > 1 ?
1938 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1939 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1940 if (!blangs.empty())
1944 frontend::Alert::warning(
1945 _("Incompatible Languages!"),
1947 _("You cannot use the following languages "
1948 "together in one LaTeX document because "
1949 "they require conflicting language packages:\n"
1954 // Japanese might be required only in some children of a document,
1955 // but once required, we must keep use_japanese true.
1956 runparams.use_japanese |= features.isRequired("japanese");
1959 // Restore the parenthood if needed
1960 if (!runparams.is_child)
1961 d->ignore_parent = false;
1966 // mark the beginning of the body to separate it from InPreamble insets
1967 os.texrow().start(TexRow::beginDocument());
1968 os << "\\begin{document}\n";
1970 // mark the start of a new paragraph by simulating a newline,
1971 // so that os.afterParbreak() returns true at document start
1974 // output the parent macros
1975 MacroSet::iterator it = parentMacros.begin();
1976 MacroSet::iterator end = parentMacros.end();
1977 for (; it != end; ++it) {
1978 int num_lines = (*it)->write(os.os(), true);
1979 os.texrow().newlines(num_lines);
1982 } // output_preamble
1984 LYXERR(Debug::INFO, "preamble finished, now the body.");
1987 latexParagraphs(*this, text(), os, runparams);
1989 // Restore the parenthood if needed
1990 if (!runparams.is_child)
1991 d->ignore_parent = false;
1993 // add this just in case after all the paragraphs
1996 if (output_preamble) {
1997 os << "\\end{document}\n";
1998 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2000 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2002 runparams_in.encoding = runparams.encoding;
2004 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2005 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2009 void Buffer::makeDocBookFile(FileName const & fname,
2010 OutputParams const & runparams,
2011 OutputWhat output) const
2013 LYXERR(Debug::LATEX, "makeDocBookFile...");
2016 if (!openFileWrite(ofs, fname))
2019 // make sure we are ready to export
2020 // this needs to be done before we validate
2022 updateMacroInstances(OutputUpdate);
2024 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2028 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2032 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2033 OutputParams const & runparams,
2034 OutputWhat output) const
2036 LaTeXFeatures features(*this, params(), runparams);
2041 DocumentClass const & tclass = params().documentClass();
2042 string const & top_element = tclass.latexname();
2044 bool const output_preamble =
2045 output == FullSource || output == OnlyPreamble;
2046 bool const output_body =
2047 output == FullSource || output == OnlyBody;
2049 if (output_preamble) {
2050 if (runparams.flavor == OutputParams::XML)
2051 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2054 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2057 if (! tclass.class_header().empty())
2058 os << from_ascii(tclass.class_header());
2059 else if (runparams.flavor == OutputParams::XML)
2060 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2061 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2063 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2065 docstring preamble = params().preamble;
2066 if (runparams.flavor != OutputParams::XML ) {
2067 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2068 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2069 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2070 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2073 string const name = runparams.nice
2074 ? changeExtension(absFileName(), ".sgml") : fname;
2075 preamble += features.getIncludedFiles(name);
2076 preamble += features.getLyXSGMLEntities();
2078 if (!preamble.empty()) {
2079 os << "\n [ " << preamble << " ]";
2085 string top = top_element;
2087 if (runparams.flavor == OutputParams::XML)
2088 top += params().language->code();
2090 top += params().language->code().substr(0, 2);
2093 if (!params().options.empty()) {
2095 top += params().options;
2098 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2099 << " file was created by LyX " << lyx_version
2100 << "\n See http://www.lyx.org/ for more information -->\n";
2102 params().documentClass().counters().reset();
2104 sgml::openTag(os, top);
2106 docbookParagraphs(text(), *this, os, runparams);
2107 sgml::closeTag(os, top_element);
2112 void Buffer::makeLyXHTMLFile(FileName const & fname,
2113 OutputParams const & runparams) const
2115 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2118 if (!openFileWrite(ofs, fname))
2121 // make sure we are ready to export
2122 // this has to be done before we validate
2123 updateBuffer(UpdateMaster, OutputUpdate);
2124 updateMacroInstances(OutputUpdate);
2126 writeLyXHTMLSource(ofs, runparams, FullSource);
2130 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2134 void Buffer::writeLyXHTMLSource(odocstream & os,
2135 OutputParams const & runparams,
2136 OutputWhat output) const
2138 LaTeXFeatures features(*this, params(), runparams);
2140 d->bibinfo_.makeCitationLabels(*this);
2142 bool const output_preamble =
2143 output == FullSource || output == OnlyPreamble;
2144 bool const output_body =
2145 output == FullSource || output == OnlyBody || output == IncludedFile;
2147 if (output_preamble) {
2148 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2149 << "<!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"
2150 // FIXME Language should be set properly.
2151 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2153 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2154 // FIXME Presumably need to set this right
2155 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2157 docstring const & doctitle = features.htmlTitle();
2159 << (doctitle.empty() ?
2160 from_ascii("LyX Document") :
2161 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2164 docstring styles = features.getTClassHTMLPreamble();
2165 if (!styles.empty())
2166 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2168 styles = features.getPreambleSnippets().str;
2169 if (!styles.empty())
2170 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2172 // we will collect CSS information in a stream, and then output it
2173 // either here, as part of the header, or else in a separate file.
2174 odocstringstream css;
2175 styles = features.getCSSSnippets();
2176 if (!styles.empty())
2177 css << "/* LyX Provided Styles */\n" << styles << '\n';
2179 styles = features.getTClassHTMLStyles();
2180 if (!styles.empty())
2181 css << "/* Layout-provided Styles */\n" << styles << '\n';
2183 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2184 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2185 if (needfg || needbg) {
2186 css << "\nbody {\n";
2189 << from_ascii(X11hexname(params().fontcolor))
2192 css << " background-color: "
2193 << from_ascii(X11hexname(params().backgroundcolor))
2198 docstring const dstyles = css.str();
2199 if (!dstyles.empty()) {
2200 bool written = false;
2201 if (params().html_css_as_file) {
2202 // open a file for CSS info
2204 string const fcssname = addName(temppath(), "docstyle.css");
2205 FileName const fcssfile = FileName(fcssname);
2206 if (openFileWrite(ocss, fcssfile)) {
2210 // write link to header
2211 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2213 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2216 // we are here if the CSS is supposed to be written to the header
2217 // or if we failed to write it to an external file.
2219 os << "<style type='text/css'>\n"
2228 bool const output_body_tag = (output != IncludedFile);
2229 if (output_body_tag)
2230 os << "<body dir=\"auto\">\n";
2232 if (output != IncludedFile)
2233 // if we're an included file, the counters are in the master.
2234 params().documentClass().counters().reset();
2235 xhtmlParagraphs(text(), *this, xs, runparams);
2236 if (output_body_tag)
2240 if (output_preamble)
2245 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2246 // Other flags: -wall -v0 -x
2247 int Buffer::runChktex()
2251 // get LaTeX-Filename
2252 FileName const path(temppath());
2253 string const name = addName(path.absFileName(), latexName());
2254 string const org_path = filePath();
2256 PathChanger p(path); // path to LaTeX file
2257 message(_("Running chktex..."));
2259 // Generate the LaTeX file if neccessary
2260 OutputParams runparams(¶ms().encoding());
2261 runparams.flavor = OutputParams::LATEX;
2262 runparams.nice = false;
2263 runparams.linelen = lyxrc.plaintext_linelen;
2264 makeLaTeXFile(FileName(name), org_path, runparams);
2267 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2268 int const res = chktex.run(terr); // run chktex
2271 Alert::error(_("chktex failure"),
2272 _("Could not run chktex successfully."));
2274 ErrorList & errlist = d->errorLists["ChkTeX"];
2276 bufferErrors(terr, errlist);
2281 if (runparams.silent)
2282 d->errorLists["ChkTeX"].clear();
2290 void Buffer::validate(LaTeXFeatures & features) const
2292 // Validate the buffer params, but not for included
2293 // files, since they also use the parent buffer's
2295 if (!features.runparams().is_child)
2296 params().validate(features);
2298 for (Paragraph const & p : paragraphs())
2299 p.validate(features);
2301 if (lyxerr.debugging(Debug::LATEX)) {
2302 features.showStruct();
2307 void Buffer::getLabelList(vector<docstring> & list) const
2309 // If this is a child document, use the master's list instead.
2311 masterBuffer()->getLabelList(list);
2316 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2317 Toc::const_iterator toc_it = toc->begin();
2318 Toc::const_iterator end = toc->end();
2319 for (; toc_it != end; ++toc_it) {
2320 if (toc_it->depth() == 0)
2321 list.push_back(toc_it->str());
2326 void Buffer::updateBibfilesCache(UpdateScope scope) const
2328 // FIXME This is probably unnecssary, given where we call this.
2329 // If this is a child document, use the parent's cache instead.
2330 if (parent() && scope != UpdateChildOnly) {
2331 masterBuffer()->updateBibfilesCache();
2335 d->bibfiles_cache_.clear();
2336 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2337 if (it->lyxCode() == BIBTEX_CODE) {
2338 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2339 support::FileNamePairList const bibfiles = inset.getBibFiles();
2340 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2343 } else if (it->lyxCode() == INCLUDE_CODE) {
2344 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2345 Buffer const * const incbuf = inset.getChildBuffer();
2348 support::FileNamePairList const & bibfiles =
2349 incbuf->getBibfilesCache(UpdateChildOnly);
2350 if (!bibfiles.empty()) {
2351 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2357 d->bibfile_cache_valid_ = true;
2358 d->bibinfo_cache_valid_ = false;
2359 d->cite_labels_valid_ = false;
2363 void Buffer::invalidateBibinfoCache() const
2365 d->bibinfo_cache_valid_ = false;
2366 d->cite_labels_valid_ = false;
2367 // also invalidate the cache for the parent buffer
2368 Buffer const * const pbuf = d->parent();
2370 pbuf->invalidateBibinfoCache();
2374 void Buffer::invalidateBibfileCache() const
2376 d->bibfile_cache_valid_ = false;
2377 d->bibinfo_cache_valid_ = false;
2378 d->cite_labels_valid_ = false;
2379 // also invalidate the cache for the parent buffer
2380 Buffer const * const pbuf = d->parent();
2382 pbuf->invalidateBibfileCache();
2386 support::FileNamePairList const & Buffer::getBibfilesCache(UpdateScope scope) const
2388 // FIXME This is probably unnecessary, given where we call this.
2389 // If this is a child document, use the master's cache instead.
2390 Buffer const * const pbuf = masterBuffer();
2391 if (pbuf != this && scope != UpdateChildOnly)
2392 return pbuf->getBibfilesCache();
2394 if (!d->bibfile_cache_valid_)
2395 this->updateBibfilesCache(scope);
2397 return d->bibfiles_cache_;
2401 BiblioInfo const & Buffer::masterBibInfo() const
2403 Buffer const * const tmp = masterBuffer();
2405 return tmp->masterBibInfo();
2410 void Buffer::checkIfBibInfoCacheIsValid() const
2412 // use the master's cache
2413 Buffer const * const tmp = masterBuffer();
2415 tmp->checkIfBibInfoCacheIsValid();
2419 // compare the cached timestamps with the actual ones.
2420 FileNamePairList const & bibfiles_cache = getBibfilesCache();
2421 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2422 FileNamePairList::const_iterator en = bibfiles_cache.end();
2423 for (; ei != en; ++ ei) {
2424 FileName const fn = ei->second;
2425 time_t lastw = fn.lastModified();
2426 time_t prevw = d->bibfile_status_[fn];
2427 if (lastw != prevw) {
2428 d->bibinfo_cache_valid_ = false;
2429 d->cite_labels_valid_ = false;
2430 d->bibfile_status_[fn] = lastw;
2436 void Buffer::reloadBibInfoCache() const
2438 // use the master's cache
2439 Buffer const * const tmp = masterBuffer();
2441 tmp->reloadBibInfoCache();
2445 checkIfBibInfoCacheIsValid();
2446 if (d->bibinfo_cache_valid_)
2449 d->bibinfo_.clear();
2451 d->bibinfo_cache_valid_ = true;
2455 void Buffer::collectBibKeys() const
2457 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2458 it->collectBibKeys(it);
2462 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2464 Buffer const * tmp = masterBuffer();
2465 BiblioInfo & masterbi = (tmp == this) ?
2466 d->bibinfo_ : tmp->d->bibinfo_;
2467 masterbi.mergeBiblioInfo(bi);
2471 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2473 Buffer const * tmp = masterBuffer();
2474 BiblioInfo & masterbi = (tmp == this) ?
2475 d->bibinfo_ : tmp->d->bibinfo_;
2480 void Buffer::makeCitationLabels() const
2482 Buffer const * const master = masterBuffer();
2483 return d->bibinfo_.makeCitationLabels(*master);
2487 bool Buffer::citeLabelsValid() const
2489 return masterBuffer()->d->cite_labels_valid_;
2493 void Buffer::removeBiblioTempFiles() const
2495 // We remove files that contain LaTeX commands specific to the
2496 // particular bibliographic style being used, in order to avoid
2497 // LaTeX errors when we switch style.
2498 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2499 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2500 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2501 aux_file.removeFile();
2502 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2503 bbl_file.removeFile();
2504 // Also for the parent buffer
2505 Buffer const * const pbuf = parent();
2507 pbuf->removeBiblioTempFiles();
2511 bool Buffer::isDepClean(string const & name) const
2513 DepClean::const_iterator const it = d->dep_clean.find(name);
2514 if (it == d->dep_clean.end())
2520 void Buffer::markDepClean(string const & name)
2522 d->dep_clean[name] = true;
2526 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2529 // FIXME? if there is an Buffer LFUN that can be dispatched even
2530 // if internal, put a switch '(cmd.action)' here.
2536 switch (cmd.action()) {
2538 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2539 flag.setOnOff(isReadonly());
2542 // FIXME: There is need for a command-line import.
2543 //case LFUN_BUFFER_IMPORT:
2545 case LFUN_BUFFER_AUTO_SAVE:
2548 case LFUN_BUFFER_EXPORT_CUSTOM:
2549 // FIXME: Nothing to check here?
2552 case LFUN_BUFFER_EXPORT: {
2553 docstring const arg = cmd.argument();
2554 if (arg == "custom") {
2558 string format = (arg.empty() || arg == "default") ?
2559 params().getDefaultOutputFormat() : to_utf8(arg);
2560 size_t pos = format.find(' ');
2561 if (pos != string::npos)
2562 format = format.substr(0, pos);
2563 enable = params().isExportable(format, false);
2565 flag.message(bformat(
2566 _("Don't know how to export to format: %1$s"), arg));
2570 case LFUN_BUFFER_CHKTEX:
2571 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2574 case LFUN_BUILD_PROGRAM:
2575 enable = params().isExportable("program", false);
2578 case LFUN_BRANCH_ACTIVATE:
2579 case LFUN_BRANCH_DEACTIVATE:
2580 case LFUN_BRANCH_MASTER_ACTIVATE:
2581 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2582 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2583 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2584 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2585 : params().branchlist();
2586 docstring const branchName = cmd.argument();
2587 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2591 case LFUN_BRANCH_ADD:
2592 case LFUN_BRANCHES_RENAME:
2593 // if no Buffer is present, then of course we won't be called!
2596 case LFUN_BUFFER_LANGUAGE:
2597 enable = !isReadonly();
2600 case LFUN_BUFFER_VIEW_CACHE:
2601 (d->preview_file_).refresh();
2602 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2605 case LFUN_CHANGES_TRACK:
2606 flag.setEnabled(true);
2607 flag.setOnOff(params().track_changes);
2610 case LFUN_CHANGES_OUTPUT:
2611 flag.setEnabled(true);
2612 flag.setOnOff(params().output_changes);
2615 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2616 flag.setOnOff(params().compressed);
2620 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2621 flag.setOnOff(params().output_sync);
2628 flag.setEnabled(enable);
2633 void Buffer::dispatch(string const & command, DispatchResult & result)
2635 return dispatch(lyxaction.lookupFunc(command), result);
2639 // NOTE We can end up here even if we have no GUI, because we are called
2640 // by LyX::exec to handled command-line requests. So we may need to check
2641 // whether we have a GUI or not. The boolean use_gui holds this information.
2642 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2645 // FIXME? if there is an Buffer LFUN that can be dispatched even
2646 // if internal, put a switch '(cmd.action())' here.
2647 dr.dispatched(false);
2650 string const argument = to_utf8(func.argument());
2651 // We'll set this back to false if need be.
2652 bool dispatched = true;
2653 undo().beginUndoGroup();
2655 switch (func.action()) {
2656 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2657 if (lyxvc().inUse()) {
2658 string log = lyxvc().toggleReadOnly();
2663 setReadonly(!isReadonly());
2666 case LFUN_BUFFER_EXPORT: {
2667 string const format = (argument.empty() || argument == "default") ?
2668 params().getDefaultOutputFormat() : argument;
2669 ExportStatus const status = doExport(format, false);
2670 dr.setError(status != ExportSuccess);
2671 if (status != ExportSuccess)
2672 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2673 from_utf8(format)));
2677 case LFUN_BUILD_PROGRAM: {
2678 ExportStatus const status = doExport("program", true);
2679 dr.setError(status != ExportSuccess);
2680 if (status != ExportSuccess)
2681 dr.setMessage(_("Error generating literate programming code."));
2685 case LFUN_BUFFER_CHKTEX:
2689 case LFUN_BUFFER_EXPORT_CUSTOM: {
2691 string command = split(argument, format_name, ' ');
2692 Format const * format = formats.getFormat(format_name);
2694 lyxerr << "Format \"" << format_name
2695 << "\" not recognized!"
2700 // The name of the file created by the conversion process
2703 // Output to filename
2704 if (format->name() == "lyx") {
2705 string const latexname = latexName(false);
2706 filename = changeExtension(latexname,
2707 format->extension());
2708 filename = addName(temppath(), filename);
2710 if (!writeFile(FileName(filename)))
2714 doExport(format_name, true, filename);
2717 // Substitute $$FName for filename
2718 if (!contains(command, "$$FName"))
2719 command = "( " + command + " ) < $$FName";
2720 command = subst(command, "$$FName", filename);
2722 // Execute the command in the background
2724 call.startscript(Systemcall::DontWait, command,
2725 filePath(), layoutPos());
2729 // FIXME: There is need for a command-line import.
2731 case LFUN_BUFFER_IMPORT:
2736 case LFUN_BUFFER_AUTO_SAVE:
2738 resetAutosaveTimers();
2741 case LFUN_BRANCH_ACTIVATE:
2742 case LFUN_BRANCH_DEACTIVATE:
2743 case LFUN_BRANCH_MASTER_ACTIVATE:
2744 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2745 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2746 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2747 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2750 docstring const branch_name = func.argument();
2751 // the case without a branch name is handled elsewhere
2752 if (branch_name.empty()) {
2756 Branch * branch = buf->params().branchlist().find(branch_name);
2758 LYXERR0("Branch " << branch_name << " does not exist.");
2760 docstring const msg =
2761 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2765 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2766 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2767 if (branch->isSelected() != activate) {
2768 buf->undo().recordUndoBufferParams(CursorData());
2769 branch->setSelected(activate);
2771 dr.screenUpdate(Update::Force);
2772 dr.forceBufferUpdate();
2777 case LFUN_BRANCH_ADD: {
2778 docstring branch_name = func.argument();
2779 if (branch_name.empty()) {
2783 BranchList & branch_list = params().branchlist();
2784 vector<docstring> const branches =
2785 getVectorFromString(branch_name, branch_list.separator());
2787 for (vector<docstring>::const_iterator it = branches.begin();
2788 it != branches.end(); ++it) {
2790 Branch * branch = branch_list.find(branch_name);
2792 LYXERR0("Branch " << branch_name << " already exists.");
2796 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2798 undo().recordUndoBufferParams(CursorData());
2799 branch_list.add(branch_name);
2800 branch = branch_list.find(branch_name);
2801 string const x11hexname = X11hexname(branch->color());
2802 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2803 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2805 dr.screenUpdate(Update::Force);
2813 case LFUN_BRANCHES_RENAME: {
2814 if (func.argument().empty())
2817 docstring const oldname = from_utf8(func.getArg(0));
2818 docstring const newname = from_utf8(func.getArg(1));
2819 InsetIterator it = inset_iterator_begin(inset());
2820 InsetIterator const end = inset_iterator_end(inset());
2821 bool success = false;
2822 for (; it != end; ++it) {
2823 if (it->lyxCode() == BRANCH_CODE) {
2824 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2825 if (ins.branch() == oldname) {
2826 undo().recordUndo(CursorData(it));
2827 ins.rename(newname);
2832 if (it->lyxCode() == INCLUDE_CODE) {
2833 // get buffer of external file
2834 InsetInclude const & ins =
2835 static_cast<InsetInclude const &>(*it);
2836 Buffer * child = ins.getChildBuffer();
2839 child->dispatch(func, dr);
2844 dr.screenUpdate(Update::Force);
2845 dr.forceBufferUpdate();
2850 case LFUN_BUFFER_VIEW_CACHE:
2851 if (!formats.view(*this, d->preview_file_,
2852 d->preview_format_))
2853 dr.setMessage(_("Error viewing the output file."));
2856 case LFUN_CHANGES_TRACK:
2857 if (params().save_transient_properties)
2858 undo().recordUndoBufferParams(CursorData());
2859 params().track_changes = !params().track_changes;
2860 if (!params().track_changes)
2861 dr.forceChangesUpdate();
2864 case LFUN_CHANGES_OUTPUT:
2865 if (params().save_transient_properties)
2866 undo().recordUndoBufferParams(CursorData());
2867 params().output_changes = !params().output_changes;
2868 if (params().output_changes) {
2869 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2870 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2871 LaTeXFeatures::isAvailable("xcolor");
2873 if (!dvipost && !xcolorulem) {
2874 Alert::warning(_("Changes not shown in LaTeX output"),
2875 _("Changes will not be highlighted in LaTeX output, "
2876 "because neither dvipost nor xcolor/ulem are installed.\n"
2877 "Please install these packages or redefine "
2878 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2879 } else if (!xcolorulem) {
2880 Alert::warning(_("Changes not shown in LaTeX output"),
2881 _("Changes will not be highlighted in LaTeX output "
2882 "when using pdflatex, because xcolor and ulem are not installed.\n"
2883 "Please install both packages or redefine "
2884 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2889 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2890 // turn compression on/off
2891 undo().recordUndoBufferParams(CursorData());
2892 params().compressed = !params().compressed;
2895 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2896 undo().recordUndoBufferParams(CursorData());
2897 params().output_sync = !params().output_sync;
2904 dr.dispatched(dispatched);
2905 undo().endUndoGroup();
2909 void Buffer::changeLanguage(Language const * from, Language const * to)
2911 LASSERT(from, return);
2912 LASSERT(to, return);
2914 for_each(par_iterator_begin(),
2916 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2920 bool Buffer::isMultiLingual() const
2922 ParConstIterator end = par_iterator_end();
2923 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2924 if (it->isMultiLingual(params()))
2931 std::set<Language const *> Buffer::getLanguages() const
2933 std::set<Language const *> languages;
2934 getLanguages(languages);
2939 void Buffer::getLanguages(std::set<Language const *> & languages) const
2941 ParConstIterator end = par_iterator_end();
2942 // add the buffer language, even if it's not actively used
2943 languages.insert(language());
2944 // iterate over the paragraphs
2945 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2946 it->getLanguages(languages);
2948 ListOfBuffers clist = getDescendents();
2949 ListOfBuffers::const_iterator cit = clist.begin();
2950 ListOfBuffers::const_iterator const cen = clist.end();
2951 for (; cit != cen; ++cit)
2952 (*cit)->getLanguages(languages);
2956 DocIterator Buffer::getParFromID(int const id) const
2958 Buffer * buf = const_cast<Buffer *>(this);
2960 // This means non-existent
2961 return doc_iterator_end(buf);
2963 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2964 if (it.paragraph().id() == id)
2967 return doc_iterator_end(buf);
2971 bool Buffer::hasParWithID(int const id) const
2973 return !getParFromID(id).atEnd();
2977 ParIterator Buffer::par_iterator_begin()
2979 return ParIterator(doc_iterator_begin(this));
2983 ParIterator Buffer::par_iterator_end()
2985 return ParIterator(doc_iterator_end(this));
2989 ParConstIterator Buffer::par_iterator_begin() const
2991 return ParConstIterator(doc_iterator_begin(this));
2995 ParConstIterator Buffer::par_iterator_end() const
2997 return ParConstIterator(doc_iterator_end(this));
3001 Language const * Buffer::language() const
3003 return params().language;
3007 docstring const Buffer::B_(string const & l10n) const
3009 return params().B_(l10n);
3013 bool Buffer::isClean() const
3015 return d->lyx_clean;
3019 bool Buffer::isChecksumModified() const
3021 LASSERT(d->filename.exists(), return false);
3022 return d->checksum_ != d->filename.checksum();
3026 void Buffer::saveCheckSum() const
3028 FileName const & file = d->filename;
3031 if (file.exists()) {
3032 d->timestamp_ = file.lastModified();
3033 d->checksum_ = file.checksum();
3035 // in the case of save to a new file.
3042 void Buffer::markClean() const
3044 if (!d->lyx_clean) {
3045 d->lyx_clean = true;
3048 // if the .lyx file has been saved, we don't need an
3050 d->bak_clean = true;
3051 d->undo_.markDirty();
3052 clearExternalModification();
3056 void Buffer::setUnnamed(bool flag)
3062 bool Buffer::isUnnamed() const
3069 /// Don't check unnamed, here: isInternal() is used in
3070 /// newBuffer(), where the unnamed flag has not been set by anyone
3071 /// yet. Also, for an internal buffer, there should be no need for
3072 /// retrieving fileName() nor for checking if it is unnamed or not.
3073 bool Buffer::isInternal() const
3075 return d->internal_buffer;
3079 void Buffer::setInternal(bool flag)
3081 d->internal_buffer = flag;
3085 void Buffer::markDirty()
3088 d->lyx_clean = false;
3091 d->bak_clean = false;
3093 DepClean::iterator it = d->dep_clean.begin();
3094 DepClean::const_iterator const end = d->dep_clean.end();
3096 for (; it != end; ++it)
3101 FileName Buffer::fileName() const
3107 string Buffer::absFileName() const
3109 return d->filename.absFileName();
3113 string Buffer::filePath() const
3115 string const abs = d->filename.onlyPath().absFileName();
3118 int last = abs.length() - 1;
3120 return abs[last] == '/' ? abs : abs + '/';
3124 DocFileName Buffer::getReferencedFileName(string const & fn) const
3127 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3128 result.set(fn, filePath());
3130 // filePath() ends with a path separator
3131 FileName const test(filePath() + fn);
3133 result.set(fn, filePath());
3135 result.set(fn, params().origin);
3142 string const Buffer::prepareFileNameForLaTeX(string const & name,
3143 string const & ext, bool nice) const
3145 string const fname = makeAbsPath(name, filePath()).absFileName();
3146 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3152 return to_utf8(makeRelPath(from_utf8(fname),
3153 from_utf8(masterBuffer()->filePath())));
3157 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3158 FileNamePairList const bibfilelist,
3159 bool const add_extension) const
3161 // If we are processing the LaTeX file in a temp directory then
3162 // copy the .bib databases to this temp directory, mangling their
3163 // names in the process. Store this mangled name in the list of
3165 // (We need to do all this because BibTeX *really*, *really*
3166 // can't handle "files with spaces" and Windows users tend to
3167 // use such filenames.)
3168 // Otherwise, store the (maybe absolute) path to the original,
3169 // unmangled database name.
3171 vector<docstring> res;
3173 // determine the export format
3174 string const tex_format = flavor2format(runparams.flavor);
3176 // check for spaces in paths
3177 bool found_space = false;
3179 FileNamePairList::const_iterator it = bibfilelist.begin();
3180 FileNamePairList::const_iterator en = bibfilelist.end();
3181 for (; it != en; ++it) {
3182 string utf8input = to_utf8(it->first);
3184 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3185 FileName const try_in_file =
3186 makeAbsPath(database + ".bib", filePath());
3187 bool const not_from_texmf = try_in_file.isReadableFile();
3189 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3191 // mangledFileName() needs the extension
3192 DocFileName const in_file = DocFileName(try_in_file);
3193 database = removeExtension(in_file.mangledFileName());
3194 FileName const out_file = makeAbsPath(database + ".bib",
3195 masterBuffer()->temppath());
3196 bool const success = in_file.copyTo(out_file);
3198 LYXERR0("Failed to copy '" << in_file
3199 << "' to '" << out_file << "'");
3201 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3202 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3203 if (!isValidLaTeXFileName(database)) {
3204 frontend::Alert::warning(_("Invalid filename"),
3205 _("The following filename will cause troubles "
3206 "when running the exported file through LaTeX: ") +
3207 from_utf8(database));
3209 if (!isValidDVIFileName(database)) {
3210 frontend::Alert::warning(_("Problematic filename for DVI"),
3211 _("The following filename can cause troubles "
3212 "when running the exported file through LaTeX "
3213 "and opening the resulting DVI: ") +
3214 from_utf8(database), true);
3222 docstring const path = from_utf8(latex_path(database));
3224 if (contains(path, ' '))
3227 if (find(res.begin(), res.end(), path) == res.end())
3228 res.push_back(path);
3231 // Check if there are spaces in the path and warn BibTeX users, if so.
3232 // (biber can cope with such paths)
3233 if (!prefixIs(runparams.bibtex_command, "biber")) {
3234 // Post this warning only once.
3235 static bool warned_about_spaces = false;
3236 if (!warned_about_spaces &&
3237 runparams.nice && found_space) {
3238 warned_about_spaces = true;
3239 Alert::warning(_("Export Warning!"),
3240 _("There are spaces in the paths to your BibTeX databases.\n"
3241 "BibTeX will be unable to find them."));
3250 string Buffer::layoutPos() const
3252 return d->layout_position;
3256 void Buffer::setLayoutPos(string const & path)
3259 d->layout_position.clear();
3263 LATTEST(FileName::isAbsolute(path));
3265 d->layout_position =
3266 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3268 if (d->layout_position.empty())
3269 d->layout_position = ".";
3273 bool Buffer::isReadonly() const
3275 return d->read_only;
3279 void Buffer::setParent(Buffer const * buffer)
3281 // Avoids recursive include.
3282 d->setParent(buffer == this ? 0 : buffer);
3287 Buffer const * Buffer::parent() const
3293 ListOfBuffers Buffer::allRelatives() const
3295 ListOfBuffers lb = masterBuffer()->getDescendents();
3296 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3301 Buffer const * Buffer::masterBuffer() const
3303 // FIXME Should be make sure we are not in some kind
3304 // of recursive include? A -> B -> A will crash this.
3305 Buffer const * const pbuf = d->parent();
3309 return pbuf->masterBuffer();
3313 bool Buffer::isChild(Buffer * child) const
3315 return d->children_positions.find(child) != d->children_positions.end();
3319 DocIterator Buffer::firstChildPosition(Buffer const * child)
3321 Impl::BufferPositionMap::iterator it;
3322 it = d->children_positions.find(child);
3323 if (it == d->children_positions.end())
3324 return DocIterator(this);
3329 bool Buffer::hasChildren() const
3331 return !d->children_positions.empty();
3335 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3337 // loop over children
3338 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3339 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3340 for (; it != end; ++it) {
3341 Buffer * child = const_cast<Buffer *>(it->first);
3343 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3344 if (bit != clist.end())
3346 clist.push_back(child);
3348 // there might be grandchildren
3349 child->collectChildren(clist, true);
3354 ListOfBuffers Buffer::getChildren() const
3357 collectChildren(v, false);
3358 // Make sure we have not included ourselves.
3359 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3360 if (bit != v.end()) {
3361 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3368 ListOfBuffers Buffer::getDescendents() const
3371 collectChildren(v, true);
3372 // Make sure we have not included ourselves.
3373 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3374 if (bit != v.end()) {
3375 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3382 template<typename M>
3383 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3388 typename M::const_iterator it = m.lower_bound(x);
3389 if (it == m.begin())
3397 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3398 DocIterator const & pos) const
3400 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3402 // if paragraphs have no macro context set, pos will be empty
3406 // we haven't found anything yet
3407 DocIterator bestPos = owner_->par_iterator_begin();
3408 MacroData const * bestData = 0;
3410 // find macro definitions for name
3411 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3412 if (nameIt != macros.end()) {
3413 // find last definition in front of pos or at pos itself
3414 PositionScopeMacroMap::const_iterator it
3415 = greatest_below(nameIt->second, pos);
3416 if (it != nameIt->second.end()) {
3418 // scope ends behind pos?
3419 if (pos < it->second.scope) {
3420 // Looks good, remember this. If there
3421 // is no external macro behind this,
3422 // we found the right one already.
3423 bestPos = it->first;
3424 bestData = &it->second.macro;
3428 // try previous macro if there is one
3429 if (it == nameIt->second.begin())
3436 // find macros in included files
3437 PositionScopeBufferMap::const_iterator it
3438 = greatest_below(position_to_children, pos);
3439 if (it == position_to_children.end())
3440 // no children before
3444 // do we know something better (i.e. later) already?
3445 if (it->first < bestPos )
3448 // scope ends behind pos?
3449 if (pos < it->second.scope
3450 && (cloned_buffer_ ||
3451 theBufferList().isLoaded(it->second.buffer))) {
3452 // look for macro in external file
3454 MacroData const * data
3455 = it->second.buffer->getMacro(name, false);
3458 bestPos = it->first;
3464 // try previous file if there is one
3465 if (it == position_to_children.begin())
3470 // return the best macro we have found
3475 MacroData const * Buffer::getMacro(docstring const & name,
3476 DocIterator const & pos, bool global) const
3481 // query buffer macros
3482 MacroData const * data = d->getBufferMacro(name, pos);
3486 // If there is a master buffer, query that
3487 Buffer const * const pbuf = d->parent();
3489 d->macro_lock = true;
3490 MacroData const * macro = pbuf->getMacro(
3491 name, *this, false);
3492 d->macro_lock = false;
3498 data = MacroTable::globalMacros().get(name);
3507 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3509 // set scope end behind the last paragraph
3510 DocIterator scope = par_iterator_begin();
3511 scope.pit() = scope.lastpit() + 1;
3513 return getMacro(name, scope, global);
3517 MacroData const * Buffer::getMacro(docstring const & name,
3518 Buffer const & child, bool global) const
3520 // look where the child buffer is included first
3521 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3522 if (it == d->children_positions.end())
3525 // check for macros at the inclusion position
3526 return getMacro(name, it->second, global);
3530 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3532 pit_type const lastpit = it.lastpit();
3534 // look for macros in each paragraph
3535 while (it.pit() <= lastpit) {
3536 Paragraph & par = it.paragraph();
3538 // iterate over the insets of the current paragraph
3539 InsetList const & insets = par.insetList();
3540 InsetList::const_iterator iit = insets.begin();
3541 InsetList::const_iterator end = insets.end();
3542 for (; iit != end; ++iit) {
3543 it.pos() = iit->pos;
3545 // is it a nested text inset?
3546 if (iit->inset->asInsetText()) {
3547 // Inset needs its own scope?
3548 InsetText const * itext = iit->inset->asInsetText();
3549 bool newScope = itext->isMacroScope();
3551 // scope which ends just behind the inset
3552 DocIterator insetScope = it;
3555 // collect macros in inset
3556 it.push_back(CursorSlice(*iit->inset));
3557 updateMacros(it, newScope ? insetScope : scope);
3562 if (iit->inset->asInsetTabular()) {
3563 CursorSlice slice(*iit->inset);
3564 size_t const numcells = slice.nargs();
3565 for (; slice.idx() < numcells; slice.forwardIdx()) {
3566 it.push_back(slice);
3567 updateMacros(it, scope);
3573 // is it an external file?
3574 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3575 // get buffer of external file
3576 InsetInclude const & inset =
3577 static_cast<InsetInclude const &>(*iit->inset);
3579 Buffer * child = inset.getChildBuffer();
3584 // register its position, but only when it is
3585 // included first in the buffer
3586 if (children_positions.find(child) ==
3587 children_positions.end())
3588 children_positions[child] = it;
3590 // register child with its scope
3591 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3595 InsetMath * im = iit->inset->asInsetMath();
3596 if (doing_export && im) {
3597 InsetMathHull * hull = im->asHullInset();
3599 hull->recordLocation(it);
3602 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3606 MathMacroTemplate & macroTemplate =
3607 *iit->inset->asInsetMath()->asMacroTemplate();
3608 MacroContext mc(owner_, it);
3609 macroTemplate.updateToContext(mc);
3612 bool valid = macroTemplate.validMacro();
3613 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3614 // then the BufferView's cursor will be invalid in
3615 // some cases which leads to crashes.
3620 // FIXME (Abdel), I don't understand why we pass 'it' here
3621 // instead of 'macroTemplate' defined above... is this correct?
3622 macros[macroTemplate.name()][it] =
3623 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3633 void Buffer::updateMacros() const
3638 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3640 // start with empty table
3642 d->children_positions.clear();
3643 d->position_to_children.clear();
3645 // Iterate over buffer, starting with first paragraph
3646 // The scope must be bigger than any lookup DocIterator
3647 // later. For the global lookup, lastpit+1 is used, hence
3648 // we use lastpit+2 here.
3649 DocIterator it = par_iterator_begin();
3650 DocIterator outerScope = it;
3651 outerScope.pit() = outerScope.lastpit() + 2;
3652 d->updateMacros(it, outerScope);
3656 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3658 InsetIterator it = inset_iterator_begin(inset());
3659 InsetIterator const end = inset_iterator_end(inset());
3660 for (; it != end; ++it) {
3661 if (it->lyxCode() == BRANCH_CODE) {
3662 InsetBranch & br = static_cast<InsetBranch &>(*it);
3663 docstring const name = br.branch();
3664 if (!from_master && !params().branchlist().find(name))
3665 result.push_back(name);
3666 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3667 result.push_back(name);
3670 if (it->lyxCode() == INCLUDE_CODE) {
3671 // get buffer of external file
3672 InsetInclude const & ins =
3673 static_cast<InsetInclude const &>(*it);
3674 Buffer * child = ins.getChildBuffer();
3677 child->getUsedBranches(result, true);
3680 // remove duplicates
3685 void Buffer::updateMacroInstances(UpdateType utype) const
3687 LYXERR(Debug::MACROS, "updateMacroInstances for "
3688 << d->filename.onlyFileName());
3689 DocIterator it = doc_iterator_begin(this);
3691 DocIterator const end = doc_iterator_end(this);
3692 for (; it != end; it.forwardInset()) {
3693 // look for MathData cells in InsetMathNest insets
3694 InsetMath * minset = it.nextInset()->asInsetMath();
3698 // update macro in all cells of the InsetMathNest
3699 DocIterator::idx_type n = minset->nargs();
3700 MacroContext mc = MacroContext(this, it);
3701 for (DocIterator::idx_type i = 0; i < n; ++i) {
3702 MathData & data = minset->cell(i);
3703 data.updateMacros(0, mc, utype, 0);
3709 void Buffer::listMacroNames(MacroNameSet & macros) const
3714 d->macro_lock = true;
3716 // loop over macro names
3717 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3718 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3719 for (; nameIt != nameEnd; ++nameIt)
3720 macros.insert(nameIt->first);
3722 // loop over children
3723 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3724 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3725 for (; it != end; ++it)
3726 it->first->listMacroNames(macros);
3729 Buffer const * const pbuf = d->parent();
3731 pbuf->listMacroNames(macros);
3733 d->macro_lock = false;
3737 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3739 Buffer const * const pbuf = d->parent();
3744 pbuf->listMacroNames(names);
3747 MacroNameSet::iterator it = names.begin();
3748 MacroNameSet::iterator end = names.end();
3749 for (; it != end; ++it) {
3751 MacroData const * data =
3752 pbuf->getMacro(*it, *this, false);
3754 macros.insert(data);
3756 // we cannot access the original MathMacroTemplate anymore
3757 // here to calls validate method. So we do its work here manually.
3758 // FIXME: somehow make the template accessible here.
3759 if (data->optionals() > 0)
3760 features.require("xargs");
3766 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3769 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3771 RefCache::iterator it = d->ref_cache_.find(label);
3772 if (it != d->ref_cache_.end())
3773 return it->second.second;
3775 static InsetLabel const * dummy_il = 0;
3776 static References const dummy_refs = References();
3777 it = d->ref_cache_.insert(
3778 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3779 return it->second.second;
3783 Buffer::References const & Buffer::references(docstring const & label) const
3785 return const_cast<Buffer *>(this)->getReferenceCache(label);
3789 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3791 References & refs = getReferenceCache(label);
3792 refs.push_back(make_pair(inset, it));
3796 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3798 masterBuffer()->d->ref_cache_[label].first = il;
3802 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3804 return masterBuffer()->d->ref_cache_[label].first;
3808 void Buffer::clearReferenceCache() const
3811 d->ref_cache_.clear();
3815 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3817 //FIXME: This does not work for child documents yet.
3818 reloadBibInfoCache();
3820 // Check if the label 'from' appears more than once
3821 BiblioInfo const & keys = masterBibInfo();
3822 BiblioInfo::const_iterator bit = keys.begin();
3823 BiblioInfo::const_iterator bend = keys.end();
3824 vector<docstring> labels;
3826 for (; bit != bend; ++bit)
3828 labels.push_back(bit->first);
3830 if (count(labels.begin(), labels.end(), from) > 1)
3833 string const paramName = "key";
3834 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3835 if (it->lyxCode() != CITE_CODE)
3837 InsetCommand * inset = it->asInsetCommand();
3838 docstring const oldValue = inset->getParam(paramName);
3839 if (oldValue == from)
3840 inset->setParam(paramName, to);
3844 // returns NULL if id-to-row conversion is unsupported
3845 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3846 pit_type par_begin, pit_type par_end,
3847 OutputWhat output, bool master) const
3849 unique_ptr<TexRow> texrow;
3850 OutputParams runparams(¶ms().encoding());
3851 runparams.nice = true;
3852 runparams.flavor = params().getOutputFlavor(format);
3853 runparams.linelen = lyxrc.plaintext_linelen;
3854 // No side effect of file copying and image conversion
3855 runparams.dryrun = true;
3857 if (output == CurrentParagraph) {
3858 runparams.par_begin = par_begin;
3859 runparams.par_end = par_end;
3860 if (par_begin + 1 == par_end) {
3862 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3866 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3867 convert<docstring>(par_begin),
3868 convert<docstring>(par_end - 1))
3871 // output paragraphs
3872 if (runparams.flavor == OutputParams::LYX) {
3873 Paragraph const & par = text().paragraphs()[par_begin];
3875 depth_type dt = par.getDepth();
3876 par.write(ods, params(), dt);
3877 os << from_utf8(ods.str());
3878 } else if (runparams.flavor == OutputParams::HTML) {
3880 setMathFlavor(runparams);
3881 xhtmlParagraphs(text(), *this, xs, runparams);
3882 } else if (runparams.flavor == OutputParams::TEXT) {
3884 // FIXME Handles only one paragraph, unlike the others.
3885 // Probably should have some routine with a signature like them.
3886 writePlaintextParagraph(*this,
3887 text().paragraphs()[par_begin], os, runparams, dummy);
3888 } else if (params().isDocBook()) {
3889 docbookParagraphs(text(), *this, os, runparams);
3891 // If we are previewing a paragraph, even if this is the
3892 // child of some other buffer, let's cut the link here,
3893 // so that no concurring settings from the master
3894 // (e.g. branch state) interfere (see #8101).
3896 d->ignore_parent = true;
3897 // We need to validate the Buffer params' features here
3898 // in order to know if we should output polyglossia
3899 // macros (instead of babel macros)
3900 LaTeXFeatures features(*this, params(), runparams);
3902 runparams.use_polyglossia = features.usePolyglossia();
3903 // latex or literate
3906 ots.texrow().newlines(2);
3908 latexParagraphs(*this, text(), ots, runparams);
3909 texrow = ots.releaseTexRow();
3911 // Restore the parenthood
3913 d->ignore_parent = false;
3917 if (output == FullSource)
3918 os << _("Preview source code");
3919 else if (output == OnlyPreamble)
3920 os << _("Preview preamble");
3921 else if (output == OnlyBody)
3922 os << _("Preview body");
3924 if (runparams.flavor == OutputParams::LYX) {
3926 if (output == FullSource)
3928 else if (output == OnlyPreamble)
3929 params().writeFile(ods, this);
3930 else if (output == OnlyBody)
3932 os << from_utf8(ods.str());
3933 } else if (runparams.flavor == OutputParams::HTML) {
3934 writeLyXHTMLSource(os, runparams, output);
3935 } else if (runparams.flavor == OutputParams::TEXT) {
3936 if (output == OnlyPreamble) {
3937 os << "% "<< _("Plain text does not have a preamble.");
3939 writePlaintextFile(*this, os, runparams);
3940 } else if (params().isDocBook()) {
3941 writeDocBookSource(os, absFileName(), runparams, output);
3943 // latex or literate
3946 ots.texrow().newlines(2);
3948 runparams.is_child = true;
3949 writeLaTeXSource(ots, string(), runparams, output);
3950 texrow = ots.releaseTexRow();
3957 ErrorList & Buffer::errorList(string const & type) const
3959 return d->errorLists[type];
3963 void Buffer::updateTocItem(std::string const & type,
3964 DocIterator const & dit) const
3967 d->gui_->updateTocItem(type, dit);
3971 void Buffer::structureChanged() const
3974 d->gui_->structureChanged();
3978 void Buffer::errors(string const & err, bool from_master) const
3981 d->gui_->errors(err, from_master);
3985 void Buffer::message(docstring const & msg) const
3988 d->gui_->message(msg);
3992 void Buffer::setBusy(bool on) const
3995 d->gui_->setBusy(on);
3999 void Buffer::updateTitles() const
4002 d->wa_->updateTitles();
4006 void Buffer::resetAutosaveTimers() const
4009 d->gui_->resetAutosaveTimers();
4013 bool Buffer::hasGuiDelegate() const
4019 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4028 class AutoSaveBuffer : public ForkedProcess {
4031 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4032 : buffer_(buffer), fname_(fname) {}
4034 virtual shared_ptr<ForkedProcess> clone() const
4036 return make_shared<AutoSaveBuffer>(*this);
4041 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4042 from_utf8(fname_.absFileName())));
4043 return run(DontWait);
4047 virtual int generateChild();
4049 Buffer const & buffer_;
4054 int AutoSaveBuffer::generateChild()
4056 #if defined(__APPLE__)
4057 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4058 * We should use something else like threads.
4060 * Since I do not know how to determine at run time what is the OS X
4061 * version, I just disable forking altogether for now (JMarc)
4063 pid_t const pid = -1;
4065 // tmp_ret will be located (usually) in /tmp
4066 // will that be a problem?
4067 // Note that this calls ForkedCalls::fork(), so it's
4068 // ok cross-platform.
4069 pid_t const pid = fork();
4070 // If you want to debug the autosave
4071 // you should set pid to -1, and comment out the fork.
4072 if (pid != 0 && pid != -1)
4076 // pid = -1 signifies that lyx was unable
4077 // to fork. But we will do the save
4079 bool failed = false;
4080 TempFile tempfile("lyxautoXXXXXX.lyx");
4081 tempfile.setAutoRemove(false);
4082 FileName const tmp_ret = tempfile.name();
4083 if (!tmp_ret.empty()) {
4084 if (!buffer_.writeFile(tmp_ret))
4086 else if (!tmp_ret.moveTo(fname_))
4092 // failed to write/rename tmp_ret so try writing direct
4093 if (!buffer_.writeFile(fname_)) {
4094 // It is dangerous to do this in the child,
4095 // but safe in the parent, so...
4096 if (pid == -1) // emit message signal.
4097 buffer_.message(_("Autosave failed!"));
4101 if (pid == 0) // we are the child so...
4110 FileName Buffer::getEmergencyFileName() const
4112 return FileName(d->filename.absFileName() + ".emergency");
4116 FileName Buffer::getAutosaveFileName() const
4118 // if the document is unnamed try to save in the backup dir, else
4119 // in the default document path, and as a last try in the filePath,
4120 // which will most often be the temporary directory
4123 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4124 : lyxrc.backupdir_path;
4125 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4128 string const fname = "#" + d->filename.onlyFileName() + "#";
4130 return makeAbsPath(fname, fpath);
4134 void Buffer::removeAutosaveFile() const
4136 FileName const f = getAutosaveFileName();
4142 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4144 FileName const newauto = getAutosaveFileName();
4146 if (newauto != oldauto && oldauto.exists())
4147 if (!oldauto.moveTo(newauto))
4148 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4152 bool Buffer::autoSave() const
4154 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4155 if (buf->d->bak_clean || isReadonly())
4158 message(_("Autosaving current document..."));
4159 buf->d->bak_clean = true;
4161 FileName const fname = getAutosaveFileName();
4162 LASSERT(d->cloned_buffer_, return false);
4164 // If this buffer is cloned, we assume that
4165 // we are running in a separate thread already.
4166 TempFile tempfile("lyxautoXXXXXX.lyx");
4167 tempfile.setAutoRemove(false);
4168 FileName const tmp_ret = tempfile.name();
4169 if (!tmp_ret.empty()) {
4171 // assume successful write of tmp_ret
4172 if (tmp_ret.moveTo(fname))
4175 // failed to write/rename tmp_ret so try writing direct
4176 return writeFile(fname);
4180 void Buffer::setExportStatus(bool e) const
4182 d->doing_export = e;
4183 ListOfBuffers clist = getDescendents();
4184 ListOfBuffers::const_iterator cit = clist.begin();
4185 ListOfBuffers::const_iterator const cen = clist.end();
4186 for (; cit != cen; ++cit)
4187 (*cit)->d->doing_export = e;
4191 bool Buffer::isExporting() const
4193 return d->doing_export;
4197 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4201 return doExport(target, put_in_tempdir, result_file);
4204 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4205 string & result_file) const
4207 bool const update_unincluded =
4208 params().maintain_unincluded_children
4209 && !params().getIncludedChildren().empty();
4211 // (1) export with all included children (omit \includeonly)
4212 if (update_unincluded) {
4213 ExportStatus const status =
4214 doExport(target, put_in_tempdir, true, result_file);
4215 if (status != ExportSuccess)
4218 // (2) export with included children only
4219 return doExport(target, put_in_tempdir, false, result_file);
4223 void Buffer::setMathFlavor(OutputParams & op) const
4225 switch (params().html_math_output) {
4226 case BufferParams::MathML:
4227 op.math_flavor = OutputParams::MathAsMathML;
4229 case BufferParams::HTML:
4230 op.math_flavor = OutputParams::MathAsHTML;
4232 case BufferParams::Images:
4233 op.math_flavor = OutputParams::MathAsImages;
4235 case BufferParams::LaTeX:
4236 op.math_flavor = OutputParams::MathAsLaTeX;
4242 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4243 bool includeall, string & result_file) const
4245 LYXERR(Debug::FILES, "target=" << target);
4246 OutputParams runparams(¶ms().encoding());
4247 string format = target;
4248 string dest_filename;
4249 size_t pos = target.find(' ');
4250 if (pos != string::npos) {
4251 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4252 format = target.substr(0, pos);
4253 if (format == "default")
4254 format = params().getDefaultOutputFormat();
4255 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4256 FileName(dest_filename).onlyPath().createPath();
4257 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4259 MarkAsExporting exporting(this);
4260 string backend_format;
4261 runparams.flavor = OutputParams::LATEX;
4262 runparams.linelen = lyxrc.plaintext_linelen;
4263 runparams.includeall = includeall;
4264 vector<string> backs = params().backends();
4265 Converters converters = theConverters();
4266 bool need_nice_file = false;
4267 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4268 // Get shortest path to format
4269 converters.buildGraph();
4270 Graph::EdgePath path;
4271 for (vector<string>::const_iterator it = backs.begin();
4272 it != backs.end(); ++it) {
4273 Graph::EdgePath p = converters.getPath(*it, format);
4274 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4275 backend_format = *it;
4280 if (!put_in_tempdir) {
4281 // Only show this alert if this is an export to a non-temporary
4282 // file (not for previewing).
4283 Alert::error(_("Couldn't export file"), bformat(
4284 _("No information for exporting the format %1$s."),
4285 formats.prettyName(format)));
4287 return ExportNoPathToFormat;
4289 runparams.flavor = converters.getFlavor(path, this);
4290 Graph::EdgePath::const_iterator it = path.begin();
4291 Graph::EdgePath::const_iterator en = path.end();
4292 for (; it != en; ++it)
4293 if (theConverters().get(*it).nice()) {
4294 need_nice_file = true;
4299 backend_format = format;
4300 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4301 // FIXME: Don't hardcode format names here, but use a flag
4302 if (backend_format == "pdflatex")
4303 runparams.flavor = OutputParams::PDFLATEX;
4304 else if (backend_format == "luatex")
4305 runparams.flavor = OutputParams::LUATEX;
4306 else if (backend_format == "dviluatex")
4307 runparams.flavor = OutputParams::DVILUATEX;
4308 else if (backend_format == "xetex")
4309 runparams.flavor = OutputParams::XETEX;
4312 string filename = latexName(false);
4313 filename = addName(temppath(), filename);
4314 filename = changeExtension(filename,
4315 formats.extension(backend_format));
4316 LYXERR(Debug::FILES, "filename=" << filename);
4318 // Plain text backend
4319 if (backend_format == "text") {
4320 runparams.flavor = OutputParams::TEXT;
4321 writePlaintextFile(*this, FileName(filename), runparams);
4324 else if (backend_format == "xhtml") {
4325 runparams.flavor = OutputParams::HTML;
4326 setMathFlavor(runparams);
4327 makeLyXHTMLFile(FileName(filename), runparams);
4328 } else if (backend_format == "lyx")
4329 writeFile(FileName(filename));
4331 else if (params().isDocBook()) {
4332 runparams.nice = !put_in_tempdir;
4333 makeDocBookFile(FileName(filename), runparams);
4336 else if (backend_format == format || need_nice_file) {
4337 runparams.nice = true;
4338 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4339 if (d->cloned_buffer_)
4340 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4343 } else if (!lyxrc.tex_allows_spaces
4344 && contains(filePath(), ' ')) {
4345 Alert::error(_("File name error"),
4346 _("The directory path to the document cannot contain spaces."));
4347 return ExportTexPathHasSpaces;
4349 runparams.nice = false;
4350 bool const success = makeLaTeXFile(
4351 FileName(filename), filePath(), runparams);
4352 if (d->cloned_buffer_)
4353 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4358 string const error_type = (format == "program")
4359 ? "Build" : params().bufferFormat();
4360 ErrorList & error_list = d->errorLists[error_type];
4361 string const ext = formats.extension(format);
4362 FileName const tmp_result_file(changeExtension(filename, ext));
4363 bool const success = converters.convert(this, FileName(filename),
4364 tmp_result_file, FileName(absFileName()), backend_format, format,
4367 // Emit the signal to show the error list or copy it back to the
4368 // cloned Buffer so that it can be emitted afterwards.
4369 if (format != backend_format) {
4370 if (runparams.silent)
4372 else if (d->cloned_buffer_)
4373 d->cloned_buffer_->d->errorLists[error_type] =
4374 d->errorLists[error_type];
4377 // also to the children, in case of master-buffer-view
4378 ListOfBuffers clist = getDescendents();
4379 ListOfBuffers::const_iterator cit = clist.begin();
4380 ListOfBuffers::const_iterator const cen = clist.end();
4381 for (; cit != cen; ++cit) {
4382 if (runparams.silent)
4383 (*cit)->d->errorLists[error_type].clear();
4384 else if (d->cloned_buffer_) {
4385 // Enable reverse search by copying back the
4386 // texrow object to the cloned buffer.
4387 // FIXME: this is not thread safe.
4388 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4389 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4390 (*cit)->d->errorLists[error_type];
4392 (*cit)->errors(error_type, true);
4396 if (d->cloned_buffer_) {
4397 // Enable reverse dvi or pdf to work by copying back the texrow
4398 // object to the cloned buffer.
4399 // FIXME: There is a possibility of concurrent access to texrow
4400 // here from the main GUI thread that should be securized.
4401 d->cloned_buffer_->d->texrow = d->texrow;
4402 string const error_type = params().bufferFormat();
4403 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4407 if (put_in_tempdir) {
4408 result_file = tmp_result_file.absFileName();
4409 return success ? ExportSuccess : ExportConverterError;
4412 if (dest_filename.empty())
4413 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4415 result_file = dest_filename;
4416 // We need to copy referenced files (e. g. included graphics
4417 // if format == "dvi") to the result dir.
4418 vector<ExportedFile> const files =
4419 runparams.exportdata->externalFiles(format);
4420 string const dest = runparams.export_folder.empty() ?
4421 onlyPath(result_file) : runparams.export_folder;
4422 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4423 : force_overwrite == ALL_FILES;
4424 CopyStatus status = use_force ? FORCE : SUCCESS;
4426 vector<ExportedFile>::const_iterator it = files.begin();
4427 vector<ExportedFile>::const_iterator const en = files.end();
4428 for (; it != en && status != CANCEL; ++it) {
4429 string const fmt = formats.getFormatFromFile(it->sourceName);
4430 string fixedName = it->exportName;
4431 if (!runparams.export_folder.empty()) {
4432 // Relative pathnames starting with ../ will be sanitized
4433 // if exporting to a different folder
4434 while (fixedName.substr(0, 3) == "../")
4435 fixedName = fixedName.substr(3, fixedName.length() - 3);
4437 FileName fixedFileName = makeAbsPath(fixedName, dest);
4438 fixedFileName.onlyPath().createPath();
4439 status = copyFile(fmt, it->sourceName,
4441 it->exportName, status == FORCE,
4442 runparams.export_folder.empty());
4445 if (status == CANCEL) {
4446 message(_("Document export cancelled."));
4447 return ExportCancel;
4450 if (tmp_result_file.exists()) {
4451 // Finally copy the main file
4452 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4453 : force_overwrite != NO_FILES;
4454 if (status == SUCCESS && use_force)
4456 status = copyFile(format, tmp_result_file,
4457 FileName(result_file), result_file,
4459 if (status == CANCEL) {
4460 message(_("Document export cancelled."));
4461 return ExportCancel;
4463 message(bformat(_("Document exported as %1$s "
4465 formats.prettyName(format),
4466 makeDisplayPath(result_file)));
4469 // This must be a dummy converter like fax (bug 1888)
4470 message(bformat(_("Document exported as %1$s"),
4471 formats.prettyName(format)));
4474 return success ? ExportSuccess : ExportConverterError;
4478 Buffer::ExportStatus Buffer::preview(string const & format) const
4480 bool const update_unincluded =
4481 params().maintain_unincluded_children
4482 && !params().getIncludedChildren().empty();
4483 return preview(format, update_unincluded);
4487 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4489 MarkAsExporting exporting(this);
4491 // (1) export with all included children (omit \includeonly)
4493 ExportStatus const status = doExport(format, true, true, result_file);
4494 if (status != ExportSuccess)
4497 // (2) export with included children only
4498 ExportStatus const status = doExport(format, true, false, result_file);
4499 FileName const previewFile(result_file);
4501 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4502 theimpl->preview_file_ = previewFile;
4503 theimpl->preview_format_ = format;
4504 theimpl->preview_error_ = (status != ExportSuccess);
4506 if (status != ExportSuccess)
4509 if (previewFile.exists())
4510 return formats.view(*this, previewFile, format) ?
4511 PreviewSuccess : PreviewError;
4513 // Successful export but no output file?
4514 // Probably a bug in error detection.
4515 LATTEST(status != ExportSuccess);
4520 Buffer::ReadStatus Buffer::extractFromVC()
4522 bool const found = LyXVC::file_not_found_hook(d->filename);
4524 return ReadFileNotFound;
4525 if (!d->filename.isReadableFile())
4531 Buffer::ReadStatus Buffer::loadEmergency()
4533 FileName const emergencyFile = getEmergencyFileName();
4534 if (!emergencyFile.exists()
4535 || emergencyFile.lastModified() <= d->filename.lastModified())
4536 return ReadFileNotFound;
4538 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4539 docstring const text = bformat(_("An emergency save of the document "
4540 "%1$s exists.\n\nRecover emergency save?"), file);
4542 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4543 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4549 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4550 bool const success = (ret_llf == ReadSuccess);
4553 Alert::warning(_("File is read-only"),
4554 bformat(_("An emergency file is successfully loaded, "
4555 "but the original file %1$s is marked read-only. "
4556 "Please make sure to save the document as a different "
4557 "file."), from_utf8(d->filename.absFileName())));
4560 lyxvc().file_found_hook(d->filename);
4561 str = _("Document was successfully recovered.");
4563 str = _("Document was NOT successfully recovered.");
4564 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4565 makeDisplayPath(emergencyFile.absFileName()));
4567 int const del_emerg =
4568 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4569 _("&Remove"), _("&Keep"));
4570 if (del_emerg == 0) {
4571 emergencyFile.removeFile();
4573 Alert::warning(_("Emergency file deleted"),
4574 _("Do not forget to save your file now!"), true);
4576 return success ? ReadSuccess : ReadEmergencyFailure;
4579 int const del_emerg =
4580 Alert::prompt(_("Delete emergency file?"),
4581 _("Remove emergency file now?"), 1, 1,
4582 _("&Remove"), _("&Keep"));
4584 emergencyFile.removeFile();
4585 return ReadOriginal;
4595 Buffer::ReadStatus Buffer::loadAutosave()
4597 // Now check if autosave file is newer.
4598 FileName const autosaveFile = getAutosaveFileName();
4599 if (!autosaveFile.exists()
4600 || autosaveFile.lastModified() <= d->filename.lastModified())
4601 return ReadFileNotFound;
4603 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4604 docstring const text = bformat(_("The backup of the document %1$s "
4605 "is newer.\n\nLoad the backup instead?"), file);
4606 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4607 _("&Load backup"), _("Load &original"), _("&Cancel"));
4612 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4613 // the file is not saved if we load the autosave file.
4614 if (ret_llf == ReadSuccess) {
4616 Alert::warning(_("File is read-only"),
4617 bformat(_("A backup file is successfully loaded, "
4618 "but the original file %1$s is marked read-only. "
4619 "Please make sure to save the document as a "
4621 from_utf8(d->filename.absFileName())));
4624 lyxvc().file_found_hook(d->filename);
4627 return ReadAutosaveFailure;
4630 // Here we delete the autosave
4631 autosaveFile.removeFile();
4632 return ReadOriginal;
4640 Buffer::ReadStatus Buffer::loadLyXFile()
4642 if (!d->filename.isReadableFile()) {
4643 ReadStatus const ret_rvc = extractFromVC();
4644 if (ret_rvc != ReadSuccess)
4648 ReadStatus const ret_re = loadEmergency();
4649 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4652 ReadStatus const ret_ra = loadAutosave();
4653 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4656 return loadThisLyXFile(d->filename);
4660 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4662 return readFile(fn);
4666 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4668 for (auto const & err : terr) {
4669 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4670 int errorRow = err.error_in_line;
4671 Buffer const * buf = 0;
4673 if (err.child_name.empty())
4674 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4676 // The error occurred in a child
4677 for (Buffer const * child : getDescendents()) {
4678 string const child_name =
4679 DocFileName(changeExtension(child->absFileName(), "tex")).
4681 if (err.child_name != child_name)
4683 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4684 if (!TexRow::isNone(start)) {
4685 buf = d->cloned_buffer_
4686 ? child->d->cloned_buffer_->d->owner_
4693 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4699 void Buffer::setBuffersForInsets() const
4701 inset().setBuffer(const_cast<Buffer &>(*this));
4705 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4707 LBUFERR(!text().paragraphs().empty());
4709 // Use the master text class also for child documents
4710 Buffer const * const master = masterBuffer();
4711 DocumentClass const & textclass = master->params().documentClass();
4713 // do this only if we are the top-level Buffer
4714 if (master == this) {
4715 textclass.counters().reset(from_ascii("bibitem"));
4716 reloadBibInfoCache();
4719 // keep the buffers to be children in this set. If the call from the
4720 // master comes back we can see which of them were actually seen (i.e.
4721 // via an InsetInclude). The remaining ones in the set need still be updated.
4722 static std::set<Buffer const *> bufToUpdate;
4723 if (scope == UpdateMaster) {
4724 // If this is a child document start with the master
4725 if (master != this) {
4726 bufToUpdate.insert(this);
4727 master->updateBuffer(UpdateMaster, utype);
4728 // If the master buffer has no gui associated with it, then the TocModel is
4729 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4730 // (bug 5699). The same happens if the master buffer is open in a different
4731 // window. This test catches both possibilities.
4732 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4733 // There remains a problem here: If there is another child open in yet a third
4734 // window, that TOC is not updated. So some more general solution is needed at
4736 if (master->d->gui_ != d->gui_)
4739 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4740 if (bufToUpdate.find(this) == bufToUpdate.end())
4744 // start over the counters in the master
4745 textclass.counters().reset();
4748 // update will be done below for this buffer
4749 bufToUpdate.erase(this);
4751 // update all caches
4752 clearReferenceCache();
4754 setChangesPresent(false);
4756 Buffer & cbuf = const_cast<Buffer &>(*this);
4759 ParIterator parit = cbuf.par_iterator_begin();
4760 updateBuffer(parit, utype);
4763 /// Update the tocBackend for any buffer. The outliner uses the master's,
4764 /// and the navigation menu uses the child's.
4765 cbuf.tocBackend().update(true, utype);
4770 d->bibinfo_cache_valid_ = true;
4771 d->cite_labels_valid_ = true;
4772 if (scope == UpdateMaster)
4773 cbuf.structureChanged();
4777 static depth_type getDepth(DocIterator const & it)
4779 depth_type depth = 0;
4780 for (size_t i = 0 ; i < it.depth() ; ++i)
4781 if (!it[i].inset().inMathed())
4782 depth += it[i].paragraph().getDepth() + 1;
4783 // remove 1 since the outer inset does not count
4784 // we should have at least one non-math inset, so
4785 // depth should nevery be 0. but maybe it is worth
4786 // marking this, just in case.
4788 // coverity[INTEGER_OVERFLOW]
4792 static depth_type getItemDepth(ParIterator const & it)
4794 Paragraph const & par = *it;
4795 LabelType const labeltype = par.layout().labeltype;
4797 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4800 // this will hold the lowest depth encountered up to now.
4801 depth_type min_depth = getDepth(it);
4802 ParIterator prev_it = it;
4805 --prev_it.top().pit();
4807 // start of nested inset: go to outer par
4809 if (prev_it.empty()) {
4810 // start of document: nothing to do
4815 // We search for the first paragraph with same label
4816 // that is not more deeply nested.
4817 Paragraph & prev_par = *prev_it;
4818 depth_type const prev_depth = getDepth(prev_it);
4819 if (labeltype == prev_par.layout().labeltype) {
4820 if (prev_depth < min_depth)
4821 return prev_par.itemdepth + 1;
4822 if (prev_depth == min_depth)
4823 return prev_par.itemdepth;
4825 min_depth = min(min_depth, prev_depth);
4826 // small optimization: if we are at depth 0, we won't
4827 // find anything else
4828 if (prev_depth == 0)
4834 static bool needEnumCounterReset(ParIterator const & it)
4836 Paragraph const & par = *it;
4837 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4838 depth_type const cur_depth = par.getDepth();
4839 ParIterator prev_it = it;
4840 while (prev_it.pit()) {
4841 --prev_it.top().pit();
4842 Paragraph const & prev_par = *prev_it;
4843 if (prev_par.getDepth() <= cur_depth)
4844 return prev_par.layout().name() != par.layout().name();
4846 // start of nested inset: reset
4851 // set the label of a paragraph. This includes the counters.
4852 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4854 BufferParams const & bp = owner_->masterBuffer()->params();
4855 DocumentClass const & textclass = bp.documentClass();
4856 Paragraph & par = it.paragraph();
4857 Layout const & layout = par.layout();
4858 Counters & counters = textclass.counters();
4860 if (par.params().startOfAppendix()) {
4861 // We want to reset the counter corresponding to toplevel sectioning
4862 Layout const & lay = textclass.getTOCLayout();
4863 docstring const cnt = lay.counter;
4865 counters.reset(cnt);
4866 counters.appendix(true);
4868 par.params().appendix(counters.appendix());
4870 // Compute the item depth of the paragraph
4871 par.itemdepth = getItemDepth(it);
4873 if (layout.margintype == MARGIN_MANUAL) {
4874 if (par.params().labelWidthString().empty())
4875 par.params().labelWidthString(par.expandLabel(layout, bp));
4876 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4877 // we do not need to do anything here, since the empty case is
4878 // handled during export.
4880 par.params().labelWidthString(docstring());
4883 switch(layout.labeltype) {
4884 case LABEL_ITEMIZE: {
4885 // At some point of time we should do something more
4886 // clever here, like:
4887 // par.params().labelString(
4888 // bp.user_defined_bullet(par.itemdepth).getText());
4889 // for now, use a simple hardcoded label
4890 docstring itemlabel;
4891 switch (par.itemdepth) {
4893 itemlabel = char_type(0x2022);
4896 itemlabel = char_type(0x2013);
4899 itemlabel = char_type(0x2217);
4902 itemlabel = char_type(0x2219); // or 0x00b7
4905 par.params().labelString(itemlabel);
4909 case LABEL_ENUMERATE: {
4910 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4912 switch (par.itemdepth) {
4921 enumcounter += "iv";
4924 // not a valid enumdepth...
4928 // Increase the master counter?
4929 if (layout.stepmastercounter && needEnumCounterReset(it))
4930 counters.stepMaster(enumcounter, utype);
4932 // Maybe we have to reset the enumeration counter.
4933 if (!layout.resumecounter && needEnumCounterReset(it))
4934 counters.reset(enumcounter);
4935 counters.step(enumcounter, utype);
4937 string const & lang = par.getParLanguage(bp)->code();
4938 par.params().labelString(counters.theCounter(enumcounter, lang));
4943 case LABEL_SENSITIVE: {
4944 string const & type = counters.current_float();
4945 docstring full_label;
4947 full_label = owner_->B_("Senseless!!! ");
4949 docstring name = owner_->B_(textclass.floats().getType(type).name());
4950 if (counters.hasCounter(from_utf8(type))) {
4951 string const & lang = par.getParLanguage(bp)->code();
4952 counters.step(from_utf8(type), utype);
4953 full_label = bformat(from_ascii("%1$s %2$s:"),
4955 counters.theCounter(from_utf8(type), lang));
4957 full_label = bformat(from_ascii("%1$s #:"), name);
4959 par.params().labelString(full_label);
4963 case LABEL_NO_LABEL:
4964 par.params().labelString(docstring());
4968 case LABEL_CENTERED:
4969 case LABEL_STATIC: {
4970 docstring const & lcounter = layout.counter;
4971 if (!lcounter.empty()) {
4972 if (layout.toclevel <= bp.secnumdepth
4973 && (layout.latextype != LATEX_ENVIRONMENT
4974 || it.text()->isFirstInSequence(it.pit()))) {
4975 if (counters.hasCounter(lcounter))
4976 counters.step(lcounter, utype);
4977 par.params().labelString(par.expandLabel(layout, bp));
4979 par.params().labelString(docstring());
4981 par.params().labelString(par.expandLabel(layout, bp));
4987 par.params().labelString(par.expandLabel(layout, bp));
4992 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4994 // LASSERT: Is it safe to continue here, or should we just return?
4995 LASSERT(parit.pit() == 0, /**/);
4997 // Set the position of the text in the buffer to be able
4998 // to resolve macros in it.
4999 parit.text()->setMacrocontextPosition(parit);
5001 depth_type maxdepth = 0;
5002 pit_type const lastpit = parit.lastpit();
5003 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5004 // reduce depth if necessary
5005 if (parit->params().depth() > maxdepth) {
5006 /** FIXME: this function is const, but
5007 * nevertheless it modifies the buffer. To be
5008 * cleaner, one should modify the buffer in
5009 * another function, which is actually
5010 * non-const. This would however be costly in
5011 * terms of code duplication.
5013 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5014 parit->params().depth(maxdepth);
5016 maxdepth = parit->getMaxDepthAfter();
5018 if (utype == OutputUpdate) {
5019 // track the active counters
5020 // we have to do this for the master buffer, since the local
5021 // buffer isn't tracking anything.
5022 masterBuffer()->params().documentClass().counters().
5023 setActiveLayout(parit->layout());
5026 // set the counter for this paragraph
5027 d->setLabel(parit, utype);
5029 // update change-tracking flag
5030 parit->addChangesToBuffer(*this);
5033 InsetList::const_iterator iit = parit->insetList().begin();
5034 InsetList::const_iterator end = parit->insetList().end();
5035 for (; iit != end; ++iit) {
5036 parit.pos() = iit->pos;
5037 iit->inset->updateBuffer(parit, utype);
5043 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5044 WordLangTuple & word_lang, docstring_list & suggestions) const
5048 suggestions.clear();
5049 word_lang = WordLangTuple();
5050 bool const to_end = to.empty();
5051 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5052 // OK, we start from here.
5053 for (; from != end; from.forwardPos()) {
5054 // This skips all insets with spell check disabled.
5055 while (!from.allowSpellCheck()) {
5059 // If from is at the end of the document (which is possible
5060 // when "from" was changed above) LyX will crash later otherwise.
5061 if (from.atEnd() || (!to_end && from >= end))
5064 from.paragraph().spellCheck();
5065 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5066 if (SpellChecker::misspelled(res)) {
5070 // Do not increase progress when from == to, otherwise the word
5071 // count will be wrong.
5081 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5083 bool inword = false;
5088 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5089 if (!dit.inTexted()) {
5094 Paragraph const & par = dit.paragraph();
5095 pos_type const pos = dit.pos();
5097 // Copied and adapted from isWordSeparator() in Paragraph
5098 if (pos == dit.lastpos()) {
5101 Inset const * ins = par.getInset(pos);
5102 if (ins && skipNoOutput && !ins->producesOutput()) {
5105 // stop if end of range was skipped
5106 if (!to.atEnd() && dit >= to)
5109 } else if (!par.isDeleted(pos)) {
5110 if (par.isWordSeparator(pos))
5116 if (ins && ins->isLetter())
5118 else if (ins && ins->isSpace())
5121 char_type const c = par.getChar(pos);
5122 if (isPrintableNonspace(c))
5124 else if (isSpace(c))
5134 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5136 d->updateStatistics(from, to, skipNoOutput);
5140 int Buffer::wordCount() const
5142 return d->wordCount();
5146 int Buffer::charCount(bool with_blanks) const
5148 return d->charCount(with_blanks);
5152 Buffer::ReadStatus Buffer::reload()
5155 // c.f. bug http://www.lyx.org/trac/ticket/6587
5156 removeAutosaveFile();
5157 // e.g., read-only status could have changed due to version control
5158 d->filename.refresh();
5159 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5161 // clear parent. this will get reset if need be.
5163 ReadStatus const status = loadLyXFile();
5164 if (status == ReadSuccess) {
5169 message(bformat(_("Document %1$s reloaded."), disp_fn));
5172 message(bformat(_("Could not reload document %1$s."), disp_fn));
5182 bool Buffer::saveAs(FileName const & fn)
5184 FileName const old_name = fileName();
5185 FileName const old_auto = getAutosaveFileName();
5186 bool const old_unnamed = isUnnamed();
5187 bool success = true;
5188 d->old_position = filePath();
5195 // bring the autosave file with us, just in case.
5196 moveAutosaveFile(old_auto);
5197 // validate version control data and
5198 // correct buffer title
5199 lyxvc().file_found_hook(fileName());
5201 // the file has now been saved to the new location.
5202 // we need to check that the locations of child buffers
5204 checkChildBuffers();
5205 checkMasterBuffer();
5208 // reset the old filename and unnamed state
5209 setFileName(old_name);
5210 setUnnamed(old_unnamed);
5214 d->old_position.clear();
5219 void Buffer::checkChildBuffers()
5221 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5222 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5223 for (; it != en; ++it) {
5224 DocIterator dit = it->second;
5225 Buffer * cbuf = const_cast<Buffer *>(it->first);
5226 if (!cbuf || !theBufferList().isLoaded(cbuf))
5228 Inset * inset = dit.nextInset();
5229 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5230 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5231 docstring const & incfile = inset_inc->getParam("filename");
5232 string oldloc = cbuf->absFileName();
5233 string newloc = makeAbsPath(to_utf8(incfile),
5234 onlyPath(absFileName())).absFileName();
5235 if (oldloc == newloc)
5237 // the location of the child file is incorrect.
5239 inset_inc->setChildBuffer(0);
5241 // invalidate cache of children
5242 d->children_positions.clear();
5243 d->position_to_children.clear();
5247 // If a child has been saved under a different name/path, it might have been
5248 // orphaned. Therefore the master needs to be reset (bug 8161).
5249 void Buffer::checkMasterBuffer()
5251 Buffer const * const master = masterBuffer();
5255 // necessary to re-register the child (bug 5873)
5256 // FIXME: clean up updateMacros (here, only
5257 // child registering is needed).
5258 master->updateMacros();
5259 // (re)set master as master buffer, but only
5260 // if we are a real child
5261 if (master->isChild(this))
5268 string Buffer::includedFilePath(string const & name, string const & ext) const
5270 if (d->old_position.empty() ||
5271 equivalent(FileName(d->old_position), FileName(filePath())))
5274 bool isabsolute = FileName::isAbsolute(name);
5275 // both old_position and filePath() end with a path separator
5276 string absname = isabsolute ? name : d->old_position + name;
5278 // if old_position is set to origin, we need to do the equivalent of
5279 // getReferencedFileName() (see readDocument())
5280 if (!isabsolute && d->old_position == params().origin) {
5281 FileName const test(addExtension(filePath() + name, ext));
5283 absname = filePath() + name;
5286 if (!FileName(addExtension(absname, ext)).exists())
5290 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5292 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5293 from_utf8(filePath())));
5297 void Buffer::setChangesPresent(bool b) const
5299 d->tracked_changes_present_ = b;
5303 bool Buffer::areChangesPresent() const
5305 return d->tracked_changes_present_;
5309 void Buffer::updateChangesPresent() const
5311 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5312 setChangesPresent(false);
5313 ParConstIterator it = par_iterator_begin();
5314 ParConstIterator const end = par_iterator_end();
5315 for (; !areChangesPresent() && it != end; ++it)
5316 it->addChangesToBuffer(*this);
5320 void Buffer::Impl::refreshFileMonitor()
5322 if (file_monitor_ && file_monitor_->filename() == filename.absFileName())
5323 return file_monitor_->refresh();
5325 // The previous file monitor is invalid
5326 // This also destroys the previous file monitor and all its connections
5327 file_monitor_ = FileSystemWatcher::monitor(filename);
5328 fileExternallyModified(false);
5329 // file_monitor_ will be destroyed with *this, so it is not going to call a
5330 // destroyed object method.
5331 file_monitor_->connect([this](){ fileExternallyModified(true); });
5335 void Buffer::Impl::fileExternallyModified(bool modified) const
5338 lyx_clean = bak_clean = false;
5339 externally_modified_ = modified;
5341 wa_->updateTitles();
5345 bool Buffer::notifiesExternalModification() const
5347 return d->isExternallyModified();
5351 void Buffer::clearExternalModification() const
5353 d->fileExternallyModified(false);