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/InsetMathMacroTemplate.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 /// Notify or clear of external modification
383 void fileExternallyModified(bool exists);
385 /// has been externally modified? Can be reset by the user.
386 mutable bool externally_modified_;
389 /// So we can force access via the accessors.
390 mutable Buffer const * parent_buffer;
396 FileMonitorPtr file_monitor_;
400 /// Creates the per buffer temporary directory
401 static FileName createBufferTmpDir()
403 // FIXME This would be the ideal application for a TempDir class (like
404 // TempFile but for directories)
409 Mutex::Locker locker(&mutex);
410 counter = convert<string>(count++);
412 // We are in our own directory. Why bother to mangle name?
413 // In fact I wrote this code to circumvent a problematic behaviour
414 // (bug?) of EMX mkstemp().
415 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
418 if (!tmpfl.createDirectory(0777)) {
419 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
420 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
421 from_utf8(tmpfl.absFileName())));
427 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
428 Buffer const * cloned_buffer)
429 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
430 internal_buffer(false), read_only(readonly_), filename(file),
431 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
432 ignore_parent(false), toc_backend(owner), macro_lock(false),
433 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
434 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
435 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
436 clone_list_(0), doing_export(false),
437 tracked_changes_present_(0), externally_modified_(false), parent_buffer(0),
438 word_count_(0), char_count_(0), blank_count_(0)
440 refreshFileMonitor();
441 if (!cloned_buffer_) {
442 temppath = createBufferTmpDir();
443 lyxvc.setBuffer(owner_);
445 wa_ = new frontend::WorkAreaManager;
448 temppath = cloned_buffer_->d->temppath;
449 file_fully_loaded = true;
450 params = cloned_buffer_->d->params;
451 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
452 bibinfo_ = cloned_buffer_->d->bibinfo_;
453 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
454 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
455 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
456 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
457 unnamed = cloned_buffer_->d->unnamed;
458 internal_buffer = cloned_buffer_->d->internal_buffer;
459 layout_position = cloned_buffer_->d->layout_position;
460 preview_file_ = cloned_buffer_->d->preview_file_;
461 preview_format_ = cloned_buffer_->d->preview_format_;
462 preview_error_ = cloned_buffer_->d->preview_error_;
463 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
467 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
468 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
470 LYXERR(Debug::INFO, "Buffer::Buffer()");
472 d->inset = new InsetText(*cloned_buffer->d->inset);
473 d->inset->setBuffer(*this);
474 // FIXME: optimize this loop somewhat, maybe by creating a new
475 // general recursive Inset::setId().
476 DocIterator it = doc_iterator_begin(this);
477 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
478 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
479 it.paragraph().setId(cloned_it.paragraph().id());
481 d->inset = new InsetText(this);
482 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
488 LYXERR(Debug::INFO, "Buffer::~Buffer()");
489 // here the buffer should take care that it is
490 // saved properly, before it goes into the void.
492 // GuiView already destroyed
496 // No need to do additional cleanups for internal buffer.
502 // this is in case of recursive includes: we won't try to delete
503 // ourselves as a child.
504 d->clone_list_->erase(this);
505 // loop over children
506 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
507 Impl::BufferPositionMap::iterator end = d->children_positions.end();
508 for (; it != end; ++it) {
509 Buffer * child = const_cast<Buffer *>(it->first);
510 if (d->clone_list_->erase(child))
513 // if we're the master buffer, then we should get rid of the list
516 // If this is not empty, we have leaked something. Worse, one of the
517 // children still has a reference to this list. But we will try to
518 // continue, rather than shut down.
519 LATTEST(d->clone_list_->empty());
520 list<CloneList *>::iterator it =
521 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
522 if (it == cloned_buffers.end()) {
523 // We will leak in this case, but it is safe to continue.
526 cloned_buffers.erase(it);
527 delete d->clone_list_;
529 // FIXME Do we really need to do this right before we delete d?
530 // clear references to children in macro tables
531 d->children_positions.clear();
532 d->position_to_children.clear();
534 // loop over children
535 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
536 Impl::BufferPositionMap::iterator end = d->children_positions.end();
537 for (; it != end; ++it) {
538 Buffer * child = const_cast<Buffer *>(it->first);
539 if (theBufferList().isLoaded(child)) {
540 if (theBufferList().isOthersChild(this, child))
543 theBufferList().release(child);
548 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
550 msg += emergencyWrite();
552 msg += " " + _("Save failed! Document is lost.");
554 Alert::warning(_("Attempting to close changed document!"), msg);
557 // FIXME Do we really need to do this right before we delete d?
558 // clear references to children in macro tables
559 d->children_positions.clear();
560 d->position_to_children.clear();
562 if (!d->temppath.destroyDirectory()) {
563 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
564 from_utf8(d->temppath.absFileName())));
573 Buffer * Buffer::cloneFromMaster() const
576 cloned_buffers.push_back(new CloneList);
577 CloneList * clones = cloned_buffers.back();
579 masterBuffer()->cloneWithChildren(bufmap, clones);
581 // make sure we got cloned
582 BufferMap::const_iterator bit = bufmap.find(this);
583 LASSERT(bit != bufmap.end(), return 0);
584 Buffer * cloned_buffer = bit->second;
586 return cloned_buffer;
590 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
592 // have we already been cloned?
593 if (bufmap.find(this) != bufmap.end())
596 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
598 // The clone needs its own DocumentClass, since running updateBuffer() will
599 // modify it, and we would otherwise be sharing it with the original Buffer.
600 buffer_clone->params().makeDocumentClass(true);
602 cap::switchBetweenClasses(
603 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
604 static_cast<InsetText &>(buffer_clone->inset()), el);
606 bufmap[this] = buffer_clone;
607 clones->insert(buffer_clone);
608 buffer_clone->d->clone_list_ = clones;
609 buffer_clone->d->macro_lock = true;
610 buffer_clone->d->children_positions.clear();
612 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
613 // math macro caches need to be rethought and simplified.
614 // I am not sure wether we should handle Buffer cloning here or in BufferList.
615 // Right now BufferList knows nothing about buffer clones.
616 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
617 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
618 for (; it != end; ++it) {
619 DocIterator dit = it->first.clone(buffer_clone);
620 dit.setBuffer(buffer_clone);
621 Buffer * child = const_cast<Buffer *>(it->second.buffer);
623 child->cloneWithChildren(bufmap, clones);
624 BufferMap::iterator const bit = bufmap.find(child);
625 LASSERT(bit != bufmap.end(), continue);
626 Buffer * child_clone = bit->second;
628 Inset * inset = dit.nextInset();
629 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
630 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
631 inset_inc->setChildBuffer(child_clone);
632 child_clone->d->setParent(buffer_clone);
633 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
634 buffer_clone->setChild(dit, child_clone);
636 buffer_clone->d->macro_lock = false;
641 Buffer * Buffer::cloneBufferOnly() const {
642 cloned_buffers.push_back(new CloneList);
643 CloneList * clones = cloned_buffers.back();
644 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
646 // The clone needs its own DocumentClass, since running updateBuffer() will
647 // modify it, and we would otherwise be sharing it with the original Buffer.
648 buffer_clone->params().makeDocumentClass(true);
650 cap::switchBetweenClasses(
651 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
652 static_cast<InsetText &>(buffer_clone->inset()), el);
654 clones->insert(buffer_clone);
655 buffer_clone->d->clone_list_ = clones;
657 // we won't be cloning the children
658 buffer_clone->d->children_positions.clear();
663 bool Buffer::isClone() const
665 return d->cloned_buffer_;
669 void Buffer::changed(bool update_metrics) const
672 d->wa_->redrawAll(update_metrics);
676 frontend::WorkAreaManager & Buffer::workAreaManager() const
683 Text & Buffer::text() const
685 return d->inset->text();
689 Inset & Buffer::inset() const
695 BufferParams & Buffer::params()
701 BufferParams const & Buffer::params() const
707 BufferParams const & Buffer::masterParams() const
709 if (masterBuffer() == this)
712 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
713 // Copy child authors to the params. We need those pointers.
714 AuthorList const & child_authors = params().authors();
715 AuthorList::Authors::const_iterator it = child_authors.begin();
716 for (; it != child_authors.end(); ++it)
717 mparams.authors().record(*it);
722 double Buffer::fontScalingFactor() const
724 return isExporting() ? 75.0 * params().html_math_img_scale
725 : 0.01 * lyxrc.dpi * lyxrc.currentZoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
729 ParagraphList & Buffer::paragraphs()
731 return text().paragraphs();
735 ParagraphList const & Buffer::paragraphs() const
737 return text().paragraphs();
741 LyXVC & Buffer::lyxvc()
747 LyXVC const & Buffer::lyxvc() const
753 string const Buffer::temppath() const
755 return d->temppath.absFileName();
759 TexRow & Buffer::texrow()
765 TexRow const & Buffer::texrow() const
771 TocBackend & Buffer::tocBackend() const
773 return d->toc_backend;
777 Undo & Buffer::undo()
783 void Buffer::setChild(DocIterator const & dit, Buffer * child)
785 d->children_positions[child] = dit;
789 string Buffer::latexName(bool const no_path) const
791 FileName latex_name =
792 makeLatexName(d->exportFileName());
793 return no_path ? latex_name.onlyFileName()
794 : latex_name.absFileName();
798 FileName Buffer::Impl::exportFileName() const
800 docstring const branch_suffix =
801 params.branchlist().getFileNameSuffix();
802 if (branch_suffix.empty())
805 string const name = filename.onlyFileNameWithoutExt()
806 + to_utf8(branch_suffix);
807 FileName res(filename.onlyPath().absFileName() + "/" + name);
808 res.changeExtension(filename.extension());
814 string Buffer::logName(LogType * type) const
816 string const filename = latexName(false);
818 if (filename.empty()) {
824 string const path = temppath();
826 FileName const fname(addName(temppath(),
827 onlyFileName(changeExtension(filename,
830 // FIXME: how do we know this is the name of the build log?
831 FileName const bname(
832 addName(path, onlyFileName(
833 changeExtension(filename,
834 theFormats().extension(params().bufferFormat()) + ".out"))));
836 // Also consider the master buffer log file
837 FileName masterfname = fname;
838 LogType mtype = latexlog;
839 if (masterBuffer() != this) {
840 string const mlogfile = masterBuffer()->logName(&mtype);
841 masterfname = FileName(mlogfile);
844 // If no Latex log or Build log is newer, show Build log
845 if (bname.exists() &&
846 ((!fname.exists() && !masterfname.exists())
847 || (fname.lastModified() < bname.lastModified()
848 && masterfname.lastModified() < bname.lastModified()))) {
849 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
852 return bname.absFileName();
853 // If we have a newer master file log or only a master log, show this
854 } else if (fname != masterfname
855 && (!fname.exists() && (masterfname.exists()
856 || fname.lastModified() < masterfname.lastModified()))) {
857 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
860 return masterfname.absFileName();
862 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
865 return fname.absFileName();
869 void Buffer::setReadonly(bool const flag)
871 if (d->read_only != flag) {
878 void Buffer::setFileName(FileName const & fname)
880 bool const changed = fname != d->filename;
882 d->refreshFileMonitor();
884 lyxvc().file_found_hook(fname);
885 setReadonly(d->filename.isReadOnly());
891 int Buffer::readHeader(Lexer & lex)
893 int unknown_tokens = 0;
895 int begin_header_line = -1;
897 // Initialize parameters that may be/go lacking in header:
898 params().branchlist().clear();
899 params().preamble.erase();
900 params().options.erase();
901 params().master.erase();
902 params().float_placement.erase();
903 params().paperwidth.erase();
904 params().paperheight.erase();
905 params().leftmargin.erase();
906 params().rightmargin.erase();
907 params().topmargin.erase();
908 params().bottommargin.erase();
909 params().headheight.erase();
910 params().headsep.erase();
911 params().footskip.erase();
912 params().columnsep.erase();
913 params().fonts_cjk.erase();
914 params().listings_params.clear();
915 params().clearLayoutModules();
916 params().clearRemovedModules();
917 params().clearIncludedChildren();
918 params().pdfoptions().clear();
919 params().indiceslist().clear();
920 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
921 params().isbackgroundcolor = false;
922 params().fontcolor = RGBColor(0, 0, 0);
923 params().isfontcolor = false;
924 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
925 params().boxbgcolor = RGBColor(0xFF, 0, 0);
926 params().html_latex_start.clear();
927 params().html_latex_end.clear();
928 params().html_math_img_scale = 1.0;
929 params().output_sync_macro.erase();
930 params().setLocalLayout(docstring(), false);
931 params().setLocalLayout(docstring(), true);
932 params().biblio_opts.erase();
933 params().biblatex_bibstyle.erase();
934 params().biblatex_citestyle.erase();
935 params().multibib.erase();
937 for (int i = 0; i < 4; ++i) {
938 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
939 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
942 ErrorList & errorList = d->errorLists["Parse"];
951 if (token == "\\end_header")
955 if (token == "\\begin_header") {
956 begin_header_line = line;
960 LYXERR(Debug::PARSER, "Handling document header token: `"
963 string const result =
964 params().readToken(lex, token, d->filename.onlyPath());
965 if (!result.empty()) {
966 if (token == "\\textclass") {
967 d->layout_position = result;
970 docstring const s = bformat(_("Unknown token: "
974 errorList.push_back(ErrorItem(_("Document header error"), s));
978 if (begin_header_line) {
979 docstring const s = _("\\begin_header is missing");
980 errorList.push_back(ErrorItem(_("Document header error"), s));
983 params().makeDocumentClass();
985 return unknown_tokens;
990 // changed to be public and have one parameter
991 // Returns true if "\end_document" is not read (Asger)
992 bool Buffer::readDocument(Lexer & lex)
994 ErrorList & errorList = d->errorLists["Parse"];
997 // remove dummy empty par
998 paragraphs().clear();
1000 if (!lex.checkFor("\\begin_document")) {
1001 docstring const s = _("\\begin_document is missing");
1002 errorList.push_back(ErrorItem(_("Document header error"), s));
1007 if (params().output_changes) {
1008 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1009 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1010 LaTeXFeatures::isAvailable("xcolor");
1012 if (!dvipost && !xcolorulem) {
1013 Alert::warning(_("Changes not shown in LaTeX output"),
1014 _("Changes will not be highlighted in LaTeX output, "
1015 "because neither dvipost nor xcolor/ulem are installed.\n"
1016 "Please install these packages or redefine "
1017 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1018 } else if (!xcolorulem) {
1019 Alert::warning(_("Changes not shown in LaTeX output"),
1020 _("Changes will not be highlighted in LaTeX output "
1021 "when using pdflatex, because xcolor and ulem are not installed.\n"
1022 "Please install both packages or redefine "
1023 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1027 if (!parent() && !params().master.empty()) {
1028 FileName const master_file = makeAbsPath(params().master,
1029 onlyPath(absFileName()));
1030 if (isLyXFileName(master_file.absFileName())) {
1032 checkAndLoadLyXFile(master_file, true);
1034 // necessary e.g. after a reload
1035 // to re-register the child (bug 5873)
1036 // FIXME: clean up updateMacros (here, only
1037 // child registering is needed).
1038 master->updateMacros();
1039 // set master as master buffer, but only
1040 // if we are a real child
1041 if (master->isChild(this))
1043 // if the master is not fully loaded
1044 // it is probably just loading this
1045 // child. No warning needed then.
1046 else if (master->isFullyLoaded())
1047 LYXERR0("The master '"
1049 << "' assigned to this document ("
1051 << ") does not include "
1052 "this document. Ignoring the master assignment.");
1057 // assure we have a default index
1058 params().indiceslist().addDefault(B_("Index"));
1061 if (FileName::isAbsolute(params().origin))
1062 d->old_position = params().origin;
1064 d->old_position = filePath();
1065 bool const res = text().read(lex, errorList, d->inset);
1066 d->old_position.clear();
1068 // inform parent buffer about local macros
1070 Buffer const * pbuf = parent();
1071 UserMacroSet::const_iterator cit = usermacros.begin();
1072 UserMacroSet::const_iterator end = usermacros.end();
1073 for (; cit != end; ++cit)
1074 pbuf->usermacros.insert(*cit);
1078 updateMacroInstances(InternalUpdate);
1083 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1085 Format const * fmt = theFormats().getFormat(format);
1088 // It is important to use the correct extension here, since some
1089 // converters create a wrong output file otherwise (e.g. html2latex)
1090 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1091 FileName const name(tempfile.name());
1092 ofdocstream os(name.toFilesystemEncoding().c_str());
1093 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1094 bool const success = !(os << contents).fail();
1097 bool converted = false;
1099 params().compressed = false;
1101 // remove dummy empty par
1102 paragraphs().clear();
1104 converted = importFile(format, name, errorList);
1113 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1115 if (!theConverters().isReachable(format, "lyx"))
1118 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1119 FileName const lyx(tempfile.name());
1120 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1121 return readFile(lyx) == ReadSuccess;
1127 bool Buffer::readString(string const & s)
1129 params().compressed = false;
1132 istringstream is(s);
1134 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1135 FileName const fn = tempfile.name();
1138 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1140 if (success && file_format != LYX_FORMAT) {
1141 // We need to call lyx2lyx, so write the input to a file
1142 ofstream os(fn.toFilesystemEncoding().c_str());
1145 // lyxvc in readFile
1146 if (readFile(fn) != ReadSuccess)
1150 if (readDocument(lex))
1156 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1160 if (!lex.setFile(fname)) {
1161 Alert::error(_("File Not Found"),
1162 bformat(_("Unable to open file `%1$s'."),
1163 from_utf8(fn.absFileName())));
1164 return ReadFileNotFound;
1168 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1169 if (ret_plf != ReadSuccess)
1172 if (file_format != LYX_FORMAT) {
1174 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1175 if (ret_clf != ReadSuccess)
1177 ret_clf = readFile(tmpFile);
1178 if (ret_clf == ReadSuccess) {
1179 d->file_format = file_format;
1180 d->need_format_backup = true;
1185 // FIXME: InsetInfo needs to know whether the file is under VCS
1186 // during the parse process, so this has to be done before.
1187 lyxvc().file_found_hook(d->filename);
1189 if (readDocument(lex)) {
1190 Alert::error(_("Document format failure"),
1191 bformat(_("%1$s ended unexpectedly, which means"
1192 " that it is probably corrupted."),
1193 from_utf8(fn.absFileName())));
1194 return ReadDocumentFailure;
1197 d->file_fully_loaded = true;
1198 d->read_only = !d->filename.isWritable();
1199 params().compressed = theFormats().isZippedFile(d->filename);
1205 bool Buffer::isFullyLoaded() const
1207 return d->file_fully_loaded;
1211 void Buffer::setFullyLoaded(bool value)
1213 d->file_fully_loaded = value;
1217 bool Buffer::lastPreviewError() const
1219 return d->preview_error_;
1223 PreviewLoader * Buffer::loader() const
1225 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1227 if (!d->preview_loader_)
1228 d->preview_loader_ = new PreviewLoader(*this);
1229 return d->preview_loader_;
1233 void Buffer::removePreviews() const
1235 delete d->preview_loader_;
1236 d->preview_loader_ = 0;
1240 void Buffer::updatePreviews() const
1242 PreviewLoader * ploader = loader();
1246 InsetIterator it = inset_iterator_begin(*d->inset);
1247 InsetIterator const end = inset_iterator_end(*d->inset);
1248 for (; it != end; ++it)
1249 it->addPreview(it, *ploader);
1251 ploader->startLoading();
1255 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1256 FileName const & fn, int & file_format) const
1258 if(!lex.checkFor("\\lyxformat")) {
1259 Alert::error(_("Document format failure"),
1260 bformat(_("%1$s is not a readable LyX document."),
1261 from_utf8(fn.absFileName())));
1262 return ReadNoLyXFormat;
1268 // LyX formats 217 and earlier were written as 2.17. This corresponds
1269 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1270 // these cases. See also: www.lyx.org/trac/changeset/1313.
1271 size_t dot = tmp_format.find_first_of(".,");
1272 if (dot != string::npos)
1273 tmp_format.erase(dot, 1);
1275 file_format = convert<int>(tmp_format);
1280 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1281 FileName & tmpfile, int from_format)
1283 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1284 tempfile.setAutoRemove(false);
1285 tmpfile = tempfile.name();
1286 if(tmpfile.empty()) {
1287 Alert::error(_("Conversion failed"),
1288 bformat(_("%1$s is from a different"
1289 " version of LyX, but a temporary"
1290 " file for converting it could"
1291 " not be created."),
1292 from_utf8(fn.absFileName())));
1293 return LyX2LyXNoTempFile;
1296 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1297 if (lyx2lyx.empty()) {
1298 Alert::error(_("Conversion script not found"),
1299 bformat(_("%1$s is from a different"
1300 " version of LyX, but the"
1301 " conversion script lyx2lyx"
1302 " could not be found."),
1303 from_utf8(fn.absFileName())));
1304 return LyX2LyXNotFound;
1308 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1309 ostringstream command;
1310 command << os::python()
1311 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1312 << " -t " << convert<string>(LYX_FORMAT)
1313 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1314 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1315 string const command_str = command.str();
1317 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1319 cmd_ret const ret = runCommand(command_str);
1320 if (ret.first != 0) {
1321 if (from_format < LYX_FORMAT) {
1322 Alert::error(_("Conversion script failed"),
1323 bformat(_("%1$s is from an older version"
1324 " of LyX and the lyx2lyx script"
1325 " failed to convert it."),
1326 from_utf8(fn.absFileName())));
1327 return LyX2LyXOlderFormat;
1329 Alert::error(_("Conversion script failed"),
1330 bformat(_("%1$s is from a newer version"
1331 " of LyX and the lyx2lyx script"
1332 " failed to convert it."),
1333 from_utf8(fn.absFileName())));
1334 return LyX2LyXNewerFormat;
1341 FileName Buffer::getBackupName() const {
1342 FileName const & fn = fileName();
1343 string const fname = fn.onlyFileNameWithoutExt();
1344 string const fext = fn.extension() + "~";
1345 string const fpath = lyxrc.backupdir_path.empty() ?
1346 fn.onlyPath().absFileName() :
1347 lyxrc.backupdir_path;
1348 string const fform = convert<string>(d->file_format);
1349 string const backname = fname + "-lyxformat-" + fform;
1350 FileName backup(addName(fpath, addExtension(backname, fext)));
1352 // limit recursion, just in case
1354 unsigned long orig_checksum = 0;
1355 while (backup.exists() && v < 100) {
1356 if (orig_checksum == 0)
1357 orig_checksum = fn.checksum();
1358 unsigned long new_checksum = backup.checksum();
1359 if (orig_checksum == new_checksum) {
1360 LYXERR(Debug::FILES, "Not backing up " << fn <<
1361 "since " << backup << "has the same checksum.");
1362 // a bit of a hack, but we have to check this anyway
1363 // below, and setting this is simpler than introducing
1364 // a special boolean for this purpose.
1368 string const newbackname = backname + "-" + convert<string>(v);
1369 backup.set(addName(fpath, addExtension(newbackname, fext)));
1372 return v < 100 ? backup : FileName();
1376 // Should probably be moved to somewhere else: BufferView? GuiView?
1377 bool Buffer::save() const
1379 docstring const file = makeDisplayPath(absFileName(), 20);
1380 d->filename.refresh();
1382 // check the read-only status before moving the file as a backup
1383 if (d->filename.exists()) {
1384 bool const read_only = !d->filename.isWritable();
1386 Alert::warning(_("File is read-only"),
1387 bformat(_("The file %1$s cannot be written because it "
1388 "is marked as read-only."), file));
1393 // ask if the disk file has been externally modified (use checksum method)
1394 if (fileName().exists() && isChecksumModified()) {
1396 bformat(_("Document %1$s has been externally modified. "
1397 "Are you sure you want to overwrite this file?"), file);
1398 int const ret = Alert::prompt(_("Overwrite modified file?"),
1399 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1404 // We don't need autosaves in the immediate future. (Asger)
1405 resetAutosaveTimers();
1407 // if the file does not yet exist, none of the backup activity
1408 // that follows is necessary
1409 if (!fileName().exists()) {
1410 if (!writeFile(fileName()))
1416 // we first write the file to a new name, then move it to its
1417 // proper location once that has been done successfully. that
1418 // way we preserve the original file if something goes wrong.
1419 string const justname = fileName().onlyFileNameWithoutExt();
1420 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1421 justname + "-XXXXXX.lyx");
1422 bool const symlink = fileName().isSymLink();
1424 tempfile->setAutoRemove(false);
1426 FileName savefile(tempfile->name());
1427 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1428 if (!writeFile(savefile))
1431 // we will set this to false if we fail
1432 bool made_backup = true;
1434 FileName backupName;
1435 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1437 if (d->need_format_backup)
1438 backupName = getBackupName();
1440 // If we for some reason failed to find a backup name in case of
1441 // a format change, this will still set one. It's the best we can
1443 if (backupName.empty()) {
1444 backupName.set(fileName().absFileName() + "~");
1445 if (!lyxrc.backupdir_path.empty()) {
1446 string const mangledName =
1447 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1448 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1452 LYXERR(Debug::FILES, "Backing up original file to " <<
1453 backupName.absFileName());
1454 // Except file is symlink do not copy because of #6587.
1455 // Hard links have bad luck.
1456 made_backup = symlink ?
1457 fileName().copyTo(backupName):
1458 fileName().moveTo(backupName);
1461 Alert::error(_("Backup failure"),
1462 bformat(_("Cannot create backup file %1$s.\n"
1463 "Please check whether the directory exists and is writable."),
1464 from_utf8(backupName.absFileName())));
1465 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1466 } else if (d->need_format_backup) {
1467 // the original file has been backed up successfully, so we
1468 // will not need to do that again
1469 d->need_format_backup = false;
1473 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1474 // Only do this if tempfile is not in autoremove mode
1477 // If we have no symlink, we can simply rename the temp file.
1478 // Otherwise, we need to copy it so the symlink stays intact.
1479 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1480 savefile.moveTo(fileName()))
1482 // saveCheckSum() was already called by writeFile(), but the
1483 // time stamp is invalidated by copying/moving
1486 if (d->file_format != LYX_FORMAT)
1487 // the file associated with this buffer is now in the current format
1488 d->file_format = LYX_FORMAT;
1491 // else we saved the file, but failed to move it to the right location.
1493 if (needBackup && made_backup && !symlink) {
1494 // the original file was moved to some new location, so it will look
1495 // to the user as if it was deleted. (see bug #9234.) we could try
1496 // to restore it, but that would basically mean trying to do again
1497 // what we just failed to do. better to leave things as they are.
1498 Alert::error(_("Write failure"),
1499 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1500 "But LyX could not move it to:\n %2$s.\n"
1501 "Your original file has been backed up to:\n %3$s"),
1502 from_utf8(savefile.absFileName()),
1503 from_utf8(fileName().absFileName()),
1504 from_utf8(backupName.absFileName())));
1506 // either we did not try to make a backup, or else we tried and failed,
1507 // or else the original file was a symlink, in which case it was copied,
1508 // not moved. so the original file is intact.
1509 Alert::error(_("Write failure"),
1510 bformat(_("Cannot move saved file to:\n %1$s.\n"
1511 "But the file has successfully been saved as:\n %2$s."),
1512 from_utf8(fileName().absFileName()),
1513 from_utf8(savefile.absFileName())));
1519 bool Buffer::writeFile(FileName const & fname) const
1521 if (d->read_only && fname == d->filename)
1524 bool retval = false;
1526 docstring const str = bformat(_("Saving document %1$s..."),
1527 makeDisplayPath(fname.absFileName()));
1530 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1532 if (params().compressed) {
1533 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1534 retval = ofs && write(ofs);
1536 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1537 retval = ofs && write(ofs);
1541 message(str + _(" could not write file!"));
1546 // removeAutosaveFile();
1549 message(str + _(" done."));
1555 docstring Buffer::emergencyWrite()
1557 // No need to save if the buffer has not changed.
1561 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1563 docstring user_message = bformat(
1564 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1566 // We try to save three places:
1567 // 1) Same place as document. Unless it is an unnamed doc.
1569 string s = absFileName();
1572 if (writeFile(FileName(s))) {
1574 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1575 return user_message;
1577 user_message += " " + _("Save failed! Trying again...\n");
1581 // 2) In HOME directory.
1582 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1584 lyxerr << ' ' << s << endl;
1585 if (writeFile(FileName(s))) {
1587 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1588 return user_message;
1591 user_message += " " + _("Save failed! Trying yet again...\n");
1593 // 3) In "/tmp" directory.
1594 // MakeAbsPath to prepend the current
1595 // drive letter on OS/2
1596 s = addName(package().temp_dir().absFileName(), absFileName());
1598 lyxerr << ' ' << s << endl;
1599 if (writeFile(FileName(s))) {
1601 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1602 return user_message;
1605 user_message += " " + _("Save failed! Document is lost.");
1608 return user_message;
1612 bool Buffer::write(ostream & ofs) const
1615 // Use the standard "C" locale for file output.
1616 ofs.imbue(locale::classic());
1619 // The top of the file should not be written by params().
1621 // write out a comment in the top of the file
1622 // Important: Keep the version formatting in sync with lyx2lyx and
1623 // tex2lyx (bug 7951)
1624 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1625 << " created this file. For more info see http://www.lyx.org/\n"
1626 << "\\lyxformat " << LYX_FORMAT << "\n"
1627 << "\\begin_document\n";
1629 /// For each author, set 'used' to true if there is a change
1630 /// by this author in the document; otherwise set it to 'false'.
1631 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1632 AuthorList::Authors::const_iterator a_end = params().authors().end();
1633 for (; a_it != a_end; ++a_it)
1634 a_it->setUsed(false);
1636 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1637 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1638 for ( ; it != end; ++it)
1639 it->checkAuthors(params().authors());
1641 // now write out the buffer parameters.
1642 ofs << "\\begin_header\n";
1643 params().writeFile(ofs, this);
1644 ofs << "\\end_header\n";
1647 ofs << "\n\\begin_body\n";
1649 ofs << "\n\\end_body\n";
1651 // Write marker that shows file is complete
1652 ofs << "\\end_document" << endl;
1654 // Shouldn't really be needed....
1657 // how to check if close went ok?
1658 // Following is an attempt... (BE 20001011)
1660 // good() returns false if any error occurred, including some
1661 // formatting error.
1662 // bad() returns true if something bad happened in the buffer,
1663 // which should include file system full errors.
1668 lyxerr << "File was not closed properly." << endl;
1675 bool Buffer::makeLaTeXFile(FileName const & fname,
1676 string const & original_path,
1677 OutputParams const & runparams_in,
1678 OutputWhat output) const
1680 OutputParams runparams = runparams_in;
1682 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1683 // Check here, because the "flavor" is not known in BufferParams::encoding()
1684 // (power users can override this safety measure selecting "utf8-plain").
1685 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1686 && (runparams.encoding->name() != "utf8-plain"))
1687 runparams.encoding = encodings.fromLyXName("ascii");
1689 string const encoding = runparams.encoding->iconvName();
1690 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1693 try { ofs.reset(encoding); }
1694 catch (iconv_codecvt_facet_exception const & e) {
1695 lyxerr << "Caught iconv exception: " << e.what() << endl;
1696 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1697 "verify that the support software for your encoding (%1$s) is "
1698 "properly installed"), from_ascii(encoding)));
1701 if (!openFileWrite(ofs, fname))
1704 ErrorList & errorList = d->errorLists["Export"];
1706 bool failed_export = false;
1709 // make sure we are ready to export
1710 // this needs to be done before we validate
1711 // FIXME Do we need to do this all the time? I.e., in children
1712 // of a master we are exporting?
1714 updateMacroInstances(OutputUpdate);
1717 writeLaTeXSource(os, original_path, runparams, output);
1719 catch (EncodingException const & e) {
1720 docstring const failed(1, e.failed_char);
1722 oss << "0x" << hex << e.failed_char << dec;
1723 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1724 " (code point %2$s)"),
1725 failed, from_utf8(oss.str()));
1726 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1727 "representable in the chosen encoding.\n"
1728 "Changing the document encoding to utf8 could help."),
1729 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1730 failed_export = true;
1732 catch (iconv_codecvt_facet_exception const & e) {
1733 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1735 failed_export = true;
1737 catch (exception const & e) {
1738 errorList.push_back(ErrorItem(_("conversion failed"),
1740 lyxerr << e.what() << endl;
1741 failed_export = true;
1744 lyxerr << "Caught some really weird exception..." << endl;
1748 d->texrow = move(os.texrow());
1752 failed_export = true;
1753 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1756 if (runparams_in.silent)
1760 return !failed_export;
1764 void Buffer::writeLaTeXSource(otexstream & os,
1765 string const & original_path,
1766 OutputParams const & runparams_in,
1767 OutputWhat output) const
1769 // The child documents, if any, shall be already loaded at this point.
1771 OutputParams runparams = runparams_in;
1773 // XeTeX with TeX fonts is only safe with ASCII encoding,
1774 // Check here, because the "flavor" is not known in BufferParams::encoding()
1775 // (power users can override this safety measure selecting "utf8-plain").
1776 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1777 && (runparams.encoding->name() != "utf8-plain"))
1778 runparams.encoding = encodings.fromLyXName("ascii");
1779 // FIXME: when only the current paragraph is shown, this is ignored
1780 // (or not reached) and characters encodable in the current
1781 // encoding are not converted to ASCII-representation.
1783 // If we are compiling a file standalone, even if this is the
1784 // child of some other buffer, let's cut the link here, so the
1785 // file is really independent and no concurring settings from
1786 // the master (e.g. branch state) interfere (see #8100).
1787 if (!runparams.is_child)
1788 d->ignore_parent = true;
1790 // Classify the unicode characters appearing in math insets
1791 BufferEncodings::initUnicodeMath(*this);
1793 // validate the buffer.
1794 LYXERR(Debug::LATEX, " Validating buffer...");
1795 LaTeXFeatures features(*this, params(), runparams);
1797 // This is only set once per document (in master)
1798 if (!runparams.is_child)
1799 runparams.use_polyglossia = features.usePolyglossia();
1800 LYXERR(Debug::LATEX, " Buffer validation done.");
1802 bool const output_preamble =
1803 output == FullSource || output == OnlyPreamble;
1804 bool const output_body =
1805 output == FullSource || output == OnlyBody;
1807 // The starting paragraph of the coming rows is the
1808 // first paragraph of the document. (Asger)
1809 if (output_preamble && runparams.nice) {
1810 os << "%% LyX " << lyx_version << " created this file. "
1811 "For more info, see http://www.lyx.org/.\n"
1812 "%% Do not edit unless you really know what "
1815 LYXERR(Debug::INFO, "lyx document header finished");
1817 // There are a few differences between nice LaTeX and usual files:
1818 // usual files have \batchmode and special input@path to allow
1819 // inclusion of figures specified by an explicitly relative path
1820 // (i.e., a path starting with './' or '../') with either \input or
1821 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1822 // input@path is set when the actual parameter original_path is set.
1823 // This is done for usual tex-file, but not for nice-latex-file.
1824 // (Matthias 250696)
1825 // Note that input@path is only needed for something the user does
1826 // in the preamble, included .tex files or ERT, files included by
1827 // LyX work without it.
1828 if (output_preamble) {
1829 if (!runparams.nice) {
1830 // code for usual, NOT nice-latex-file
1831 os << "\\batchmode\n"; // changed from \nonstopmode
1833 if (!original_path.empty()) {
1835 // We don't know the encoding of inputpath
1836 docstring const inputpath = from_utf8(original_path);
1837 docstring uncodable_glyphs;
1838 Encoding const * const enc = runparams.encoding;
1840 for (size_t n = 0; n < inputpath.size(); ++n) {
1841 if (!enc->encodable(inputpath[n])) {
1842 docstring const glyph(1, inputpath[n]);
1843 LYXERR0("Uncodable character '"
1845 << "' in input path!");
1846 uncodable_glyphs += glyph;
1851 // warn user if we found uncodable glyphs.
1852 if (!uncodable_glyphs.empty()) {
1853 frontend::Alert::warning(
1854 _("Uncodable character in file path"),
1856 _("The path of your document\n"
1858 "contains glyphs that are unknown "
1859 "in the current document encoding "
1860 "(namely %2$s). This may result in "
1861 "incomplete output, unless "
1862 "TEXINPUTS contains the document "
1863 "directory and you don't use "
1864 "explicitly relative paths (i.e., "
1865 "paths starting with './' or "
1866 "'../') in the preamble or in ERT."
1867 "\n\nIn case of problems, choose "
1868 "an appropriate document encoding\n"
1869 "(such as utf8) or change the "
1871 inputpath, uncodable_glyphs));
1874 support::latex_path(original_path);
1875 if (contains(docdir, '#')) {
1876 docdir = subst(docdir, "#", "\\#");
1877 os << "\\catcode`\\#=11"
1878 "\\def\\#{#}\\catcode`\\#=6\n";
1880 if (contains(docdir, '%')) {
1881 docdir = subst(docdir, "%", "\\%");
1882 os << "\\catcode`\\%=11"
1883 "\\def\\%{%}\\catcode`\\%=14\n";
1885 os << "\\makeatletter\n"
1886 << "\\def\\input@path{{"
1888 << "\\makeatother\n";
1892 // get parent macros (if this buffer has a parent) which will be
1893 // written at the document begin further down.
1894 MacroSet parentMacros;
1895 listParentMacros(parentMacros, features);
1897 // Write the preamble
1898 runparams.use_babel = params().writeLaTeX(os, features,
1899 d->filename.onlyPath());
1901 // Biblatex bibliographies are loaded here
1902 if (params().useBiblatex()) {
1903 vector<docstring> const bibfiles =
1904 prepareBibFilePaths(runparams, getBibfilesCache(), true);
1905 for (docstring const & file: bibfiles)
1906 os << "\\addbibresource{" << file << "}\n";
1909 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1910 && !features.hasOnlyPolyglossiaLanguages()) {
1913 vector<string> bll = features.getBabelExclusiveLanguages();
1914 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1917 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1922 blangs = bll.size() > 1 ?
1923 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1924 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1928 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1933 plangs = pll.size() > 1 ?
1934 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1935 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1936 if (!blangs.empty())
1940 frontend::Alert::warning(
1941 _("Incompatible Languages!"),
1943 _("You cannot use the following languages "
1944 "together in one LaTeX document because "
1945 "they require conflicting language packages:\n"
1950 // Japanese might be required only in some children of a document,
1951 // but once required, we must keep use_japanese true.
1952 runparams.use_japanese |= features.isRequired("japanese");
1955 // Restore the parenthood if needed
1956 if (!runparams.is_child)
1957 d->ignore_parent = false;
1962 // mark the beginning of the body to separate it from InPreamble insets
1963 os.texrow().start(TexRow::beginDocument());
1964 os << "\\begin{document}\n";
1966 // mark the start of a new paragraph by simulating a newline,
1967 // so that os.afterParbreak() returns true at document start
1970 // output the parent macros
1971 MacroSet::iterator it = parentMacros.begin();
1972 MacroSet::iterator end = parentMacros.end();
1973 for (; it != end; ++it) {
1974 int num_lines = (*it)->write(os.os(), true);
1975 os.texrow().newlines(num_lines);
1978 } // output_preamble
1980 LYXERR(Debug::INFO, "preamble finished, now the body.");
1983 latexParagraphs(*this, text(), os, runparams);
1985 // Restore the parenthood if needed
1986 if (!runparams.is_child)
1987 d->ignore_parent = false;
1989 // add this just in case after all the paragraphs
1992 if (output_preamble) {
1993 os << "\\end{document}\n";
1994 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1996 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1998 runparams_in.encoding = runparams.encoding;
2000 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2001 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2005 void Buffer::makeDocBookFile(FileName const & fname,
2006 OutputParams const & runparams,
2007 OutputWhat output) const
2009 LYXERR(Debug::LATEX, "makeDocBookFile...");
2012 if (!openFileWrite(ofs, fname))
2015 // make sure we are ready to export
2016 // this needs to be done before we validate
2018 updateMacroInstances(OutputUpdate);
2020 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2024 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2028 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2029 OutputParams const & runparams,
2030 OutputWhat output) const
2032 LaTeXFeatures features(*this, params(), runparams);
2037 DocumentClass const & tclass = params().documentClass();
2038 string const & top_element = tclass.latexname();
2040 bool const output_preamble =
2041 output == FullSource || output == OnlyPreamble;
2042 bool const output_body =
2043 output == FullSource || output == OnlyBody;
2045 if (output_preamble) {
2046 if (runparams.flavor == OutputParams::XML)
2047 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2050 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2053 if (! tclass.class_header().empty())
2054 os << from_ascii(tclass.class_header());
2055 else if (runparams.flavor == OutputParams::XML)
2056 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2057 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2059 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2061 docstring preamble = params().preamble;
2062 if (runparams.flavor != OutputParams::XML ) {
2063 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2064 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2065 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2066 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2069 string const name = runparams.nice
2070 ? changeExtension(absFileName(), ".sgml") : fname;
2071 preamble += features.getIncludedFiles(name);
2072 preamble += features.getLyXSGMLEntities();
2074 if (!preamble.empty()) {
2075 os << "\n [ " << preamble << " ]";
2081 string top = top_element;
2083 if (runparams.flavor == OutputParams::XML)
2084 top += params().language->code();
2086 top += params().language->code().substr(0, 2);
2089 if (!params().options.empty()) {
2091 top += params().options;
2094 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2095 << " file was created by LyX " << lyx_version
2096 << "\n See http://www.lyx.org/ for more information -->\n";
2098 params().documentClass().counters().reset();
2100 sgml::openTag(os, top);
2102 docbookParagraphs(text(), *this, os, runparams);
2103 sgml::closeTag(os, top_element);
2108 void Buffer::makeLyXHTMLFile(FileName const & fname,
2109 OutputParams const & runparams) const
2111 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2114 if (!openFileWrite(ofs, fname))
2117 // make sure we are ready to export
2118 // this has to be done before we validate
2119 updateBuffer(UpdateMaster, OutputUpdate);
2120 updateMacroInstances(OutputUpdate);
2122 writeLyXHTMLSource(ofs, runparams, FullSource);
2126 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2130 void Buffer::writeLyXHTMLSource(odocstream & os,
2131 OutputParams const & runparams,
2132 OutputWhat output) const
2134 LaTeXFeatures features(*this, params(), runparams);
2136 d->bibinfo_.makeCitationLabels(*this);
2138 bool const output_preamble =
2139 output == FullSource || output == OnlyPreamble;
2140 bool const output_body =
2141 output == FullSource || output == OnlyBody || output == IncludedFile;
2143 if (output_preamble) {
2144 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2145 << "<!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"
2146 // FIXME Language should be set properly.
2147 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2149 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2150 // FIXME Presumably need to set this right
2151 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2153 docstring const & doctitle = features.htmlTitle();
2155 << (doctitle.empty() ?
2156 from_ascii("LyX Document") :
2157 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2160 docstring styles = features.getTClassHTMLPreamble();
2161 if (!styles.empty())
2162 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2164 styles = features.getPreambleSnippets().str;
2165 if (!styles.empty())
2166 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2168 // we will collect CSS information in a stream, and then output it
2169 // either here, as part of the header, or else in a separate file.
2170 odocstringstream css;
2171 styles = features.getCSSSnippets();
2172 if (!styles.empty())
2173 css << "/* LyX Provided Styles */\n" << styles << '\n';
2175 styles = features.getTClassHTMLStyles();
2176 if (!styles.empty())
2177 css << "/* Layout-provided Styles */\n" << styles << '\n';
2179 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2180 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2181 if (needfg || needbg) {
2182 css << "\nbody {\n";
2185 << from_ascii(X11hexname(params().fontcolor))
2188 css << " background-color: "
2189 << from_ascii(X11hexname(params().backgroundcolor))
2194 docstring const dstyles = css.str();
2195 if (!dstyles.empty()) {
2196 bool written = false;
2197 if (params().html_css_as_file) {
2198 // open a file for CSS info
2200 string const fcssname = addName(temppath(), "docstyle.css");
2201 FileName const fcssfile = FileName(fcssname);
2202 if (openFileWrite(ocss, fcssfile)) {
2206 // write link to header
2207 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2209 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2212 // we are here if the CSS is supposed to be written to the header
2213 // or if we failed to write it to an external file.
2215 os << "<style type='text/css'>\n"
2224 bool const output_body_tag = (output != IncludedFile);
2225 if (output_body_tag)
2226 os << "<body dir=\"auto\">\n";
2228 if (output != IncludedFile)
2229 // if we're an included file, the counters are in the master.
2230 params().documentClass().counters().reset();
2231 xhtmlParagraphs(text(), *this, xs, runparams);
2232 if (output_body_tag)
2236 if (output_preamble)
2241 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2242 // Other flags: -wall -v0 -x
2243 int Buffer::runChktex()
2247 // get LaTeX-Filename
2248 FileName const path(temppath());
2249 string const name = addName(path.absFileName(), latexName());
2250 string const org_path = filePath();
2252 PathChanger p(path); // path to LaTeX file
2253 message(_("Running chktex..."));
2255 // Generate the LaTeX file if neccessary
2256 OutputParams runparams(¶ms().encoding());
2257 runparams.flavor = OutputParams::LATEX;
2258 runparams.nice = false;
2259 runparams.linelen = lyxrc.plaintext_linelen;
2260 makeLaTeXFile(FileName(name), org_path, runparams);
2263 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2264 int const res = chktex.run(terr); // run chktex
2267 Alert::error(_("chktex failure"),
2268 _("Could not run chktex successfully."));
2270 ErrorList & errlist = d->errorLists["ChkTeX"];
2272 bufferErrors(terr, errlist);
2277 if (runparams.silent)
2278 d->errorLists["ChkTeX"].clear();
2286 void Buffer::validate(LaTeXFeatures & features) const
2288 // Validate the buffer params, but not for included
2289 // files, since they also use the parent buffer's
2291 if (!features.runparams().is_child)
2292 params().validate(features);
2294 for (Paragraph const & p : paragraphs())
2295 p.validate(features);
2297 if (lyxerr.debugging(Debug::LATEX)) {
2298 features.showStruct();
2303 void Buffer::getLabelList(vector<docstring> & list) const
2305 // If this is a child document, use the master's list instead.
2307 masterBuffer()->getLabelList(list);
2312 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2313 Toc::const_iterator toc_it = toc->begin();
2314 Toc::const_iterator end = toc->end();
2315 for (; toc_it != end; ++toc_it) {
2316 if (toc_it->depth() == 0)
2317 list.push_back(toc_it->str());
2322 void Buffer::updateBibfilesCache(UpdateScope scope) const
2324 // FIXME This is probably unnecssary, given where we call this.
2325 // If this is a child document, use the parent's cache instead.
2326 if (parent() && scope != UpdateChildOnly) {
2327 masterBuffer()->updateBibfilesCache();
2331 d->bibfiles_cache_.clear();
2332 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2333 if (it->lyxCode() == BIBTEX_CODE) {
2334 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2335 support::FileNamePairList const bibfiles = inset.getBibFiles();
2336 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2339 } else if (it->lyxCode() == INCLUDE_CODE) {
2340 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2341 Buffer const * const incbuf = inset.getChildBuffer();
2344 support::FileNamePairList const & bibfiles =
2345 incbuf->getBibfilesCache(UpdateChildOnly);
2346 if (!bibfiles.empty()) {
2347 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2353 d->bibfile_cache_valid_ = true;
2354 d->bibinfo_cache_valid_ = false;
2355 d->cite_labels_valid_ = false;
2359 void Buffer::invalidateBibinfoCache() const
2361 d->bibinfo_cache_valid_ = false;
2362 d->cite_labels_valid_ = false;
2363 // also invalidate the cache for the parent buffer
2364 Buffer const * const pbuf = d->parent();
2366 pbuf->invalidateBibinfoCache();
2370 void Buffer::invalidateBibfileCache() const
2372 d->bibfile_cache_valid_ = false;
2373 d->bibinfo_cache_valid_ = false;
2374 d->cite_labels_valid_ = false;
2375 // also invalidate the cache for the parent buffer
2376 Buffer const * const pbuf = d->parent();
2378 pbuf->invalidateBibfileCache();
2382 support::FileNamePairList const & Buffer::getBibfilesCache(UpdateScope scope) const
2384 // FIXME This is probably unnecessary, given where we call this.
2385 // If this is a child document, use the master's cache instead.
2386 Buffer const * const pbuf = masterBuffer();
2387 if (pbuf != this && scope != UpdateChildOnly)
2388 return pbuf->getBibfilesCache();
2390 if (!d->bibfile_cache_valid_)
2391 this->updateBibfilesCache(scope);
2393 return d->bibfiles_cache_;
2397 BiblioInfo const & Buffer::masterBibInfo() const
2399 Buffer const * const tmp = masterBuffer();
2401 return tmp->masterBibInfo();
2406 void Buffer::checkIfBibInfoCacheIsValid() const
2408 // use the master's cache
2409 Buffer const * const tmp = masterBuffer();
2411 tmp->checkIfBibInfoCacheIsValid();
2415 // compare the cached timestamps with the actual ones.
2416 FileNamePairList const & bibfiles_cache = getBibfilesCache();
2417 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2418 FileNamePairList::const_iterator en = bibfiles_cache.end();
2419 for (; ei != en; ++ ei) {
2420 FileName const fn = ei->second;
2421 time_t lastw = fn.lastModified();
2422 time_t prevw = d->bibfile_status_[fn];
2423 if (lastw != prevw) {
2424 d->bibinfo_cache_valid_ = false;
2425 d->cite_labels_valid_ = false;
2426 d->bibfile_status_[fn] = lastw;
2432 void Buffer::reloadBibInfoCache() const
2434 // use the master's cache
2435 Buffer const * const tmp = masterBuffer();
2437 tmp->reloadBibInfoCache();
2441 checkIfBibInfoCacheIsValid();
2442 if (d->bibinfo_cache_valid_)
2445 d->bibinfo_.clear();
2447 d->bibinfo_cache_valid_ = true;
2451 void Buffer::collectBibKeys() const
2453 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2454 it->collectBibKeys(it);
2458 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2460 Buffer const * tmp = masterBuffer();
2461 BiblioInfo & masterbi = (tmp == this) ?
2462 d->bibinfo_ : tmp->d->bibinfo_;
2463 masterbi.mergeBiblioInfo(bi);
2467 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2469 Buffer const * tmp = masterBuffer();
2470 BiblioInfo & masterbi = (tmp == this) ?
2471 d->bibinfo_ : tmp->d->bibinfo_;
2476 void Buffer::makeCitationLabels() const
2478 Buffer const * const master = masterBuffer();
2479 return d->bibinfo_.makeCitationLabels(*master);
2483 bool Buffer::citeLabelsValid() const
2485 return masterBuffer()->d->cite_labels_valid_;
2489 void Buffer::removeBiblioTempFiles() const
2491 // We remove files that contain LaTeX commands specific to the
2492 // particular bibliographic style being used, in order to avoid
2493 // LaTeX errors when we switch style.
2494 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2495 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2496 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2497 aux_file.removeFile();
2498 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2499 bbl_file.removeFile();
2500 // Also for the parent buffer
2501 Buffer const * const pbuf = parent();
2503 pbuf->removeBiblioTempFiles();
2507 bool Buffer::isDepClean(string const & name) const
2509 DepClean::const_iterator const it = d->dep_clean.find(name);
2510 if (it == d->dep_clean.end())
2516 void Buffer::markDepClean(string const & name)
2518 d->dep_clean[name] = true;
2522 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2525 // FIXME? if there is an Buffer LFUN that can be dispatched even
2526 // if internal, put a switch '(cmd.action)' here.
2532 switch (cmd.action()) {
2534 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2535 flag.setOnOff(hasReadonlyFlag());
2538 // FIXME: There is need for a command-line import.
2539 //case LFUN_BUFFER_IMPORT:
2541 case LFUN_BUFFER_AUTO_SAVE:
2544 case LFUN_BUFFER_EXPORT_CUSTOM:
2545 // FIXME: Nothing to check here?
2548 case LFUN_BUFFER_EXPORT: {
2549 docstring const arg = cmd.argument();
2550 if (arg == "custom") {
2554 string format = (arg.empty() || arg == "default") ?
2555 params().getDefaultOutputFormat() : to_utf8(arg);
2556 size_t pos = format.find(' ');
2557 if (pos != string::npos)
2558 format = format.substr(0, pos);
2559 enable = params().isExportable(format, false);
2561 flag.message(bformat(
2562 _("Don't know how to export to format: %1$s"), arg));
2566 case LFUN_BUFFER_CHKTEX:
2567 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2570 case LFUN_BUILD_PROGRAM:
2571 enable = params().isExportable("program", false);
2574 case LFUN_BRANCH_ACTIVATE:
2575 case LFUN_BRANCH_DEACTIVATE:
2576 case LFUN_BRANCH_MASTER_ACTIVATE:
2577 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2578 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2579 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2580 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2581 : params().branchlist();
2582 docstring const branchName = cmd.argument();
2583 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2587 case LFUN_BRANCH_ADD:
2588 case LFUN_BRANCHES_RENAME:
2589 // if no Buffer is present, then of course we won't be called!
2592 case LFUN_BUFFER_LANGUAGE:
2593 enable = !isReadonly();
2596 case LFUN_BUFFER_VIEW_CACHE:
2597 (d->preview_file_).refresh();
2598 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2601 case LFUN_CHANGES_TRACK:
2602 flag.setEnabled(true);
2603 flag.setOnOff(params().track_changes);
2606 case LFUN_CHANGES_OUTPUT:
2607 flag.setEnabled(true);
2608 flag.setOnOff(params().output_changes);
2611 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2612 flag.setOnOff(params().compressed);
2616 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2617 flag.setOnOff(params().output_sync);
2624 flag.setEnabled(enable);
2629 void Buffer::dispatch(string const & command, DispatchResult & result)
2631 return dispatch(lyxaction.lookupFunc(command), result);
2635 // NOTE We can end up here even if we have no GUI, because we are called
2636 // by LyX::exec to handled command-line requests. So we may need to check
2637 // whether we have a GUI or not. The boolean use_gui holds this information.
2638 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2641 // FIXME? if there is an Buffer LFUN that can be dispatched even
2642 // if internal, put a switch '(cmd.action())' here.
2643 dr.dispatched(false);
2646 string const argument = to_utf8(func.argument());
2647 // We'll set this back to false if need be.
2648 bool dispatched = true;
2649 undo().beginUndoGroup();
2651 switch (func.action()) {
2652 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2653 if (lyxvc().inUse()) {
2654 string log = lyxvc().toggleReadOnly();
2659 setReadonly(!hasReadonlyFlag());
2662 case LFUN_BUFFER_EXPORT: {
2663 string const format = (argument.empty() || argument == "default") ?
2664 params().getDefaultOutputFormat() : argument;
2665 ExportStatus const status = doExport(format, false);
2666 dr.setError(status != ExportSuccess);
2667 if (status != ExportSuccess)
2668 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2669 from_utf8(format)));
2673 case LFUN_BUILD_PROGRAM: {
2674 ExportStatus const status = doExport("program", true);
2675 dr.setError(status != ExportSuccess);
2676 if (status != ExportSuccess)
2677 dr.setMessage(_("Error generating literate programming code."));
2681 case LFUN_BUFFER_CHKTEX:
2685 case LFUN_BUFFER_EXPORT_CUSTOM: {
2687 string command = split(argument, format_name, ' ');
2688 Format const * format = theFormats().getFormat(format_name);
2690 lyxerr << "Format \"" << format_name
2691 << "\" not recognized!"
2696 // The name of the file created by the conversion process
2699 // Output to filename
2700 if (format->name() == "lyx") {
2701 string const latexname = latexName(false);
2702 filename = changeExtension(latexname,
2703 format->extension());
2704 filename = addName(temppath(), filename);
2706 if (!writeFile(FileName(filename)))
2710 doExport(format_name, true, filename);
2713 // Substitute $$FName for filename
2714 if (!contains(command, "$$FName"))
2715 command = "( " + command + " ) < $$FName";
2716 command = subst(command, "$$FName", filename);
2718 // Execute the command in the background
2720 call.startscript(Systemcall::DontWait, command,
2721 filePath(), layoutPos());
2725 // FIXME: There is need for a command-line import.
2727 case LFUN_BUFFER_IMPORT:
2732 case LFUN_BUFFER_AUTO_SAVE:
2734 resetAutosaveTimers();
2737 case LFUN_BRANCH_ACTIVATE:
2738 case LFUN_BRANCH_DEACTIVATE:
2739 case LFUN_BRANCH_MASTER_ACTIVATE:
2740 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2741 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2742 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2743 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2746 docstring const branch_name = func.argument();
2747 // the case without a branch name is handled elsewhere
2748 if (branch_name.empty()) {
2752 Branch * branch = buf->params().branchlist().find(branch_name);
2754 LYXERR0("Branch " << branch_name << " does not exist.");
2756 docstring const msg =
2757 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2761 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2762 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2763 if (branch->isSelected() != activate) {
2764 buf->undo().recordUndoBufferParams(CursorData());
2765 branch->setSelected(activate);
2767 dr.screenUpdate(Update::Force);
2768 dr.forceBufferUpdate();
2773 case LFUN_BRANCH_ADD: {
2774 docstring branch_name = func.argument();
2775 if (branch_name.empty()) {
2779 BranchList & branch_list = params().branchlist();
2780 vector<docstring> const branches =
2781 getVectorFromString(branch_name, branch_list.separator());
2783 for (vector<docstring>::const_iterator it = branches.begin();
2784 it != branches.end(); ++it) {
2786 Branch * branch = branch_list.find(branch_name);
2788 LYXERR0("Branch " << branch_name << " already exists.");
2792 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2794 undo().recordUndoBufferParams(CursorData());
2795 branch_list.add(branch_name);
2796 branch = branch_list.find(branch_name);
2797 string const x11hexname = X11hexname(branch->color());
2798 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2799 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2801 dr.screenUpdate(Update::Force);
2809 case LFUN_BRANCHES_RENAME: {
2810 if (func.argument().empty())
2813 docstring const oldname = from_utf8(func.getArg(0));
2814 docstring const newname = from_utf8(func.getArg(1));
2815 InsetIterator it = inset_iterator_begin(inset());
2816 InsetIterator const end = inset_iterator_end(inset());
2817 bool success = false;
2818 for (; it != end; ++it) {
2819 if (it->lyxCode() == BRANCH_CODE) {
2820 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2821 if (ins.branch() == oldname) {
2822 undo().recordUndo(CursorData(it));
2823 ins.rename(newname);
2828 if (it->lyxCode() == INCLUDE_CODE) {
2829 // get buffer of external file
2830 InsetInclude const & ins =
2831 static_cast<InsetInclude const &>(*it);
2832 Buffer * child = ins.getChildBuffer();
2835 child->dispatch(func, dr);
2840 dr.screenUpdate(Update::Force);
2841 dr.forceBufferUpdate();
2846 case LFUN_BUFFER_VIEW_CACHE:
2847 if (!theFormats().view(*this, d->preview_file_,
2848 d->preview_format_))
2849 dr.setMessage(_("Error viewing the output file."));
2852 case LFUN_CHANGES_TRACK:
2853 if (params().save_transient_properties)
2854 undo().recordUndoBufferParams(CursorData());
2855 params().track_changes = !params().track_changes;
2856 if (!params().track_changes)
2857 dr.forceChangesUpdate();
2860 case LFUN_CHANGES_OUTPUT:
2861 if (params().save_transient_properties)
2862 undo().recordUndoBufferParams(CursorData());
2863 params().output_changes = !params().output_changes;
2864 if (params().output_changes) {
2865 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2866 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2867 LaTeXFeatures::isAvailable("xcolor");
2869 if (!dvipost && !xcolorulem) {
2870 Alert::warning(_("Changes not shown in LaTeX output"),
2871 _("Changes will not be highlighted in LaTeX output, "
2872 "because neither dvipost nor xcolor/ulem are installed.\n"
2873 "Please install these packages or redefine "
2874 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2875 } else if (!xcolorulem) {
2876 Alert::warning(_("Changes not shown in LaTeX output"),
2877 _("Changes will not be highlighted in LaTeX output "
2878 "when using pdflatex, because xcolor and ulem are not installed.\n"
2879 "Please install both packages or redefine "
2880 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2885 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2886 // turn compression on/off
2887 undo().recordUndoBufferParams(CursorData());
2888 params().compressed = !params().compressed;
2891 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2892 undo().recordUndoBufferParams(CursorData());
2893 params().output_sync = !params().output_sync;
2900 dr.dispatched(dispatched);
2901 undo().endUndoGroup();
2905 void Buffer::changeLanguage(Language const * from, Language const * to)
2907 LASSERT(from, return);
2908 LASSERT(to, return);
2910 for_each(par_iterator_begin(),
2912 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2916 bool Buffer::isMultiLingual() const
2918 ParConstIterator end = par_iterator_end();
2919 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2920 if (it->isMultiLingual(params()))
2927 std::set<Language const *> Buffer::getLanguages() const
2929 std::set<Language const *> languages;
2930 getLanguages(languages);
2935 void Buffer::getLanguages(std::set<Language const *> & languages) const
2937 ParConstIterator end = par_iterator_end();
2938 // add the buffer language, even if it's not actively used
2939 languages.insert(language());
2940 // iterate over the paragraphs
2941 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2942 it->getLanguages(languages);
2944 ListOfBuffers clist = getDescendents();
2945 ListOfBuffers::const_iterator cit = clist.begin();
2946 ListOfBuffers::const_iterator const cen = clist.end();
2947 for (; cit != cen; ++cit)
2948 (*cit)->getLanguages(languages);
2952 DocIterator Buffer::getParFromID(int const id) const
2954 Buffer * buf = const_cast<Buffer *>(this);
2956 // This means non-existent
2957 return doc_iterator_end(buf);
2959 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2960 if (it.paragraph().id() == id)
2963 return doc_iterator_end(buf);
2967 bool Buffer::hasParWithID(int const id) const
2969 return !getParFromID(id).atEnd();
2973 ParIterator Buffer::par_iterator_begin()
2975 return ParIterator(doc_iterator_begin(this));
2979 ParIterator Buffer::par_iterator_end()
2981 return ParIterator(doc_iterator_end(this));
2985 ParConstIterator Buffer::par_iterator_begin() const
2987 return ParConstIterator(doc_iterator_begin(this));
2991 ParConstIterator Buffer::par_iterator_end() const
2993 return ParConstIterator(doc_iterator_end(this));
2997 Language const * Buffer::language() const
2999 return params().language;
3003 docstring const Buffer::B_(string const & l10n) const
3005 return params().B_(l10n);
3009 bool Buffer::isClean() const
3011 return d->lyx_clean;
3015 bool Buffer::isChecksumModified() const
3017 LASSERT(d->filename.exists(), return false);
3018 return d->checksum_ != d->filename.checksum();
3022 void Buffer::saveCheckSum() const
3024 FileName const & file = d->filename;
3026 d->checksum_ = file.exists() ? file.checksum()
3027 : 0; // in the case of save to a new file.
3031 void Buffer::markClean() const
3033 if (!d->lyx_clean) {
3034 d->lyx_clean = true;
3037 // if the .lyx file has been saved, we don't need an
3039 d->bak_clean = true;
3040 d->undo_.markDirty();
3041 clearExternalModification();
3045 void Buffer::setUnnamed(bool flag)
3051 bool Buffer::isUnnamed() const
3058 /// Don't check unnamed, here: isInternal() is used in
3059 /// newBuffer(), where the unnamed flag has not been set by anyone
3060 /// yet. Also, for an internal buffer, there should be no need for
3061 /// retrieving fileName() nor for checking if it is unnamed or not.
3062 bool Buffer::isInternal() const
3064 return d->internal_buffer;
3068 void Buffer::setInternal(bool flag)
3070 d->internal_buffer = flag;
3074 void Buffer::markDirty()
3077 d->lyx_clean = false;
3080 d->bak_clean = false;
3082 DepClean::iterator it = d->dep_clean.begin();
3083 DepClean::const_iterator const end = d->dep_clean.end();
3085 for (; it != end; ++it)
3090 FileName Buffer::fileName() const
3096 string Buffer::absFileName() const
3098 return d->filename.absFileName();
3102 string Buffer::filePath() const
3104 string const abs = d->filename.onlyPath().absFileName();
3107 int last = abs.length() - 1;
3109 return abs[last] == '/' ? abs : abs + '/';
3113 DocFileName Buffer::getReferencedFileName(string const & fn) const
3116 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3117 result.set(fn, filePath());
3119 // filePath() ends with a path separator
3120 FileName const test(filePath() + fn);
3122 result.set(fn, filePath());
3124 result.set(fn, params().origin);
3131 string const Buffer::prepareFileNameForLaTeX(string const & name,
3132 string const & ext, bool nice) const
3134 string const fname = makeAbsPath(name, filePath()).absFileName();
3135 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3141 return to_utf8(makeRelPath(from_utf8(fname),
3142 from_utf8(masterBuffer()->filePath())));
3146 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3147 FileNamePairList const bibfilelist,
3148 bool const add_extension) const
3150 // If we are processing the LaTeX file in a temp directory then
3151 // copy the .bib databases to this temp directory, mangling their
3152 // names in the process. Store this mangled name in the list of
3154 // (We need to do all this because BibTeX *really*, *really*
3155 // can't handle "files with spaces" and Windows users tend to
3156 // use such filenames.)
3157 // Otherwise, store the (maybe absolute) path to the original,
3158 // unmangled database name.
3160 vector<docstring> res;
3162 // determine the export format
3163 string const tex_format = flavor2format(runparams.flavor);
3165 // check for spaces in paths
3166 bool found_space = false;
3168 FileNamePairList::const_iterator it = bibfilelist.begin();
3169 FileNamePairList::const_iterator en = bibfilelist.end();
3170 for (; it != en; ++it) {
3171 string utf8input = to_utf8(it->first);
3173 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3174 FileName const try_in_file =
3175 makeAbsPath(database + ".bib", filePath());
3176 bool const not_from_texmf = try_in_file.isReadableFile();
3178 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3180 // mangledFileName() needs the extension
3181 DocFileName const in_file = DocFileName(try_in_file);
3182 database = removeExtension(in_file.mangledFileName());
3183 FileName const out_file = makeAbsPath(database + ".bib",
3184 masterBuffer()->temppath());
3185 bool const success = in_file.copyTo(out_file);
3187 LYXERR0("Failed to copy '" << in_file
3188 << "' to '" << out_file << "'");
3190 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3191 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3192 if (!isValidLaTeXFileName(database)) {
3193 frontend::Alert::warning(_("Invalid filename"),
3194 _("The following filename will cause troubles "
3195 "when running the exported file through LaTeX: ") +
3196 from_utf8(database));
3198 if (!isValidDVIFileName(database)) {
3199 frontend::Alert::warning(_("Problematic filename for DVI"),
3200 _("The following filename can cause troubles "
3201 "when running the exported file through LaTeX "
3202 "and opening the resulting DVI: ") +
3203 from_utf8(database), true);
3211 docstring const path = from_utf8(latex_path(database));
3213 if (contains(path, ' '))
3216 if (find(res.begin(), res.end(), path) == res.end())
3217 res.push_back(path);
3220 // Check if there are spaces in the path and warn BibTeX users, if so.
3221 // (biber can cope with such paths)
3222 if (!prefixIs(runparams.bibtex_command, "biber")) {
3223 // Post this warning only once.
3224 static bool warned_about_spaces = false;
3225 if (!warned_about_spaces &&
3226 runparams.nice && found_space) {
3227 warned_about_spaces = true;
3228 Alert::warning(_("Export Warning!"),
3229 _("There are spaces in the paths to your BibTeX databases.\n"
3230 "BibTeX will be unable to find them."));
3239 string Buffer::layoutPos() const
3241 return d->layout_position;
3245 void Buffer::setLayoutPos(string const & path)
3248 d->layout_position.clear();
3252 LATTEST(FileName::isAbsolute(path));
3254 d->layout_position =
3255 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3257 if (d->layout_position.empty())
3258 d->layout_position = ".";
3262 bool Buffer::hasReadonlyFlag() const
3264 return d->read_only;
3268 bool Buffer::isReadonly() const
3270 return hasReadonlyFlag() || notifiesExternalModification();
3274 void Buffer::setParent(Buffer const * buffer)
3276 // Avoids recursive include.
3277 d->setParent(buffer == this ? 0 : buffer);
3282 Buffer const * Buffer::parent() const
3288 ListOfBuffers Buffer::allRelatives() const
3290 ListOfBuffers lb = masterBuffer()->getDescendents();
3291 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3296 Buffer const * Buffer::masterBuffer() const
3298 // FIXME Should be make sure we are not in some kind
3299 // of recursive include? A -> B -> A will crash this.
3300 Buffer const * const pbuf = d->parent();
3304 return pbuf->masterBuffer();
3308 bool Buffer::isChild(Buffer * child) const
3310 return d->children_positions.find(child) != d->children_positions.end();
3314 DocIterator Buffer::firstChildPosition(Buffer const * child)
3316 Impl::BufferPositionMap::iterator it;
3317 it = d->children_positions.find(child);
3318 if (it == d->children_positions.end())
3319 return DocIterator(this);
3324 bool Buffer::hasChildren() const
3326 return !d->children_positions.empty();
3330 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3332 // loop over children
3333 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3334 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3335 for (; it != end; ++it) {
3336 Buffer * child = const_cast<Buffer *>(it->first);
3338 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3339 if (bit != clist.end())
3341 clist.push_back(child);
3343 // there might be grandchildren
3344 child->collectChildren(clist, true);
3349 ListOfBuffers Buffer::getChildren() const
3352 collectChildren(v, false);
3353 // Make sure we have not included ourselves.
3354 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3355 if (bit != v.end()) {
3356 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3363 ListOfBuffers Buffer::getDescendents() const
3366 collectChildren(v, true);
3367 // Make sure we have not included ourselves.
3368 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3369 if (bit != v.end()) {
3370 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3377 template<typename M>
3378 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3383 typename M::const_iterator it = m.lower_bound(x);
3384 if (it == m.begin())
3392 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3393 DocIterator const & pos) const
3395 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3397 // if paragraphs have no macro context set, pos will be empty
3401 // we haven't found anything yet
3402 DocIterator bestPos = owner_->par_iterator_begin();
3403 MacroData const * bestData = 0;
3405 // find macro definitions for name
3406 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3407 if (nameIt != macros.end()) {
3408 // find last definition in front of pos or at pos itself
3409 PositionScopeMacroMap::const_iterator it
3410 = greatest_below(nameIt->second, pos);
3411 if (it != nameIt->second.end()) {
3413 // scope ends behind pos?
3414 if (pos < it->second.scope) {
3415 // Looks good, remember this. If there
3416 // is no external macro behind this,
3417 // we found the right one already.
3418 bestPos = it->first;
3419 bestData = &it->second.macro;
3423 // try previous macro if there is one
3424 if (it == nameIt->second.begin())
3431 // find macros in included files
3432 PositionScopeBufferMap::const_iterator it
3433 = greatest_below(position_to_children, pos);
3434 if (it == position_to_children.end())
3435 // no children before
3439 // do we know something better (i.e. later) already?
3440 if (it->first < bestPos )
3443 // scope ends behind pos?
3444 if (pos < it->second.scope
3445 && (cloned_buffer_ ||
3446 theBufferList().isLoaded(it->second.buffer))) {
3447 // look for macro in external file
3449 MacroData const * data
3450 = it->second.buffer->getMacro(name, false);
3453 bestPos = it->first;
3459 // try previous file if there is one
3460 if (it == position_to_children.begin())
3465 // return the best macro we have found
3470 MacroData const * Buffer::getMacro(docstring const & name,
3471 DocIterator const & pos, bool global) const
3476 // query buffer macros
3477 MacroData const * data = d->getBufferMacro(name, pos);
3481 // If there is a master buffer, query that
3482 Buffer const * const pbuf = d->parent();
3484 d->macro_lock = true;
3485 MacroData const * macro = pbuf->getMacro(
3486 name, *this, false);
3487 d->macro_lock = false;
3493 data = MacroTable::globalMacros().get(name);
3502 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3504 // set scope end behind the last paragraph
3505 DocIterator scope = par_iterator_begin();
3506 scope.pit() = scope.lastpit() + 1;
3508 return getMacro(name, scope, global);
3512 MacroData const * Buffer::getMacro(docstring const & name,
3513 Buffer const & child, bool global) const
3515 // look where the child buffer is included first
3516 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3517 if (it == d->children_positions.end())
3520 // check for macros at the inclusion position
3521 return getMacro(name, it->second, global);
3525 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3527 pit_type const lastpit = it.lastpit();
3529 // look for macros in each paragraph
3530 while (it.pit() <= lastpit) {
3531 Paragraph & par = it.paragraph();
3533 // iterate over the insets of the current paragraph
3534 InsetList const & insets = par.insetList();
3535 InsetList::const_iterator iit = insets.begin();
3536 InsetList::const_iterator end = insets.end();
3537 for (; iit != end; ++iit) {
3538 it.pos() = iit->pos;
3540 // is it a nested text inset?
3541 if (iit->inset->asInsetText()) {
3542 // Inset needs its own scope?
3543 InsetText const * itext = iit->inset->asInsetText();
3544 bool newScope = itext->isMacroScope();
3546 // scope which ends just behind the inset
3547 DocIterator insetScope = it;
3550 // collect macros in inset
3551 it.push_back(CursorSlice(*iit->inset));
3552 updateMacros(it, newScope ? insetScope : scope);
3557 if (iit->inset->asInsetTabular()) {
3558 CursorSlice slice(*iit->inset);
3559 size_t const numcells = slice.nargs();
3560 for (; slice.idx() < numcells; slice.forwardIdx()) {
3561 it.push_back(slice);
3562 updateMacros(it, scope);
3568 // is it an external file?
3569 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3570 // get buffer of external file
3571 InsetInclude const & inset =
3572 static_cast<InsetInclude const &>(*iit->inset);
3574 Buffer * child = inset.getChildBuffer();
3579 // register its position, but only when it is
3580 // included first in the buffer
3581 if (children_positions.find(child) ==
3582 children_positions.end())
3583 children_positions[child] = it;
3585 // register child with its scope
3586 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3590 InsetMath * im = iit->inset->asInsetMath();
3591 if (doing_export && im) {
3592 InsetMathHull * hull = im->asHullInset();
3594 hull->recordLocation(it);
3597 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3601 InsetMathMacroTemplate & macroTemplate =
3602 *iit->inset->asInsetMath()->asMacroTemplate();
3603 MacroContext mc(owner_, it);
3604 macroTemplate.updateToContext(mc);
3607 bool valid = macroTemplate.validMacro();
3608 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3609 // then the BufferView's cursor will be invalid in
3610 // some cases which leads to crashes.
3615 // FIXME (Abdel), I don't understand why we pass 'it' here
3616 // instead of 'macroTemplate' defined above... is this correct?
3617 macros[macroTemplate.name()][it] =
3618 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3628 void Buffer::updateMacros() const
3633 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3635 // start with empty table
3637 d->children_positions.clear();
3638 d->position_to_children.clear();
3640 // Iterate over buffer, starting with first paragraph
3641 // The scope must be bigger than any lookup DocIterator
3642 // later. For the global lookup, lastpit+1 is used, hence
3643 // we use lastpit+2 here.
3644 DocIterator it = par_iterator_begin();
3645 DocIterator outerScope = it;
3646 outerScope.pit() = outerScope.lastpit() + 2;
3647 d->updateMacros(it, outerScope);
3651 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3653 InsetIterator it = inset_iterator_begin(inset());
3654 InsetIterator const end = inset_iterator_end(inset());
3655 for (; it != end; ++it) {
3656 if (it->lyxCode() == BRANCH_CODE) {
3657 InsetBranch & br = static_cast<InsetBranch &>(*it);
3658 docstring const name = br.branch();
3659 if (!from_master && !params().branchlist().find(name))
3660 result.push_back(name);
3661 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3662 result.push_back(name);
3665 if (it->lyxCode() == INCLUDE_CODE) {
3666 // get buffer of external file
3667 InsetInclude const & ins =
3668 static_cast<InsetInclude const &>(*it);
3669 Buffer * child = ins.getChildBuffer();
3672 child->getUsedBranches(result, true);
3675 // remove duplicates
3680 void Buffer::updateMacroInstances(UpdateType utype) const
3682 LYXERR(Debug::MACROS, "updateMacroInstances for "
3683 << d->filename.onlyFileName());
3684 DocIterator it = doc_iterator_begin(this);
3686 DocIterator const end = doc_iterator_end(this);
3687 for (; it != end; it.forwardInset()) {
3688 // look for MathData cells in InsetMathNest insets
3689 InsetMath * minset = it.nextInset()->asInsetMath();
3693 // update macro in all cells of the InsetMathNest
3694 DocIterator::idx_type n = minset->nargs();
3695 MacroContext mc = MacroContext(this, it);
3696 for (DocIterator::idx_type i = 0; i < n; ++i) {
3697 MathData & data = minset->cell(i);
3698 data.updateMacros(0, mc, utype, 0);
3704 void Buffer::listMacroNames(MacroNameSet & macros) const
3709 d->macro_lock = true;
3711 // loop over macro names
3712 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3713 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3714 for (; nameIt != nameEnd; ++nameIt)
3715 macros.insert(nameIt->first);
3717 // loop over children
3718 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3719 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3720 for (; it != end; ++it)
3721 it->first->listMacroNames(macros);
3724 Buffer const * const pbuf = d->parent();
3726 pbuf->listMacroNames(macros);
3728 d->macro_lock = false;
3732 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3734 Buffer const * const pbuf = d->parent();
3739 pbuf->listMacroNames(names);
3742 MacroNameSet::iterator it = names.begin();
3743 MacroNameSet::iterator end = names.end();
3744 for (; it != end; ++it) {
3746 MacroData const * data =
3747 pbuf->getMacro(*it, *this, false);
3749 macros.insert(data);
3751 // we cannot access the original InsetMathMacroTemplate anymore
3752 // here to calls validate method. So we do its work here manually.
3753 // FIXME: somehow make the template accessible here.
3754 if (data->optionals() > 0)
3755 features.require("xargs");
3761 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3764 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3766 RefCache::iterator it = d->ref_cache_.find(label);
3767 if (it != d->ref_cache_.end())
3768 return it->second.second;
3770 static InsetLabel const * dummy_il = 0;
3771 static References const dummy_refs = References();
3772 it = d->ref_cache_.insert(
3773 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3774 return it->second.second;
3778 Buffer::References const & Buffer::references(docstring const & label) const
3780 return const_cast<Buffer *>(this)->getReferenceCache(label);
3784 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3786 References & refs = getReferenceCache(label);
3787 refs.push_back(make_pair(inset, it));
3791 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3793 masterBuffer()->d->ref_cache_[label].first = il;
3797 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3799 return masterBuffer()->d->ref_cache_[label].first;
3803 void Buffer::clearReferenceCache() const
3806 d->ref_cache_.clear();
3810 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3812 //FIXME: This does not work for child documents yet.
3813 reloadBibInfoCache();
3815 // Check if the label 'from' appears more than once
3816 BiblioInfo const & keys = masterBibInfo();
3817 BiblioInfo::const_iterator bit = keys.begin();
3818 BiblioInfo::const_iterator bend = keys.end();
3819 vector<docstring> labels;
3821 for (; bit != bend; ++bit)
3823 labels.push_back(bit->first);
3825 if (count(labels.begin(), labels.end(), from) > 1)
3828 string const paramName = "key";
3829 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3830 if (it->lyxCode() != CITE_CODE)
3832 InsetCommand * inset = it->asInsetCommand();
3833 docstring const oldValue = inset->getParam(paramName);
3834 if (oldValue == from)
3835 inset->setParam(paramName, to);
3839 // returns NULL if id-to-row conversion is unsupported
3840 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3841 pit_type par_begin, pit_type par_end,
3842 OutputWhat output, bool master) const
3844 unique_ptr<TexRow> texrow;
3845 OutputParams runparams(¶ms().encoding());
3846 runparams.nice = true;
3847 runparams.flavor = params().getOutputFlavor(format);
3848 runparams.linelen = lyxrc.plaintext_linelen;
3849 // No side effect of file copying and image conversion
3850 runparams.dryrun = true;
3852 if (output == CurrentParagraph) {
3853 runparams.par_begin = par_begin;
3854 runparams.par_end = par_end;
3855 if (par_begin + 1 == par_end) {
3857 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3861 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3862 convert<docstring>(par_begin),
3863 convert<docstring>(par_end - 1))
3866 // output paragraphs
3867 if (runparams.flavor == OutputParams::LYX) {
3868 Paragraph const & par = text().paragraphs()[par_begin];
3870 depth_type dt = par.getDepth();
3871 par.write(ods, params(), dt);
3872 os << from_utf8(ods.str());
3873 } else if (runparams.flavor == OutputParams::HTML) {
3875 setMathFlavor(runparams);
3876 xhtmlParagraphs(text(), *this, xs, runparams);
3877 } else if (runparams.flavor == OutputParams::TEXT) {
3879 // FIXME Handles only one paragraph, unlike the others.
3880 // Probably should have some routine with a signature like them.
3881 writePlaintextParagraph(*this,
3882 text().paragraphs()[par_begin], os, runparams, dummy);
3883 } else if (params().isDocBook()) {
3884 docbookParagraphs(text(), *this, os, runparams);
3886 // If we are previewing a paragraph, even if this is the
3887 // child of some other buffer, let's cut the link here,
3888 // so that no concurring settings from the master
3889 // (e.g. branch state) interfere (see #8101).
3891 d->ignore_parent = true;
3892 // We need to validate the Buffer params' features here
3893 // in order to know if we should output polyglossia
3894 // macros (instead of babel macros)
3895 LaTeXFeatures features(*this, params(), runparams);
3897 runparams.use_polyglossia = features.usePolyglossia();
3898 // latex or literate
3901 ots.texrow().newlines(2);
3903 latexParagraphs(*this, text(), ots, runparams);
3904 texrow = ots.releaseTexRow();
3906 // Restore the parenthood
3908 d->ignore_parent = false;
3912 if (output == FullSource)
3913 os << _("Preview source code");
3914 else if (output == OnlyPreamble)
3915 os << _("Preview preamble");
3916 else if (output == OnlyBody)
3917 os << _("Preview body");
3919 if (runparams.flavor == OutputParams::LYX) {
3921 if (output == FullSource)
3923 else if (output == OnlyPreamble)
3924 params().writeFile(ods, this);
3925 else if (output == OnlyBody)
3927 os << from_utf8(ods.str());
3928 } else if (runparams.flavor == OutputParams::HTML) {
3929 writeLyXHTMLSource(os, runparams, output);
3930 } else if (runparams.flavor == OutputParams::TEXT) {
3931 if (output == OnlyPreamble) {
3932 os << "% "<< _("Plain text does not have a preamble.");
3934 writePlaintextFile(*this, os, runparams);
3935 } else if (params().isDocBook()) {
3936 writeDocBookSource(os, absFileName(), runparams, output);
3938 // latex or literate
3941 ots.texrow().newlines(2);
3943 runparams.is_child = true;
3945 writeLaTeXSource(ots, string(), runparams, output);
3946 texrow = ots.releaseTexRow();
3953 ErrorList & Buffer::errorList(string const & type) const
3955 return d->errorLists[type];
3959 void Buffer::updateTocItem(std::string const & type,
3960 DocIterator const & dit) const
3963 d->gui_->updateTocItem(type, dit);
3967 void Buffer::structureChanged() const
3970 d->gui_->structureChanged();
3974 void Buffer::errors(string const & err, bool from_master) const
3977 d->gui_->errors(err, from_master);
3981 void Buffer::message(docstring const & msg) const
3984 d->gui_->message(msg);
3988 void Buffer::setBusy(bool on) const
3991 d->gui_->setBusy(on);
3995 void Buffer::updateTitles() const
3998 d->wa_->updateTitles();
4002 void Buffer::resetAutosaveTimers() const
4005 d->gui_->resetAutosaveTimers();
4009 bool Buffer::hasGuiDelegate() const
4015 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4024 class AutoSaveBuffer : public ForkedProcess {
4027 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4028 : buffer_(buffer), fname_(fname) {}
4030 virtual shared_ptr<ForkedProcess> clone() const
4032 return make_shared<AutoSaveBuffer>(*this);
4037 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4038 from_utf8(fname_.absFileName())));
4039 return run(DontWait);
4043 virtual int generateChild();
4045 Buffer const & buffer_;
4050 int AutoSaveBuffer::generateChild()
4052 #if defined(__APPLE__)
4053 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4054 * We should use something else like threads.
4056 * Since I do not know how to determine at run time what is the OS X
4057 * version, I just disable forking altogether for now (JMarc)
4059 pid_t const pid = -1;
4061 // tmp_ret will be located (usually) in /tmp
4062 // will that be a problem?
4063 // Note that this calls ForkedCalls::fork(), so it's
4064 // ok cross-platform.
4065 pid_t const pid = fork();
4066 // If you want to debug the autosave
4067 // you should set pid to -1, and comment out the fork.
4068 if (pid != 0 && pid != -1)
4072 // pid = -1 signifies that lyx was unable
4073 // to fork. But we will do the save
4075 bool failed = false;
4076 TempFile tempfile("lyxautoXXXXXX.lyx");
4077 tempfile.setAutoRemove(false);
4078 FileName const tmp_ret = tempfile.name();
4079 if (!tmp_ret.empty()) {
4080 if (!buffer_.writeFile(tmp_ret))
4082 else if (!tmp_ret.moveTo(fname_))
4088 // failed to write/rename tmp_ret so try writing direct
4089 if (!buffer_.writeFile(fname_)) {
4090 // It is dangerous to do this in the child,
4091 // but safe in the parent, so...
4092 if (pid == -1) // emit message signal.
4093 buffer_.message(_("Autosave failed!"));
4097 if (pid == 0) // we are the child so...
4106 FileName Buffer::getEmergencyFileName() const
4108 return FileName(d->filename.absFileName() + ".emergency");
4112 FileName Buffer::getAutosaveFileName() const
4114 // if the document is unnamed try to save in the backup dir, else
4115 // in the default document path, and as a last try in the filePath,
4116 // which will most often be the temporary directory
4119 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4120 : lyxrc.backupdir_path;
4121 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4124 string const fname = "#" + d->filename.onlyFileName() + "#";
4126 return makeAbsPath(fname, fpath);
4130 void Buffer::removeAutosaveFile() const
4132 FileName const f = getAutosaveFileName();
4138 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4140 FileName const newauto = getAutosaveFileName();
4142 if (newauto != oldauto && oldauto.exists())
4143 if (!oldauto.moveTo(newauto))
4144 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4148 bool Buffer::autoSave() const
4150 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4151 if (buf->d->bak_clean || hasReadonlyFlag())
4154 message(_("Autosaving current document..."));
4155 buf->d->bak_clean = true;
4157 FileName const fname = getAutosaveFileName();
4158 LASSERT(d->cloned_buffer_, return false);
4160 // If this buffer is cloned, we assume that
4161 // we are running in a separate thread already.
4162 TempFile tempfile("lyxautoXXXXXX.lyx");
4163 tempfile.setAutoRemove(false);
4164 FileName const tmp_ret = tempfile.name();
4165 if (!tmp_ret.empty()) {
4167 // assume successful write of tmp_ret
4168 if (tmp_ret.moveTo(fname))
4171 // failed to write/rename tmp_ret so try writing direct
4172 return writeFile(fname);
4176 void Buffer::setExportStatus(bool e) const
4178 d->doing_export = e;
4179 ListOfBuffers clist = getDescendents();
4180 ListOfBuffers::const_iterator cit = clist.begin();
4181 ListOfBuffers::const_iterator const cen = clist.end();
4182 for (; cit != cen; ++cit)
4183 (*cit)->d->doing_export = e;
4187 bool Buffer::isExporting() const
4189 return d->doing_export;
4193 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4197 return doExport(target, put_in_tempdir, result_file);
4200 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4201 string & result_file) const
4203 bool const update_unincluded =
4204 params().maintain_unincluded_children
4205 && !params().getIncludedChildren().empty();
4207 // (1) export with all included children (omit \includeonly)
4208 if (update_unincluded) {
4209 ExportStatus const status =
4210 doExport(target, put_in_tempdir, true, result_file);
4211 if (status != ExportSuccess)
4214 // (2) export with included children only
4215 return doExport(target, put_in_tempdir, false, result_file);
4219 void Buffer::setMathFlavor(OutputParams & op) const
4221 switch (params().html_math_output) {
4222 case BufferParams::MathML:
4223 op.math_flavor = OutputParams::MathAsMathML;
4225 case BufferParams::HTML:
4226 op.math_flavor = OutputParams::MathAsHTML;
4228 case BufferParams::Images:
4229 op.math_flavor = OutputParams::MathAsImages;
4231 case BufferParams::LaTeX:
4232 op.math_flavor = OutputParams::MathAsLaTeX;
4238 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4239 bool includeall, string & result_file) const
4241 LYXERR(Debug::FILES, "target=" << target);
4242 OutputParams runparams(¶ms().encoding());
4243 string format = target;
4244 string dest_filename;
4245 size_t pos = target.find(' ');
4246 if (pos != string::npos) {
4247 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4248 format = target.substr(0, pos);
4249 if (format == "default")
4250 format = params().getDefaultOutputFormat();
4251 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4252 FileName(dest_filename).onlyPath().createPath();
4253 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4255 MarkAsExporting exporting(this);
4256 string backend_format;
4257 runparams.flavor = OutputParams::LATEX;
4258 runparams.linelen = lyxrc.plaintext_linelen;
4259 runparams.includeall = includeall;
4260 vector<string> backs = params().backends();
4261 Converters converters = theConverters();
4262 bool need_nice_file = false;
4263 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4264 // Get shortest path to format
4265 converters.buildGraph();
4266 Graph::EdgePath path;
4267 for (vector<string>::const_iterator it = backs.begin();
4268 it != backs.end(); ++it) {
4269 Graph::EdgePath p = converters.getPath(*it, format);
4270 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4271 backend_format = *it;
4276 if (!put_in_tempdir) {
4277 // Only show this alert if this is an export to a non-temporary
4278 // file (not for previewing).
4279 Alert::error(_("Couldn't export file"), bformat(
4280 _("No information for exporting the format %1$s."),
4281 theFormats().prettyName(format)));
4283 return ExportNoPathToFormat;
4285 runparams.flavor = converters.getFlavor(path, this);
4286 Graph::EdgePath::const_iterator it = path.begin();
4287 Graph::EdgePath::const_iterator en = path.end();
4288 for (; it != en; ++it)
4289 if (theConverters().get(*it).nice()) {
4290 need_nice_file = true;
4295 backend_format = format;
4296 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4297 // FIXME: Don't hardcode format names here, but use a flag
4298 if (backend_format == "pdflatex")
4299 runparams.flavor = OutputParams::PDFLATEX;
4300 else if (backend_format == "luatex")
4301 runparams.flavor = OutputParams::LUATEX;
4302 else if (backend_format == "dviluatex")
4303 runparams.flavor = OutputParams::DVILUATEX;
4304 else if (backend_format == "xetex")
4305 runparams.flavor = OutputParams::XETEX;
4308 string filename = latexName(false);
4309 filename = addName(temppath(), filename);
4310 filename = changeExtension(filename,
4311 theFormats().extension(backend_format));
4312 LYXERR(Debug::FILES, "filename=" << filename);
4314 // Plain text backend
4315 if (backend_format == "text") {
4316 runparams.flavor = OutputParams::TEXT;
4317 writePlaintextFile(*this, FileName(filename), runparams);
4320 else if (backend_format == "xhtml") {
4321 runparams.flavor = OutputParams::HTML;
4322 setMathFlavor(runparams);
4323 makeLyXHTMLFile(FileName(filename), runparams);
4324 } else if (backend_format == "lyx")
4325 writeFile(FileName(filename));
4327 else if (params().isDocBook()) {
4328 runparams.nice = !put_in_tempdir;
4329 makeDocBookFile(FileName(filename), runparams);
4332 else if (backend_format == format || need_nice_file) {
4333 runparams.nice = true;
4334 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4335 if (d->cloned_buffer_)
4336 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4339 } else if (!lyxrc.tex_allows_spaces
4340 && contains(filePath(), ' ')) {
4341 Alert::error(_("File name error"),
4342 _("The directory path to the document cannot contain spaces."));
4343 return ExportTexPathHasSpaces;
4345 runparams.nice = false;
4346 bool const success = makeLaTeXFile(
4347 FileName(filename), filePath(), runparams);
4348 if (d->cloned_buffer_)
4349 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4354 string const error_type = (format == "program")
4355 ? "Build" : params().bufferFormat();
4356 ErrorList & error_list = d->errorLists[error_type];
4357 string const ext = theFormats().extension(format);
4358 FileName const tmp_result_file(changeExtension(filename, ext));
4359 bool const success = converters.convert(this, FileName(filename),
4360 tmp_result_file, FileName(absFileName()), backend_format, format,
4363 // Emit the signal to show the error list or copy it back to the
4364 // cloned Buffer so that it can be emitted afterwards.
4365 if (format != backend_format) {
4366 if (runparams.silent)
4368 else if (d->cloned_buffer_)
4369 d->cloned_buffer_->d->errorLists[error_type] =
4370 d->errorLists[error_type];
4373 // also to the children, in case of master-buffer-view
4374 ListOfBuffers clist = getDescendents();
4375 ListOfBuffers::const_iterator cit = clist.begin();
4376 ListOfBuffers::const_iterator const cen = clist.end();
4377 for (; cit != cen; ++cit) {
4378 if (runparams.silent)
4379 (*cit)->d->errorLists[error_type].clear();
4380 else if (d->cloned_buffer_) {
4381 // Enable reverse search by copying back the
4382 // texrow object to the cloned buffer.
4383 // FIXME: this is not thread safe.
4384 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4385 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4386 (*cit)->d->errorLists[error_type];
4388 (*cit)->errors(error_type, true);
4392 if (d->cloned_buffer_) {
4393 // Enable reverse dvi or pdf to work by copying back the texrow
4394 // object to the cloned buffer.
4395 // FIXME: There is a possibility of concurrent access to texrow
4396 // here from the main GUI thread that should be securized.
4397 d->cloned_buffer_->d->texrow = d->texrow;
4398 string const error_type = params().bufferFormat();
4399 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4403 if (put_in_tempdir) {
4404 result_file = tmp_result_file.absFileName();
4405 return success ? ExportSuccess : ExportConverterError;
4408 if (dest_filename.empty())
4409 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4411 result_file = dest_filename;
4412 // We need to copy referenced files (e. g. included graphics
4413 // if format == "dvi") to the result dir.
4414 vector<ExportedFile> const files =
4415 runparams.exportdata->externalFiles(format);
4416 string const dest = runparams.export_folder.empty() ?
4417 onlyPath(result_file) : runparams.export_folder;
4418 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4419 : force_overwrite == ALL_FILES;
4420 CopyStatus status = use_force ? FORCE : SUCCESS;
4422 vector<ExportedFile>::const_iterator it = files.begin();
4423 vector<ExportedFile>::const_iterator const en = files.end();
4424 for (; it != en && status != CANCEL; ++it) {
4425 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4426 string fixedName = it->exportName;
4427 if (!runparams.export_folder.empty()) {
4428 // Relative pathnames starting with ../ will be sanitized
4429 // if exporting to a different folder
4430 while (fixedName.substr(0, 3) == "../")
4431 fixedName = fixedName.substr(3, fixedName.length() - 3);
4433 FileName fixedFileName = makeAbsPath(fixedName, dest);
4434 fixedFileName.onlyPath().createPath();
4435 status = copyFile(fmt, it->sourceName,
4437 it->exportName, status == FORCE,
4438 runparams.export_folder.empty());
4441 if (status == CANCEL) {
4442 message(_("Document export cancelled."));
4443 return ExportCancel;
4446 if (tmp_result_file.exists()) {
4447 // Finally copy the main file
4448 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4449 : force_overwrite != NO_FILES;
4450 if (status == SUCCESS && use_force)
4452 status = copyFile(format, tmp_result_file,
4453 FileName(result_file), result_file,
4455 if (status == CANCEL) {
4456 message(_("Document export cancelled."));
4457 return ExportCancel;
4459 message(bformat(_("Document exported as %1$s "
4461 theFormats().prettyName(format),
4462 makeDisplayPath(result_file)));
4465 // This must be a dummy converter like fax (bug 1888)
4466 message(bformat(_("Document exported as %1$s"),
4467 theFormats().prettyName(format)));
4470 return success ? ExportSuccess : ExportConverterError;
4474 Buffer::ExportStatus Buffer::preview(string const & format) const
4476 bool const update_unincluded =
4477 params().maintain_unincluded_children
4478 && !params().getIncludedChildren().empty();
4479 return preview(format, update_unincluded);
4483 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4485 MarkAsExporting exporting(this);
4487 // (1) export with all included children (omit \includeonly)
4489 ExportStatus const status = doExport(format, true, true, result_file);
4490 if (status != ExportSuccess)
4493 // (2) export with included children only
4494 ExportStatus const status = doExport(format, true, false, result_file);
4495 FileName const previewFile(result_file);
4497 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4498 theimpl->preview_file_ = previewFile;
4499 theimpl->preview_format_ = format;
4500 theimpl->preview_error_ = (status != ExportSuccess);
4502 if (status != ExportSuccess)
4505 if (previewFile.exists())
4506 return theFormats().view(*this, previewFile, format) ?
4507 PreviewSuccess : PreviewError;
4509 // Successful export but no output file?
4510 // Probably a bug in error detection.
4511 LATTEST(status != ExportSuccess);
4516 Buffer::ReadStatus Buffer::extractFromVC()
4518 bool const found = LyXVC::file_not_found_hook(d->filename);
4520 return ReadFileNotFound;
4521 if (!d->filename.isReadableFile())
4527 Buffer::ReadStatus Buffer::loadEmergency()
4529 FileName const emergencyFile = getEmergencyFileName();
4530 if (!emergencyFile.exists()
4531 || emergencyFile.lastModified() <= d->filename.lastModified())
4532 return ReadFileNotFound;
4534 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4535 docstring const text = bformat(_("An emergency save of the document "
4536 "%1$s exists.\n\nRecover emergency save?"), file);
4538 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4539 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4545 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4546 bool const success = (ret_llf == ReadSuccess);
4548 if (hasReadonlyFlag()) {
4549 Alert::warning(_("File is read-only"),
4550 bformat(_("An emergency file is successfully loaded, "
4551 "but the original file %1$s is marked read-only. "
4552 "Please make sure to save the document as a different "
4553 "file."), from_utf8(d->filename.absFileName())));
4556 lyxvc().file_found_hook(d->filename);
4557 str = _("Document was successfully recovered.");
4559 str = _("Document was NOT successfully recovered.");
4560 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4561 makeDisplayPath(emergencyFile.absFileName()));
4563 int const del_emerg =
4564 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4565 _("&Remove"), _("&Keep"));
4566 if (del_emerg == 0) {
4567 emergencyFile.removeFile();
4569 Alert::warning(_("Emergency file deleted"),
4570 _("Do not forget to save your file now!"), true);
4572 return success ? ReadSuccess : ReadEmergencyFailure;
4575 int const del_emerg =
4576 Alert::prompt(_("Delete emergency file?"),
4577 _("Remove emergency file now?"), 1, 1,
4578 _("&Remove"), _("&Keep"));
4580 emergencyFile.removeFile();
4581 return ReadOriginal;
4591 Buffer::ReadStatus Buffer::loadAutosave()
4593 // Now check if autosave file is newer.
4594 FileName const autosaveFile = getAutosaveFileName();
4595 if (!autosaveFile.exists()
4596 || autosaveFile.lastModified() <= d->filename.lastModified())
4597 return ReadFileNotFound;
4599 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4600 docstring const text = bformat(_("The backup of the document %1$s "
4601 "is newer.\n\nLoad the backup instead?"), file);
4602 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4603 _("&Load backup"), _("Load &original"), _("&Cancel"));
4608 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4609 // the file is not saved if we load the autosave file.
4610 if (ret_llf == ReadSuccess) {
4611 if (hasReadonlyFlag()) {
4612 Alert::warning(_("File is read-only"),
4613 bformat(_("A backup file is successfully loaded, "
4614 "but the original file %1$s is marked read-only. "
4615 "Please make sure to save the document as a "
4617 from_utf8(d->filename.absFileName())));
4620 lyxvc().file_found_hook(d->filename);
4623 return ReadAutosaveFailure;
4626 // Here we delete the autosave
4627 autosaveFile.removeFile();
4628 return ReadOriginal;
4636 Buffer::ReadStatus Buffer::loadLyXFile()
4638 if (!d->filename.isReadableFile()) {
4639 ReadStatus const ret_rvc = extractFromVC();
4640 if (ret_rvc != ReadSuccess)
4644 ReadStatus const ret_re = loadEmergency();
4645 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4648 ReadStatus const ret_ra = loadAutosave();
4649 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4652 return loadThisLyXFile(d->filename);
4656 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4658 return readFile(fn);
4662 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4664 for (auto const & err : terr) {
4665 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4666 int errorRow = err.error_in_line;
4667 Buffer const * buf = 0;
4669 if (err.child_name.empty())
4670 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4672 // The error occurred in a child
4673 for (Buffer const * child : getDescendents()) {
4674 string const child_name =
4675 DocFileName(changeExtension(child->absFileName(), "tex")).
4677 if (err.child_name != child_name)
4679 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4680 if (!TexRow::isNone(start)) {
4681 buf = d->cloned_buffer_
4682 ? child->d->cloned_buffer_->d->owner_
4689 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4695 void Buffer::setBuffersForInsets() const
4697 inset().setBuffer(const_cast<Buffer &>(*this));
4701 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4703 LBUFERR(!text().paragraphs().empty());
4705 // Use the master text class also for child documents
4706 Buffer const * const master = masterBuffer();
4707 DocumentClass const & textclass = master->params().documentClass();
4709 // do this only if we are the top-level Buffer
4710 if (master == this) {
4711 textclass.counters().reset(from_ascii("bibitem"));
4712 reloadBibInfoCache();
4715 // keep the buffers to be children in this set. If the call from the
4716 // master comes back we can see which of them were actually seen (i.e.
4717 // via an InsetInclude). The remaining ones in the set need still be updated.
4718 static std::set<Buffer const *> bufToUpdate;
4719 if (scope == UpdateMaster) {
4720 // If this is a child document start with the master
4721 if (master != this) {
4722 bufToUpdate.insert(this);
4723 master->updateBuffer(UpdateMaster, utype);
4724 // If the master buffer has no gui associated with it, then the TocModel is
4725 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4726 // (bug 5699). The same happens if the master buffer is open in a different
4727 // window. This test catches both possibilities.
4728 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4729 // There remains a problem here: If there is another child open in yet a third
4730 // window, that TOC is not updated. So some more general solution is needed at
4732 if (master->d->gui_ != d->gui_)
4735 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4736 if (bufToUpdate.find(this) == bufToUpdate.end())
4740 // start over the counters in the master
4741 textclass.counters().reset();
4744 // update will be done below for this buffer
4745 bufToUpdate.erase(this);
4747 // update all caches
4748 clearReferenceCache();
4750 setChangesPresent(false);
4752 Buffer & cbuf = const_cast<Buffer &>(*this);
4755 ParIterator parit = cbuf.par_iterator_begin();
4756 updateBuffer(parit, utype);
4759 // If this document has siblings, then update the TocBackend later. The
4760 // reason is to ensure that later siblings are up to date when e.g. the
4761 // broken or not status of references is computed. The update is called
4762 // in InsetInclude::addToToc.
4765 d->bibinfo_cache_valid_ = true;
4766 d->cite_labels_valid_ = true;
4768 cbuf.tocBackend().update(true, utype);
4769 if (scope == UpdateMaster)
4770 cbuf.structureChanged();
4774 static depth_type getDepth(DocIterator const & it)
4776 depth_type depth = 0;
4777 for (size_t i = 0 ; i < it.depth() ; ++i)
4778 if (!it[i].inset().inMathed())
4779 depth += it[i].paragraph().getDepth() + 1;
4780 // remove 1 since the outer inset does not count
4781 // we should have at least one non-math inset, so
4782 // depth should nevery be 0. but maybe it is worth
4783 // marking this, just in case.
4785 // coverity[INTEGER_OVERFLOW]
4789 static depth_type getItemDepth(ParIterator const & it)
4791 Paragraph const & par = *it;
4792 LabelType const labeltype = par.layout().labeltype;
4794 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4797 // this will hold the lowest depth encountered up to now.
4798 depth_type min_depth = getDepth(it);
4799 ParIterator prev_it = it;
4802 --prev_it.top().pit();
4804 // start of nested inset: go to outer par
4806 if (prev_it.empty()) {
4807 // start of document: nothing to do
4812 // We search for the first paragraph with same label
4813 // that is not more deeply nested.
4814 Paragraph & prev_par = *prev_it;
4815 depth_type const prev_depth = getDepth(prev_it);
4816 if (labeltype == prev_par.layout().labeltype) {
4817 if (prev_depth < min_depth)
4818 return prev_par.itemdepth + 1;
4819 if (prev_depth == min_depth)
4820 return prev_par.itemdepth;
4822 min_depth = min(min_depth, prev_depth);
4823 // small optimization: if we are at depth 0, we won't
4824 // find anything else
4825 if (prev_depth == 0)
4831 static bool needEnumCounterReset(ParIterator const & it)
4833 Paragraph const & par = *it;
4834 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4835 depth_type const cur_depth = par.getDepth();
4836 ParIterator prev_it = it;
4837 while (prev_it.pit()) {
4838 --prev_it.top().pit();
4839 Paragraph const & prev_par = *prev_it;
4840 if (prev_par.getDepth() <= cur_depth)
4841 return prev_par.layout().name() != par.layout().name();
4843 // start of nested inset: reset
4848 // set the label of a paragraph. This includes the counters.
4849 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4851 BufferParams const & bp = owner_->masterBuffer()->params();
4852 DocumentClass const & textclass = bp.documentClass();
4853 Paragraph & par = it.paragraph();
4854 Layout const & layout = par.layout();
4855 Counters & counters = textclass.counters();
4857 if (par.params().startOfAppendix()) {
4858 // We want to reset the counter corresponding to toplevel sectioning
4859 Layout const & lay = textclass.getTOCLayout();
4860 docstring const cnt = lay.counter;
4862 counters.reset(cnt);
4863 counters.appendix(true);
4865 par.params().appendix(counters.appendix());
4867 // Compute the item depth of the paragraph
4868 par.itemdepth = getItemDepth(it);
4870 if (layout.margintype == MARGIN_MANUAL) {
4871 if (par.params().labelWidthString().empty())
4872 par.params().labelWidthString(par.expandLabel(layout, bp));
4873 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4874 // we do not need to do anything here, since the empty case is
4875 // handled during export.
4877 par.params().labelWidthString(docstring());
4880 switch(layout.labeltype) {
4881 case LABEL_ITEMIZE: {
4882 // At some point of time we should do something more
4883 // clever here, like:
4884 // par.params().labelString(
4885 // bp.user_defined_bullet(par.itemdepth).getText());
4886 // for now, use a simple hardcoded label
4887 docstring itemlabel;
4888 switch (par.itemdepth) {
4890 itemlabel = char_type(0x2022);
4893 itemlabel = char_type(0x2013);
4896 itemlabel = char_type(0x2217);
4899 itemlabel = char_type(0x2219); // or 0x00b7
4902 par.params().labelString(itemlabel);
4906 case LABEL_ENUMERATE: {
4907 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4909 switch (par.itemdepth) {
4918 enumcounter += "iv";
4921 // not a valid enumdepth...
4925 // Increase the master counter?
4926 if (layout.stepmastercounter && needEnumCounterReset(it))
4927 counters.stepMaster(enumcounter, utype);
4929 // Maybe we have to reset the enumeration counter.
4930 if (!layout.resumecounter && needEnumCounterReset(it))
4931 counters.reset(enumcounter);
4932 counters.step(enumcounter, utype);
4934 string const & lang = par.getParLanguage(bp)->code();
4935 par.params().labelString(counters.theCounter(enumcounter, lang));
4940 case LABEL_SENSITIVE: {
4941 string const & type = counters.current_float();
4942 docstring full_label;
4944 full_label = owner_->B_("Senseless!!! ");
4946 docstring name = owner_->B_(textclass.floats().getType(type).name());
4947 if (counters.hasCounter(from_utf8(type))) {
4948 string const & lang = par.getParLanguage(bp)->code();
4949 counters.step(from_utf8(type), utype);
4950 full_label = bformat(from_ascii("%1$s %2$s:"),
4952 counters.theCounter(from_utf8(type), lang));
4954 full_label = bformat(from_ascii("%1$s #:"), name);
4956 par.params().labelString(full_label);
4960 case LABEL_NO_LABEL:
4961 par.params().labelString(docstring());
4965 case LABEL_CENTERED:
4966 case LABEL_STATIC: {
4967 docstring const & lcounter = layout.counter;
4968 if (!lcounter.empty()) {
4969 if (layout.toclevel <= bp.secnumdepth
4970 && (layout.latextype != LATEX_ENVIRONMENT
4971 || it.text()->isFirstInSequence(it.pit()))) {
4972 if (counters.hasCounter(lcounter))
4973 counters.step(lcounter, utype);
4974 par.params().labelString(par.expandLabel(layout, bp));
4976 par.params().labelString(docstring());
4978 par.params().labelString(par.expandLabel(layout, bp));
4984 par.params().labelString(par.expandLabel(layout, bp));
4989 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4991 // LASSERT: Is it safe to continue here, or should we just return?
4992 LASSERT(parit.pit() == 0, /**/);
4994 // Set the position of the text in the buffer to be able
4995 // to resolve macros in it.
4996 parit.text()->setMacrocontextPosition(parit);
4998 depth_type maxdepth = 0;
4999 pit_type const lastpit = parit.lastpit();
5000 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5001 // reduce depth if necessary
5002 if (parit->params().depth() > maxdepth) {
5003 /** FIXME: this function is const, but
5004 * nevertheless it modifies the buffer. To be
5005 * cleaner, one should modify the buffer in
5006 * another function, which is actually
5007 * non-const. This would however be costly in
5008 * terms of code duplication.
5010 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5011 parit->params().depth(maxdepth);
5013 maxdepth = parit->getMaxDepthAfter();
5015 if (utype == OutputUpdate) {
5016 // track the active counters
5017 // we have to do this for the master buffer, since the local
5018 // buffer isn't tracking anything.
5019 masterBuffer()->params().documentClass().counters().
5020 setActiveLayout(parit->layout());
5023 // set the counter for this paragraph
5024 d->setLabel(parit, utype);
5026 // update change-tracking flag
5027 parit->addChangesToBuffer(*this);
5030 InsetList::const_iterator iit = parit->insetList().begin();
5031 InsetList::const_iterator end = parit->insetList().end();
5032 for (; iit != end; ++iit) {
5033 parit.pos() = iit->pos;
5034 iit->inset->updateBuffer(parit, utype);
5040 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5041 WordLangTuple & word_lang, docstring_list & suggestions) const
5045 suggestions.clear();
5046 word_lang = WordLangTuple();
5047 bool const to_end = to.empty();
5048 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5049 // OK, we start from here.
5050 for (; from != end; from.forwardPos()) {
5051 // This skips all insets with spell check disabled.
5052 while (!from.allowSpellCheck()) {
5056 // If from is at the end of the document (which is possible
5057 // when "from" was changed above) LyX will crash later otherwise.
5058 if (from.atEnd() || (!to_end && from >= end))
5061 from.paragraph().spellCheck();
5062 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5063 if (SpellChecker::misspelled(res)) {
5067 // Do not increase progress when from == to, otherwise the word
5068 // count will be wrong.
5078 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5080 bool inword = false;
5085 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5086 if (!dit.inTexted()) {
5091 Paragraph const & par = dit.paragraph();
5092 pos_type const pos = dit.pos();
5094 // Copied and adapted from isWordSeparator() in Paragraph
5095 if (pos == dit.lastpos()) {
5098 Inset const * ins = par.getInset(pos);
5099 if (ins && skipNoOutput && !ins->producesOutput()) {
5102 // stop if end of range was skipped
5103 if (!to.atEnd() && dit >= to)
5106 } else if (!par.isDeleted(pos)) {
5107 if (par.isWordSeparator(pos))
5113 if (ins && ins->isLetter())
5115 else if (ins && ins->isSpace())
5118 char_type const c = par.getChar(pos);
5119 if (isPrintableNonspace(c))
5121 else if (isSpace(c))
5131 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5133 d->updateStatistics(from, to, skipNoOutput);
5137 int Buffer::wordCount() const
5139 return d->wordCount();
5143 int Buffer::charCount(bool with_blanks) const
5145 return d->charCount(with_blanks);
5149 Buffer::ReadStatus Buffer::reload()
5152 // c.f. bug http://www.lyx.org/trac/ticket/6587
5153 removeAutosaveFile();
5154 // e.g., read-only status could have changed due to version control
5155 d->filename.refresh();
5156 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5158 // clear parent. this will get reset if need be.
5160 ReadStatus const status = loadLyXFile();
5161 if (status == ReadSuccess) {
5166 message(bformat(_("Document %1$s reloaded."), disp_fn));
5169 message(bformat(_("Could not reload document %1$s."), disp_fn));
5179 bool Buffer::saveAs(FileName const & fn)
5181 FileName const old_name = fileName();
5182 FileName const old_auto = getAutosaveFileName();
5183 bool const old_unnamed = isUnnamed();
5184 bool success = true;
5185 d->old_position = filePath();
5192 // bring the autosave file with us, just in case.
5193 moveAutosaveFile(old_auto);
5194 // validate version control data and
5195 // correct buffer title
5196 lyxvc().file_found_hook(fileName());
5198 // the file has now been saved to the new location.
5199 // we need to check that the locations of child buffers
5201 checkChildBuffers();
5202 checkMasterBuffer();
5205 // reset the old filename and unnamed state
5206 setFileName(old_name);
5207 setUnnamed(old_unnamed);
5211 d->old_position.clear();
5216 void Buffer::checkChildBuffers()
5218 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5219 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5220 for (; it != en; ++it) {
5221 DocIterator dit = it->second;
5222 Buffer * cbuf = const_cast<Buffer *>(it->first);
5223 if (!cbuf || !theBufferList().isLoaded(cbuf))
5225 Inset * inset = dit.nextInset();
5226 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5227 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5228 docstring const & incfile = inset_inc->getParam("filename");
5229 string oldloc = cbuf->absFileName();
5230 string newloc = makeAbsPath(to_utf8(incfile),
5231 onlyPath(absFileName())).absFileName();
5232 if (oldloc == newloc)
5234 // the location of the child file is incorrect.
5236 inset_inc->setChildBuffer(0);
5238 // invalidate cache of children
5239 d->children_positions.clear();
5240 d->position_to_children.clear();
5244 // If a child has been saved under a different name/path, it might have been
5245 // orphaned. Therefore the master needs to be reset (bug 8161).
5246 void Buffer::checkMasterBuffer()
5248 Buffer const * const master = masterBuffer();
5252 // necessary to re-register the child (bug 5873)
5253 // FIXME: clean up updateMacros (here, only
5254 // child registering is needed).
5255 master->updateMacros();
5256 // (re)set master as master buffer, but only
5257 // if we are a real child
5258 if (master->isChild(this))
5265 string Buffer::includedFilePath(string const & name, string const & ext) const
5267 if (d->old_position.empty() ||
5268 equivalent(FileName(d->old_position), FileName(filePath())))
5271 bool isabsolute = FileName::isAbsolute(name);
5272 // both old_position and filePath() end with a path separator
5273 string absname = isabsolute ? name : d->old_position + name;
5275 // if old_position is set to origin, we need to do the equivalent of
5276 // getReferencedFileName() (see readDocument())
5277 if (!isabsolute && d->old_position == params().origin) {
5278 FileName const test(addExtension(filePath() + name, ext));
5280 absname = filePath() + name;
5283 if (!FileName(addExtension(absname, ext)).exists())
5287 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5289 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5290 from_utf8(filePath())));
5294 void Buffer::setChangesPresent(bool b) const
5296 d->tracked_changes_present_ = b;
5300 bool Buffer::areChangesPresent() const
5302 return d->tracked_changes_present_;
5306 void Buffer::updateChangesPresent() const
5308 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5309 setChangesPresent(false);
5310 ParConstIterator it = par_iterator_begin();
5311 ParConstIterator const end = par_iterator_end();
5312 for (; !areChangesPresent() && it != end; ++it)
5313 it->addChangesToBuffer(*this);
5317 void Buffer::Impl::refreshFileMonitor()
5319 if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5320 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 // file_monitor_ will be destroyed with *this, so it is not going to call a
5328 // destroyed object method.
5329 file_monitor_->connect([this](bool exists) {
5330 fileExternallyModified(exists);
5335 void Buffer::Impl::fileExternallyModified(bool const exists)
5337 // ignore notifications after our own saving operations
5338 if (checksum_ == filename.checksum()) {
5339 LYXERR(Debug::FILES, "External modification but "
5340 "checksum unchanged: " << filename);
5343 lyx_clean = bak_clean = false;
5344 // If the file has been deleted, only mark the file as dirty since it is
5345 // pointless to prompt for reloading. If later a file is moved into this
5346 // location, then the externally modified warning will appear then.
5348 externally_modified_ = true;
5349 // Update external modification notification.
5350 // Dirty buffers must be visible at all times.
5351 if (wa_ && wa_->unhide(owner_))
5352 wa_->updateTitles();
5354 // Unable to unhide the buffer (e.g. no GUI or not current View)
5359 bool Buffer::notifiesExternalModification() const
5361 return d->externally_modified_;
5365 void Buffer::clearExternalModification() const
5367 d->externally_modified_ = false;
5369 d->wa_->updateTitles();