3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
60 #include "texstream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/GraphicsCache.h"
83 #include "graphics/PreviewLoader.h"
85 #include "frontends/alert.h"
86 #include "frontends/Delegates.h"
87 #include "frontends/WorkAreaManager.h"
89 #include "support/lassert.h"
90 #include "support/convert.h"
91 #include "support/debug.h"
92 #include "support/docstring_list.h"
93 #include "support/ExceptionMessage.h"
94 #include "support/FileMonitor.h"
95 #include "support/FileName.h"
96 #include "support/FileNameList.h"
97 #include "support/filetools.h"
98 #include "support/ForkedCalls.h"
99 #include "support/gettext.h"
100 #include "support/gzstream.h"
101 #include "support/lstrings.h"
102 #include "support/lyxalgo.h"
103 #include "support/mutex.h"
104 #include "support/os.h"
105 #include "support/Package.h"
106 #include "support/PathChanger.h"
107 #include "support/Systemcall.h"
108 #include "support/TempFile.h"
109 #include "support/textutils.h"
110 #include "support/types.h"
112 #include "support/bind.h"
124 using namespace lyx::support;
125 using namespace lyx::graphics;
129 namespace Alert = frontend::Alert;
130 namespace os = support::os;
134 int const LYX_FORMAT = LYX_FORMAT_LYX;
136 typedef map<string, bool> DepClean;
137 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
142 // A storehouse for the cloned buffers.
143 list<CloneList *> cloned_buffers;
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
153 delete preview_loader_;
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this an unnamed file (New...)?
195 /// is this an internal bufffer?
196 bool internal_buffer;
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
210 /// original format of loaded file
213 /// if the file was originally loaded from an older format, do
214 /// we need to back it up still?
215 bool need_format_backup;
217 /// Ignore the parent (e.g. when exporting a child standalone)?
221 mutable TocBackend toc_backend;
226 ScopeMacro(DocIterator const & s, MacroData const & m)
227 : scope(s), macro(m) {}
231 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
232 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
233 /// map from the macro name to the position map,
234 /// which maps the macro definition position to the scope and the MacroData.
235 NamePositionScopeMacroMap macros;
236 /// This seem to change the way Buffer::getMacro() works
237 mutable bool macro_lock;
239 /// positions of child buffers in the buffer
240 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
242 ScopeBuffer() : buffer(0) {}
243 ScopeBuffer(DocIterator const & s, Buffer const * b)
244 : scope(s), buffer(b) {}
246 Buffer const * buffer;
248 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
249 /// position of children buffers in this buffer
250 BufferPositionMap children_positions;
251 /// map from children inclusion positions to their scope and their buffer
252 PositionScopeBufferMap position_to_children;
254 /// Contains the old buffer filePath() while saving-as, or the
255 /// directory where the document was last saved while loading.
258 /** Keeps track of the path of local layout files.
259 * If possible, it is always relative to the buffer path.
260 * Empty for layouts in system or user directory.
262 string layout_position;
264 /// Container for all sort of Buffer dependant errors.
265 map<string, ErrorList> errorLists;
267 /// checksum used to test if the file has been externally modified. Used to
268 /// double check whether the file had been externally modified when saving.
269 unsigned long checksum_;
272 frontend::WorkAreaManager * wa_;
274 frontend::GuiBufferDelegate * gui_;
279 /// A cache for the bibfiles (including bibfiles of loaded child
280 /// documents), needed for appropriate update of natbib labels.
281 mutable support::FileNamePairList bibfiles_cache_;
283 // FIXME The caching mechanism could be improved. At present, we have a
284 // cache for each Buffer, that caches all the bibliography info for that
285 // Buffer. A more efficient solution would be to have a global cache per
286 // file, and then to construct the Buffer's bibinfo from that.
287 /// A cache for bibliography info
288 mutable BiblioInfo bibinfo_;
289 /// whether the bibinfo cache is valid
290 mutable bool bibinfo_cache_valid_;
291 /// whether the bibfile cache is valid
292 mutable bool bibfile_cache_valid_;
293 /// Cache of timestamps of .bib files
294 map<FileName, time_t> bibfile_status_;
295 /// Indicates whether the bibinfo has changed since the last time
296 /// we ran updateBuffer(), i.e., whether citation labels may need
298 mutable bool cite_labels_valid_;
300 /// These two hold the file name and format, written to by
301 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
302 FileName preview_file_;
303 string preview_format_;
304 /// If there was an error when previewing, on the next preview we do
305 /// a fresh compile (e.g. in case the user installed a package that
309 mutable RefCache ref_cache_;
311 /// our Text that should be wrapped in an InsetText
315 PreviewLoader * preview_loader_;
317 /// This is here to force the test to be done whenever parent_buffer
319 Buffer const * parent() const
321 // ignore_parent temporarily "orphans" a buffer
322 // (e.g. if a child is compiled standalone)
325 // if parent_buffer is not loaded, then it has been unloaded,
326 // which means that parent_buffer is an invalid pointer. So we
327 // set it to null in that case.
328 // however, the BufferList doesn't know about cloned buffers, so
329 // they will always be regarded as unloaded. in that case, we hope
331 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
333 return parent_buffer;
337 void setParent(Buffer const * pb)
339 if (parent_buffer == pb)
342 if (!cloned_buffer_ && parent_buffer && pb)
343 LYXERR0("Warning: a buffer should not have two parents!");
345 if (!cloned_buffer_ && parent_buffer) {
346 parent_buffer->invalidateBibfileCache();
347 parent_buffer->invalidateBibinfoCache();
351 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
352 /// This one is useful for preview detached in a thread.
353 Buffer const * cloned_buffer_;
355 CloneList * clone_list_;
356 /// are we in the process of exporting this buffer?
357 mutable bool doing_export;
359 /// compute statistics
360 /// \p from initial position
361 /// \p to points to the end position
362 void updateStatistics(DocIterator & from, DocIterator & to,
363 bool skipNoOutput = true);
364 /// statistics accessor functions
365 int wordCount() const
369 int charCount(bool with_blanks) const
372 + (with_blanks ? blank_count_ : 0);
375 // does the buffer contain tracked changes? (if so, we automatically
376 // display the review toolbar, for instance)
377 mutable bool tracked_changes_present_;
379 // Make sure the file monitor monitors the good file.
380 void refreshFileMonitor();
382 /// has it been notified of an external modification?
383 bool isExternallyModified() const { return externally_modified_; }
385 /// Notify or clear of external modification
386 void fileExternallyModified(bool modified) const;
388 /// Block notifications of external modifications
389 FileMonitorBlocker blockFileMonitor() { return file_monitor_->block(10); }
392 /// So we can force access via the accessors.
393 mutable Buffer const * parent_buffer;
399 /// has been externally modified? Can be reset by the user.
400 mutable bool externally_modified_;
402 FileMonitorPtr file_monitor_;
406 /// Creates the per buffer temporary directory
407 static FileName createBufferTmpDir()
409 // FIXME This would be the ideal application for a TempDir class (like
410 // TempFile but for directories)
415 Mutex::Locker locker(&mutex);
416 counter = convert<string>(count++);
418 // We are in our own directory. Why bother to mangle name?
419 // In fact I wrote this code to circumvent a problematic behaviour
420 // (bug?) of EMX mkstemp().
421 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
424 if (!tmpfl.createDirectory(0777)) {
425 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
426 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
427 from_utf8(tmpfl.absFileName())));
433 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
434 Buffer const * cloned_buffer)
435 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
436 internal_buffer(false), read_only(readonly_), filename(file),
437 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
438 ignore_parent(false), toc_backend(owner), macro_lock(false),
439 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
440 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
441 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
442 clone_list_(0), doing_export(false),
443 tracked_changes_present_(0), parent_buffer(0),
444 word_count_(0), char_count_(0), blank_count_(0),
445 externally_modified_(false)
447 refreshFileMonitor();
448 if (!cloned_buffer_) {
449 temppath = createBufferTmpDir();
450 lyxvc.setBuffer(owner_);
452 wa_ = new frontend::WorkAreaManager;
455 temppath = cloned_buffer_->d->temppath;
456 file_fully_loaded = true;
457 params = cloned_buffer_->d->params;
458 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
459 bibinfo_ = cloned_buffer_->d->bibinfo_;
460 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
461 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
462 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
463 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
464 unnamed = cloned_buffer_->d->unnamed;
465 internal_buffer = cloned_buffer_->d->internal_buffer;
466 layout_position = cloned_buffer_->d->layout_position;
467 preview_file_ = cloned_buffer_->d->preview_file_;
468 preview_format_ = cloned_buffer_->d->preview_format_;
469 preview_error_ = cloned_buffer_->d->preview_error_;
470 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
474 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
475 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
477 LYXERR(Debug::INFO, "Buffer::Buffer()");
479 d->inset = new InsetText(*cloned_buffer->d->inset);
480 d->inset->setBuffer(*this);
481 // FIXME: optimize this loop somewhat, maybe by creating a new
482 // general recursive Inset::setId().
483 DocIterator it = doc_iterator_begin(this);
484 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
485 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
486 it.paragraph().setId(cloned_it.paragraph().id());
488 d->inset = new InsetText(this);
489 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
495 LYXERR(Debug::INFO, "Buffer::~Buffer()");
496 // here the buffer should take care that it is
497 // saved properly, before it goes into the void.
499 // GuiView already destroyed
503 // No need to do additional cleanups for internal buffer.
509 // this is in case of recursive includes: we won't try to delete
510 // ourselves as a child.
511 d->clone_list_->erase(this);
512 // loop over children
513 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
514 Impl::BufferPositionMap::iterator end = d->children_positions.end();
515 for (; it != end; ++it) {
516 Buffer * child = const_cast<Buffer *>(it->first);
517 if (d->clone_list_->erase(child))
520 // if we're the master buffer, then we should get rid of the list
523 // If this is not empty, we have leaked something. Worse, one of the
524 // children still has a reference to this list. But we will try to
525 // continue, rather than shut down.
526 LATTEST(d->clone_list_->empty());
527 list<CloneList *>::iterator it =
528 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
529 if (it == cloned_buffers.end()) {
530 // We will leak in this case, but it is safe to continue.
533 cloned_buffers.erase(it);
534 delete d->clone_list_;
536 // FIXME Do we really need to do this right before we delete d?
537 // clear references to children in macro tables
538 d->children_positions.clear();
539 d->position_to_children.clear();
541 // loop over children
542 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
543 Impl::BufferPositionMap::iterator end = d->children_positions.end();
544 for (; it != end; ++it) {
545 Buffer * child = const_cast<Buffer *>(it->first);
546 if (theBufferList().isLoaded(child)) {
547 if (theBufferList().isOthersChild(this, child))
550 theBufferList().release(child);
555 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
556 msg += emergencyWrite();
557 Alert::warning(_("Attempting to close changed document!"), msg);
560 // FIXME Do we really need to do this right before we delete d?
561 // clear references to children in macro tables
562 d->children_positions.clear();
563 d->position_to_children.clear();
565 if (!d->temppath.destroyDirectory()) {
566 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
567 from_utf8(d->temppath.absFileName())));
576 Buffer * Buffer::cloneFromMaster() const
579 cloned_buffers.push_back(new CloneList);
580 CloneList * clones = cloned_buffers.back();
582 masterBuffer()->cloneWithChildren(bufmap, clones);
584 // make sure we got cloned
585 BufferMap::const_iterator bit = bufmap.find(this);
586 LASSERT(bit != bufmap.end(), return 0);
587 Buffer * cloned_buffer = bit->second;
589 return cloned_buffer;
593 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
595 // have we already been cloned?
596 if (bufmap.find(this) != bufmap.end())
599 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
601 // The clone needs its own DocumentClass, since running updateBuffer() will
602 // modify it, and we would otherwise be sharing it with the original Buffer.
603 buffer_clone->params().makeDocumentClass(true);
605 cap::switchBetweenClasses(
606 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
607 static_cast<InsetText &>(buffer_clone->inset()), el);
609 bufmap[this] = buffer_clone;
610 clones->insert(buffer_clone);
611 buffer_clone->d->clone_list_ = clones;
612 buffer_clone->d->macro_lock = true;
613 buffer_clone->d->children_positions.clear();
615 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
616 // math macro caches need to be rethought and simplified.
617 // I am not sure wether we should handle Buffer cloning here or in BufferList.
618 // Right now BufferList knows nothing about buffer clones.
619 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
620 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
621 for (; it != end; ++it) {
622 DocIterator dit = it->first.clone(buffer_clone);
623 dit.setBuffer(buffer_clone);
624 Buffer * child = const_cast<Buffer *>(it->second.buffer);
626 child->cloneWithChildren(bufmap, clones);
627 BufferMap::iterator const bit = bufmap.find(child);
628 LASSERT(bit != bufmap.end(), continue);
629 Buffer * child_clone = bit->second;
631 Inset * inset = dit.nextInset();
632 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
633 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
634 inset_inc->setChildBuffer(child_clone);
635 child_clone->d->setParent(buffer_clone);
636 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
637 buffer_clone->setChild(dit, child_clone);
639 buffer_clone->d->macro_lock = false;
644 Buffer * Buffer::cloneBufferOnly() const {
645 cloned_buffers.push_back(new CloneList);
646 CloneList * clones = cloned_buffers.back();
647 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
649 // The clone needs its own DocumentClass, since running updateBuffer() will
650 // modify it, and we would otherwise be sharing it with the original Buffer.
651 buffer_clone->params().makeDocumentClass(true);
653 cap::switchBetweenClasses(
654 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
655 static_cast<InsetText &>(buffer_clone->inset()), el);
657 clones->insert(buffer_clone);
658 buffer_clone->d->clone_list_ = clones;
660 // we won't be cloning the children
661 buffer_clone->d->children_positions.clear();
666 bool Buffer::isClone() const
668 return d->cloned_buffer_;
672 void Buffer::changed(bool update_metrics) const
675 d->wa_->redrawAll(update_metrics);
679 frontend::WorkAreaManager & Buffer::workAreaManager() const
686 Text & Buffer::text() const
688 return d->inset->text();
692 Inset & Buffer::inset() const
698 BufferParams & Buffer::params()
704 BufferParams const & Buffer::params() const
710 BufferParams const & Buffer::masterParams() const
712 if (masterBuffer() == this)
715 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
716 // Copy child authors to the params. We need those pointers.
717 AuthorList const & child_authors = params().authors();
718 AuthorList::Authors::const_iterator it = child_authors.begin();
719 for (; it != child_authors.end(); ++it)
720 mparams.authors().record(*it);
725 double Buffer::fontScalingFactor() const
727 return isExporting() ? 75.0 * params().html_math_img_scale
728 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
732 ParagraphList & Buffer::paragraphs()
734 return text().paragraphs();
738 ParagraphList const & Buffer::paragraphs() const
740 return text().paragraphs();
744 LyXVC & Buffer::lyxvc()
750 LyXVC const & Buffer::lyxvc() const
756 string const Buffer::temppath() const
758 return d->temppath.absFileName();
762 TexRow & Buffer::texrow()
768 TexRow const & Buffer::texrow() const
774 TocBackend & Buffer::tocBackend() const
776 return d->toc_backend;
780 Undo & Buffer::undo()
786 void Buffer::setChild(DocIterator const & dit, Buffer * child)
788 d->children_positions[child] = dit;
792 string Buffer::latexName(bool const no_path) const
794 FileName latex_name =
795 makeLatexName(d->exportFileName());
796 return no_path ? latex_name.onlyFileName()
797 : latex_name.absFileName();
801 FileName Buffer::Impl::exportFileName() const
803 docstring const branch_suffix =
804 params.branchlist().getFileNameSuffix();
805 if (branch_suffix.empty())
808 string const name = filename.onlyFileNameWithoutExt()
809 + to_utf8(branch_suffix);
810 FileName res(filename.onlyPath().absFileName() + "/" + name);
811 res.changeExtension(filename.extension());
817 string Buffer::logName(LogType * type) const
819 string const filename = latexName(false);
821 if (filename.empty()) {
827 string const path = temppath();
829 FileName const fname(addName(temppath(),
830 onlyFileName(changeExtension(filename,
833 // FIXME: how do we know this is the name of the build log?
834 FileName const bname(
835 addName(path, onlyFileName(
836 changeExtension(filename,
837 theFormats().extension(params().bufferFormat()) + ".out"))));
839 // Also consider the master buffer log file
840 FileName masterfname = fname;
841 LogType mtype = latexlog;
842 if (masterBuffer() != this) {
843 string const mlogfile = masterBuffer()->logName(&mtype);
844 masterfname = FileName(mlogfile);
847 // If no Latex log or Build log is newer, show Build log
848 if (bname.exists() &&
849 ((!fname.exists() && !masterfname.exists())
850 || (fname.lastModified() < bname.lastModified()
851 && masterfname.lastModified() < bname.lastModified()))) {
852 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
855 return bname.absFileName();
856 // If we have a newer master file log or only a master log, show this
857 } else if (fname != masterfname
858 && (!fname.exists() && (masterfname.exists()
859 || fname.lastModified() < masterfname.lastModified()))) {
860 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
863 return masterfname.absFileName();
865 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
868 return fname.absFileName();
872 void Buffer::setReadonly(bool const flag)
874 if (d->read_only != flag) {
881 void Buffer::setFileName(FileName const & fname)
883 bool const changed = fname != d->filename;
885 d->refreshFileMonitor();
887 lyxvc().file_found_hook(fname);
888 setReadonly(d->filename.isReadOnly());
894 int Buffer::readHeader(Lexer & lex)
896 int unknown_tokens = 0;
898 int begin_header_line = -1;
900 // Initialize parameters that may be/go lacking in header:
901 params().branchlist().clear();
902 params().preamble.erase();
903 params().options.erase();
904 params().master.erase();
905 params().float_placement.erase();
906 params().paperwidth.erase();
907 params().paperheight.erase();
908 params().leftmargin.erase();
909 params().rightmargin.erase();
910 params().topmargin.erase();
911 params().bottommargin.erase();
912 params().headheight.erase();
913 params().headsep.erase();
914 params().footskip.erase();
915 params().columnsep.erase();
916 params().fonts_cjk.erase();
917 params().listings_params.clear();
918 params().clearLayoutModules();
919 params().clearRemovedModules();
920 params().clearIncludedChildren();
921 params().pdfoptions().clear();
922 params().indiceslist().clear();
923 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
924 params().isbackgroundcolor = false;
925 params().fontcolor = RGBColor(0, 0, 0);
926 params().isfontcolor = false;
927 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
928 params().boxbgcolor = RGBColor(0xFF, 0, 0);
929 params().html_latex_start.clear();
930 params().html_latex_end.clear();
931 params().html_math_img_scale = 1.0;
932 params().output_sync_macro.erase();
933 params().setLocalLayout(docstring(), false);
934 params().setLocalLayout(docstring(), true);
935 params().biblio_opts.erase();
936 params().biblatex_bibstyle.erase();
937 params().biblatex_citestyle.erase();
938 params().multibib.erase();
940 for (int i = 0; i < 4; ++i) {
941 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
942 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
945 ErrorList & errorList = d->errorLists["Parse"];
954 if (token == "\\end_header")
958 if (token == "\\begin_header") {
959 begin_header_line = line;
963 LYXERR(Debug::PARSER, "Handling document header token: `"
966 string const result =
967 params().readToken(lex, token, d->filename.onlyPath());
968 if (!result.empty()) {
969 if (token == "\\textclass") {
970 d->layout_position = result;
973 docstring const s = bformat(_("Unknown token: "
977 errorList.push_back(ErrorItem(_("Document header error"), s));
981 if (begin_header_line) {
982 docstring const s = _("\\begin_header is missing");
983 errorList.push_back(ErrorItem(_("Document header error"), s));
986 params().makeDocumentClass();
988 return unknown_tokens;
993 // changed to be public and have one parameter
994 // Returns true if "\end_document" is not read (Asger)
995 bool Buffer::readDocument(Lexer & lex)
997 ErrorList & errorList = d->errorLists["Parse"];
1000 // remove dummy empty par
1001 paragraphs().clear();
1003 if (!lex.checkFor("\\begin_document")) {
1004 docstring const s = _("\\begin_document is missing");
1005 errorList.push_back(ErrorItem(_("Document header error"), s));
1010 if (params().output_changes) {
1011 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1012 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1013 LaTeXFeatures::isAvailable("xcolor");
1015 if (!dvipost && !xcolorulem) {
1016 Alert::warning(_("Changes not shown in LaTeX output"),
1017 _("Changes will not be highlighted in LaTeX output, "
1018 "because neither dvipost nor xcolor/ulem are installed.\n"
1019 "Please install these packages or redefine "
1020 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1021 } else if (!xcolorulem) {
1022 Alert::warning(_("Changes not shown in LaTeX output"),
1023 _("Changes will not be highlighted in LaTeX output "
1024 "when using pdflatex, because xcolor and ulem are not installed.\n"
1025 "Please install both packages or redefine "
1026 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1030 if (!parent() && !params().master.empty()) {
1031 FileName const master_file = makeAbsPath(params().master,
1032 onlyPath(absFileName()));
1033 if (isLyXFileName(master_file.absFileName())) {
1035 checkAndLoadLyXFile(master_file, true);
1037 // necessary e.g. after a reload
1038 // to re-register the child (bug 5873)
1039 // FIXME: clean up updateMacros (here, only
1040 // child registering is needed).
1041 master->updateMacros();
1042 // set master as master buffer, but only
1043 // if we are a real child
1044 if (master->isChild(this))
1046 // if the master is not fully loaded
1047 // it is probably just loading this
1048 // child. No warning needed then.
1049 else if (master->isFullyLoaded())
1050 LYXERR0("The master '"
1052 << "' assigned to this document ("
1054 << ") does not include "
1055 "this document. Ignoring the master assignment.");
1060 // assure we have a default index
1061 params().indiceslist().addDefault(B_("Index"));
1064 if (FileName::isAbsolute(params().origin))
1065 d->old_position = params().origin;
1067 d->old_position = filePath();
1068 bool const res = text().read(lex, errorList, d->inset);
1069 d->old_position.clear();
1071 // inform parent buffer about local macros
1073 Buffer const * pbuf = parent();
1074 UserMacroSet::const_iterator cit = usermacros.begin();
1075 UserMacroSet::const_iterator end = usermacros.end();
1076 for (; cit != end; ++cit)
1077 pbuf->usermacros.insert(*cit);
1081 updateMacroInstances(InternalUpdate);
1086 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1088 Format const * fmt = theFormats().getFormat(format);
1091 // It is important to use the correct extension here, since some
1092 // converters create a wrong output file otherwise (e.g. html2latex)
1093 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1094 FileName const name(tempfile.name());
1095 ofdocstream os(name.toFilesystemEncoding().c_str());
1096 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1097 bool const success = !(os << contents).fail();
1100 bool converted = false;
1102 params().compressed = false;
1104 // remove dummy empty par
1105 paragraphs().clear();
1107 converted = importFile(format, name, errorList);
1116 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1118 if (!theConverters().isReachable(format, "lyx"))
1121 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1122 FileName const lyx(tempfile.name());
1123 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1124 return readFile(lyx) == ReadSuccess;
1130 bool Buffer::readString(string const & s)
1132 params().compressed = false;
1135 istringstream is(s);
1137 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1138 FileName const fn = tempfile.name();
1141 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1143 if (success && file_format != LYX_FORMAT) {
1144 // We need to call lyx2lyx, so write the input to a file
1145 ofstream os(fn.toFilesystemEncoding().c_str());
1148 // lyxvc in readFile
1149 if (readFile(fn) != ReadSuccess)
1153 if (readDocument(lex))
1159 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1163 if (!lex.setFile(fname)) {
1164 Alert::error(_("File Not Found"),
1165 bformat(_("Unable to open file `%1$s'."),
1166 from_utf8(fn.absFileName())));
1167 return ReadFileNotFound;
1171 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1172 if (ret_plf != ReadSuccess)
1175 if (file_format != LYX_FORMAT) {
1177 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1178 if (ret_clf != ReadSuccess)
1180 ret_clf = readFile(tmpFile);
1181 if (ret_clf == ReadSuccess) {
1182 d->file_format = file_format;
1183 d->need_format_backup = true;
1188 // FIXME: InsetInfo needs to know whether the file is under VCS
1189 // during the parse process, so this has to be done before.
1190 lyxvc().file_found_hook(d->filename);
1192 if (readDocument(lex)) {
1193 Alert::error(_("Document format failure"),
1194 bformat(_("%1$s ended unexpectedly, which means"
1195 " that it is probably corrupted."),
1196 from_utf8(fn.absFileName())));
1197 return ReadDocumentFailure;
1200 d->file_fully_loaded = true;
1201 d->read_only = !d->filename.isWritable();
1202 params().compressed = theFormats().isZippedFile(d->filename);
1208 bool Buffer::isFullyLoaded() const
1210 return d->file_fully_loaded;
1214 void Buffer::setFullyLoaded(bool value)
1216 d->file_fully_loaded = value;
1220 bool Buffer::lastPreviewError() const
1222 return d->preview_error_;
1226 PreviewLoader * Buffer::loader() const
1228 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1230 if (!d->preview_loader_)
1231 d->preview_loader_ = new PreviewLoader(*this);
1232 return d->preview_loader_;
1236 void Buffer::removePreviews() const
1238 delete d->preview_loader_;
1239 d->preview_loader_ = 0;
1243 void Buffer::updatePreviews() const
1245 PreviewLoader * ploader = loader();
1249 InsetIterator it = inset_iterator_begin(*d->inset);
1250 InsetIterator const end = inset_iterator_end(*d->inset);
1251 for (; it != end; ++it)
1252 it->addPreview(it, *ploader);
1254 ploader->startLoading();
1258 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1259 FileName const & fn, int & file_format) const
1261 if(!lex.checkFor("\\lyxformat")) {
1262 Alert::error(_("Document format failure"),
1263 bformat(_("%1$s is not a readable LyX document."),
1264 from_utf8(fn.absFileName())));
1265 return ReadNoLyXFormat;
1271 // LyX formats 217 and earlier were written as 2.17. This corresponds
1272 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1273 // these cases. See also: www.lyx.org/trac/changeset/1313.
1274 size_t dot = tmp_format.find_first_of(".,");
1275 if (dot != string::npos)
1276 tmp_format.erase(dot, 1);
1278 file_format = convert<int>(tmp_format);
1283 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1284 FileName & tmpfile, int from_format)
1286 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1287 tempfile.setAutoRemove(false);
1288 tmpfile = tempfile.name();
1289 if(tmpfile.empty()) {
1290 Alert::error(_("Conversion failed"),
1291 bformat(_("%1$s is from a different"
1292 " version of LyX, but a temporary"
1293 " file for converting it could"
1294 " not be created."),
1295 from_utf8(fn.absFileName())));
1296 return LyX2LyXNoTempFile;
1299 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1300 if (lyx2lyx.empty()) {
1301 Alert::error(_("Conversion script not found"),
1302 bformat(_("%1$s is from a different"
1303 " version of LyX, but the"
1304 " conversion script lyx2lyx"
1305 " could not be found."),
1306 from_utf8(fn.absFileName())));
1307 return LyX2LyXNotFound;
1311 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1312 ostringstream command;
1313 command << os::python()
1314 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1315 << " -t " << convert<string>(LYX_FORMAT)
1316 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1317 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1318 string const command_str = command.str();
1320 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1322 cmd_ret const ret = runCommand(command_str);
1323 if (ret.first != 0) {
1324 if (from_format < LYX_FORMAT) {
1325 Alert::error(_("Conversion script failed"),
1326 bformat(_("%1$s is from an older version"
1327 " of LyX and the lyx2lyx script"
1328 " failed to convert it."),
1329 from_utf8(fn.absFileName())));
1330 return LyX2LyXOlderFormat;
1332 Alert::error(_("Conversion script failed"),
1333 bformat(_("%1$s is from a newer version"
1334 " of LyX and the lyx2lyx script"
1335 " failed to convert it."),
1336 from_utf8(fn.absFileName())));
1337 return LyX2LyXNewerFormat;
1344 FileName Buffer::getBackupName() const {
1345 FileName const & fn = fileName();
1346 string const fname = fn.onlyFileNameWithoutExt();
1347 string const fext = fn.extension() + "~";
1348 string const fpath = lyxrc.backupdir_path.empty() ?
1349 fn.onlyPath().absFileName() :
1350 lyxrc.backupdir_path;
1351 string const fform = convert<string>(d->file_format);
1352 string const backname = fname + "-lyxformat-" + fform;
1353 FileName backup(addName(fpath, addExtension(backname, fext)));
1355 // limit recursion, just in case
1357 unsigned long orig_checksum = 0;
1358 while (backup.exists() && v < 100) {
1359 if (orig_checksum == 0)
1360 orig_checksum = fn.checksum();
1361 unsigned long new_checksum = backup.checksum();
1362 if (orig_checksum == new_checksum) {
1363 LYXERR(Debug::FILES, "Not backing up " << fn <<
1364 "since " << backup << "has the same checksum.");
1365 // a bit of a hack, but we have to check this anyway
1366 // below, and setting this is simpler than introducing
1367 // a special boolean for this purpose.
1371 string const newbackname = backname + "-" + convert<string>(v);
1372 backup.set(addName(fpath, addExtension(newbackname, fext)));
1375 return v < 100 ? backup : FileName();
1379 // Should probably be moved to somewhere else: BufferView? GuiView?
1380 bool Buffer::save() const
1382 FileMonitorBlocker block = d->blockFileMonitor();
1383 docstring const file = makeDisplayPath(absFileName(), 20);
1384 d->filename.refresh();
1386 // check the read-only status before moving the file as a backup
1387 if (d->filename.exists()) {
1388 bool const read_only = !d->filename.isWritable();
1390 Alert::warning(_("File is read-only"),
1391 bformat(_("The file %1$s cannot be written because it "
1392 "is marked as read-only."), file));
1397 // ask if the disk file has been externally modified (use checksum method)
1398 if (fileName().exists() && isChecksumModified()) {
1400 bformat(_("Document %1$s has been externally modified. "
1401 "Are you sure you want to overwrite this file?"), file);
1402 int const ret = Alert::prompt(_("Overwrite modified file?"),
1403 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1408 // We don't need autosaves in the immediate future. (Asger)
1409 resetAutosaveTimers();
1411 // if the file does not yet exist, none of the backup activity
1412 // that follows is necessary
1413 if (!fileName().exists()) {
1414 if (!writeFile(fileName()))
1420 // we first write the file to a new name, then move it to its
1421 // proper location once that has been done successfully. that
1422 // way we preserve the original file if something goes wrong.
1423 string const justname = fileName().onlyFileNameWithoutExt();
1424 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1425 justname + "-XXXXXX.lyx");
1426 bool const symlink = fileName().isSymLink();
1428 tempfile->setAutoRemove(false);
1430 FileName savefile(tempfile->name());
1431 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1432 if (!writeFile(savefile))
1435 // we will set this to false if we fail
1436 bool made_backup = true;
1438 FileName backupName;
1439 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1441 if (d->need_format_backup)
1442 backupName = getBackupName();
1444 // If we for some reason failed to find a backup name in case of
1445 // a format change, this will still set one. It's the best we can
1447 if (backupName.empty()) {
1448 backupName.set(fileName().absFileName() + "~");
1449 if (!lyxrc.backupdir_path.empty()) {
1450 string const mangledName =
1451 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1452 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1456 LYXERR(Debug::FILES, "Backing up original file to " <<
1457 backupName.absFileName());
1458 // Except file is symlink do not copy because of #6587.
1459 // Hard links have bad luck.
1460 made_backup = symlink ?
1461 fileName().copyTo(backupName):
1462 fileName().moveTo(backupName);
1465 Alert::error(_("Backup failure"),
1466 bformat(_("Cannot create backup file %1$s.\n"
1467 "Please check whether the directory exists and is writable."),
1468 from_utf8(backupName.absFileName())));
1469 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1470 } else if (d->need_format_backup) {
1471 // the original file has been backed up successfully, so we
1472 // will not need to do that again
1473 d->need_format_backup = false;
1477 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1478 // Only do this if tempfile is not in autoremove mode
1481 // If we have no symlink, we can simply rename the temp file.
1482 // Otherwise, we need to copy it so the symlink stays intact.
1483 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1484 savefile.moveTo(fileName()))
1486 // saveCheckSum() was already called by writeFile(), but the
1487 // time stamp is invalidated by copying/moving
1490 if (d->file_format != LYX_FORMAT)
1491 // the file associated with this buffer is now in the current format
1492 d->file_format = LYX_FORMAT;
1495 // else we saved the file, but failed to move it to the right location.
1497 if (needBackup && made_backup && !symlink) {
1498 // the original file was moved to some new location, so it will look
1499 // to the user as if it was deleted. (see bug #9234.) we could try
1500 // to restore it, but that would basically mean trying to do again
1501 // what we just failed to do. better to leave things as they are.
1502 Alert::error(_("Write failure"),
1503 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1504 "But LyX could not move it to:\n %2$s.\n"
1505 "Your original file has been backed up to:\n %3$s"),
1506 from_utf8(savefile.absFileName()),
1507 from_utf8(fileName().absFileName()),
1508 from_utf8(backupName.absFileName())));
1510 // either we did not try to make a backup, or else we tried and failed,
1511 // or else the original file was a symlink, in which case it was copied,
1512 // not moved. so the original file is intact.
1513 Alert::error(_("Write failure"),
1514 bformat(_("Cannot move saved file to:\n %1$s.\n"
1515 "But the file has successfully been saved as:\n %2$s."),
1516 from_utf8(fileName().absFileName()),
1517 from_utf8(savefile.absFileName())));
1523 bool Buffer::writeFile(FileName const & fname) const
1525 if (d->read_only && fname == d->filename)
1528 bool retval = false;
1530 docstring const str = bformat(_("Saving document %1$s..."),
1531 makeDisplayPath(fname.absFileName()));
1534 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1536 if (params().compressed) {
1537 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1538 retval = ofs && write(ofs);
1540 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1541 retval = ofs && write(ofs);
1545 message(str + _(" could not write file!"));
1550 // removeAutosaveFile();
1553 message(str + _(" done."));
1559 docstring Buffer::emergencyWrite()
1561 // No need to save if the buffer has not changed.
1565 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1567 docstring user_message = bformat(
1568 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1570 // We try to save three places:
1571 // 1) Same place as document. Unless it is an unnamed doc.
1573 string s = absFileName();
1576 if (writeFile(FileName(s))) {
1578 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1579 return user_message;
1581 user_message += " " + _("Save failed! Trying again...\n");
1585 // 2) In HOME directory.
1586 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1588 lyxerr << ' ' << s << endl;
1589 if (writeFile(FileName(s))) {
1591 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1592 return user_message;
1595 user_message += " " + _("Save failed! Trying yet again...\n");
1597 // 3) In "/tmp" directory.
1598 // MakeAbsPath to prepend the current
1599 // drive letter on OS/2
1600 s = addName(package().temp_dir().absFileName(), absFileName());
1602 lyxerr << ' ' << s << endl;
1603 if (writeFile(FileName(s))) {
1605 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1606 return user_message;
1609 user_message += " " + _("Save failed! Bummer. Document is lost.");
1612 return user_message;
1616 bool Buffer::write(ostream & ofs) const
1619 // Use the standard "C" locale for file output.
1620 ofs.imbue(locale::classic());
1623 // The top of the file should not be written by params().
1625 // write out a comment in the top of the file
1626 // Important: Keep the version formatting in sync with lyx2lyx and
1627 // tex2lyx (bug 7951)
1628 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1629 << " created this file. For more info see http://www.lyx.org/\n"
1630 << "\\lyxformat " << LYX_FORMAT << "\n"
1631 << "\\begin_document\n";
1633 /// For each author, set 'used' to true if there is a change
1634 /// by this author in the document; otherwise set it to 'false'.
1635 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1636 AuthorList::Authors::const_iterator a_end = params().authors().end();
1637 for (; a_it != a_end; ++a_it)
1638 a_it->setUsed(false);
1640 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1641 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1642 for ( ; it != end; ++it)
1643 it->checkAuthors(params().authors());
1645 // now write out the buffer parameters.
1646 ofs << "\\begin_header\n";
1647 params().writeFile(ofs, this);
1648 ofs << "\\end_header\n";
1651 ofs << "\n\\begin_body\n";
1653 ofs << "\n\\end_body\n";
1655 // Write marker that shows file is complete
1656 ofs << "\\end_document" << endl;
1658 // Shouldn't really be needed....
1661 // how to check if close went ok?
1662 // Following is an attempt... (BE 20001011)
1664 // good() returns false if any error occurred, including some
1665 // formatting error.
1666 // bad() returns true if something bad happened in the buffer,
1667 // which should include file system full errors.
1672 lyxerr << "File was not closed properly." << endl;
1679 bool Buffer::makeLaTeXFile(FileName const & fname,
1680 string const & original_path,
1681 OutputParams const & runparams_in,
1682 OutputWhat output) const
1684 OutputParams runparams = runparams_in;
1686 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1687 // Check here, because the "flavor" is not known in BufferParams::encoding()
1688 // (power users can override this safety measure selecting "utf8-plain").
1689 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1690 && (runparams.encoding->name() != "utf8-plain"))
1691 runparams.encoding = encodings.fromLyXName("ascii");
1693 string const encoding = runparams.encoding->iconvName();
1694 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1697 try { ofs.reset(encoding); }
1698 catch (iconv_codecvt_facet_exception const & e) {
1699 lyxerr << "Caught iconv exception: " << e.what() << endl;
1700 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1701 "verify that the support software for your encoding (%1$s) is "
1702 "properly installed"), from_ascii(encoding)));
1705 if (!openFileWrite(ofs, fname))
1708 ErrorList & errorList = d->errorLists["Export"];
1710 bool failed_export = false;
1713 // make sure we are ready to export
1714 // this needs to be done before we validate
1715 // FIXME Do we need to do this all the time? I.e., in children
1716 // of a master we are exporting?
1718 updateMacroInstances(OutputUpdate);
1721 writeLaTeXSource(os, original_path, runparams, output);
1723 catch (EncodingException const & e) {
1724 docstring const failed(1, e.failed_char);
1726 oss << "0x" << hex << e.failed_char << dec;
1727 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1728 " (code point %2$s)"),
1729 failed, from_utf8(oss.str()));
1730 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1731 "representable in the chosen encoding.\n"
1732 "Changing the document encoding to utf8 could help."),
1733 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1734 failed_export = true;
1736 catch (iconv_codecvt_facet_exception const & e) {
1737 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1739 failed_export = true;
1741 catch (exception const & e) {
1742 errorList.push_back(ErrorItem(_("conversion failed"),
1744 lyxerr << e.what() << endl;
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(hasReadonlyFlag());
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(!hasReadonlyFlag());
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 = theFormats().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 (!theFormats().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;
3030 d->checksum_ = file.exists() ? file.checksum()
3031 : 0; // in the case of save to a new file.
3035 void Buffer::markClean() const
3037 if (!d->lyx_clean) {
3038 d->lyx_clean = true;
3041 // if the .lyx file has been saved, we don't need an
3043 d->bak_clean = true;
3044 d->undo_.markDirty();
3045 clearExternalModification();
3049 void Buffer::setUnnamed(bool flag)
3055 bool Buffer::isUnnamed() const
3062 /// Don't check unnamed, here: isInternal() is used in
3063 /// newBuffer(), where the unnamed flag has not been set by anyone
3064 /// yet. Also, for an internal buffer, there should be no need for
3065 /// retrieving fileName() nor for checking if it is unnamed or not.
3066 bool Buffer::isInternal() const
3068 return d->internal_buffer;
3072 void Buffer::setInternal(bool flag)
3074 d->internal_buffer = flag;
3078 void Buffer::markDirty()
3081 d->lyx_clean = false;
3084 d->bak_clean = false;
3086 DepClean::iterator it = d->dep_clean.begin();
3087 DepClean::const_iterator const end = d->dep_clean.end();
3089 for (; it != end; ++it)
3094 FileName Buffer::fileName() const
3100 string Buffer::absFileName() const
3102 return d->filename.absFileName();
3106 string Buffer::filePath() const
3108 string const abs = d->filename.onlyPath().absFileName();
3111 int last = abs.length() - 1;
3113 return abs[last] == '/' ? abs : abs + '/';
3117 DocFileName Buffer::getReferencedFileName(string const & fn) const
3120 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3121 result.set(fn, filePath());
3123 // filePath() ends with a path separator
3124 FileName const test(filePath() + fn);
3126 result.set(fn, filePath());
3128 result.set(fn, params().origin);
3135 string const Buffer::prepareFileNameForLaTeX(string const & name,
3136 string const & ext, bool nice) const
3138 string const fname = makeAbsPath(name, filePath()).absFileName();
3139 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3145 return to_utf8(makeRelPath(from_utf8(fname),
3146 from_utf8(masterBuffer()->filePath())));
3150 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3151 FileNamePairList const bibfilelist,
3152 bool const add_extension) const
3154 // If we are processing the LaTeX file in a temp directory then
3155 // copy the .bib databases to this temp directory, mangling their
3156 // names in the process. Store this mangled name in the list of
3158 // (We need to do all this because BibTeX *really*, *really*
3159 // can't handle "files with spaces" and Windows users tend to
3160 // use such filenames.)
3161 // Otherwise, store the (maybe absolute) path to the original,
3162 // unmangled database name.
3164 vector<docstring> res;
3166 // determine the export format
3167 string const tex_format = flavor2format(runparams.flavor);
3169 // check for spaces in paths
3170 bool found_space = false;
3172 FileNamePairList::const_iterator it = bibfilelist.begin();
3173 FileNamePairList::const_iterator en = bibfilelist.end();
3174 for (; it != en; ++it) {
3175 string utf8input = to_utf8(it->first);
3177 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3178 FileName const try_in_file =
3179 makeAbsPath(database + ".bib", filePath());
3180 bool const not_from_texmf = try_in_file.isReadableFile();
3182 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3184 // mangledFileName() needs the extension
3185 DocFileName const in_file = DocFileName(try_in_file);
3186 database = removeExtension(in_file.mangledFileName());
3187 FileName const out_file = makeAbsPath(database + ".bib",
3188 masterBuffer()->temppath());
3189 bool const success = in_file.copyTo(out_file);
3191 LYXERR0("Failed to copy '" << in_file
3192 << "' to '" << out_file << "'");
3194 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3195 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3196 if (!isValidLaTeXFileName(database)) {
3197 frontend::Alert::warning(_("Invalid filename"),
3198 _("The following filename will cause troubles "
3199 "when running the exported file through LaTeX: ") +
3200 from_utf8(database));
3202 if (!isValidDVIFileName(database)) {
3203 frontend::Alert::warning(_("Problematic filename for DVI"),
3204 _("The following filename can cause troubles "
3205 "when running the exported file through LaTeX "
3206 "and opening the resulting DVI: ") +
3207 from_utf8(database), true);
3215 docstring const path = from_utf8(latex_path(database));
3217 if (contains(path, ' '))
3220 if (find(res.begin(), res.end(), path) == res.end())
3221 res.push_back(path);
3224 // Check if there are spaces in the path and warn BibTeX users, if so.
3225 // (biber can cope with such paths)
3226 if (!prefixIs(runparams.bibtex_command, "biber")) {
3227 // Post this warning only once.
3228 static bool warned_about_spaces = false;
3229 if (!warned_about_spaces &&
3230 runparams.nice && found_space) {
3231 warned_about_spaces = true;
3232 Alert::warning(_("Export Warning!"),
3233 _("There are spaces in the paths to your BibTeX databases.\n"
3234 "BibTeX will be unable to find them."));
3243 string Buffer::layoutPos() const
3245 return d->layout_position;
3249 void Buffer::setLayoutPos(string const & path)
3252 d->layout_position.clear();
3256 LATTEST(FileName::isAbsolute(path));
3258 d->layout_position =
3259 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3261 if (d->layout_position.empty())
3262 d->layout_position = ".";
3266 bool Buffer::hasReadonlyFlag() const
3268 return d->read_only;
3272 bool Buffer::isReadonly() const
3274 return hasReadonlyFlag() || notifiesExternalModification();
3278 void Buffer::setParent(Buffer const * buffer)
3280 // Avoids recursive include.
3281 d->setParent(buffer == this ? 0 : buffer);
3286 Buffer const * Buffer::parent() const
3292 ListOfBuffers Buffer::allRelatives() const
3294 ListOfBuffers lb = masterBuffer()->getDescendents();
3295 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3300 Buffer const * Buffer::masterBuffer() const
3302 // FIXME Should be make sure we are not in some kind
3303 // of recursive include? A -> B -> A will crash this.
3304 Buffer const * const pbuf = d->parent();
3308 return pbuf->masterBuffer();
3312 bool Buffer::isChild(Buffer * child) const
3314 return d->children_positions.find(child) != d->children_positions.end();
3318 DocIterator Buffer::firstChildPosition(Buffer const * child)
3320 Impl::BufferPositionMap::iterator it;
3321 it = d->children_positions.find(child);
3322 if (it == d->children_positions.end())
3323 return DocIterator(this);
3328 bool Buffer::hasChildren() const
3330 return !d->children_positions.empty();
3334 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3336 // loop over children
3337 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3338 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3339 for (; it != end; ++it) {
3340 Buffer * child = const_cast<Buffer *>(it->first);
3342 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3343 if (bit != clist.end())
3345 clist.push_back(child);
3347 // there might be grandchildren
3348 child->collectChildren(clist, true);
3353 ListOfBuffers Buffer::getChildren() const
3356 collectChildren(v, false);
3357 // Make sure we have not included ourselves.
3358 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3359 if (bit != v.end()) {
3360 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3367 ListOfBuffers Buffer::getDescendents() const
3370 collectChildren(v, true);
3371 // Make sure we have not included ourselves.
3372 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3373 if (bit != v.end()) {
3374 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3381 template<typename M>
3382 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3387 typename M::const_iterator it = m.lower_bound(x);
3388 if (it == m.begin())
3396 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3397 DocIterator const & pos) const
3399 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3401 // if paragraphs have no macro context set, pos will be empty
3405 // we haven't found anything yet
3406 DocIterator bestPos = owner_->par_iterator_begin();
3407 MacroData const * bestData = 0;
3409 // find macro definitions for name
3410 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3411 if (nameIt != macros.end()) {
3412 // find last definition in front of pos or at pos itself
3413 PositionScopeMacroMap::const_iterator it
3414 = greatest_below(nameIt->second, pos);
3415 if (it != nameIt->second.end()) {
3417 // scope ends behind pos?
3418 if (pos < it->second.scope) {
3419 // Looks good, remember this. If there
3420 // is no external macro behind this,
3421 // we found the right one already.
3422 bestPos = it->first;
3423 bestData = &it->second.macro;
3427 // try previous macro if there is one
3428 if (it == nameIt->second.begin())
3435 // find macros in included files
3436 PositionScopeBufferMap::const_iterator it
3437 = greatest_below(position_to_children, pos);
3438 if (it == position_to_children.end())
3439 // no children before
3443 // do we know something better (i.e. later) already?
3444 if (it->first < bestPos )
3447 // scope ends behind pos?
3448 if (pos < it->second.scope
3449 && (cloned_buffer_ ||
3450 theBufferList().isLoaded(it->second.buffer))) {
3451 // look for macro in external file
3453 MacroData const * data
3454 = it->second.buffer->getMacro(name, false);
3457 bestPos = it->first;
3463 // try previous file if there is one
3464 if (it == position_to_children.begin())
3469 // return the best macro we have found
3474 MacroData const * Buffer::getMacro(docstring const & name,
3475 DocIterator const & pos, bool global) const
3480 // query buffer macros
3481 MacroData const * data = d->getBufferMacro(name, pos);
3485 // If there is a master buffer, query that
3486 Buffer const * const pbuf = d->parent();
3488 d->macro_lock = true;
3489 MacroData const * macro = pbuf->getMacro(
3490 name, *this, false);
3491 d->macro_lock = false;
3497 data = MacroTable::globalMacros().get(name);
3506 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3508 // set scope end behind the last paragraph
3509 DocIterator scope = par_iterator_begin();
3510 scope.pit() = scope.lastpit() + 1;
3512 return getMacro(name, scope, global);
3516 MacroData const * Buffer::getMacro(docstring const & name,
3517 Buffer const & child, bool global) const
3519 // look where the child buffer is included first
3520 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3521 if (it == d->children_positions.end())
3524 // check for macros at the inclusion position
3525 return getMacro(name, it->second, global);
3529 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3531 pit_type const lastpit = it.lastpit();
3533 // look for macros in each paragraph
3534 while (it.pit() <= lastpit) {
3535 Paragraph & par = it.paragraph();
3537 // iterate over the insets of the current paragraph
3538 InsetList const & insets = par.insetList();
3539 InsetList::const_iterator iit = insets.begin();
3540 InsetList::const_iterator end = insets.end();
3541 for (; iit != end; ++iit) {
3542 it.pos() = iit->pos;
3544 // is it a nested text inset?
3545 if (iit->inset->asInsetText()) {
3546 // Inset needs its own scope?
3547 InsetText const * itext = iit->inset->asInsetText();
3548 bool newScope = itext->isMacroScope();
3550 // scope which ends just behind the inset
3551 DocIterator insetScope = it;
3554 // collect macros in inset
3555 it.push_back(CursorSlice(*iit->inset));
3556 updateMacros(it, newScope ? insetScope : scope);
3561 if (iit->inset->asInsetTabular()) {
3562 CursorSlice slice(*iit->inset);
3563 size_t const numcells = slice.nargs();
3564 for (; slice.idx() < numcells; slice.forwardIdx()) {
3565 it.push_back(slice);
3566 updateMacros(it, scope);
3572 // is it an external file?
3573 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3574 // get buffer of external file
3575 InsetInclude const & inset =
3576 static_cast<InsetInclude const &>(*iit->inset);
3578 Buffer * child = inset.getChildBuffer();
3583 // register its position, but only when it is
3584 // included first in the buffer
3585 if (children_positions.find(child) ==
3586 children_positions.end())
3587 children_positions[child] = it;
3589 // register child with its scope
3590 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3594 InsetMath * im = iit->inset->asInsetMath();
3595 if (doing_export && im) {
3596 InsetMathHull * hull = im->asHullInset();
3598 hull->recordLocation(it);
3601 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3605 MathMacroTemplate & macroTemplate =
3606 *iit->inset->asInsetMath()->asMacroTemplate();
3607 MacroContext mc(owner_, it);
3608 macroTemplate.updateToContext(mc);
3611 bool valid = macroTemplate.validMacro();
3612 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3613 // then the BufferView's cursor will be invalid in
3614 // some cases which leads to crashes.
3619 // FIXME (Abdel), I don't understand why we pass 'it' here
3620 // instead of 'macroTemplate' defined above... is this correct?
3621 macros[macroTemplate.name()][it] =
3622 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3632 void Buffer::updateMacros() const
3637 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3639 // start with empty table
3641 d->children_positions.clear();
3642 d->position_to_children.clear();
3644 // Iterate over buffer, starting with first paragraph
3645 // The scope must be bigger than any lookup DocIterator
3646 // later. For the global lookup, lastpit+1 is used, hence
3647 // we use lastpit+2 here.
3648 DocIterator it = par_iterator_begin();
3649 DocIterator outerScope = it;
3650 outerScope.pit() = outerScope.lastpit() + 2;
3651 d->updateMacros(it, outerScope);
3655 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3657 InsetIterator it = inset_iterator_begin(inset());
3658 InsetIterator const end = inset_iterator_end(inset());
3659 for (; it != end; ++it) {
3660 if (it->lyxCode() == BRANCH_CODE) {
3661 InsetBranch & br = static_cast<InsetBranch &>(*it);
3662 docstring const name = br.branch();
3663 if (!from_master && !params().branchlist().find(name))
3664 result.push_back(name);
3665 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3666 result.push_back(name);
3669 if (it->lyxCode() == INCLUDE_CODE) {
3670 // get buffer of external file
3671 InsetInclude const & ins =
3672 static_cast<InsetInclude const &>(*it);
3673 Buffer * child = ins.getChildBuffer();
3676 child->getUsedBranches(result, true);
3679 // remove duplicates
3684 void Buffer::updateMacroInstances(UpdateType utype) const
3686 LYXERR(Debug::MACROS, "updateMacroInstances for "
3687 << d->filename.onlyFileName());
3688 DocIterator it = doc_iterator_begin(this);
3690 DocIterator const end = doc_iterator_end(this);
3691 for (; it != end; it.forwardInset()) {
3692 // look for MathData cells in InsetMathNest insets
3693 InsetMath * minset = it.nextInset()->asInsetMath();
3697 // update macro in all cells of the InsetMathNest
3698 DocIterator::idx_type n = minset->nargs();
3699 MacroContext mc = MacroContext(this, it);
3700 for (DocIterator::idx_type i = 0; i < n; ++i) {
3701 MathData & data = minset->cell(i);
3702 data.updateMacros(0, mc, utype, 0);
3708 void Buffer::listMacroNames(MacroNameSet & macros) const
3713 d->macro_lock = true;
3715 // loop over macro names
3716 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3717 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3718 for (; nameIt != nameEnd; ++nameIt)
3719 macros.insert(nameIt->first);
3721 // loop over children
3722 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3723 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3724 for (; it != end; ++it)
3725 it->first->listMacroNames(macros);
3728 Buffer const * const pbuf = d->parent();
3730 pbuf->listMacroNames(macros);
3732 d->macro_lock = false;
3736 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3738 Buffer const * const pbuf = d->parent();
3743 pbuf->listMacroNames(names);
3746 MacroNameSet::iterator it = names.begin();
3747 MacroNameSet::iterator end = names.end();
3748 for (; it != end; ++it) {
3750 MacroData const * data =
3751 pbuf->getMacro(*it, *this, false);
3753 macros.insert(data);
3755 // we cannot access the original MathMacroTemplate anymore
3756 // here to calls validate method. So we do its work here manually.
3757 // FIXME: somehow make the template accessible here.
3758 if (data->optionals() > 0)
3759 features.require("xargs");
3765 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3768 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3770 RefCache::iterator it = d->ref_cache_.find(label);
3771 if (it != d->ref_cache_.end())
3772 return it->second.second;
3774 static InsetLabel const * dummy_il = 0;
3775 static References const dummy_refs = References();
3776 it = d->ref_cache_.insert(
3777 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3778 return it->second.second;
3782 Buffer::References const & Buffer::references(docstring const & label) const
3784 return const_cast<Buffer *>(this)->getReferenceCache(label);
3788 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3790 References & refs = getReferenceCache(label);
3791 refs.push_back(make_pair(inset, it));
3795 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3797 masterBuffer()->d->ref_cache_[label].first = il;
3801 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3803 return masterBuffer()->d->ref_cache_[label].first;
3807 void Buffer::clearReferenceCache() const
3810 d->ref_cache_.clear();
3814 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3816 //FIXME: This does not work for child documents yet.
3817 reloadBibInfoCache();
3819 // Check if the label 'from' appears more than once
3820 BiblioInfo const & keys = masterBibInfo();
3821 BiblioInfo::const_iterator bit = keys.begin();
3822 BiblioInfo::const_iterator bend = keys.end();
3823 vector<docstring> labels;
3825 for (; bit != bend; ++bit)
3827 labels.push_back(bit->first);
3829 if (count(labels.begin(), labels.end(), from) > 1)
3832 string const paramName = "key";
3833 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3834 if (it->lyxCode() != CITE_CODE)
3836 InsetCommand * inset = it->asInsetCommand();
3837 docstring const oldValue = inset->getParam(paramName);
3838 if (oldValue == from)
3839 inset->setParam(paramName, to);
3843 // returns NULL if id-to-row conversion is unsupported
3844 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3845 pit_type par_begin, pit_type par_end,
3846 OutputWhat output, bool master) const
3848 unique_ptr<TexRow> texrow;
3849 OutputParams runparams(¶ms().encoding());
3850 runparams.nice = true;
3851 runparams.flavor = params().getOutputFlavor(format);
3852 runparams.linelen = lyxrc.plaintext_linelen;
3853 // No side effect of file copying and image conversion
3854 runparams.dryrun = true;
3856 if (output == CurrentParagraph) {
3857 runparams.par_begin = par_begin;
3858 runparams.par_end = par_end;
3859 if (par_begin + 1 == par_end) {
3861 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3865 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3866 convert<docstring>(par_begin),
3867 convert<docstring>(par_end - 1))
3870 // output paragraphs
3871 if (runparams.flavor == OutputParams::LYX) {
3872 Paragraph const & par = text().paragraphs()[par_begin];
3874 depth_type dt = par.getDepth();
3875 par.write(ods, params(), dt);
3876 os << from_utf8(ods.str());
3877 } else if (runparams.flavor == OutputParams::HTML) {
3879 setMathFlavor(runparams);
3880 xhtmlParagraphs(text(), *this, xs, runparams);
3881 } else if (runparams.flavor == OutputParams::TEXT) {
3883 // FIXME Handles only one paragraph, unlike the others.
3884 // Probably should have some routine with a signature like them.
3885 writePlaintextParagraph(*this,
3886 text().paragraphs()[par_begin], os, runparams, dummy);
3887 } else if (params().isDocBook()) {
3888 docbookParagraphs(text(), *this, os, runparams);
3890 // If we are previewing a paragraph, even if this is the
3891 // child of some other buffer, let's cut the link here,
3892 // so that no concurring settings from the master
3893 // (e.g. branch state) interfere (see #8101).
3895 d->ignore_parent = true;
3896 // We need to validate the Buffer params' features here
3897 // in order to know if we should output polyglossia
3898 // macros (instead of babel macros)
3899 LaTeXFeatures features(*this, params(), runparams);
3901 runparams.use_polyglossia = features.usePolyglossia();
3902 // latex or literate
3905 ots.texrow().newlines(2);
3907 latexParagraphs(*this, text(), ots, runparams);
3908 texrow = ots.releaseTexRow();
3910 // Restore the parenthood
3912 d->ignore_parent = false;
3916 if (output == FullSource)
3917 os << _("Preview source code");
3918 else if (output == OnlyPreamble)
3919 os << _("Preview preamble");
3920 else if (output == OnlyBody)
3921 os << _("Preview body");
3923 if (runparams.flavor == OutputParams::LYX) {
3925 if (output == FullSource)
3927 else if (output == OnlyPreamble)
3928 params().writeFile(ods, this);
3929 else if (output == OnlyBody)
3931 os << from_utf8(ods.str());
3932 } else if (runparams.flavor == OutputParams::HTML) {
3933 writeLyXHTMLSource(os, runparams, output);
3934 } else if (runparams.flavor == OutputParams::TEXT) {
3935 if (output == OnlyPreamble) {
3936 os << "% "<< _("Plain text does not have a preamble.");
3938 writePlaintextFile(*this, os, runparams);
3939 } else if (params().isDocBook()) {
3940 writeDocBookSource(os, absFileName(), runparams, output);
3942 // latex or literate
3945 ots.texrow().newlines(2);
3947 runparams.is_child = true;
3948 writeLaTeXSource(ots, string(), runparams, output);
3949 texrow = ots.releaseTexRow();
3956 ErrorList & Buffer::errorList(string const & type) const
3958 return d->errorLists[type];
3962 void Buffer::updateTocItem(std::string const & type,
3963 DocIterator const & dit) const
3966 d->gui_->updateTocItem(type, dit);
3970 void Buffer::structureChanged() const
3973 d->gui_->structureChanged();
3977 void Buffer::errors(string const & err, bool from_master) const
3980 d->gui_->errors(err, from_master);
3984 void Buffer::message(docstring const & msg) const
3987 d->gui_->message(msg);
3991 void Buffer::setBusy(bool on) const
3994 d->gui_->setBusy(on);
3998 void Buffer::updateTitles() const
4001 d->wa_->updateTitles();
4005 void Buffer::resetAutosaveTimers() const
4008 d->gui_->resetAutosaveTimers();
4012 bool Buffer::hasGuiDelegate() const
4018 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4027 class AutoSaveBuffer : public ForkedProcess {
4030 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4031 : buffer_(buffer), fname_(fname) {}
4033 virtual shared_ptr<ForkedProcess> clone() const
4035 return make_shared<AutoSaveBuffer>(*this);
4040 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4041 from_utf8(fname_.absFileName())));
4042 return run(DontWait);
4046 virtual int generateChild();
4048 Buffer const & buffer_;
4053 int AutoSaveBuffer::generateChild()
4055 #if defined(__APPLE__)
4056 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4057 * We should use something else like threads.
4059 * Since I do not know how to determine at run time what is the OS X
4060 * version, I just disable forking altogether for now (JMarc)
4062 pid_t const pid = -1;
4064 // tmp_ret will be located (usually) in /tmp
4065 // will that be a problem?
4066 // Note that this calls ForkedCalls::fork(), so it's
4067 // ok cross-platform.
4068 pid_t const pid = fork();
4069 // If you want to debug the autosave
4070 // you should set pid to -1, and comment out the fork.
4071 if (pid != 0 && pid != -1)
4075 // pid = -1 signifies that lyx was unable
4076 // to fork. But we will do the save
4078 bool failed = false;
4079 TempFile tempfile("lyxautoXXXXXX.lyx");
4080 tempfile.setAutoRemove(false);
4081 FileName const tmp_ret = tempfile.name();
4082 if (!tmp_ret.empty()) {
4083 if (!buffer_.writeFile(tmp_ret))
4085 else if (!tmp_ret.moveTo(fname_))
4091 // failed to write/rename tmp_ret so try writing direct
4092 if (!buffer_.writeFile(fname_)) {
4093 // It is dangerous to do this in the child,
4094 // but safe in the parent, so...
4095 if (pid == -1) // emit message signal.
4096 buffer_.message(_("Autosave failed!"));
4100 if (pid == 0) // we are the child so...
4109 FileName Buffer::getEmergencyFileName() const
4111 return FileName(d->filename.absFileName() + ".emergency");
4115 FileName Buffer::getAutosaveFileName() const
4117 // if the document is unnamed try to save in the backup dir, else
4118 // in the default document path, and as a last try in the filePath,
4119 // which will most often be the temporary directory
4122 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4123 : lyxrc.backupdir_path;
4124 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4127 string const fname = "#" + d->filename.onlyFileName() + "#";
4129 return makeAbsPath(fname, fpath);
4133 void Buffer::removeAutosaveFile() const
4135 FileName const f = getAutosaveFileName();
4141 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4143 FileName const newauto = getAutosaveFileName();
4145 if (newauto != oldauto && oldauto.exists())
4146 if (!oldauto.moveTo(newauto))
4147 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4151 bool Buffer::autoSave() const
4153 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4154 if (buf->d->bak_clean || hasReadonlyFlag())
4157 message(_("Autosaving current document..."));
4158 buf->d->bak_clean = true;
4160 FileName const fname = getAutosaveFileName();
4161 LASSERT(d->cloned_buffer_, return false);
4163 // If this buffer is cloned, we assume that
4164 // we are running in a separate thread already.
4165 TempFile tempfile("lyxautoXXXXXX.lyx");
4166 tempfile.setAutoRemove(false);
4167 FileName const tmp_ret = tempfile.name();
4168 if (!tmp_ret.empty()) {
4170 // assume successful write of tmp_ret
4171 if (tmp_ret.moveTo(fname))
4174 // failed to write/rename tmp_ret so try writing direct
4175 return writeFile(fname);
4179 void Buffer::setExportStatus(bool e) const
4181 d->doing_export = e;
4182 ListOfBuffers clist = getDescendents();
4183 ListOfBuffers::const_iterator cit = clist.begin();
4184 ListOfBuffers::const_iterator const cen = clist.end();
4185 for (; cit != cen; ++cit)
4186 (*cit)->d->doing_export = e;
4190 bool Buffer::isExporting() const
4192 return d->doing_export;
4196 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4200 return doExport(target, put_in_tempdir, result_file);
4203 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4204 string & result_file) const
4206 bool const update_unincluded =
4207 params().maintain_unincluded_children
4208 && !params().getIncludedChildren().empty();
4210 // (1) export with all included children (omit \includeonly)
4211 if (update_unincluded) {
4212 ExportStatus const status =
4213 doExport(target, put_in_tempdir, true, result_file);
4214 if (status != ExportSuccess)
4217 // (2) export with included children only
4218 return doExport(target, put_in_tempdir, false, result_file);
4222 void Buffer::setMathFlavor(OutputParams & op) const
4224 switch (params().html_math_output) {
4225 case BufferParams::MathML:
4226 op.math_flavor = OutputParams::MathAsMathML;
4228 case BufferParams::HTML:
4229 op.math_flavor = OutputParams::MathAsHTML;
4231 case BufferParams::Images:
4232 op.math_flavor = OutputParams::MathAsImages;
4234 case BufferParams::LaTeX:
4235 op.math_flavor = OutputParams::MathAsLaTeX;
4241 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4242 bool includeall, string & result_file) const
4244 LYXERR(Debug::FILES, "target=" << target);
4245 OutputParams runparams(¶ms().encoding());
4246 string format = target;
4247 string dest_filename;
4248 size_t pos = target.find(' ');
4249 if (pos != string::npos) {
4250 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4251 format = target.substr(0, pos);
4252 if (format == "default")
4253 format = params().getDefaultOutputFormat();
4254 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4255 FileName(dest_filename).onlyPath().createPath();
4256 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4258 MarkAsExporting exporting(this);
4259 string backend_format;
4260 runparams.flavor = OutputParams::LATEX;
4261 runparams.linelen = lyxrc.plaintext_linelen;
4262 runparams.includeall = includeall;
4263 vector<string> backs = params().backends();
4264 Converters converters = theConverters();
4265 bool need_nice_file = false;
4266 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4267 // Get shortest path to format
4268 converters.buildGraph();
4269 Graph::EdgePath path;
4270 for (vector<string>::const_iterator it = backs.begin();
4271 it != backs.end(); ++it) {
4272 Graph::EdgePath p = converters.getPath(*it, format);
4273 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4274 backend_format = *it;
4279 if (!put_in_tempdir) {
4280 // Only show this alert if this is an export to a non-temporary
4281 // file (not for previewing).
4282 Alert::error(_("Couldn't export file"), bformat(
4283 _("No information for exporting the format %1$s."),
4284 theFormats().prettyName(format)));
4286 return ExportNoPathToFormat;
4288 runparams.flavor = converters.getFlavor(path, this);
4289 Graph::EdgePath::const_iterator it = path.begin();
4290 Graph::EdgePath::const_iterator en = path.end();
4291 for (; it != en; ++it)
4292 if (theConverters().get(*it).nice()) {
4293 need_nice_file = true;
4298 backend_format = format;
4299 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4300 // FIXME: Don't hardcode format names here, but use a flag
4301 if (backend_format == "pdflatex")
4302 runparams.flavor = OutputParams::PDFLATEX;
4303 else if (backend_format == "luatex")
4304 runparams.flavor = OutputParams::LUATEX;
4305 else if (backend_format == "dviluatex")
4306 runparams.flavor = OutputParams::DVILUATEX;
4307 else if (backend_format == "xetex")
4308 runparams.flavor = OutputParams::XETEX;
4311 string filename = latexName(false);
4312 filename = addName(temppath(), filename);
4313 filename = changeExtension(filename,
4314 theFormats().extension(backend_format));
4315 LYXERR(Debug::FILES, "filename=" << filename);
4317 // Plain text backend
4318 if (backend_format == "text") {
4319 runparams.flavor = OutputParams::TEXT;
4320 writePlaintextFile(*this, FileName(filename), runparams);
4323 else if (backend_format == "xhtml") {
4324 runparams.flavor = OutputParams::HTML;
4325 setMathFlavor(runparams);
4326 makeLyXHTMLFile(FileName(filename), runparams);
4327 } else if (backend_format == "lyx")
4328 writeFile(FileName(filename));
4330 else if (params().isDocBook()) {
4331 runparams.nice = !put_in_tempdir;
4332 makeDocBookFile(FileName(filename), runparams);
4335 else if (backend_format == format || need_nice_file) {
4336 runparams.nice = true;
4337 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4338 if (d->cloned_buffer_)
4339 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4342 } else if (!lyxrc.tex_allows_spaces
4343 && contains(filePath(), ' ')) {
4344 Alert::error(_("File name error"),
4345 _("The directory path to the document cannot contain spaces."));
4346 return ExportTexPathHasSpaces;
4348 runparams.nice = false;
4349 bool const success = makeLaTeXFile(
4350 FileName(filename), filePath(), runparams);
4351 if (d->cloned_buffer_)
4352 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4357 string const error_type = (format == "program")
4358 ? "Build" : params().bufferFormat();
4359 ErrorList & error_list = d->errorLists[error_type];
4360 string const ext = theFormats().extension(format);
4361 FileName const tmp_result_file(changeExtension(filename, ext));
4362 bool const success = converters.convert(this, FileName(filename),
4363 tmp_result_file, FileName(absFileName()), backend_format, format,
4366 // Emit the signal to show the error list or copy it back to the
4367 // cloned Buffer so that it can be emitted afterwards.
4368 if (format != backend_format) {
4369 if (runparams.silent)
4371 else if (d->cloned_buffer_)
4372 d->cloned_buffer_->d->errorLists[error_type] =
4373 d->errorLists[error_type];
4376 // also to the children, in case of master-buffer-view
4377 ListOfBuffers clist = getDescendents();
4378 ListOfBuffers::const_iterator cit = clist.begin();
4379 ListOfBuffers::const_iterator const cen = clist.end();
4380 for (; cit != cen; ++cit) {
4381 if (runparams.silent)
4382 (*cit)->d->errorLists[error_type].clear();
4383 else if (d->cloned_buffer_) {
4384 // Enable reverse search by copying back the
4385 // texrow object to the cloned buffer.
4386 // FIXME: this is not thread safe.
4387 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4388 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4389 (*cit)->d->errorLists[error_type];
4391 (*cit)->errors(error_type, true);
4395 if (d->cloned_buffer_) {
4396 // Enable reverse dvi or pdf to work by copying back the texrow
4397 // object to the cloned buffer.
4398 // FIXME: There is a possibility of concurrent access to texrow
4399 // here from the main GUI thread that should be securized.
4400 d->cloned_buffer_->d->texrow = d->texrow;
4401 string const error_type = params().bufferFormat();
4402 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4406 if (put_in_tempdir) {
4407 result_file = tmp_result_file.absFileName();
4408 return success ? ExportSuccess : ExportConverterError;
4411 if (dest_filename.empty())
4412 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4414 result_file = dest_filename;
4415 // We need to copy referenced files (e. g. included graphics
4416 // if format == "dvi") to the result dir.
4417 vector<ExportedFile> const files =
4418 runparams.exportdata->externalFiles(format);
4419 string const dest = runparams.export_folder.empty() ?
4420 onlyPath(result_file) : runparams.export_folder;
4421 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4422 : force_overwrite == ALL_FILES;
4423 CopyStatus status = use_force ? FORCE : SUCCESS;
4425 vector<ExportedFile>::const_iterator it = files.begin();
4426 vector<ExportedFile>::const_iterator const en = files.end();
4427 for (; it != en && status != CANCEL; ++it) {
4428 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4429 string fixedName = it->exportName;
4430 if (!runparams.export_folder.empty()) {
4431 // Relative pathnames starting with ../ will be sanitized
4432 // if exporting to a different folder
4433 while (fixedName.substr(0, 3) == "../")
4434 fixedName = fixedName.substr(3, fixedName.length() - 3);
4436 FileName fixedFileName = makeAbsPath(fixedName, dest);
4437 fixedFileName.onlyPath().createPath();
4438 status = copyFile(fmt, it->sourceName,
4440 it->exportName, status == FORCE,
4441 runparams.export_folder.empty());
4444 if (status == CANCEL) {
4445 message(_("Document export cancelled."));
4446 return ExportCancel;
4449 if (tmp_result_file.exists()) {
4450 // Finally copy the main file
4451 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4452 : force_overwrite != NO_FILES;
4453 if (status == SUCCESS && use_force)
4455 status = copyFile(format, tmp_result_file,
4456 FileName(result_file), result_file,
4458 if (status == CANCEL) {
4459 message(_("Document export cancelled."));
4460 return ExportCancel;
4462 message(bformat(_("Document exported as %1$s "
4464 theFormats().prettyName(format),
4465 makeDisplayPath(result_file)));
4468 // This must be a dummy converter like fax (bug 1888)
4469 message(bformat(_("Document exported as %1$s"),
4470 theFormats().prettyName(format)));
4473 return success ? ExportSuccess : ExportConverterError;
4477 Buffer::ExportStatus Buffer::preview(string const & format) const
4479 bool const update_unincluded =
4480 params().maintain_unincluded_children
4481 && !params().getIncludedChildren().empty();
4482 return preview(format, update_unincluded);
4486 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4488 MarkAsExporting exporting(this);
4490 // (1) export with all included children (omit \includeonly)
4492 ExportStatus const status = doExport(format, true, true, result_file);
4493 if (status != ExportSuccess)
4496 // (2) export with included children only
4497 ExportStatus const status = doExport(format, true, false, result_file);
4498 FileName const previewFile(result_file);
4500 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4501 theimpl->preview_file_ = previewFile;
4502 theimpl->preview_format_ = format;
4503 theimpl->preview_error_ = (status != ExportSuccess);
4505 if (status != ExportSuccess)
4508 if (previewFile.exists())
4509 return theFormats().view(*this, previewFile, format) ?
4510 PreviewSuccess : PreviewError;
4512 // Successful export but no output file?
4513 // Probably a bug in error detection.
4514 LATTEST(status != ExportSuccess);
4519 Buffer::ReadStatus Buffer::extractFromVC()
4521 bool const found = LyXVC::file_not_found_hook(d->filename);
4523 return ReadFileNotFound;
4524 if (!d->filename.isReadableFile())
4530 Buffer::ReadStatus Buffer::loadEmergency()
4532 FileName const emergencyFile = getEmergencyFileName();
4533 if (!emergencyFile.exists()
4534 || emergencyFile.lastModified() <= d->filename.lastModified())
4535 return ReadFileNotFound;
4537 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4538 docstring const text = bformat(_("An emergency save of the document "
4539 "%1$s exists.\n\nRecover emergency save?"), file);
4541 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4542 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4548 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4549 bool const success = (ret_llf == ReadSuccess);
4551 if (hasReadonlyFlag()) {
4552 Alert::warning(_("File is read-only"),
4553 bformat(_("An emergency file is successfully loaded, "
4554 "but the original file %1$s is marked read-only. "
4555 "Please make sure to save the document as a different "
4556 "file."), from_utf8(d->filename.absFileName())));
4559 lyxvc().file_found_hook(d->filename);
4560 str = _("Document was successfully recovered.");
4562 str = _("Document was NOT successfully recovered.");
4563 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4564 makeDisplayPath(emergencyFile.absFileName()));
4566 int const del_emerg =
4567 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4568 _("&Remove"), _("&Keep"));
4569 if (del_emerg == 0) {
4570 emergencyFile.removeFile();
4572 Alert::warning(_("Emergency file deleted"),
4573 _("Do not forget to save your file now!"), true);
4575 return success ? ReadSuccess : ReadEmergencyFailure;
4578 int const del_emerg =
4579 Alert::prompt(_("Delete emergency file?"),
4580 _("Remove emergency file now?"), 1, 1,
4581 _("&Remove"), _("&Keep"));
4583 emergencyFile.removeFile();
4584 return ReadOriginal;
4594 Buffer::ReadStatus Buffer::loadAutosave()
4596 // Now check if autosave file is newer.
4597 FileName const autosaveFile = getAutosaveFileName();
4598 if (!autosaveFile.exists()
4599 || autosaveFile.lastModified() <= d->filename.lastModified())
4600 return ReadFileNotFound;
4602 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4603 docstring const text = bformat(_("The backup of the document %1$s "
4604 "is newer.\n\nLoad the backup instead?"), file);
4605 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4606 _("&Load backup"), _("Load &original"), _("&Cancel"));
4611 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4612 // the file is not saved if we load the autosave file.
4613 if (ret_llf == ReadSuccess) {
4614 if (hasReadonlyFlag()) {
4615 Alert::warning(_("File is read-only"),
4616 bformat(_("A backup file is successfully loaded, "
4617 "but the original file %1$s is marked read-only. "
4618 "Please make sure to save the document as a "
4620 from_utf8(d->filename.absFileName())));
4623 lyxvc().file_found_hook(d->filename);
4626 return ReadAutosaveFailure;
4629 // Here we delete the autosave
4630 autosaveFile.removeFile();
4631 return ReadOriginal;
4639 Buffer::ReadStatus Buffer::loadLyXFile()
4641 if (!d->filename.isReadableFile()) {
4642 ReadStatus const ret_rvc = extractFromVC();
4643 if (ret_rvc != ReadSuccess)
4647 ReadStatus const ret_re = loadEmergency();
4648 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4651 ReadStatus const ret_ra = loadAutosave();
4652 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4655 return loadThisLyXFile(d->filename);
4659 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4661 return readFile(fn);
4665 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4667 for (auto const & err : terr) {
4668 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4669 int errorRow = err.error_in_line;
4670 Buffer const * buf = 0;
4672 if (err.child_name.empty())
4673 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4675 // The error occurred in a child
4676 for (Buffer const * child : getDescendents()) {
4677 string const child_name =
4678 DocFileName(changeExtension(child->absFileName(), "tex")).
4680 if (err.child_name != child_name)
4682 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4683 if (!TexRow::isNone(start)) {
4684 buf = d->cloned_buffer_
4685 ? child->d->cloned_buffer_->d->owner_
4692 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4698 void Buffer::setBuffersForInsets() const
4700 inset().setBuffer(const_cast<Buffer &>(*this));
4704 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4706 LBUFERR(!text().paragraphs().empty());
4708 // Use the master text class also for child documents
4709 Buffer const * const master = masterBuffer();
4710 DocumentClass const & textclass = master->params().documentClass();
4712 // do this only if we are the top-level Buffer
4713 if (master == this) {
4714 textclass.counters().reset(from_ascii("bibitem"));
4715 reloadBibInfoCache();
4718 // keep the buffers to be children in this set. If the call from the
4719 // master comes back we can see which of them were actually seen (i.e.
4720 // via an InsetInclude). The remaining ones in the set need still be updated.
4721 static std::set<Buffer const *> bufToUpdate;
4722 if (scope == UpdateMaster) {
4723 // If this is a child document start with the master
4724 if (master != this) {
4725 bufToUpdate.insert(this);
4726 master->updateBuffer(UpdateMaster, utype);
4727 // If the master buffer has no gui associated with it, then the TocModel is
4728 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4729 // (bug 5699). The same happens if the master buffer is open in a different
4730 // window. This test catches both possibilities.
4731 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4732 // There remains a problem here: If there is another child open in yet a third
4733 // window, that TOC is not updated. So some more general solution is needed at
4735 if (master->d->gui_ != d->gui_)
4738 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4739 if (bufToUpdate.find(this) == bufToUpdate.end())
4743 // start over the counters in the master
4744 textclass.counters().reset();
4747 // update will be done below for this buffer
4748 bufToUpdate.erase(this);
4750 // update all caches
4751 clearReferenceCache();
4753 setChangesPresent(false);
4755 Buffer & cbuf = const_cast<Buffer &>(*this);
4758 ParIterator parit = cbuf.par_iterator_begin();
4759 updateBuffer(parit, utype);
4762 /// Update the tocBackend for any buffer. The outliner uses the master's,
4763 /// and the navigation menu uses the child's.
4764 cbuf.tocBackend().update(true, utype);
4769 d->bibinfo_cache_valid_ = true;
4770 d->cite_labels_valid_ = true;
4771 if (scope == UpdateMaster)
4772 cbuf.structureChanged();
4776 static depth_type getDepth(DocIterator const & it)
4778 depth_type depth = 0;
4779 for (size_t i = 0 ; i < it.depth() ; ++i)
4780 if (!it[i].inset().inMathed())
4781 depth += it[i].paragraph().getDepth() + 1;
4782 // remove 1 since the outer inset does not count
4783 // we should have at least one non-math inset, so
4784 // depth should nevery be 0. but maybe it is worth
4785 // marking this, just in case.
4787 // coverity[INTEGER_OVERFLOW]
4791 static depth_type getItemDepth(ParIterator const & it)
4793 Paragraph const & par = *it;
4794 LabelType const labeltype = par.layout().labeltype;
4796 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4799 // this will hold the lowest depth encountered up to now.
4800 depth_type min_depth = getDepth(it);
4801 ParIterator prev_it = it;
4804 --prev_it.top().pit();
4806 // start of nested inset: go to outer par
4808 if (prev_it.empty()) {
4809 // start of document: nothing to do
4814 // We search for the first paragraph with same label
4815 // that is not more deeply nested.
4816 Paragraph & prev_par = *prev_it;
4817 depth_type const prev_depth = getDepth(prev_it);
4818 if (labeltype == prev_par.layout().labeltype) {
4819 if (prev_depth < min_depth)
4820 return prev_par.itemdepth + 1;
4821 if (prev_depth == min_depth)
4822 return prev_par.itemdepth;
4824 min_depth = min(min_depth, prev_depth);
4825 // small optimization: if we are at depth 0, we won't
4826 // find anything else
4827 if (prev_depth == 0)
4833 static bool needEnumCounterReset(ParIterator const & it)
4835 Paragraph const & par = *it;
4836 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4837 depth_type const cur_depth = par.getDepth();
4838 ParIterator prev_it = it;
4839 while (prev_it.pit()) {
4840 --prev_it.top().pit();
4841 Paragraph const & prev_par = *prev_it;
4842 if (prev_par.getDepth() <= cur_depth)
4843 return prev_par.layout().name() != par.layout().name();
4845 // start of nested inset: reset
4850 // set the label of a paragraph. This includes the counters.
4851 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4853 BufferParams const & bp = owner_->masterBuffer()->params();
4854 DocumentClass const & textclass = bp.documentClass();
4855 Paragraph & par = it.paragraph();
4856 Layout const & layout = par.layout();
4857 Counters & counters = textclass.counters();
4859 if (par.params().startOfAppendix()) {
4860 // We want to reset the counter corresponding to toplevel sectioning
4861 Layout const & lay = textclass.getTOCLayout();
4862 docstring const cnt = lay.counter;
4864 counters.reset(cnt);
4865 counters.appendix(true);
4867 par.params().appendix(counters.appendix());
4869 // Compute the item depth of the paragraph
4870 par.itemdepth = getItemDepth(it);
4872 if (layout.margintype == MARGIN_MANUAL) {
4873 if (par.params().labelWidthString().empty())
4874 par.params().labelWidthString(par.expandLabel(layout, bp));
4875 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4876 // we do not need to do anything here, since the empty case is
4877 // handled during export.
4879 par.params().labelWidthString(docstring());
4882 switch(layout.labeltype) {
4883 case LABEL_ITEMIZE: {
4884 // At some point of time we should do something more
4885 // clever here, like:
4886 // par.params().labelString(
4887 // bp.user_defined_bullet(par.itemdepth).getText());
4888 // for now, use a simple hardcoded label
4889 docstring itemlabel;
4890 switch (par.itemdepth) {
4892 itemlabel = char_type(0x2022);
4895 itemlabel = char_type(0x2013);
4898 itemlabel = char_type(0x2217);
4901 itemlabel = char_type(0x2219); // or 0x00b7
4904 par.params().labelString(itemlabel);
4908 case LABEL_ENUMERATE: {
4909 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4911 switch (par.itemdepth) {
4920 enumcounter += "iv";
4923 // not a valid enumdepth...
4927 // Increase the master counter?
4928 if (layout.stepmastercounter && needEnumCounterReset(it))
4929 counters.stepMaster(enumcounter, utype);
4931 // Maybe we have to reset the enumeration counter.
4932 if (!layout.resumecounter && needEnumCounterReset(it))
4933 counters.reset(enumcounter);
4934 counters.step(enumcounter, utype);
4936 string const & lang = par.getParLanguage(bp)->code();
4937 par.params().labelString(counters.theCounter(enumcounter, lang));
4942 case LABEL_SENSITIVE: {
4943 string const & type = counters.current_float();
4944 docstring full_label;
4946 full_label = owner_->B_("Senseless!!! ");
4948 docstring name = owner_->B_(textclass.floats().getType(type).name());
4949 if (counters.hasCounter(from_utf8(type))) {
4950 string const & lang = par.getParLanguage(bp)->code();
4951 counters.step(from_utf8(type), utype);
4952 full_label = bformat(from_ascii("%1$s %2$s:"),
4954 counters.theCounter(from_utf8(type), lang));
4956 full_label = bformat(from_ascii("%1$s #:"), name);
4958 par.params().labelString(full_label);
4962 case LABEL_NO_LABEL:
4963 par.params().labelString(docstring());
4967 case LABEL_CENTERED:
4968 case LABEL_STATIC: {
4969 docstring const & lcounter = layout.counter;
4970 if (!lcounter.empty()) {
4971 if (layout.toclevel <= bp.secnumdepth
4972 && (layout.latextype != LATEX_ENVIRONMENT
4973 || it.text()->isFirstInSequence(it.pit()))) {
4974 if (counters.hasCounter(lcounter))
4975 counters.step(lcounter, utype);
4976 par.params().labelString(par.expandLabel(layout, bp));
4978 par.params().labelString(docstring());
4980 par.params().labelString(par.expandLabel(layout, bp));
4986 par.params().labelString(par.expandLabel(layout, bp));
4991 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4993 // LASSERT: Is it safe to continue here, or should we just return?
4994 LASSERT(parit.pit() == 0, /**/);
4996 // Set the position of the text in the buffer to be able
4997 // to resolve macros in it.
4998 parit.text()->setMacrocontextPosition(parit);
5000 depth_type maxdepth = 0;
5001 pit_type const lastpit = parit.lastpit();
5002 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5003 // reduce depth if necessary
5004 if (parit->params().depth() > maxdepth) {
5005 /** FIXME: this function is const, but
5006 * nevertheless it modifies the buffer. To be
5007 * cleaner, one should modify the buffer in
5008 * another function, which is actually
5009 * non-const. This would however be costly in
5010 * terms of code duplication.
5012 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5013 parit->params().depth(maxdepth);
5015 maxdepth = parit->getMaxDepthAfter();
5017 if (utype == OutputUpdate) {
5018 // track the active counters
5019 // we have to do this for the master buffer, since the local
5020 // buffer isn't tracking anything.
5021 masterBuffer()->params().documentClass().counters().
5022 setActiveLayout(parit->layout());
5025 // set the counter for this paragraph
5026 d->setLabel(parit, utype);
5028 // update change-tracking flag
5029 parit->addChangesToBuffer(*this);
5032 InsetList::const_iterator iit = parit->insetList().begin();
5033 InsetList::const_iterator end = parit->insetList().end();
5034 for (; iit != end; ++iit) {
5035 parit.pos() = iit->pos;
5036 iit->inset->updateBuffer(parit, utype);
5042 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5043 WordLangTuple & word_lang, docstring_list & suggestions) const
5047 suggestions.clear();
5048 word_lang = WordLangTuple();
5049 bool const to_end = to.empty();
5050 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5051 // OK, we start from here.
5052 for (; from != end; from.forwardPos()) {
5053 // This skips all insets with spell check disabled.
5054 while (!from.allowSpellCheck()) {
5058 // If from is at the end of the document (which is possible
5059 // when "from" was changed above) LyX will crash later otherwise.
5060 if (from.atEnd() || (!to_end && from >= end))
5063 from.paragraph().spellCheck();
5064 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5065 if (SpellChecker::misspelled(res)) {
5069 // Do not increase progress when from == to, otherwise the word
5070 // count will be wrong.
5080 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5082 bool inword = false;
5087 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5088 if (!dit.inTexted()) {
5093 Paragraph const & par = dit.paragraph();
5094 pos_type const pos = dit.pos();
5096 // Copied and adapted from isWordSeparator() in Paragraph
5097 if (pos == dit.lastpos()) {
5100 Inset const * ins = par.getInset(pos);
5101 if (ins && skipNoOutput && !ins->producesOutput()) {
5104 // stop if end of range was skipped
5105 if (!to.atEnd() && dit >= to)
5108 } else if (!par.isDeleted(pos)) {
5109 if (par.isWordSeparator(pos))
5115 if (ins && ins->isLetter())
5117 else if (ins && ins->isSpace())
5120 char_type const c = par.getChar(pos);
5121 if (isPrintableNonspace(c))
5123 else if (isSpace(c))
5133 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5135 d->updateStatistics(from, to, skipNoOutput);
5139 int Buffer::wordCount() const
5141 return d->wordCount();
5145 int Buffer::charCount(bool with_blanks) const
5147 return d->charCount(with_blanks);
5151 Buffer::ReadStatus Buffer::reload()
5154 // c.f. bug http://www.lyx.org/trac/ticket/6587
5155 removeAutosaveFile();
5156 // e.g., read-only status could have changed due to version control
5157 d->filename.refresh();
5158 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5160 // clear parent. this will get reset if need be.
5162 ReadStatus const status = loadLyXFile();
5163 if (status == ReadSuccess) {
5168 message(bformat(_("Document %1$s reloaded."), disp_fn));
5171 message(bformat(_("Could not reload document %1$s."), disp_fn));
5181 bool Buffer::saveAs(FileName const & fn)
5183 FileName const old_name = fileName();
5184 FileName const old_auto = getAutosaveFileName();
5185 bool const old_unnamed = isUnnamed();
5186 bool success = true;
5187 d->old_position = filePath();
5194 // bring the autosave file with us, just in case.
5195 moveAutosaveFile(old_auto);
5196 // validate version control data and
5197 // correct buffer title
5198 lyxvc().file_found_hook(fileName());
5200 // the file has now been saved to the new location.
5201 // we need to check that the locations of child buffers
5203 checkChildBuffers();
5204 checkMasterBuffer();
5207 // reset the old filename and unnamed state
5208 setFileName(old_name);
5209 setUnnamed(old_unnamed);
5213 d->old_position.clear();
5218 void Buffer::checkChildBuffers()
5220 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5221 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5222 for (; it != en; ++it) {
5223 DocIterator dit = it->second;
5224 Buffer * cbuf = const_cast<Buffer *>(it->first);
5225 if (!cbuf || !theBufferList().isLoaded(cbuf))
5227 Inset * inset = dit.nextInset();
5228 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5229 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5230 docstring const & incfile = inset_inc->getParam("filename");
5231 string oldloc = cbuf->absFileName();
5232 string newloc = makeAbsPath(to_utf8(incfile),
5233 onlyPath(absFileName())).absFileName();
5234 if (oldloc == newloc)
5236 // the location of the child file is incorrect.
5238 inset_inc->setChildBuffer(0);
5240 // invalidate cache of children
5241 d->children_positions.clear();
5242 d->position_to_children.clear();
5246 // If a child has been saved under a different name/path, it might have been
5247 // orphaned. Therefore the master needs to be reset (bug 8161).
5248 void Buffer::checkMasterBuffer()
5250 Buffer const * const master = masterBuffer();
5254 // necessary to re-register the child (bug 5873)
5255 // FIXME: clean up updateMacros (here, only
5256 // child registering is needed).
5257 master->updateMacros();
5258 // (re)set master as master buffer, but only
5259 // if we are a real child
5260 if (master->isChild(this))
5267 string Buffer::includedFilePath(string const & name, string const & ext) const
5269 if (d->old_position.empty() ||
5270 equivalent(FileName(d->old_position), FileName(filePath())))
5273 bool isabsolute = FileName::isAbsolute(name);
5274 // both old_position and filePath() end with a path separator
5275 string absname = isabsolute ? name : d->old_position + name;
5277 // if old_position is set to origin, we need to do the equivalent of
5278 // getReferencedFileName() (see readDocument())
5279 if (!isabsolute && d->old_position == params().origin) {
5280 FileName const test(addExtension(filePath() + name, ext));
5282 absname = filePath() + name;
5285 if (!FileName(addExtension(absname, ext)).exists())
5289 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5291 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5292 from_utf8(filePath())));
5296 void Buffer::setChangesPresent(bool b) const
5298 d->tracked_changes_present_ = b;
5302 bool Buffer::areChangesPresent() const
5304 return d->tracked_changes_present_;
5308 void Buffer::updateChangesPresent() const
5310 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5311 setChangesPresent(false);
5312 ParConstIterator it = par_iterator_begin();
5313 ParConstIterator const end = par_iterator_end();
5314 for (; !areChangesPresent() && it != end; ++it)
5315 it->addChangesToBuffer(*this);
5319 void Buffer::Impl::refreshFileMonitor()
5321 if (file_monitor_ && file_monitor_->filename() == filename.absFileName())
5322 return file_monitor_->refresh();
5324 // The previous file monitor is invalid
5325 // This also destroys the previous file monitor and all its connections
5326 file_monitor_ = FileSystemWatcher::monitor(filename);
5327 fileExternallyModified(false);
5328 // file_monitor_ will be destroyed with *this, so it is not going to call a
5329 // destroyed object method.
5330 file_monitor_->connect([this](){ fileExternallyModified(true); });
5334 void Buffer::Impl::fileExternallyModified(bool modified) const
5337 lyx_clean = bak_clean = false;
5338 externally_modified_ = modified;
5340 wa_->updateTitles();
5344 bool Buffer::notifiesExternalModification() const
5346 return d->isExternallyModified();
5350 void Buffer::clearExternalModification() const
5352 d->fileExternallyModified(false);