3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
60 #include "texstream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/GraphicsCache.h"
83 #include "graphics/PreviewLoader.h"
85 #include "frontends/alert.h"
86 #include "frontends/Delegates.h"
87 #include "frontends/WorkAreaManager.h"
89 #include "support/lassert.h"
90 #include "support/convert.h"
91 #include "support/debug.h"
92 #include "support/docstring_list.h"
93 #include "support/ExceptionMessage.h"
94 #include "support/FileMonitor.h"
95 #include "support/FileName.h"
96 #include "support/FileNameList.h"
97 #include "support/filetools.h"
98 #include "support/ForkedCalls.h"
99 #include "support/gettext.h"
100 #include "support/gzstream.h"
101 #include "support/lstrings.h"
102 #include "support/lyxalgo.h"
103 #include "support/mutex.h"
104 #include "support/os.h"
105 #include "support/Package.h"
106 #include "support/PathChanger.h"
107 #include "support/Systemcall.h"
108 #include "support/TempFile.h"
109 #include "support/textutils.h"
110 #include "support/types.h"
112 #include "support/bind.h"
124 using namespace lyx::support;
125 using namespace lyx::graphics;
129 namespace Alert = frontend::Alert;
130 namespace os = support::os;
134 int const LYX_FORMAT = LYX_FORMAT_LYX;
136 typedef map<string, bool> DepClean;
137 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
142 // A storehouse for the cloned buffers.
143 list<CloneList *> cloned_buffers;
149 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
153 delete preview_loader_;
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this an unnamed file (New...)?
195 /// is this an internal bufffer?
196 bool internal_buffer;
201 /// name of the file the buffer is associated with.
204 /** Set to true only when the file is fully loaded.
205 * Used to prevent the premature generation of previews
206 * and by the citation inset.
208 bool file_fully_loaded;
210 /// original format of loaded file
213 /// if the file was originally loaded from an older format, do
214 /// we need to back it up still?
215 bool need_format_backup;
217 /// Ignore the parent (e.g. when exporting a child standalone)?
221 mutable TocBackend toc_backend;
226 ScopeMacro(DocIterator const & s, MacroData const & m)
227 : scope(s), macro(m) {}
231 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
232 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
233 /// map from the macro name to the position map,
234 /// which maps the macro definition position to the scope and the MacroData.
235 NamePositionScopeMacroMap macros;
236 /// This seem to change the way Buffer::getMacro() works
237 mutable bool macro_lock;
239 /// positions of child buffers in the buffer
240 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
242 ScopeBuffer() : buffer(0) {}
243 ScopeBuffer(DocIterator const & s, Buffer const * b)
244 : scope(s), buffer(b) {}
246 Buffer const * buffer;
248 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
249 /// position of children buffers in this buffer
250 BufferPositionMap children_positions;
251 /// map from children inclusion positions to their scope and their buffer
252 PositionScopeBufferMap position_to_children;
254 /// Contains the old buffer filePath() while saving-as, or the
255 /// directory where the document was last saved while loading.
258 /** Keeps track of the path of local layout files.
259 * If possible, it is always relative to the buffer path.
260 * Empty for layouts in system or user directory.
262 string layout_position;
264 /// Container for all sort of Buffer dependant errors.
265 map<string, ErrorList> errorLists;
267 /// checksum used to test if the file has been externally modified. Used to
268 /// double check whether the file had been externally modified when saving.
269 unsigned long checksum_;
272 frontend::WorkAreaManager * wa_;
274 frontend::GuiBufferDelegate * gui_;
279 /// A cache for the bibfiles (including bibfiles of loaded child
280 /// documents), needed for appropriate update of natbib labels.
281 mutable support::FileNamePairList bibfiles_cache_;
283 // FIXME The caching mechanism could be improved. At present, we have a
284 // cache for each Buffer, that caches all the bibliography info for that
285 // Buffer. A more efficient solution would be to have a global cache per
286 // file, and then to construct the Buffer's bibinfo from that.
287 /// A cache for bibliography info
288 mutable BiblioInfo bibinfo_;
289 /// whether the bibinfo cache is valid
290 mutable bool bibinfo_cache_valid_;
291 /// whether the bibfile cache is valid
292 mutable bool bibfile_cache_valid_;
293 /// Cache of timestamps of .bib files
294 map<FileName, time_t> bibfile_status_;
295 /// Indicates whether the bibinfo has changed since the last time
296 /// we ran updateBuffer(), i.e., whether citation labels may need
298 mutable bool cite_labels_valid_;
300 /// These two hold the file name and format, written to by
301 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
302 FileName preview_file_;
303 string preview_format_;
304 /// If there was an error when previewing, on the next preview we do
305 /// a fresh compile (e.g. in case the user installed a package that
309 mutable RefCache ref_cache_;
311 /// our Text that should be wrapped in an InsetText
315 PreviewLoader * preview_loader_;
317 /// This is here to force the test to be done whenever parent_buffer
319 Buffer const * parent() const
321 // ignore_parent temporarily "orphans" a buffer
322 // (e.g. if a child is compiled standalone)
325 // if parent_buffer is not loaded, then it has been unloaded,
326 // which means that parent_buffer is an invalid pointer. So we
327 // set it to null in that case.
328 // however, the BufferList doesn't know about cloned buffers, so
329 // they will always be regarded as unloaded. in that case, we hope
331 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
333 return parent_buffer;
337 void setParent(Buffer const * pb)
339 if (parent_buffer == pb)
342 if (!cloned_buffer_ && parent_buffer && pb)
343 LYXERR0("Warning: a buffer should not have two parents!");
345 if (!cloned_buffer_ && parent_buffer) {
346 parent_buffer->invalidateBibfileCache();
347 parent_buffer->invalidateBibinfoCache();
351 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
352 /// This one is useful for preview detached in a thread.
353 Buffer const * cloned_buffer_;
355 CloneList * clone_list_;
356 /// are we in the process of exporting this buffer?
357 mutable bool doing_export;
359 /// compute statistics
360 /// \p from initial position
361 /// \p to points to the end position
362 void updateStatistics(DocIterator & from, DocIterator & to,
363 bool skipNoOutput = true);
364 /// statistics accessor functions
365 int wordCount() const
369 int charCount(bool with_blanks) const
372 + (with_blanks ? blank_count_ : 0);
375 // does the buffer contain tracked changes? (if so, we automatically
376 // display the review toolbar, for instance)
377 mutable bool tracked_changes_present_;
379 // Make sure the file monitor monitors the good file.
380 void refreshFileMonitor();
382 /// has it been notified of an external modification?
383 bool isExternallyModified() const { return externally_modified_; }
385 /// Notify or clear of external modification
386 void fileExternallyModified(bool modified) const;
388 /// Block notifications of external modifications
389 FileMonitorBlocker blockFileMonitor() { return file_monitor_->block(10); }
392 /// So we can force access via the accessors.
393 mutable Buffer const * parent_buffer;
399 /// has been externally modified? Can be reset by the user.
400 mutable bool externally_modified_;
402 FileMonitorPtr file_monitor_;
406 /// Creates the per buffer temporary directory
407 static FileName createBufferTmpDir()
409 // FIXME This would be the ideal application for a TempDir class (like
410 // TempFile but for directories)
415 Mutex::Locker locker(&mutex);
416 counter = convert<string>(count++);
418 // We are in our own directory. Why bother to mangle name?
419 // In fact I wrote this code to circumvent a problematic behaviour
420 // (bug?) of EMX mkstemp().
421 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
424 if (!tmpfl.createDirectory(0777)) {
425 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
426 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
427 from_utf8(tmpfl.absFileName())));
433 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
434 Buffer const * cloned_buffer)
435 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
436 internal_buffer(false), read_only(readonly_), filename(file),
437 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
438 ignore_parent(false), toc_backend(owner), macro_lock(false),
439 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
440 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
441 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
442 clone_list_(0), doing_export(false),
443 tracked_changes_present_(0), parent_buffer(0),
444 word_count_(0), char_count_(0), blank_count_(0),
445 externally_modified_(false)
447 refreshFileMonitor();
448 if (!cloned_buffer_) {
449 temppath = createBufferTmpDir();
450 lyxvc.setBuffer(owner_);
452 wa_ = new frontend::WorkAreaManager;
455 temppath = cloned_buffer_->d->temppath;
456 file_fully_loaded = true;
457 params = cloned_buffer_->d->params;
458 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
459 bibinfo_ = cloned_buffer_->d->bibinfo_;
460 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
461 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
462 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
463 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
464 unnamed = cloned_buffer_->d->unnamed;
465 internal_buffer = cloned_buffer_->d->internal_buffer;
466 layout_position = cloned_buffer_->d->layout_position;
467 preview_file_ = cloned_buffer_->d->preview_file_;
468 preview_format_ = cloned_buffer_->d->preview_format_;
469 preview_error_ = cloned_buffer_->d->preview_error_;
470 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
474 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
475 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
477 LYXERR(Debug::INFO, "Buffer::Buffer()");
479 d->inset = new InsetText(*cloned_buffer->d->inset);
480 d->inset->setBuffer(*this);
481 // FIXME: optimize this loop somewhat, maybe by creating a new
482 // general recursive Inset::setId().
483 DocIterator it = doc_iterator_begin(this);
484 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
485 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
486 it.paragraph().setId(cloned_it.paragraph().id());
488 d->inset = new InsetText(this);
489 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
495 LYXERR(Debug::INFO, "Buffer::~Buffer()");
496 // here the buffer should take care that it is
497 // saved properly, before it goes into the void.
499 // GuiView already destroyed
503 // No need to do additional cleanups for internal buffer.
509 // this is in case of recursive includes: we won't try to delete
510 // ourselves as a child.
511 d->clone_list_->erase(this);
512 // loop over children
513 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
514 Impl::BufferPositionMap::iterator end = d->children_positions.end();
515 for (; it != end; ++it) {
516 Buffer * child = const_cast<Buffer *>(it->first);
517 if (d->clone_list_->erase(child))
520 // if we're the master buffer, then we should get rid of the list
523 // If this is not empty, we have leaked something. Worse, one of the
524 // children still has a reference to this list. But we will try to
525 // continue, rather than shut down.
526 LATTEST(d->clone_list_->empty());
527 list<CloneList *>::iterator it =
528 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
529 if (it == cloned_buffers.end()) {
530 // We will leak in this case, but it is safe to continue.
533 cloned_buffers.erase(it);
534 delete d->clone_list_;
536 // FIXME Do we really need to do this right before we delete d?
537 // clear references to children in macro tables
538 d->children_positions.clear();
539 d->position_to_children.clear();
541 // loop over children
542 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
543 Impl::BufferPositionMap::iterator end = d->children_positions.end();
544 for (; it != end; ++it) {
545 Buffer * child = const_cast<Buffer *>(it->first);
546 if (theBufferList().isLoaded(child)) {
547 if (theBufferList().isOthersChild(this, child))
550 theBufferList().release(child);
555 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
557 msg += emergencyWrite();
559 msg += " " + _("Save failed! Document is lost.");
561 Alert::warning(_("Attempting to close changed document!"), msg);
564 // FIXME Do we really need to do this right before we delete d?
565 // clear references to children in macro tables
566 d->children_positions.clear();
567 d->position_to_children.clear();
569 if (!d->temppath.destroyDirectory()) {
570 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
571 from_utf8(d->temppath.absFileName())));
580 Buffer * Buffer::cloneFromMaster() const
583 cloned_buffers.push_back(new CloneList);
584 CloneList * clones = cloned_buffers.back();
586 masterBuffer()->cloneWithChildren(bufmap, clones);
588 // make sure we got cloned
589 BufferMap::const_iterator bit = bufmap.find(this);
590 LASSERT(bit != bufmap.end(), return 0);
591 Buffer * cloned_buffer = bit->second;
593 return cloned_buffer;
597 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
599 // have we already been cloned?
600 if (bufmap.find(this) != bufmap.end())
603 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
605 // The clone needs its own DocumentClass, since running updateBuffer() will
606 // modify it, and we would otherwise be sharing it with the original Buffer.
607 buffer_clone->params().makeDocumentClass(true);
609 cap::switchBetweenClasses(
610 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
611 static_cast<InsetText &>(buffer_clone->inset()), el);
613 bufmap[this] = buffer_clone;
614 clones->insert(buffer_clone);
615 buffer_clone->d->clone_list_ = clones;
616 buffer_clone->d->macro_lock = true;
617 buffer_clone->d->children_positions.clear();
619 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
620 // math macro caches need to be rethought and simplified.
621 // I am not sure wether we should handle Buffer cloning here or in BufferList.
622 // Right now BufferList knows nothing about buffer clones.
623 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
624 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
625 for (; it != end; ++it) {
626 DocIterator dit = it->first.clone(buffer_clone);
627 dit.setBuffer(buffer_clone);
628 Buffer * child = const_cast<Buffer *>(it->second.buffer);
630 child->cloneWithChildren(bufmap, clones);
631 BufferMap::iterator const bit = bufmap.find(child);
632 LASSERT(bit != bufmap.end(), continue);
633 Buffer * child_clone = bit->second;
635 Inset * inset = dit.nextInset();
636 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
637 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
638 inset_inc->setChildBuffer(child_clone);
639 child_clone->d->setParent(buffer_clone);
640 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
641 buffer_clone->setChild(dit, child_clone);
643 buffer_clone->d->macro_lock = false;
648 Buffer * Buffer::cloneBufferOnly() const {
649 cloned_buffers.push_back(new CloneList);
650 CloneList * clones = cloned_buffers.back();
651 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
653 // The clone needs its own DocumentClass, since running updateBuffer() will
654 // modify it, and we would otherwise be sharing it with the original Buffer.
655 buffer_clone->params().makeDocumentClass(true);
657 cap::switchBetweenClasses(
658 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
659 static_cast<InsetText &>(buffer_clone->inset()), el);
661 clones->insert(buffer_clone);
662 buffer_clone->d->clone_list_ = clones;
664 // we won't be cloning the children
665 buffer_clone->d->children_positions.clear();
670 bool Buffer::isClone() const
672 return d->cloned_buffer_;
676 void Buffer::changed(bool update_metrics) const
679 d->wa_->redrawAll(update_metrics);
683 frontend::WorkAreaManager & Buffer::workAreaManager() const
690 Text & Buffer::text() const
692 return d->inset->text();
696 Inset & Buffer::inset() const
702 BufferParams & Buffer::params()
708 BufferParams const & Buffer::params() const
714 BufferParams const & Buffer::masterParams() const
716 if (masterBuffer() == this)
719 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
720 // Copy child authors to the params. We need those pointers.
721 AuthorList const & child_authors = params().authors();
722 AuthorList::Authors::const_iterator it = child_authors.begin();
723 for (; it != child_authors.end(); ++it)
724 mparams.authors().record(*it);
729 double Buffer::fontScalingFactor() const
731 return isExporting() ? 75.0 * params().html_math_img_scale
732 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
736 ParagraphList & Buffer::paragraphs()
738 return text().paragraphs();
742 ParagraphList const & Buffer::paragraphs() const
744 return text().paragraphs();
748 LyXVC & Buffer::lyxvc()
754 LyXVC const & Buffer::lyxvc() const
760 string const Buffer::temppath() const
762 return d->temppath.absFileName();
766 TexRow & Buffer::texrow()
772 TexRow const & Buffer::texrow() const
778 TocBackend & Buffer::tocBackend() const
780 return d->toc_backend;
784 Undo & Buffer::undo()
790 void Buffer::setChild(DocIterator const & dit, Buffer * child)
792 d->children_positions[child] = dit;
796 string Buffer::latexName(bool const no_path) const
798 FileName latex_name =
799 makeLatexName(d->exportFileName());
800 return no_path ? latex_name.onlyFileName()
801 : latex_name.absFileName();
805 FileName Buffer::Impl::exportFileName() const
807 docstring const branch_suffix =
808 params.branchlist().getFileNameSuffix();
809 if (branch_suffix.empty())
812 string const name = filename.onlyFileNameWithoutExt()
813 + to_utf8(branch_suffix);
814 FileName res(filename.onlyPath().absFileName() + "/" + name);
815 res.changeExtension(filename.extension());
821 string Buffer::logName(LogType * type) const
823 string const filename = latexName(false);
825 if (filename.empty()) {
831 string const path = temppath();
833 FileName const fname(addName(temppath(),
834 onlyFileName(changeExtension(filename,
837 // FIXME: how do we know this is the name of the build log?
838 FileName const bname(
839 addName(path, onlyFileName(
840 changeExtension(filename,
841 theFormats().extension(params().bufferFormat()) + ".out"))));
843 // Also consider the master buffer log file
844 FileName masterfname = fname;
845 LogType mtype = latexlog;
846 if (masterBuffer() != this) {
847 string const mlogfile = masterBuffer()->logName(&mtype);
848 masterfname = FileName(mlogfile);
851 // If no Latex log or Build log is newer, show Build log
852 if (bname.exists() &&
853 ((!fname.exists() && !masterfname.exists())
854 || (fname.lastModified() < bname.lastModified()
855 && masterfname.lastModified() < bname.lastModified()))) {
856 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
859 return bname.absFileName();
860 // If we have a newer master file log or only a master log, show this
861 } else if (fname != masterfname
862 && (!fname.exists() && (masterfname.exists()
863 || fname.lastModified() < masterfname.lastModified()))) {
864 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
867 return masterfname.absFileName();
869 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
872 return fname.absFileName();
876 void Buffer::setReadonly(bool const flag)
878 if (d->read_only != flag) {
885 void Buffer::setFileName(FileName const & fname)
887 bool const changed = fname != d->filename;
889 d->refreshFileMonitor();
891 lyxvc().file_found_hook(fname);
892 setReadonly(d->filename.isReadOnly());
898 int Buffer::readHeader(Lexer & lex)
900 int unknown_tokens = 0;
902 int begin_header_line = -1;
904 // Initialize parameters that may be/go lacking in header:
905 params().branchlist().clear();
906 params().preamble.erase();
907 params().options.erase();
908 params().master.erase();
909 params().float_placement.erase();
910 params().paperwidth.erase();
911 params().paperheight.erase();
912 params().leftmargin.erase();
913 params().rightmargin.erase();
914 params().topmargin.erase();
915 params().bottommargin.erase();
916 params().headheight.erase();
917 params().headsep.erase();
918 params().footskip.erase();
919 params().columnsep.erase();
920 params().fonts_cjk.erase();
921 params().listings_params.clear();
922 params().clearLayoutModules();
923 params().clearRemovedModules();
924 params().clearIncludedChildren();
925 params().pdfoptions().clear();
926 params().indiceslist().clear();
927 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
928 params().isbackgroundcolor = false;
929 params().fontcolor = RGBColor(0, 0, 0);
930 params().isfontcolor = false;
931 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
932 params().boxbgcolor = RGBColor(0xFF, 0, 0);
933 params().html_latex_start.clear();
934 params().html_latex_end.clear();
935 params().html_math_img_scale = 1.0;
936 params().output_sync_macro.erase();
937 params().setLocalLayout(docstring(), false);
938 params().setLocalLayout(docstring(), true);
939 params().biblio_opts.erase();
940 params().biblatex_bibstyle.erase();
941 params().biblatex_citestyle.erase();
942 params().multibib.erase();
944 for (int i = 0; i < 4; ++i) {
945 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
946 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
949 ErrorList & errorList = d->errorLists["Parse"];
958 if (token == "\\end_header")
962 if (token == "\\begin_header") {
963 begin_header_line = line;
967 LYXERR(Debug::PARSER, "Handling document header token: `"
970 string const result =
971 params().readToken(lex, token, d->filename.onlyPath());
972 if (!result.empty()) {
973 if (token == "\\textclass") {
974 d->layout_position = result;
977 docstring const s = bformat(_("Unknown token: "
981 errorList.push_back(ErrorItem(_("Document header error"), s));
985 if (begin_header_line) {
986 docstring const s = _("\\begin_header is missing");
987 errorList.push_back(ErrorItem(_("Document header error"), s));
990 params().makeDocumentClass();
992 return unknown_tokens;
997 // changed to be public and have one parameter
998 // Returns true if "\end_document" is not read (Asger)
999 bool Buffer::readDocument(Lexer & lex)
1001 ErrorList & errorList = d->errorLists["Parse"];
1004 // remove dummy empty par
1005 paragraphs().clear();
1007 if (!lex.checkFor("\\begin_document")) {
1008 docstring const s = _("\\begin_document is missing");
1009 errorList.push_back(ErrorItem(_("Document header error"), s));
1014 if (params().output_changes) {
1015 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1016 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
1017 LaTeXFeatures::isAvailable("xcolor");
1019 if (!dvipost && !xcolorulem) {
1020 Alert::warning(_("Changes not shown in LaTeX output"),
1021 _("Changes will not be highlighted in LaTeX output, "
1022 "because neither dvipost nor xcolor/ulem are installed.\n"
1023 "Please install these packages or redefine "
1024 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1025 } else if (!xcolorulem) {
1026 Alert::warning(_("Changes not shown in LaTeX output"),
1027 _("Changes will not be highlighted in LaTeX output "
1028 "when using pdflatex, because xcolor and ulem are not installed.\n"
1029 "Please install both packages or redefine "
1030 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1034 if (!parent() && !params().master.empty()) {
1035 FileName const master_file = makeAbsPath(params().master,
1036 onlyPath(absFileName()));
1037 if (isLyXFileName(master_file.absFileName())) {
1039 checkAndLoadLyXFile(master_file, true);
1041 // necessary e.g. after a reload
1042 // to re-register the child (bug 5873)
1043 // FIXME: clean up updateMacros (here, only
1044 // child registering is needed).
1045 master->updateMacros();
1046 // set master as master buffer, but only
1047 // if we are a real child
1048 if (master->isChild(this))
1050 // if the master is not fully loaded
1051 // it is probably just loading this
1052 // child. No warning needed then.
1053 else if (master->isFullyLoaded())
1054 LYXERR0("The master '"
1056 << "' assigned to this document ("
1058 << ") does not include "
1059 "this document. Ignoring the master assignment.");
1064 // assure we have a default index
1065 params().indiceslist().addDefault(B_("Index"));
1068 if (FileName::isAbsolute(params().origin))
1069 d->old_position = params().origin;
1071 d->old_position = filePath();
1072 bool const res = text().read(lex, errorList, d->inset);
1073 d->old_position.clear();
1075 // inform parent buffer about local macros
1077 Buffer const * pbuf = parent();
1078 UserMacroSet::const_iterator cit = usermacros.begin();
1079 UserMacroSet::const_iterator end = usermacros.end();
1080 for (; cit != end; ++cit)
1081 pbuf->usermacros.insert(*cit);
1085 updateMacroInstances(InternalUpdate);
1090 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1092 Format const * fmt = theFormats().getFormat(format);
1095 // It is important to use the correct extension here, since some
1096 // converters create a wrong output file otherwise (e.g. html2latex)
1097 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1098 FileName const name(tempfile.name());
1099 ofdocstream os(name.toFilesystemEncoding().c_str());
1100 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1101 bool const success = !(os << contents).fail();
1104 bool converted = false;
1106 params().compressed = false;
1108 // remove dummy empty par
1109 paragraphs().clear();
1111 converted = importFile(format, name, errorList);
1120 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1122 if (!theConverters().isReachable(format, "lyx"))
1125 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1126 FileName const lyx(tempfile.name());
1127 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1128 return readFile(lyx) == ReadSuccess;
1134 bool Buffer::readString(string const & s)
1136 params().compressed = false;
1139 istringstream is(s);
1141 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1142 FileName const fn = tempfile.name();
1145 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1147 if (success && file_format != LYX_FORMAT) {
1148 // We need to call lyx2lyx, so write the input to a file
1149 ofstream os(fn.toFilesystemEncoding().c_str());
1152 // lyxvc in readFile
1153 if (readFile(fn) != ReadSuccess)
1157 if (readDocument(lex))
1163 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1167 if (!lex.setFile(fname)) {
1168 Alert::error(_("File Not Found"),
1169 bformat(_("Unable to open file `%1$s'."),
1170 from_utf8(fn.absFileName())));
1171 return ReadFileNotFound;
1175 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1176 if (ret_plf != ReadSuccess)
1179 if (file_format != LYX_FORMAT) {
1181 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1182 if (ret_clf == ReadSuccess) {
1183 ret_clf = readFile(tmpFile);
1184 if (ret_clf == ReadSuccess) {
1185 d->file_format = file_format;
1186 d->need_format_backup = true;
1190 if (ret_clf != ReadSuccess) {
1191 int const ret = Alert::prompt(_("Document format failure"),
1192 _("Fileformat unrecognized by lyx2lyx. Trying to load anyway, "
1193 "but some contents might be lost and LyX might crash!\n"
1194 "Would you like to proceed ?"), 0, 1, _("&No"), _("&Yes"));
1200 // FIXME: InsetInfo needs to know whether the file is under VCS
1201 // during the parse process, so this has to be done before.
1202 lyxvc().file_found_hook(d->filename);
1204 if (readDocument(lex)) {
1205 Alert::error(_("Document format failure"),
1206 bformat(_("%1$s ended unexpectedly, which means"
1207 " that it is probably corrupted."),
1208 from_utf8(fn.absFileName())));
1209 return ReadDocumentFailure;
1212 d->file_fully_loaded = true;
1213 d->read_only = !d->filename.isWritable();
1214 params().compressed = theFormats().isZippedFile(d->filename);
1220 bool Buffer::isFullyLoaded() const
1222 return d->file_fully_loaded;
1226 void Buffer::setFullyLoaded(bool value)
1228 d->file_fully_loaded = value;
1232 bool Buffer::lastPreviewError() const
1234 return d->preview_error_;
1238 PreviewLoader * Buffer::loader() const
1240 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1242 if (!d->preview_loader_)
1243 d->preview_loader_ = new PreviewLoader(*this);
1244 return d->preview_loader_;
1248 void Buffer::removePreviews() const
1250 delete d->preview_loader_;
1251 d->preview_loader_ = 0;
1255 void Buffer::updatePreviews() const
1257 PreviewLoader * ploader = loader();
1261 InsetIterator it = inset_iterator_begin(*d->inset);
1262 InsetIterator const end = inset_iterator_end(*d->inset);
1263 for (; it != end; ++it)
1264 it->addPreview(it, *ploader);
1266 ploader->startLoading();
1270 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1271 FileName const & fn, int & file_format) const
1273 if(!lex.checkFor("\\lyxformat")) {
1274 Alert::error(_("Document format failure"),
1275 bformat(_("%1$s is not a readable LyX document."),
1276 from_utf8(fn.absFileName())));
1277 return ReadNoLyXFormat;
1283 // LyX formats 217 and earlier were written as 2.17. This corresponds
1284 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1285 // these cases. See also: www.lyx.org/trac/changeset/1313.
1286 size_t dot = tmp_format.find_first_of(".,");
1287 if (dot != string::npos)
1288 tmp_format.erase(dot, 1);
1290 file_format = convert<int>(tmp_format);
1295 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1296 FileName & tmpfile, int from_format)
1298 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1299 tempfile.setAutoRemove(false);
1300 tmpfile = tempfile.name();
1301 if(tmpfile.empty()) {
1302 Alert::error(_("Conversion failed"),
1303 bformat(_("%1$s is from a different"
1304 " version of LyX, but a temporary"
1305 " file for converting it could"
1306 " not be created."),
1307 from_utf8(fn.absFileName())));
1308 return LyX2LyXNoTempFile;
1311 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1312 if (lyx2lyx.empty()) {
1313 Alert::error(_("Conversion script not found"),
1314 bformat(_("%1$s is from a different"
1315 " version of LyX, but the"
1316 " conversion script lyx2lyx"
1317 " could not be found."),
1318 from_utf8(fn.absFileName())));
1319 return LyX2LyXNotFound;
1323 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1324 ostringstream command;
1325 command << os::python()
1326 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1327 << " -t " << convert<string>(LYX_FORMAT)
1328 << " -o " << quoteName(tmpfile.toSafeFilesystemEncoding())
1329 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1330 string const command_str = command.str();
1332 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1334 cmd_ret const ret = runCommand(command_str);
1335 if (ret.first != 0) {
1336 if (from_format < LYX_FORMAT) {
1337 Alert::error(_("Conversion script failed"),
1338 bformat(_("%1$s is from an older version"
1339 " of LyX and the lyx2lyx script"
1340 " failed to convert it."),
1341 from_utf8(fn.absFileName())));
1342 return LyX2LyXOlderFormat;
1344 Alert::error(_("Conversion script failed"),
1345 bformat(_("%1$s is from a newer version"
1346 " of LyX and the lyx2lyx script"
1347 " failed to convert it."),
1348 from_utf8(fn.absFileName())));
1349 return LyX2LyXNewerFormat;
1356 FileName Buffer::getBackupName() const {
1357 FileName const & fn = fileName();
1358 string const fname = fn.onlyFileNameWithoutExt();
1359 string const fext = fn.extension() + "~";
1360 string const fpath = lyxrc.backupdir_path.empty() ?
1361 fn.onlyPath().absFileName() :
1362 lyxrc.backupdir_path;
1363 string const fform = convert<string>(d->file_format);
1364 string const backname = fname + "-lyxformat-" + fform;
1365 FileName backup(addName(fpath, addExtension(backname, fext)));
1367 // limit recursion, just in case
1369 unsigned long orig_checksum = 0;
1370 while (backup.exists() && v < 100) {
1371 if (orig_checksum == 0)
1372 orig_checksum = fn.checksum();
1373 unsigned long new_checksum = backup.checksum();
1374 if (orig_checksum == new_checksum) {
1375 LYXERR(Debug::FILES, "Not backing up " << fn <<
1376 "since " << backup << "has the same checksum.");
1377 // a bit of a hack, but we have to check this anyway
1378 // below, and setting this is simpler than introducing
1379 // a special boolean for this purpose.
1383 string const newbackname = backname + "-" + convert<string>(v);
1384 backup.set(addName(fpath, addExtension(newbackname, fext)));
1387 return v < 100 ? backup : FileName();
1391 // Should probably be moved to somewhere else: BufferView? GuiView?
1392 bool Buffer::save() const
1394 FileMonitorBlocker block = d->blockFileMonitor();
1395 docstring const file = makeDisplayPath(absFileName(), 20);
1396 d->filename.refresh();
1398 // check the read-only status before moving the file as a backup
1399 if (d->filename.exists()) {
1400 bool const read_only = !d->filename.isWritable();
1402 Alert::warning(_("File is read-only"),
1403 bformat(_("The file %1$s cannot be written because it "
1404 "is marked as read-only."), file));
1409 // ask if the disk file has been externally modified (use checksum method)
1410 if (fileName().exists() && isChecksumModified()) {
1412 bformat(_("Document %1$s has been externally modified. "
1413 "Are you sure you want to overwrite this file?"), file);
1414 int const ret = Alert::prompt(_("Overwrite modified file?"),
1415 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1420 // We don't need autosaves in the immediate future. (Asger)
1421 resetAutosaveTimers();
1423 // if the file does not yet exist, none of the backup activity
1424 // that follows is necessary
1425 if (!fileName().exists()) {
1426 if (!writeFile(fileName()))
1432 // we first write the file to a new name, then move it to its
1433 // proper location once that has been done successfully. that
1434 // way we preserve the original file if something goes wrong.
1435 string const justname = fileName().onlyFileNameWithoutExt();
1436 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1437 justname + "-XXXXXX.lyx");
1438 bool const symlink = fileName().isSymLink();
1440 tempfile->setAutoRemove(false);
1442 FileName savefile(tempfile->name());
1443 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1444 if (!writeFile(savefile))
1447 // we will set this to false if we fail
1448 bool made_backup = true;
1450 FileName backupName;
1451 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1453 if (d->need_format_backup)
1454 backupName = getBackupName();
1456 // If we for some reason failed to find a backup name in case of
1457 // a format change, this will still set one. It's the best we can
1459 if (backupName.empty()) {
1460 backupName.set(fileName().absFileName() + "~");
1461 if (!lyxrc.backupdir_path.empty()) {
1462 string const mangledName =
1463 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1464 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1468 LYXERR(Debug::FILES, "Backing up original file to " <<
1469 backupName.absFileName());
1470 // Except file is symlink do not copy because of #6587.
1471 // Hard links have bad luck.
1472 made_backup = symlink ?
1473 fileName().copyTo(backupName):
1474 fileName().moveTo(backupName);
1477 Alert::error(_("Backup failure"),
1478 bformat(_("Cannot create backup file %1$s.\n"
1479 "Please check whether the directory exists and is writable."),
1480 from_utf8(backupName.absFileName())));
1481 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1482 } else if (d->need_format_backup) {
1483 // the original file has been backed up successfully, so we
1484 // will not need to do that again
1485 d->need_format_backup = false;
1489 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1490 // Only do this if tempfile is not in autoremove mode
1493 // If we have no symlink, we can simply rename the temp file.
1494 // Otherwise, we need to copy it so the symlink stays intact.
1495 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1496 savefile.moveTo(fileName()))
1498 // saveCheckSum() was already called by writeFile(), but the
1499 // time stamp is invalidated by copying/moving
1502 if (d->file_format != LYX_FORMAT)
1503 // the file associated with this buffer is now in the current format
1504 d->file_format = LYX_FORMAT;
1507 // else we saved the file, but failed to move it to the right location.
1509 if (needBackup && made_backup && !symlink) {
1510 // the original file was moved to some new location, so it will look
1511 // to the user as if it was deleted. (see bug #9234.) we could try
1512 // to restore it, but that would basically mean trying to do again
1513 // what we just failed to do. better to leave things as they are.
1514 Alert::error(_("Write failure"),
1515 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1516 "But LyX could not move it to:\n %2$s.\n"
1517 "Your original file has been backed up to:\n %3$s"),
1518 from_utf8(savefile.absFileName()),
1519 from_utf8(fileName().absFileName()),
1520 from_utf8(backupName.absFileName())));
1522 // either we did not try to make a backup, or else we tried and failed,
1523 // or else the original file was a symlink, in which case it was copied,
1524 // not moved. so the original file is intact.
1525 Alert::error(_("Write failure"),
1526 bformat(_("Cannot move saved file to:\n %1$s.\n"
1527 "But the file has successfully been saved as:\n %2$s."),
1528 from_utf8(fileName().absFileName()),
1529 from_utf8(savefile.absFileName())));
1535 bool Buffer::writeFile(FileName const & fname) const
1537 if (d->read_only && fname == d->filename)
1540 bool retval = false;
1542 docstring const str = bformat(_("Saving document %1$s..."),
1543 makeDisplayPath(fname.absFileName()));
1546 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1548 if (params().compressed) {
1549 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1550 retval = ofs && write(ofs);
1552 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1553 retval = ofs && write(ofs);
1557 message(str + _(" could not write file!"));
1562 // removeAutosaveFile();
1565 message(str + _(" done."));
1571 docstring Buffer::emergencyWrite()
1573 // No need to save if the buffer has not changed.
1577 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1579 docstring user_message = bformat(
1580 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1582 // We try to save three places:
1583 // 1) Same place as document. Unless it is an unnamed doc.
1585 string s = absFileName();
1588 if (writeFile(FileName(s))) {
1590 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1591 return user_message;
1593 user_message += " " + _("Save failed! Trying again...\n");
1597 // 2) In HOME directory.
1598 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1600 lyxerr << ' ' << s << endl;
1601 if (writeFile(FileName(s))) {
1603 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1604 return user_message;
1607 user_message += " " + _("Save failed! Trying yet again...\n");
1609 // 3) In "/tmp" directory.
1610 // MakeAbsPath to prepend the current
1611 // drive letter on OS/2
1612 s = addName(package().temp_dir().absFileName(), absFileName());
1614 lyxerr << ' ' << s << endl;
1615 if (writeFile(FileName(s))) {
1617 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1618 return user_message;
1621 user_message += " " + _("Save failed! Document is lost.");
1624 return user_message;
1628 bool Buffer::write(ostream & ofs) const
1631 // Use the standard "C" locale for file output.
1632 ofs.imbue(locale::classic());
1635 // The top of the file should not be written by params().
1637 // write out a comment in the top of the file
1638 // Important: Keep the version formatting in sync with lyx2lyx and
1639 // tex2lyx (bug 7951)
1640 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1641 << " created this file. For more info see http://www.lyx.org/\n"
1642 << "\\lyxformat " << LYX_FORMAT << "\n"
1643 << "\\begin_document\n";
1645 /// For each author, set 'used' to true if there is a change
1646 /// by this author in the document; otherwise set it to 'false'.
1647 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1648 AuthorList::Authors::const_iterator a_end = params().authors().end();
1649 for (; a_it != a_end; ++a_it)
1650 a_it->setUsed(false);
1652 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1653 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1654 for ( ; it != end; ++it)
1655 it->checkAuthors(params().authors());
1657 // now write out the buffer parameters.
1658 ofs << "\\begin_header\n";
1659 params().writeFile(ofs, this);
1660 ofs << "\\end_header\n";
1663 ofs << "\n\\begin_body\n";
1665 ofs << "\n\\end_body\n";
1667 // Write marker that shows file is complete
1668 ofs << "\\end_document" << endl;
1670 // Shouldn't really be needed....
1673 // how to check if close went ok?
1674 // Following is an attempt... (BE 20001011)
1676 // good() returns false if any error occurred, including some
1677 // formatting error.
1678 // bad() returns true if something bad happened in the buffer,
1679 // which should include file system full errors.
1684 lyxerr << "File was not closed properly." << endl;
1691 bool Buffer::makeLaTeXFile(FileName const & fname,
1692 string const & original_path,
1693 OutputParams const & runparams_in,
1694 OutputWhat output) const
1696 OutputParams runparams = runparams_in;
1698 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1699 // Check here, because the "flavor" is not known in BufferParams::encoding()
1700 // (power users can override this safety measure selecting "utf8-plain").
1701 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1702 && (runparams.encoding->name() != "utf8-plain"))
1703 runparams.encoding = encodings.fromLyXName("ascii");
1705 string const encoding = runparams.encoding->iconvName();
1706 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1709 try { ofs.reset(encoding); }
1710 catch (iconv_codecvt_facet_exception const & e) {
1711 lyxerr << "Caught iconv exception: " << e.what() << endl;
1712 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1713 "verify that the support software for your encoding (%1$s) is "
1714 "properly installed"), from_ascii(encoding)));
1717 if (!openFileWrite(ofs, fname))
1720 ErrorList & errorList = d->errorLists["Export"];
1722 bool failed_export = false;
1725 // make sure we are ready to export
1726 // this needs to be done before we validate
1727 // FIXME Do we need to do this all the time? I.e., in children
1728 // of a master we are exporting?
1730 updateMacroInstances(OutputUpdate);
1733 writeLaTeXSource(os, original_path, runparams, output);
1735 catch (EncodingException const & e) {
1736 docstring const failed(1, e.failed_char);
1738 oss << "0x" << hex << e.failed_char << dec;
1739 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1740 " (code point %2$s)"),
1741 failed, from_utf8(oss.str()));
1742 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1743 "representable in the chosen encoding.\n"
1744 "Changing the document encoding to utf8 could help."),
1745 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1746 failed_export = true;
1748 catch (iconv_codecvt_facet_exception const & e) {
1749 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1751 failed_export = true;
1753 catch (exception const & e) {
1754 errorList.push_back(ErrorItem(_("conversion failed"),
1756 lyxerr << e.what() << endl;
1757 failed_export = true;
1760 lyxerr << "Caught some really weird exception..." << endl;
1764 d->texrow = move(os.texrow());
1768 failed_export = true;
1769 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1772 if (runparams_in.silent)
1776 return !failed_export;
1780 void Buffer::writeLaTeXSource(otexstream & os,
1781 string const & original_path,
1782 OutputParams const & runparams_in,
1783 OutputWhat output) const
1785 // The child documents, if any, shall be already loaded at this point.
1787 OutputParams runparams = runparams_in;
1789 // XeTeX with TeX fonts is only safe with ASCII encoding,
1790 // Check here, because the "flavor" is not known in BufferParams::encoding()
1791 // (power users can override this safety measure selecting "utf8-plain").
1792 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1793 && (runparams.encoding->name() != "utf8-plain"))
1794 runparams.encoding = encodings.fromLyXName("ascii");
1795 // FIXME: when only the current paragraph is shown, this is ignored
1796 // (or not reached) and characters encodable in the current
1797 // encoding are not converted to ASCII-representation.
1799 // If we are compiling a file standalone, even if this is the
1800 // child of some other buffer, let's cut the link here, so the
1801 // file is really independent and no concurring settings from
1802 // the master (e.g. branch state) interfere (see #8100).
1803 if (!runparams.is_child)
1804 d->ignore_parent = true;
1806 // Classify the unicode characters appearing in math insets
1807 BufferEncodings::initUnicodeMath(*this);
1809 // validate the buffer.
1810 LYXERR(Debug::LATEX, " Validating buffer...");
1811 LaTeXFeatures features(*this, params(), runparams);
1813 // This is only set once per document (in master)
1814 if (!runparams.is_child)
1815 runparams.use_polyglossia = features.usePolyglossia();
1816 LYXERR(Debug::LATEX, " Buffer validation done.");
1818 bool const output_preamble =
1819 output == FullSource || output == OnlyPreamble;
1820 bool const output_body =
1821 output == FullSource || output == OnlyBody;
1823 // The starting paragraph of the coming rows is the
1824 // first paragraph of the document. (Asger)
1825 if (output_preamble && runparams.nice) {
1826 os << "%% LyX " << lyx_version << " created this file. "
1827 "For more info, see http://www.lyx.org/.\n"
1828 "%% Do not edit unless you really know what "
1831 LYXERR(Debug::INFO, "lyx document header finished");
1833 // There are a few differences between nice LaTeX and usual files:
1834 // usual files have \batchmode and special input@path to allow
1835 // inclusion of figures specified by an explicitly relative path
1836 // (i.e., a path starting with './' or '../') with either \input or
1837 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1838 // input@path is set when the actual parameter original_path is set.
1839 // This is done for usual tex-file, but not for nice-latex-file.
1840 // (Matthias 250696)
1841 // Note that input@path is only needed for something the user does
1842 // in the preamble, included .tex files or ERT, files included by
1843 // LyX work without it.
1844 if (output_preamble) {
1845 if (!runparams.nice) {
1846 // code for usual, NOT nice-latex-file
1847 os << "\\batchmode\n"; // changed from \nonstopmode
1849 if (!original_path.empty()) {
1851 // We don't know the encoding of inputpath
1852 docstring const inputpath = from_utf8(original_path);
1853 docstring uncodable_glyphs;
1854 Encoding const * const enc = runparams.encoding;
1856 for (size_t n = 0; n < inputpath.size(); ++n) {
1857 if (!enc->encodable(inputpath[n])) {
1858 docstring const glyph(1, inputpath[n]);
1859 LYXERR0("Uncodable character '"
1861 << "' in input path!");
1862 uncodable_glyphs += glyph;
1867 // warn user if we found uncodable glyphs.
1868 if (!uncodable_glyphs.empty()) {
1869 frontend::Alert::warning(
1870 _("Uncodable character in file path"),
1872 _("The path of your document\n"
1874 "contains glyphs that are unknown "
1875 "in the current document encoding "
1876 "(namely %2$s). This may result in "
1877 "incomplete output, unless "
1878 "TEXINPUTS contains the document "
1879 "directory and you don't use "
1880 "explicitly relative paths (i.e., "
1881 "paths starting with './' or "
1882 "'../') in the preamble or in ERT."
1883 "\n\nIn case of problems, choose "
1884 "an appropriate document encoding\n"
1885 "(such as utf8) or change the "
1887 inputpath, uncodable_glyphs));
1890 support::latex_path(original_path);
1891 if (contains(docdir, '#')) {
1892 docdir = subst(docdir, "#", "\\#");
1893 os << "\\catcode`\\#=11"
1894 "\\def\\#{#}\\catcode`\\#=6\n";
1896 if (contains(docdir, '%')) {
1897 docdir = subst(docdir, "%", "\\%");
1898 os << "\\catcode`\\%=11"
1899 "\\def\\%{%}\\catcode`\\%=14\n";
1901 os << "\\makeatletter\n"
1902 << "\\def\\input@path{{"
1904 << "\\makeatother\n";
1908 // get parent macros (if this buffer has a parent) which will be
1909 // written at the document begin further down.
1910 MacroSet parentMacros;
1911 listParentMacros(parentMacros, features);
1913 // Write the preamble
1914 runparams.use_babel = params().writeLaTeX(os, features,
1915 d->filename.onlyPath());
1917 // Biblatex bibliographies are loaded here
1918 if (params().useBiblatex()) {
1919 vector<docstring> const bibfiles =
1920 prepareBibFilePaths(runparams, getBibfilesCache(), true);
1921 for (docstring const & file: bibfiles)
1922 os << "\\addbibresource{" << file << "}\n";
1925 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1926 && !features.hasOnlyPolyglossiaLanguages()) {
1929 vector<string> bll = features.getBabelExclusiveLanguages();
1930 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1933 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1938 blangs = bll.size() > 1 ?
1939 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1940 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1944 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1949 plangs = pll.size() > 1 ?
1950 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1951 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1952 if (!blangs.empty())
1956 frontend::Alert::warning(
1957 _("Incompatible Languages!"),
1959 _("You cannot use the following languages "
1960 "together in one LaTeX document because "
1961 "they require conflicting language packages:\n"
1966 // Japanese might be required only in some children of a document,
1967 // but once required, we must keep use_japanese true.
1968 runparams.use_japanese |= features.isRequired("japanese");
1971 // Restore the parenthood if needed
1972 if (!runparams.is_child)
1973 d->ignore_parent = false;
1978 // mark the beginning of the body to separate it from InPreamble insets
1979 os.texrow().start(TexRow::beginDocument());
1980 os << "\\begin{document}\n";
1982 // mark the start of a new paragraph by simulating a newline,
1983 // so that os.afterParbreak() returns true at document start
1986 // output the parent macros
1987 MacroSet::iterator it = parentMacros.begin();
1988 MacroSet::iterator end = parentMacros.end();
1989 for (; it != end; ++it) {
1990 int num_lines = (*it)->write(os.os(), true);
1991 os.texrow().newlines(num_lines);
1994 } // output_preamble
1996 LYXERR(Debug::INFO, "preamble finished, now the body.");
1999 latexParagraphs(*this, text(), os, runparams);
2001 // Restore the parenthood if needed
2002 if (!runparams.is_child)
2003 d->ignore_parent = false;
2005 // add this just in case after all the paragraphs
2008 if (output_preamble) {
2009 os << "\\end{document}\n";
2010 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
2012 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
2014 runparams_in.encoding = runparams.encoding;
2016 LYXERR(Debug::INFO, "Finished making LaTeX file.");
2017 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
2021 void Buffer::makeDocBookFile(FileName const & fname,
2022 OutputParams const & runparams,
2023 OutputWhat output) const
2025 LYXERR(Debug::LATEX, "makeDocBookFile...");
2028 if (!openFileWrite(ofs, fname))
2031 // make sure we are ready to export
2032 // this needs to be done before we validate
2034 updateMacroInstances(OutputUpdate);
2036 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
2040 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2044 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
2045 OutputParams const & runparams,
2046 OutputWhat output) const
2048 LaTeXFeatures features(*this, params(), runparams);
2053 DocumentClass const & tclass = params().documentClass();
2054 string const & top_element = tclass.latexname();
2056 bool const output_preamble =
2057 output == FullSource || output == OnlyPreamble;
2058 bool const output_body =
2059 output == FullSource || output == OnlyBody;
2061 if (output_preamble) {
2062 if (runparams.flavor == OutputParams::XML)
2063 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2066 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2069 if (! tclass.class_header().empty())
2070 os << from_ascii(tclass.class_header());
2071 else if (runparams.flavor == OutputParams::XML)
2072 os << "PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" "
2073 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2075 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2077 docstring preamble = params().preamble;
2078 if (runparams.flavor != OutputParams::XML ) {
2079 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2080 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2081 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2082 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2085 string const name = runparams.nice
2086 ? changeExtension(absFileName(), ".sgml") : fname;
2087 preamble += features.getIncludedFiles(name);
2088 preamble += features.getLyXSGMLEntities();
2090 if (!preamble.empty()) {
2091 os << "\n [ " << preamble << " ]";
2097 string top = top_element;
2099 if (runparams.flavor == OutputParams::XML)
2100 top += params().language->code();
2102 top += params().language->code().substr(0, 2);
2105 if (!params().options.empty()) {
2107 top += params().options;
2110 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2111 << " file was created by LyX " << lyx_version
2112 << "\n See http://www.lyx.org/ for more information -->\n";
2114 params().documentClass().counters().reset();
2116 sgml::openTag(os, top);
2118 docbookParagraphs(text(), *this, os, runparams);
2119 sgml::closeTag(os, top_element);
2124 void Buffer::makeLyXHTMLFile(FileName const & fname,
2125 OutputParams const & runparams) const
2127 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2130 if (!openFileWrite(ofs, fname))
2133 // make sure we are ready to export
2134 // this has to be done before we validate
2135 updateBuffer(UpdateMaster, OutputUpdate);
2136 updateMacroInstances(OutputUpdate);
2138 writeLyXHTMLSource(ofs, runparams, FullSource);
2142 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2146 void Buffer::writeLyXHTMLSource(odocstream & os,
2147 OutputParams const & runparams,
2148 OutputWhat output) const
2150 LaTeXFeatures features(*this, params(), runparams);
2152 d->bibinfo_.makeCitationLabels(*this);
2154 bool const output_preamble =
2155 output == FullSource || output == OnlyPreamble;
2156 bool const output_body =
2157 output == FullSource || output == OnlyBody || output == IncludedFile;
2159 if (output_preamble) {
2160 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2161 << "<!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"
2162 // FIXME Language should be set properly.
2163 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2165 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2166 // FIXME Presumably need to set this right
2167 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2169 docstring const & doctitle = features.htmlTitle();
2171 << (doctitle.empty() ?
2172 from_ascii("LyX Document") :
2173 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2176 docstring styles = features.getTClassHTMLPreamble();
2177 if (!styles.empty())
2178 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2180 styles = features.getPreambleSnippets().str;
2181 if (!styles.empty())
2182 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2184 // we will collect CSS information in a stream, and then output it
2185 // either here, as part of the header, or else in a separate file.
2186 odocstringstream css;
2187 styles = features.getCSSSnippets();
2188 if (!styles.empty())
2189 css << "/* LyX Provided Styles */\n" << styles << '\n';
2191 styles = features.getTClassHTMLStyles();
2192 if (!styles.empty())
2193 css << "/* Layout-provided Styles */\n" << styles << '\n';
2195 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2196 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2197 if (needfg || needbg) {
2198 css << "\nbody {\n";
2201 << from_ascii(X11hexname(params().fontcolor))
2204 css << " background-color: "
2205 << from_ascii(X11hexname(params().backgroundcolor))
2210 docstring const dstyles = css.str();
2211 if (!dstyles.empty()) {
2212 bool written = false;
2213 if (params().html_css_as_file) {
2214 // open a file for CSS info
2216 string const fcssname = addName(temppath(), "docstyle.css");
2217 FileName const fcssfile = FileName(fcssname);
2218 if (openFileWrite(ocss, fcssfile)) {
2222 // write link to header
2223 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2225 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2228 // we are here if the CSS is supposed to be written to the header
2229 // or if we failed to write it to an external file.
2231 os << "<style type='text/css'>\n"
2240 bool const output_body_tag = (output != IncludedFile);
2241 if (output_body_tag)
2242 os << "<body dir=\"auto\">\n";
2244 if (output != IncludedFile)
2245 // if we're an included file, the counters are in the master.
2246 params().documentClass().counters().reset();
2247 xhtmlParagraphs(text(), *this, xs, runparams);
2248 if (output_body_tag)
2252 if (output_preamble)
2257 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2258 // Other flags: -wall -v0 -x
2259 int Buffer::runChktex()
2263 // get LaTeX-Filename
2264 FileName const path(temppath());
2265 string const name = addName(path.absFileName(), latexName());
2266 string const org_path = filePath();
2268 PathChanger p(path); // path to LaTeX file
2269 message(_("Running chktex..."));
2271 // Generate the LaTeX file if neccessary
2272 OutputParams runparams(¶ms().encoding());
2273 runparams.flavor = OutputParams::LATEX;
2274 runparams.nice = false;
2275 runparams.linelen = lyxrc.plaintext_linelen;
2276 makeLaTeXFile(FileName(name), org_path, runparams);
2279 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2280 int const res = chktex.run(terr); // run chktex
2283 Alert::error(_("chktex failure"),
2284 _("Could not run chktex successfully."));
2286 ErrorList & errlist = d->errorLists["ChkTeX"];
2288 bufferErrors(terr, errlist);
2293 if (runparams.silent)
2294 d->errorLists["ChkTeX"].clear();
2302 void Buffer::validate(LaTeXFeatures & features) const
2304 // Validate the buffer params, but not for included
2305 // files, since they also use the parent buffer's
2307 if (!features.runparams().is_child)
2308 params().validate(features);
2310 for (Paragraph const & p : paragraphs())
2311 p.validate(features);
2313 if (lyxerr.debugging(Debug::LATEX)) {
2314 features.showStruct();
2319 void Buffer::getLabelList(vector<docstring> & list) const
2321 // If this is a child document, use the master's list instead.
2323 masterBuffer()->getLabelList(list);
2328 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2329 Toc::const_iterator toc_it = toc->begin();
2330 Toc::const_iterator end = toc->end();
2331 for (; toc_it != end; ++toc_it) {
2332 if (toc_it->depth() == 0)
2333 list.push_back(toc_it->str());
2338 void Buffer::updateBibfilesCache(UpdateScope scope) const
2340 // FIXME This is probably unnecssary, given where we call this.
2341 // If this is a child document, use the parent's cache instead.
2342 if (parent() && scope != UpdateChildOnly) {
2343 masterBuffer()->updateBibfilesCache();
2347 d->bibfiles_cache_.clear();
2348 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2349 if (it->lyxCode() == BIBTEX_CODE) {
2350 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2351 support::FileNamePairList const bibfiles = inset.getBibFiles();
2352 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2355 } else if (it->lyxCode() == INCLUDE_CODE) {
2356 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2357 Buffer const * const incbuf = inset.getChildBuffer();
2360 support::FileNamePairList const & bibfiles =
2361 incbuf->getBibfilesCache(UpdateChildOnly);
2362 if (!bibfiles.empty()) {
2363 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2369 d->bibfile_cache_valid_ = true;
2370 d->bibinfo_cache_valid_ = false;
2371 d->cite_labels_valid_ = false;
2375 void Buffer::invalidateBibinfoCache() const
2377 d->bibinfo_cache_valid_ = false;
2378 d->cite_labels_valid_ = false;
2379 // also invalidate the cache for the parent buffer
2380 Buffer const * const pbuf = d->parent();
2382 pbuf->invalidateBibinfoCache();
2386 void Buffer::invalidateBibfileCache() const
2388 d->bibfile_cache_valid_ = false;
2389 d->bibinfo_cache_valid_ = false;
2390 d->cite_labels_valid_ = false;
2391 // also invalidate the cache for the parent buffer
2392 Buffer const * const pbuf = d->parent();
2394 pbuf->invalidateBibfileCache();
2398 support::FileNamePairList const & Buffer::getBibfilesCache(UpdateScope scope) const
2400 // FIXME This is probably unnecessary, given where we call this.
2401 // If this is a child document, use the master's cache instead.
2402 Buffer const * const pbuf = masterBuffer();
2403 if (pbuf != this && scope != UpdateChildOnly)
2404 return pbuf->getBibfilesCache();
2406 if (!d->bibfile_cache_valid_)
2407 this->updateBibfilesCache(scope);
2409 return d->bibfiles_cache_;
2413 BiblioInfo const & Buffer::masterBibInfo() const
2415 Buffer const * const tmp = masterBuffer();
2417 return tmp->masterBibInfo();
2422 void Buffer::checkIfBibInfoCacheIsValid() const
2424 // use the master's cache
2425 Buffer const * const tmp = masterBuffer();
2427 tmp->checkIfBibInfoCacheIsValid();
2431 // compare the cached timestamps with the actual ones.
2432 FileNamePairList const & bibfiles_cache = getBibfilesCache();
2433 FileNamePairList::const_iterator ei = bibfiles_cache.begin();
2434 FileNamePairList::const_iterator en = bibfiles_cache.end();
2435 for (; ei != en; ++ ei) {
2436 FileName const fn = ei->second;
2437 time_t lastw = fn.lastModified();
2438 time_t prevw = d->bibfile_status_[fn];
2439 if (lastw != prevw) {
2440 d->bibinfo_cache_valid_ = false;
2441 d->cite_labels_valid_ = false;
2442 d->bibfile_status_[fn] = lastw;
2448 void Buffer::reloadBibInfoCache() const
2450 // use the master's cache
2451 Buffer const * const tmp = masterBuffer();
2453 tmp->reloadBibInfoCache();
2457 checkIfBibInfoCacheIsValid();
2458 if (d->bibinfo_cache_valid_)
2461 d->bibinfo_.clear();
2463 d->bibinfo_cache_valid_ = true;
2467 void Buffer::collectBibKeys() const
2469 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2470 it->collectBibKeys(it);
2474 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2476 Buffer const * tmp = masterBuffer();
2477 BiblioInfo & masterbi = (tmp == this) ?
2478 d->bibinfo_ : tmp->d->bibinfo_;
2479 masterbi.mergeBiblioInfo(bi);
2483 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2485 Buffer const * tmp = masterBuffer();
2486 BiblioInfo & masterbi = (tmp == this) ?
2487 d->bibinfo_ : tmp->d->bibinfo_;
2492 void Buffer::makeCitationLabels() const
2494 Buffer const * const master = masterBuffer();
2495 return d->bibinfo_.makeCitationLabels(*master);
2499 bool Buffer::citeLabelsValid() const
2501 return masterBuffer()->d->cite_labels_valid_;
2505 void Buffer::removeBiblioTempFiles() const
2507 // We remove files that contain LaTeX commands specific to the
2508 // particular bibliographic style being used, in order to avoid
2509 // LaTeX errors when we switch style.
2510 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2511 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2512 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2513 aux_file.removeFile();
2514 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2515 bbl_file.removeFile();
2516 // Also for the parent buffer
2517 Buffer const * const pbuf = parent();
2519 pbuf->removeBiblioTempFiles();
2523 bool Buffer::isDepClean(string const & name) const
2525 DepClean::const_iterator const it = d->dep_clean.find(name);
2526 if (it == d->dep_clean.end())
2532 void Buffer::markDepClean(string const & name)
2534 d->dep_clean[name] = true;
2538 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2541 // FIXME? if there is an Buffer LFUN that can be dispatched even
2542 // if internal, put a switch '(cmd.action)' here.
2548 switch (cmd.action()) {
2550 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2551 flag.setOnOff(hasReadonlyFlag());
2554 // FIXME: There is need for a command-line import.
2555 //case LFUN_BUFFER_IMPORT:
2557 case LFUN_BUFFER_AUTO_SAVE:
2560 case LFUN_BUFFER_EXPORT_CUSTOM:
2561 // FIXME: Nothing to check here?
2564 case LFUN_BUFFER_EXPORT: {
2565 docstring const arg = cmd.argument();
2566 if (arg == "custom") {
2570 string format = (arg.empty() || arg == "default") ?
2571 params().getDefaultOutputFormat() : to_utf8(arg);
2572 size_t pos = format.find(' ');
2573 if (pos != string::npos)
2574 format = format.substr(0, pos);
2575 enable = params().isExportable(format, false);
2577 flag.message(bformat(
2578 _("Don't know how to export to format: %1$s"), arg));
2582 case LFUN_BUFFER_CHKTEX:
2583 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2586 case LFUN_BUILD_PROGRAM:
2587 enable = params().isExportable("program", false);
2590 case LFUN_BRANCH_ACTIVATE:
2591 case LFUN_BRANCH_DEACTIVATE:
2592 case LFUN_BRANCH_MASTER_ACTIVATE:
2593 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2594 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2595 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2596 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2597 : params().branchlist();
2598 docstring const branchName = cmd.argument();
2599 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2603 case LFUN_BRANCH_ADD:
2604 case LFUN_BRANCHES_RENAME:
2605 // if no Buffer is present, then of course we won't be called!
2608 case LFUN_BUFFER_LANGUAGE:
2609 enable = !isReadonly();
2612 case LFUN_BUFFER_VIEW_CACHE:
2613 (d->preview_file_).refresh();
2614 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2617 case LFUN_CHANGES_TRACK:
2618 flag.setEnabled(true);
2619 flag.setOnOff(params().track_changes);
2622 case LFUN_CHANGES_OUTPUT:
2623 flag.setEnabled(true);
2624 flag.setOnOff(params().output_changes);
2627 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2628 flag.setOnOff(params().compressed);
2632 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2633 flag.setOnOff(params().output_sync);
2640 flag.setEnabled(enable);
2645 void Buffer::dispatch(string const & command, DispatchResult & result)
2647 return dispatch(lyxaction.lookupFunc(command), result);
2651 // NOTE We can end up here even if we have no GUI, because we are called
2652 // by LyX::exec to handled command-line requests. So we may need to check
2653 // whether we have a GUI or not. The boolean use_gui holds this information.
2654 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2657 // FIXME? if there is an Buffer LFUN that can be dispatched even
2658 // if internal, put a switch '(cmd.action())' here.
2659 dr.dispatched(false);
2662 string const argument = to_utf8(func.argument());
2663 // We'll set this back to false if need be.
2664 bool dispatched = true;
2665 undo().beginUndoGroup();
2667 switch (func.action()) {
2668 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2669 if (lyxvc().inUse()) {
2670 string log = lyxvc().toggleReadOnly();
2675 setReadonly(!hasReadonlyFlag());
2678 case LFUN_BUFFER_EXPORT: {
2679 string const format = (argument.empty() || argument == "default") ?
2680 params().getDefaultOutputFormat() : argument;
2681 ExportStatus const status = doExport(format, false);
2682 dr.setError(status != ExportSuccess);
2683 if (status != ExportSuccess)
2684 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2685 from_utf8(format)));
2689 case LFUN_BUILD_PROGRAM: {
2690 ExportStatus const status = doExport("program", true);
2691 dr.setError(status != ExportSuccess);
2692 if (status != ExportSuccess)
2693 dr.setMessage(_("Error generating literate programming code."));
2697 case LFUN_BUFFER_CHKTEX:
2701 case LFUN_BUFFER_EXPORT_CUSTOM: {
2703 string command = split(argument, format_name, ' ');
2704 Format const * format = theFormats().getFormat(format_name);
2706 lyxerr << "Format \"" << format_name
2707 << "\" not recognized!"
2712 // The name of the file created by the conversion process
2715 // Output to filename
2716 if (format->name() == "lyx") {
2717 string const latexname = latexName(false);
2718 filename = changeExtension(latexname,
2719 format->extension());
2720 filename = addName(temppath(), filename);
2722 if (!writeFile(FileName(filename)))
2726 doExport(format_name, true, filename);
2729 // Substitute $$FName for filename
2730 if (!contains(command, "$$FName"))
2731 command = "( " + command + " ) < $$FName";
2732 command = subst(command, "$$FName", filename);
2734 // Execute the command in the background
2736 call.startscript(Systemcall::DontWait, command,
2737 filePath(), layoutPos());
2741 // FIXME: There is need for a command-line import.
2743 case LFUN_BUFFER_IMPORT:
2748 case LFUN_BUFFER_AUTO_SAVE:
2750 resetAutosaveTimers();
2753 case LFUN_BRANCH_ACTIVATE:
2754 case LFUN_BRANCH_DEACTIVATE:
2755 case LFUN_BRANCH_MASTER_ACTIVATE:
2756 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2757 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2758 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2759 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2762 docstring const branch_name = func.argument();
2763 // the case without a branch name is handled elsewhere
2764 if (branch_name.empty()) {
2768 Branch * branch = buf->params().branchlist().find(branch_name);
2770 LYXERR0("Branch " << branch_name << " does not exist.");
2772 docstring const msg =
2773 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2777 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2778 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2779 if (branch->isSelected() != activate) {
2780 buf->undo().recordUndoBufferParams(CursorData());
2781 branch->setSelected(activate);
2783 dr.screenUpdate(Update::Force);
2784 dr.forceBufferUpdate();
2789 case LFUN_BRANCH_ADD: {
2790 docstring branch_name = func.argument();
2791 if (branch_name.empty()) {
2795 BranchList & branch_list = params().branchlist();
2796 vector<docstring> const branches =
2797 getVectorFromString(branch_name, branch_list.separator());
2799 for (vector<docstring>::const_iterator it = branches.begin();
2800 it != branches.end(); ++it) {
2802 Branch * branch = branch_list.find(branch_name);
2804 LYXERR0("Branch " << branch_name << " already exists.");
2808 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2810 undo().recordUndoBufferParams(CursorData());
2811 branch_list.add(branch_name);
2812 branch = branch_list.find(branch_name);
2813 string const x11hexname = X11hexname(branch->color());
2814 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2815 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2817 dr.screenUpdate(Update::Force);
2825 case LFUN_BRANCHES_RENAME: {
2826 if (func.argument().empty())
2829 docstring const oldname = from_utf8(func.getArg(0));
2830 docstring const newname = from_utf8(func.getArg(1));
2831 InsetIterator it = inset_iterator_begin(inset());
2832 InsetIterator const end = inset_iterator_end(inset());
2833 bool success = false;
2834 for (; it != end; ++it) {
2835 if (it->lyxCode() == BRANCH_CODE) {
2836 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2837 if (ins.branch() == oldname) {
2838 undo().recordUndo(CursorData(it));
2839 ins.rename(newname);
2844 if (it->lyxCode() == INCLUDE_CODE) {
2845 // get buffer of external file
2846 InsetInclude const & ins =
2847 static_cast<InsetInclude const &>(*it);
2848 Buffer * child = ins.getChildBuffer();
2851 child->dispatch(func, dr);
2856 dr.screenUpdate(Update::Force);
2857 dr.forceBufferUpdate();
2862 case LFUN_BUFFER_VIEW_CACHE:
2863 if (!theFormats().view(*this, d->preview_file_,
2864 d->preview_format_))
2865 dr.setMessage(_("Error viewing the output file."));
2868 case LFUN_CHANGES_TRACK:
2869 if (params().save_transient_properties)
2870 undo().recordUndoBufferParams(CursorData());
2871 params().track_changes = !params().track_changes;
2872 if (!params().track_changes)
2873 dr.forceChangesUpdate();
2876 case LFUN_CHANGES_OUTPUT:
2877 if (params().save_transient_properties)
2878 undo().recordUndoBufferParams(CursorData());
2879 params().output_changes = !params().output_changes;
2880 if (params().output_changes) {
2881 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2882 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2883 LaTeXFeatures::isAvailable("xcolor");
2885 if (!dvipost && !xcolorulem) {
2886 Alert::warning(_("Changes not shown in LaTeX output"),
2887 _("Changes will not be highlighted in LaTeX output, "
2888 "because neither dvipost nor xcolor/ulem are installed.\n"
2889 "Please install these packages or redefine "
2890 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2891 } else if (!xcolorulem) {
2892 Alert::warning(_("Changes not shown in LaTeX output"),
2893 _("Changes will not be highlighted in LaTeX output "
2894 "when using pdflatex, because xcolor and ulem are not installed.\n"
2895 "Please install both packages or redefine "
2896 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2901 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2902 // turn compression on/off
2903 undo().recordUndoBufferParams(CursorData());
2904 params().compressed = !params().compressed;
2907 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2908 undo().recordUndoBufferParams(CursorData());
2909 params().output_sync = !params().output_sync;
2916 dr.dispatched(dispatched);
2917 undo().endUndoGroup();
2921 void Buffer::changeLanguage(Language const * from, Language const * to)
2923 LASSERT(from, return);
2924 LASSERT(to, return);
2926 for_each(par_iterator_begin(),
2928 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2932 bool Buffer::isMultiLingual() const
2934 ParConstIterator end = par_iterator_end();
2935 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2936 if (it->isMultiLingual(params()))
2943 std::set<Language const *> Buffer::getLanguages() const
2945 std::set<Language const *> languages;
2946 getLanguages(languages);
2951 void Buffer::getLanguages(std::set<Language const *> & languages) const
2953 ParConstIterator end = par_iterator_end();
2954 // add the buffer language, even if it's not actively used
2955 languages.insert(language());
2956 // iterate over the paragraphs
2957 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2958 it->getLanguages(languages);
2960 ListOfBuffers clist = getDescendents();
2961 ListOfBuffers::const_iterator cit = clist.begin();
2962 ListOfBuffers::const_iterator const cen = clist.end();
2963 for (; cit != cen; ++cit)
2964 (*cit)->getLanguages(languages);
2968 DocIterator Buffer::getParFromID(int const id) const
2970 Buffer * buf = const_cast<Buffer *>(this);
2972 // This means non-existent
2973 return doc_iterator_end(buf);
2975 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2976 if (it.paragraph().id() == id)
2979 return doc_iterator_end(buf);
2983 bool Buffer::hasParWithID(int const id) const
2985 return !getParFromID(id).atEnd();
2989 ParIterator Buffer::par_iterator_begin()
2991 return ParIterator(doc_iterator_begin(this));
2995 ParIterator Buffer::par_iterator_end()
2997 return ParIterator(doc_iterator_end(this));
3001 ParConstIterator Buffer::par_iterator_begin() const
3003 return ParConstIterator(doc_iterator_begin(this));
3007 ParConstIterator Buffer::par_iterator_end() const
3009 return ParConstIterator(doc_iterator_end(this));
3013 Language const * Buffer::language() const
3015 return params().language;
3019 docstring const Buffer::B_(string const & l10n) const
3021 return params().B_(l10n);
3025 bool Buffer::isClean() const
3027 return d->lyx_clean;
3031 bool Buffer::isChecksumModified() const
3033 LASSERT(d->filename.exists(), return false);
3034 return d->checksum_ != d->filename.checksum();
3038 void Buffer::saveCheckSum() const
3040 FileName const & file = d->filename;
3042 d->checksum_ = file.exists() ? file.checksum()
3043 : 0; // in the case of save to a new file.
3047 void Buffer::markClean() const
3049 if (!d->lyx_clean) {
3050 d->lyx_clean = true;
3053 // if the .lyx file has been saved, we don't need an
3055 d->bak_clean = true;
3056 d->undo_.markDirty();
3057 clearExternalModification();
3061 void Buffer::setUnnamed(bool flag)
3067 bool Buffer::isUnnamed() const
3074 /// Don't check unnamed, here: isInternal() is used in
3075 /// newBuffer(), where the unnamed flag has not been set by anyone
3076 /// yet. Also, for an internal buffer, there should be no need for
3077 /// retrieving fileName() nor for checking if it is unnamed or not.
3078 bool Buffer::isInternal() const
3080 return d->internal_buffer;
3084 void Buffer::setInternal(bool flag)
3086 d->internal_buffer = flag;
3090 void Buffer::markDirty()
3093 d->lyx_clean = false;
3096 d->bak_clean = false;
3098 DepClean::iterator it = d->dep_clean.begin();
3099 DepClean::const_iterator const end = d->dep_clean.end();
3101 for (; it != end; ++it)
3106 FileName Buffer::fileName() const
3112 string Buffer::absFileName() const
3114 return d->filename.absFileName();
3118 string Buffer::filePath() const
3120 string const abs = d->filename.onlyPath().absFileName();
3123 int last = abs.length() - 1;
3125 return abs[last] == '/' ? abs : abs + '/';
3129 DocFileName Buffer::getReferencedFileName(string const & fn) const
3132 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3133 result.set(fn, filePath());
3135 // filePath() ends with a path separator
3136 FileName const test(filePath() + fn);
3138 result.set(fn, filePath());
3140 result.set(fn, params().origin);
3147 string const Buffer::prepareFileNameForLaTeX(string const & name,
3148 string const & ext, bool nice) const
3150 string const fname = makeAbsPath(name, filePath()).absFileName();
3151 if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3157 return to_utf8(makeRelPath(from_utf8(fname),
3158 from_utf8(masterBuffer()->filePath())));
3162 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3163 FileNamePairList const bibfilelist,
3164 bool const add_extension) const
3166 // If we are processing the LaTeX file in a temp directory then
3167 // copy the .bib databases to this temp directory, mangling their
3168 // names in the process. Store this mangled name in the list of
3170 // (We need to do all this because BibTeX *really*, *really*
3171 // can't handle "files with spaces" and Windows users tend to
3172 // use such filenames.)
3173 // Otherwise, store the (maybe absolute) path to the original,
3174 // unmangled database name.
3176 vector<docstring> res;
3178 // determine the export format
3179 string const tex_format = flavor2format(runparams.flavor);
3181 // check for spaces in paths
3182 bool found_space = false;
3184 FileNamePairList::const_iterator it = bibfilelist.begin();
3185 FileNamePairList::const_iterator en = bibfilelist.end();
3186 for (; it != en; ++it) {
3187 string utf8input = to_utf8(it->first);
3189 prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3190 FileName const try_in_file =
3191 makeAbsPath(database + ".bib", filePath());
3192 bool const not_from_texmf = try_in_file.isReadableFile();
3194 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3196 // mangledFileName() needs the extension
3197 DocFileName const in_file = DocFileName(try_in_file);
3198 database = removeExtension(in_file.mangledFileName());
3199 FileName const out_file = makeAbsPath(database + ".bib",
3200 masterBuffer()->temppath());
3201 bool const success = in_file.copyTo(out_file);
3203 LYXERR0("Failed to copy '" << in_file
3204 << "' to '" << out_file << "'");
3206 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3207 runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3208 if (!isValidLaTeXFileName(database)) {
3209 frontend::Alert::warning(_("Invalid filename"),
3210 _("The following filename will cause troubles "
3211 "when running the exported file through LaTeX: ") +
3212 from_utf8(database));
3214 if (!isValidDVIFileName(database)) {
3215 frontend::Alert::warning(_("Problematic filename for DVI"),
3216 _("The following filename can cause troubles "
3217 "when running the exported file through LaTeX "
3218 "and opening the resulting DVI: ") +
3219 from_utf8(database), true);
3227 docstring const path = from_utf8(latex_path(database));
3229 if (contains(path, ' '))
3232 if (find(res.begin(), res.end(), path) == res.end())
3233 res.push_back(path);
3236 // Check if there are spaces in the path and warn BibTeX users, if so.
3237 // (biber can cope with such paths)
3238 if (!prefixIs(runparams.bibtex_command, "biber")) {
3239 // Post this warning only once.
3240 static bool warned_about_spaces = false;
3241 if (!warned_about_spaces &&
3242 runparams.nice && found_space) {
3243 warned_about_spaces = true;
3244 Alert::warning(_("Export Warning!"),
3245 _("There are spaces in the paths to your BibTeX databases.\n"
3246 "BibTeX will be unable to find them."));
3255 string Buffer::layoutPos() const
3257 return d->layout_position;
3261 void Buffer::setLayoutPos(string const & path)
3264 d->layout_position.clear();
3268 LATTEST(FileName::isAbsolute(path));
3270 d->layout_position =
3271 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3273 if (d->layout_position.empty())
3274 d->layout_position = ".";
3278 bool Buffer::hasReadonlyFlag() const
3280 return d->read_only;
3284 bool Buffer::isReadonly() const
3286 return hasReadonlyFlag() || notifiesExternalModification();
3290 void Buffer::setParent(Buffer const * buffer)
3292 // Avoids recursive include.
3293 d->setParent(buffer == this ? 0 : buffer);
3298 Buffer const * Buffer::parent() const
3304 ListOfBuffers Buffer::allRelatives() const
3306 ListOfBuffers lb = masterBuffer()->getDescendents();
3307 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3312 Buffer const * Buffer::masterBuffer() const
3314 // FIXME Should be make sure we are not in some kind
3315 // of recursive include? A -> B -> A will crash this.
3316 Buffer const * const pbuf = d->parent();
3320 return pbuf->masterBuffer();
3324 bool Buffer::isChild(Buffer * child) const
3326 return d->children_positions.find(child) != d->children_positions.end();
3330 DocIterator Buffer::firstChildPosition(Buffer const * child)
3332 Impl::BufferPositionMap::iterator it;
3333 it = d->children_positions.find(child);
3334 if (it == d->children_positions.end())
3335 return DocIterator(this);
3340 bool Buffer::hasChildren() const
3342 return !d->children_positions.empty();
3346 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3348 // loop over children
3349 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3350 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3351 for (; it != end; ++it) {
3352 Buffer * child = const_cast<Buffer *>(it->first);
3354 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3355 if (bit != clist.end())
3357 clist.push_back(child);
3359 // there might be grandchildren
3360 child->collectChildren(clist, true);
3365 ListOfBuffers Buffer::getChildren() const
3368 collectChildren(v, false);
3369 // Make sure we have not included ourselves.
3370 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3371 if (bit != v.end()) {
3372 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3379 ListOfBuffers Buffer::getDescendents() const
3382 collectChildren(v, true);
3383 // Make sure we have not included ourselves.
3384 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3385 if (bit != v.end()) {
3386 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3393 template<typename M>
3394 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3399 typename M::const_iterator it = m.lower_bound(x);
3400 if (it == m.begin())
3408 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3409 DocIterator const & pos) const
3411 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3413 // if paragraphs have no macro context set, pos will be empty
3417 // we haven't found anything yet
3418 DocIterator bestPos = owner_->par_iterator_begin();
3419 MacroData const * bestData = 0;
3421 // find macro definitions for name
3422 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3423 if (nameIt != macros.end()) {
3424 // find last definition in front of pos or at pos itself
3425 PositionScopeMacroMap::const_iterator it
3426 = greatest_below(nameIt->second, pos);
3427 if (it != nameIt->second.end()) {
3429 // scope ends behind pos?
3430 if (pos < it->second.scope) {
3431 // Looks good, remember this. If there
3432 // is no external macro behind this,
3433 // we found the right one already.
3434 bestPos = it->first;
3435 bestData = &it->second.macro;
3439 // try previous macro if there is one
3440 if (it == nameIt->second.begin())
3447 // find macros in included files
3448 PositionScopeBufferMap::const_iterator it
3449 = greatest_below(position_to_children, pos);
3450 if (it == position_to_children.end())
3451 // no children before
3455 // do we know something better (i.e. later) already?
3456 if (it->first < bestPos )
3459 // scope ends behind pos?
3460 if (pos < it->second.scope
3461 && (cloned_buffer_ ||
3462 theBufferList().isLoaded(it->second.buffer))) {
3463 // look for macro in external file
3465 MacroData const * data
3466 = it->second.buffer->getMacro(name, false);
3469 bestPos = it->first;
3475 // try previous file if there is one
3476 if (it == position_to_children.begin())
3481 // return the best macro we have found
3486 MacroData const * Buffer::getMacro(docstring const & name,
3487 DocIterator const & pos, bool global) const
3492 // query buffer macros
3493 MacroData const * data = d->getBufferMacro(name, pos);
3497 // If there is a master buffer, query that
3498 Buffer const * const pbuf = d->parent();
3500 d->macro_lock = true;
3501 MacroData const * macro = pbuf->getMacro(
3502 name, *this, false);
3503 d->macro_lock = false;
3509 data = MacroTable::globalMacros().get(name);
3518 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3520 // set scope end behind the last paragraph
3521 DocIterator scope = par_iterator_begin();
3522 scope.pit() = scope.lastpit() + 1;
3524 return getMacro(name, scope, global);
3528 MacroData const * Buffer::getMacro(docstring const & name,
3529 Buffer const & child, bool global) const
3531 // look where the child buffer is included first
3532 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3533 if (it == d->children_positions.end())
3536 // check for macros at the inclusion position
3537 return getMacro(name, it->second, global);
3541 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3543 pit_type const lastpit = it.lastpit();
3545 // look for macros in each paragraph
3546 while (it.pit() <= lastpit) {
3547 Paragraph & par = it.paragraph();
3549 // iterate over the insets of the current paragraph
3550 InsetList const & insets = par.insetList();
3551 InsetList::const_iterator iit = insets.begin();
3552 InsetList::const_iterator end = insets.end();
3553 for (; iit != end; ++iit) {
3554 it.pos() = iit->pos;
3556 // is it a nested text inset?
3557 if (iit->inset->asInsetText()) {
3558 // Inset needs its own scope?
3559 InsetText const * itext = iit->inset->asInsetText();
3560 bool newScope = itext->isMacroScope();
3562 // scope which ends just behind the inset
3563 DocIterator insetScope = it;
3566 // collect macros in inset
3567 it.push_back(CursorSlice(*iit->inset));
3568 updateMacros(it, newScope ? insetScope : scope);
3573 if (iit->inset->asInsetTabular()) {
3574 CursorSlice slice(*iit->inset);
3575 size_t const numcells = slice.nargs();
3576 for (; slice.idx() < numcells; slice.forwardIdx()) {
3577 it.push_back(slice);
3578 updateMacros(it, scope);
3584 // is it an external file?
3585 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3586 // get buffer of external file
3587 InsetInclude const & inset =
3588 static_cast<InsetInclude const &>(*iit->inset);
3590 Buffer * child = inset.getChildBuffer();
3595 // register its position, but only when it is
3596 // included first in the buffer
3597 if (children_positions.find(child) ==
3598 children_positions.end())
3599 children_positions[child] = it;
3601 // register child with its scope
3602 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3606 InsetMath * im = iit->inset->asInsetMath();
3607 if (doing_export && im) {
3608 InsetMathHull * hull = im->asHullInset();
3610 hull->recordLocation(it);
3613 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3617 MathMacroTemplate & macroTemplate =
3618 *iit->inset->asInsetMath()->asMacroTemplate();
3619 MacroContext mc(owner_, it);
3620 macroTemplate.updateToContext(mc);
3623 bool valid = macroTemplate.validMacro();
3624 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3625 // then the BufferView's cursor will be invalid in
3626 // some cases which leads to crashes.
3631 // FIXME (Abdel), I don't understand why we pass 'it' here
3632 // instead of 'macroTemplate' defined above... is this correct?
3633 macros[macroTemplate.name()][it] =
3634 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3644 void Buffer::updateMacros() const
3649 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3651 // start with empty table
3653 d->children_positions.clear();
3654 d->position_to_children.clear();
3656 // Iterate over buffer, starting with first paragraph
3657 // The scope must be bigger than any lookup DocIterator
3658 // later. For the global lookup, lastpit+1 is used, hence
3659 // we use lastpit+2 here.
3660 DocIterator it = par_iterator_begin();
3661 DocIterator outerScope = it;
3662 outerScope.pit() = outerScope.lastpit() + 2;
3663 d->updateMacros(it, outerScope);
3667 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3669 InsetIterator it = inset_iterator_begin(inset());
3670 InsetIterator const end = inset_iterator_end(inset());
3671 for (; it != end; ++it) {
3672 if (it->lyxCode() == BRANCH_CODE) {
3673 InsetBranch & br = static_cast<InsetBranch &>(*it);
3674 docstring const name = br.branch();
3675 if (!from_master && !params().branchlist().find(name))
3676 result.push_back(name);
3677 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3678 result.push_back(name);
3681 if (it->lyxCode() == INCLUDE_CODE) {
3682 // get buffer of external file
3683 InsetInclude const & ins =
3684 static_cast<InsetInclude const &>(*it);
3685 Buffer * child = ins.getChildBuffer();
3688 child->getUsedBranches(result, true);
3691 // remove duplicates
3696 void Buffer::updateMacroInstances(UpdateType utype) const
3698 LYXERR(Debug::MACROS, "updateMacroInstances for "
3699 << d->filename.onlyFileName());
3700 DocIterator it = doc_iterator_begin(this);
3702 DocIterator const end = doc_iterator_end(this);
3703 for (; it != end; it.forwardInset()) {
3704 // look for MathData cells in InsetMathNest insets
3705 InsetMath * minset = it.nextInset()->asInsetMath();
3709 // update macro in all cells of the InsetMathNest
3710 DocIterator::idx_type n = minset->nargs();
3711 MacroContext mc = MacroContext(this, it);
3712 for (DocIterator::idx_type i = 0; i < n; ++i) {
3713 MathData & data = minset->cell(i);
3714 data.updateMacros(0, mc, utype, 0);
3720 void Buffer::listMacroNames(MacroNameSet & macros) const
3725 d->macro_lock = true;
3727 // loop over macro names
3728 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3729 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3730 for (; nameIt != nameEnd; ++nameIt)
3731 macros.insert(nameIt->first);
3733 // loop over children
3734 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3735 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3736 for (; it != end; ++it)
3737 it->first->listMacroNames(macros);
3740 Buffer const * const pbuf = d->parent();
3742 pbuf->listMacroNames(macros);
3744 d->macro_lock = false;
3748 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3750 Buffer const * const pbuf = d->parent();
3755 pbuf->listMacroNames(names);
3758 MacroNameSet::iterator it = names.begin();
3759 MacroNameSet::iterator end = names.end();
3760 for (; it != end; ++it) {
3762 MacroData const * data =
3763 pbuf->getMacro(*it, *this, false);
3765 macros.insert(data);
3767 // we cannot access the original MathMacroTemplate anymore
3768 // here to calls validate method. So we do its work here manually.
3769 // FIXME: somehow make the template accessible here.
3770 if (data->optionals() > 0)
3771 features.require("xargs");
3777 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3780 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3782 RefCache::iterator it = d->ref_cache_.find(label);
3783 if (it != d->ref_cache_.end())
3784 return it->second.second;
3786 static InsetLabel const * dummy_il = 0;
3787 static References const dummy_refs = References();
3788 it = d->ref_cache_.insert(
3789 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3790 return it->second.second;
3794 Buffer::References const & Buffer::references(docstring const & label) const
3796 return const_cast<Buffer *>(this)->getReferenceCache(label);
3800 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3802 References & refs = getReferenceCache(label);
3803 refs.push_back(make_pair(inset, it));
3807 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3809 masterBuffer()->d->ref_cache_[label].first = il;
3813 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3815 return masterBuffer()->d->ref_cache_[label].first;
3819 void Buffer::clearReferenceCache() const
3822 d->ref_cache_.clear();
3826 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3828 //FIXME: This does not work for child documents yet.
3829 reloadBibInfoCache();
3831 // Check if the label 'from' appears more than once
3832 BiblioInfo const & keys = masterBibInfo();
3833 BiblioInfo::const_iterator bit = keys.begin();
3834 BiblioInfo::const_iterator bend = keys.end();
3835 vector<docstring> labels;
3837 for (; bit != bend; ++bit)
3839 labels.push_back(bit->first);
3841 if (count(labels.begin(), labels.end(), from) > 1)
3844 string const paramName = "key";
3845 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3846 if (it->lyxCode() != CITE_CODE)
3848 InsetCommand * inset = it->asInsetCommand();
3849 docstring const oldValue = inset->getParam(paramName);
3850 if (oldValue == from)
3851 inset->setParam(paramName, to);
3855 // returns NULL if id-to-row conversion is unsupported
3856 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3857 pit_type par_begin, pit_type par_end,
3858 OutputWhat output, bool master) const
3860 unique_ptr<TexRow> texrow;
3861 OutputParams runparams(¶ms().encoding());
3862 runparams.nice = true;
3863 runparams.flavor = params().getOutputFlavor(format);
3864 runparams.linelen = lyxrc.plaintext_linelen;
3865 // No side effect of file copying and image conversion
3866 runparams.dryrun = true;
3868 if (output == CurrentParagraph) {
3869 runparams.par_begin = par_begin;
3870 runparams.par_end = par_end;
3871 if (par_begin + 1 == par_end) {
3873 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3877 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3878 convert<docstring>(par_begin),
3879 convert<docstring>(par_end - 1))
3882 // output paragraphs
3883 if (runparams.flavor == OutputParams::LYX) {
3884 Paragraph const & par = text().paragraphs()[par_begin];
3886 depth_type dt = par.getDepth();
3887 par.write(ods, params(), dt);
3888 os << from_utf8(ods.str());
3889 } else if (runparams.flavor == OutputParams::HTML) {
3891 setMathFlavor(runparams);
3892 xhtmlParagraphs(text(), *this, xs, runparams);
3893 } else if (runparams.flavor == OutputParams::TEXT) {
3895 // FIXME Handles only one paragraph, unlike the others.
3896 // Probably should have some routine with a signature like them.
3897 writePlaintextParagraph(*this,
3898 text().paragraphs()[par_begin], os, runparams, dummy);
3899 } else if (params().isDocBook()) {
3900 docbookParagraphs(text(), *this, os, runparams);
3902 // If we are previewing a paragraph, even if this is the
3903 // child of some other buffer, let's cut the link here,
3904 // so that no concurring settings from the master
3905 // (e.g. branch state) interfere (see #8101).
3907 d->ignore_parent = true;
3908 // We need to validate the Buffer params' features here
3909 // in order to know if we should output polyglossia
3910 // macros (instead of babel macros)
3911 LaTeXFeatures features(*this, params(), runparams);
3913 runparams.use_polyglossia = features.usePolyglossia();
3914 // latex or literate
3917 ots.texrow().newlines(2);
3919 latexParagraphs(*this, text(), ots, runparams);
3920 texrow = ots.releaseTexRow();
3922 // Restore the parenthood
3924 d->ignore_parent = false;
3928 if (output == FullSource)
3929 os << _("Preview source code");
3930 else if (output == OnlyPreamble)
3931 os << _("Preview preamble");
3932 else if (output == OnlyBody)
3933 os << _("Preview body");
3935 if (runparams.flavor == OutputParams::LYX) {
3937 if (output == FullSource)
3939 else if (output == OnlyPreamble)
3940 params().writeFile(ods, this);
3941 else if (output == OnlyBody)
3943 os << from_utf8(ods.str());
3944 } else if (runparams.flavor == OutputParams::HTML) {
3945 writeLyXHTMLSource(os, runparams, output);
3946 } else if (runparams.flavor == OutputParams::TEXT) {
3947 if (output == OnlyPreamble) {
3948 os << "% "<< _("Plain text does not have a preamble.");
3950 writePlaintextFile(*this, os, runparams);
3951 } else if (params().isDocBook()) {
3952 writeDocBookSource(os, absFileName(), runparams, output);
3954 // latex or literate
3957 ots.texrow().newlines(2);
3959 runparams.is_child = true;
3960 writeLaTeXSource(ots, string(), runparams, output);
3961 texrow = ots.releaseTexRow();
3968 ErrorList & Buffer::errorList(string const & type) const
3970 return d->errorLists[type];
3974 void Buffer::updateTocItem(std::string const & type,
3975 DocIterator const & dit) const
3978 d->gui_->updateTocItem(type, dit);
3982 void Buffer::structureChanged() const
3985 d->gui_->structureChanged();
3989 void Buffer::errors(string const & err, bool from_master) const
3992 d->gui_->errors(err, from_master);
3996 void Buffer::message(docstring const & msg) const
3999 d->gui_->message(msg);
4003 void Buffer::setBusy(bool on) const
4006 d->gui_->setBusy(on);
4010 void Buffer::updateTitles() const
4013 d->wa_->updateTitles();
4017 void Buffer::resetAutosaveTimers() const
4020 d->gui_->resetAutosaveTimers();
4024 bool Buffer::hasGuiDelegate() const
4030 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4039 class AutoSaveBuffer : public ForkedProcess {
4042 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4043 : buffer_(buffer), fname_(fname) {}
4045 virtual shared_ptr<ForkedProcess> clone() const
4047 return make_shared<AutoSaveBuffer>(*this);
4052 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4053 from_utf8(fname_.absFileName())));
4054 return run(DontWait);
4058 virtual int generateChild();
4060 Buffer const & buffer_;
4065 int AutoSaveBuffer::generateChild()
4067 #if defined(__APPLE__)
4068 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4069 * We should use something else like threads.
4071 * Since I do not know how to determine at run time what is the OS X
4072 * version, I just disable forking altogether for now (JMarc)
4074 pid_t const pid = -1;
4076 // tmp_ret will be located (usually) in /tmp
4077 // will that be a problem?
4078 // Note that this calls ForkedCalls::fork(), so it's
4079 // ok cross-platform.
4080 pid_t const pid = fork();
4081 // If you want to debug the autosave
4082 // you should set pid to -1, and comment out the fork.
4083 if (pid != 0 && pid != -1)
4087 // pid = -1 signifies that lyx was unable
4088 // to fork. But we will do the save
4090 bool failed = false;
4091 TempFile tempfile("lyxautoXXXXXX.lyx");
4092 tempfile.setAutoRemove(false);
4093 FileName const tmp_ret = tempfile.name();
4094 if (!tmp_ret.empty()) {
4095 if (!buffer_.writeFile(tmp_ret))
4097 else if (!tmp_ret.moveTo(fname_))
4103 // failed to write/rename tmp_ret so try writing direct
4104 if (!buffer_.writeFile(fname_)) {
4105 // It is dangerous to do this in the child,
4106 // but safe in the parent, so...
4107 if (pid == -1) // emit message signal.
4108 buffer_.message(_("Autosave failed!"));
4112 if (pid == 0) // we are the child so...
4121 FileName Buffer::getEmergencyFileName() const
4123 return FileName(d->filename.absFileName() + ".emergency");
4127 FileName Buffer::getAutosaveFileName() const
4129 // if the document is unnamed try to save in the backup dir, else
4130 // in the default document path, and as a last try in the filePath,
4131 // which will most often be the temporary directory
4134 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4135 : lyxrc.backupdir_path;
4136 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4139 string const fname = "#" + d->filename.onlyFileName() + "#";
4141 return makeAbsPath(fname, fpath);
4145 void Buffer::removeAutosaveFile() const
4147 FileName const f = getAutosaveFileName();
4153 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4155 FileName const newauto = getAutosaveFileName();
4157 if (newauto != oldauto && oldauto.exists())
4158 if (!oldauto.moveTo(newauto))
4159 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4163 bool Buffer::autoSave() const
4165 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4166 if (buf->d->bak_clean || hasReadonlyFlag())
4169 message(_("Autosaving current document..."));
4170 buf->d->bak_clean = true;
4172 FileName const fname = getAutosaveFileName();
4173 LASSERT(d->cloned_buffer_, return false);
4175 // If this buffer is cloned, we assume that
4176 // we are running in a separate thread already.
4177 TempFile tempfile("lyxautoXXXXXX.lyx");
4178 tempfile.setAutoRemove(false);
4179 FileName const tmp_ret = tempfile.name();
4180 if (!tmp_ret.empty()) {
4182 // assume successful write of tmp_ret
4183 if (tmp_ret.moveTo(fname))
4186 // failed to write/rename tmp_ret so try writing direct
4187 return writeFile(fname);
4191 void Buffer::setExportStatus(bool e) const
4193 d->doing_export = e;
4194 ListOfBuffers clist = getDescendents();
4195 ListOfBuffers::const_iterator cit = clist.begin();
4196 ListOfBuffers::const_iterator const cen = clist.end();
4197 for (; cit != cen; ++cit)
4198 (*cit)->d->doing_export = e;
4202 bool Buffer::isExporting() const
4204 return d->doing_export;
4208 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4212 return doExport(target, put_in_tempdir, result_file);
4215 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4216 string & result_file) const
4218 bool const update_unincluded =
4219 params().maintain_unincluded_children
4220 && !params().getIncludedChildren().empty();
4222 // (1) export with all included children (omit \includeonly)
4223 if (update_unincluded) {
4224 ExportStatus const status =
4225 doExport(target, put_in_tempdir, true, result_file);
4226 if (status != ExportSuccess)
4229 // (2) export with included children only
4230 return doExport(target, put_in_tempdir, false, result_file);
4234 void Buffer::setMathFlavor(OutputParams & op) const
4236 switch (params().html_math_output) {
4237 case BufferParams::MathML:
4238 op.math_flavor = OutputParams::MathAsMathML;
4240 case BufferParams::HTML:
4241 op.math_flavor = OutputParams::MathAsHTML;
4243 case BufferParams::Images:
4244 op.math_flavor = OutputParams::MathAsImages;
4246 case BufferParams::LaTeX:
4247 op.math_flavor = OutputParams::MathAsLaTeX;
4253 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4254 bool includeall, string & result_file) const
4256 LYXERR(Debug::FILES, "target=" << target);
4257 OutputParams runparams(¶ms().encoding());
4258 string format = target;
4259 string dest_filename;
4260 size_t pos = target.find(' ');
4261 if (pos != string::npos) {
4262 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4263 format = target.substr(0, pos);
4264 if (format == "default")
4265 format = params().getDefaultOutputFormat();
4266 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4267 FileName(dest_filename).onlyPath().createPath();
4268 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4270 MarkAsExporting exporting(this);
4271 string backend_format;
4272 runparams.flavor = OutputParams::LATEX;
4273 runparams.linelen = lyxrc.plaintext_linelen;
4274 runparams.includeall = includeall;
4275 vector<string> backs = params().backends();
4276 Converters converters = theConverters();
4277 bool need_nice_file = false;
4278 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4279 // Get shortest path to format
4280 converters.buildGraph();
4281 Graph::EdgePath path;
4282 for (vector<string>::const_iterator it = backs.begin();
4283 it != backs.end(); ++it) {
4284 Graph::EdgePath p = converters.getPath(*it, format);
4285 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4286 backend_format = *it;
4291 if (!put_in_tempdir) {
4292 // Only show this alert if this is an export to a non-temporary
4293 // file (not for previewing).
4294 Alert::error(_("Couldn't export file"), bformat(
4295 _("No information for exporting the format %1$s."),
4296 theFormats().prettyName(format)));
4298 return ExportNoPathToFormat;
4300 runparams.flavor = converters.getFlavor(path, this);
4301 Graph::EdgePath::const_iterator it = path.begin();
4302 Graph::EdgePath::const_iterator en = path.end();
4303 for (; it != en; ++it)
4304 if (theConverters().get(*it).nice()) {
4305 need_nice_file = true;
4310 backend_format = format;
4311 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4312 // FIXME: Don't hardcode format names here, but use a flag
4313 if (backend_format == "pdflatex")
4314 runparams.flavor = OutputParams::PDFLATEX;
4315 else if (backend_format == "luatex")
4316 runparams.flavor = OutputParams::LUATEX;
4317 else if (backend_format == "dviluatex")
4318 runparams.flavor = OutputParams::DVILUATEX;
4319 else if (backend_format == "xetex")
4320 runparams.flavor = OutputParams::XETEX;
4323 string filename = latexName(false);
4324 filename = addName(temppath(), filename);
4325 filename = changeExtension(filename,
4326 theFormats().extension(backend_format));
4327 LYXERR(Debug::FILES, "filename=" << filename);
4329 // Plain text backend
4330 if (backend_format == "text") {
4331 runparams.flavor = OutputParams::TEXT;
4332 writePlaintextFile(*this, FileName(filename), runparams);
4335 else if (backend_format == "xhtml") {
4336 runparams.flavor = OutputParams::HTML;
4337 setMathFlavor(runparams);
4338 makeLyXHTMLFile(FileName(filename), runparams);
4339 } else if (backend_format == "lyx")
4340 writeFile(FileName(filename));
4342 else if (params().isDocBook()) {
4343 runparams.nice = !put_in_tempdir;
4344 makeDocBookFile(FileName(filename), runparams);
4347 else if (backend_format == format || need_nice_file) {
4348 runparams.nice = true;
4349 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4350 if (d->cloned_buffer_)
4351 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4354 } else if (!lyxrc.tex_allows_spaces
4355 && contains(filePath(), ' ')) {
4356 Alert::error(_("File name error"),
4357 _("The directory path to the document cannot contain spaces."));
4358 return ExportTexPathHasSpaces;
4360 runparams.nice = false;
4361 bool const success = makeLaTeXFile(
4362 FileName(filename), filePath(), runparams);
4363 if (d->cloned_buffer_)
4364 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4369 string const error_type = (format == "program")
4370 ? "Build" : params().bufferFormat();
4371 ErrorList & error_list = d->errorLists[error_type];
4372 string const ext = theFormats().extension(format);
4373 FileName const tmp_result_file(changeExtension(filename, ext));
4374 bool const success = converters.convert(this, FileName(filename),
4375 tmp_result_file, FileName(absFileName()), backend_format, format,
4378 // Emit the signal to show the error list or copy it back to the
4379 // cloned Buffer so that it can be emitted afterwards.
4380 if (format != backend_format) {
4381 if (runparams.silent)
4383 else if (d->cloned_buffer_)
4384 d->cloned_buffer_->d->errorLists[error_type] =
4385 d->errorLists[error_type];
4388 // also to the children, in case of master-buffer-view
4389 ListOfBuffers clist = getDescendents();
4390 ListOfBuffers::const_iterator cit = clist.begin();
4391 ListOfBuffers::const_iterator const cen = clist.end();
4392 for (; cit != cen; ++cit) {
4393 if (runparams.silent)
4394 (*cit)->d->errorLists[error_type].clear();
4395 else if (d->cloned_buffer_) {
4396 // Enable reverse search by copying back the
4397 // texrow object to the cloned buffer.
4398 // FIXME: this is not thread safe.
4399 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4400 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4401 (*cit)->d->errorLists[error_type];
4403 (*cit)->errors(error_type, true);
4407 if (d->cloned_buffer_) {
4408 // Enable reverse dvi or pdf to work by copying back the texrow
4409 // object to the cloned buffer.
4410 // FIXME: There is a possibility of concurrent access to texrow
4411 // here from the main GUI thread that should be securized.
4412 d->cloned_buffer_->d->texrow = d->texrow;
4413 string const error_type = params().bufferFormat();
4414 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4418 if (put_in_tempdir) {
4419 result_file = tmp_result_file.absFileName();
4420 return success ? ExportSuccess : ExportConverterError;
4423 if (dest_filename.empty())
4424 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4426 result_file = dest_filename;
4427 // We need to copy referenced files (e. g. included graphics
4428 // if format == "dvi") to the result dir.
4429 vector<ExportedFile> const files =
4430 runparams.exportdata->externalFiles(format);
4431 string const dest = runparams.export_folder.empty() ?
4432 onlyPath(result_file) : runparams.export_folder;
4433 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4434 : force_overwrite == ALL_FILES;
4435 CopyStatus status = use_force ? FORCE : SUCCESS;
4437 vector<ExportedFile>::const_iterator it = files.begin();
4438 vector<ExportedFile>::const_iterator const en = files.end();
4439 for (; it != en && status != CANCEL; ++it) {
4440 string const fmt = theFormats().getFormatFromFile(it->sourceName);
4441 string fixedName = it->exportName;
4442 if (!runparams.export_folder.empty()) {
4443 // Relative pathnames starting with ../ will be sanitized
4444 // if exporting to a different folder
4445 while (fixedName.substr(0, 3) == "../")
4446 fixedName = fixedName.substr(3, fixedName.length() - 3);
4448 FileName fixedFileName = makeAbsPath(fixedName, dest);
4449 fixedFileName.onlyPath().createPath();
4450 status = copyFile(fmt, it->sourceName,
4452 it->exportName, status == FORCE,
4453 runparams.export_folder.empty());
4456 if (status == CANCEL) {
4457 message(_("Document export cancelled."));
4458 return ExportCancel;
4461 if (tmp_result_file.exists()) {
4462 // Finally copy the main file
4463 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4464 : force_overwrite != NO_FILES;
4465 if (status == SUCCESS && use_force)
4467 status = copyFile(format, tmp_result_file,
4468 FileName(result_file), result_file,
4470 if (status == CANCEL) {
4471 message(_("Document export cancelled."));
4472 return ExportCancel;
4474 message(bformat(_("Document exported as %1$s "
4476 theFormats().prettyName(format),
4477 makeDisplayPath(result_file)));
4480 // This must be a dummy converter like fax (bug 1888)
4481 message(bformat(_("Document exported as %1$s"),
4482 theFormats().prettyName(format)));
4485 return success ? ExportSuccess : ExportConverterError;
4489 Buffer::ExportStatus Buffer::preview(string const & format) const
4491 bool const update_unincluded =
4492 params().maintain_unincluded_children
4493 && !params().getIncludedChildren().empty();
4494 return preview(format, update_unincluded);
4498 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4500 MarkAsExporting exporting(this);
4502 // (1) export with all included children (omit \includeonly)
4504 ExportStatus const status = doExport(format, true, true, result_file);
4505 if (status != ExportSuccess)
4508 // (2) export with included children only
4509 ExportStatus const status = doExport(format, true, false, result_file);
4510 FileName const previewFile(result_file);
4512 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4513 theimpl->preview_file_ = previewFile;
4514 theimpl->preview_format_ = format;
4515 theimpl->preview_error_ = (status != ExportSuccess);
4517 if (status != ExportSuccess)
4520 if (previewFile.exists())
4521 return theFormats().view(*this, previewFile, format) ?
4522 PreviewSuccess : PreviewError;
4524 // Successful export but no output file?
4525 // Probably a bug in error detection.
4526 LATTEST(status != ExportSuccess);
4531 Buffer::ReadStatus Buffer::extractFromVC()
4533 bool const found = LyXVC::file_not_found_hook(d->filename);
4535 return ReadFileNotFound;
4536 if (!d->filename.isReadableFile())
4542 Buffer::ReadStatus Buffer::loadEmergency()
4544 FileName const emergencyFile = getEmergencyFileName();
4545 if (!emergencyFile.exists()
4546 || emergencyFile.lastModified() <= d->filename.lastModified())
4547 return ReadFileNotFound;
4549 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4550 docstring const text = bformat(_("An emergency save of the document "
4551 "%1$s exists.\n\nRecover emergency save?"), file);
4553 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4554 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4560 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4561 bool const success = (ret_llf == ReadSuccess);
4563 if (hasReadonlyFlag()) {
4564 Alert::warning(_("File is read-only"),
4565 bformat(_("An emergency file is successfully loaded, "
4566 "but the original file %1$s is marked read-only. "
4567 "Please make sure to save the document as a different "
4568 "file."), from_utf8(d->filename.absFileName())));
4571 lyxvc().file_found_hook(d->filename);
4572 str = _("Document was successfully recovered.");
4574 str = _("Document was NOT successfully recovered.");
4575 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4576 makeDisplayPath(emergencyFile.absFileName()));
4578 int const del_emerg =
4579 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4580 _("&Remove"), _("&Keep"));
4581 if (del_emerg == 0) {
4582 emergencyFile.removeFile();
4584 Alert::warning(_("Emergency file deleted"),
4585 _("Do not forget to save your file now!"), true);
4587 return success ? ReadSuccess : ReadEmergencyFailure;
4590 int const del_emerg =
4591 Alert::prompt(_("Delete emergency file?"),
4592 _("Remove emergency file now?"), 1, 1,
4593 _("&Remove"), _("&Keep"));
4595 emergencyFile.removeFile();
4596 return ReadOriginal;
4606 Buffer::ReadStatus Buffer::loadAutosave()
4608 // Now check if autosave file is newer.
4609 FileName const autosaveFile = getAutosaveFileName();
4610 if (!autosaveFile.exists()
4611 || autosaveFile.lastModified() <= d->filename.lastModified())
4612 return ReadFileNotFound;
4614 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4615 docstring const text = bformat(_("The backup of the document %1$s "
4616 "is newer.\n\nLoad the backup instead?"), file);
4617 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4618 _("&Load backup"), _("Load &original"), _("&Cancel"));
4623 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4624 // the file is not saved if we load the autosave file.
4625 if (ret_llf == ReadSuccess) {
4626 if (hasReadonlyFlag()) {
4627 Alert::warning(_("File is read-only"),
4628 bformat(_("A backup file is successfully loaded, "
4629 "but the original file %1$s is marked read-only. "
4630 "Please make sure to save the document as a "
4632 from_utf8(d->filename.absFileName())));
4635 lyxvc().file_found_hook(d->filename);
4638 return ReadAutosaveFailure;
4641 // Here we delete the autosave
4642 autosaveFile.removeFile();
4643 return ReadOriginal;
4651 Buffer::ReadStatus Buffer::loadLyXFile()
4653 if (!d->filename.isReadableFile()) {
4654 ReadStatus const ret_rvc = extractFromVC();
4655 if (ret_rvc != ReadSuccess)
4659 ReadStatus const ret_re = loadEmergency();
4660 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4663 ReadStatus const ret_ra = loadAutosave();
4664 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4667 return loadThisLyXFile(d->filename);
4671 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4673 return readFile(fn);
4677 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4679 for (auto const & err : terr) {
4680 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4681 int errorRow = err.error_in_line;
4682 Buffer const * buf = 0;
4684 if (err.child_name.empty())
4685 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4687 // The error occurred in a child
4688 for (Buffer const * child : getDescendents()) {
4689 string const child_name =
4690 DocFileName(changeExtension(child->absFileName(), "tex")).
4692 if (err.child_name != child_name)
4694 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4695 if (!TexRow::isNone(start)) {
4696 buf = d->cloned_buffer_
4697 ? child->d->cloned_buffer_->d->owner_
4704 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4710 void Buffer::setBuffersForInsets() const
4712 inset().setBuffer(const_cast<Buffer &>(*this));
4716 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4718 LBUFERR(!text().paragraphs().empty());
4720 // Use the master text class also for child documents
4721 Buffer const * const master = masterBuffer();
4722 DocumentClass const & textclass = master->params().documentClass();
4724 // do this only if we are the top-level Buffer
4725 if (master == this) {
4726 textclass.counters().reset(from_ascii("bibitem"));
4727 reloadBibInfoCache();
4730 // keep the buffers to be children in this set. If the call from the
4731 // master comes back we can see which of them were actually seen (i.e.
4732 // via an InsetInclude). The remaining ones in the set need still be updated.
4733 static std::set<Buffer const *> bufToUpdate;
4734 if (scope == UpdateMaster) {
4735 // If this is a child document start with the master
4736 if (master != this) {
4737 bufToUpdate.insert(this);
4738 master->updateBuffer(UpdateMaster, utype);
4739 // If the master buffer has no gui associated with it, then the TocModel is
4740 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4741 // (bug 5699). The same happens if the master buffer is open in a different
4742 // window. This test catches both possibilities.
4743 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4744 // There remains a problem here: If there is another child open in yet a third
4745 // window, that TOC is not updated. So some more general solution is needed at
4747 if (master->d->gui_ != d->gui_)
4750 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4751 if (bufToUpdate.find(this) == bufToUpdate.end())
4755 // start over the counters in the master
4756 textclass.counters().reset();
4759 // update will be done below for this buffer
4760 bufToUpdate.erase(this);
4762 // update all caches
4763 clearReferenceCache();
4765 setChangesPresent(false);
4767 Buffer & cbuf = const_cast<Buffer &>(*this);
4770 ParIterator parit = cbuf.par_iterator_begin();
4771 updateBuffer(parit, utype);
4774 /// Update the tocBackend for any buffer. The outliner uses the master's,
4775 /// and the navigation menu uses the child's.
4776 cbuf.tocBackend().update(true, utype);
4781 d->bibinfo_cache_valid_ = true;
4782 d->cite_labels_valid_ = true;
4783 if (scope == UpdateMaster)
4784 cbuf.structureChanged();
4788 static depth_type getDepth(DocIterator const & it)
4790 depth_type depth = 0;
4791 for (size_t i = 0 ; i < it.depth() ; ++i)
4792 if (!it[i].inset().inMathed())
4793 depth += it[i].paragraph().getDepth() + 1;
4794 // remove 1 since the outer inset does not count
4795 // we should have at least one non-math inset, so
4796 // depth should nevery be 0. but maybe it is worth
4797 // marking this, just in case.
4799 // coverity[INTEGER_OVERFLOW]
4803 static depth_type getItemDepth(ParIterator const & it)
4805 Paragraph const & par = *it;
4806 LabelType const labeltype = par.layout().labeltype;
4808 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4811 // this will hold the lowest depth encountered up to now.
4812 depth_type min_depth = getDepth(it);
4813 ParIterator prev_it = it;
4816 --prev_it.top().pit();
4818 // start of nested inset: go to outer par
4820 if (prev_it.empty()) {
4821 // start of document: nothing to do
4826 // We search for the first paragraph with same label
4827 // that is not more deeply nested.
4828 Paragraph & prev_par = *prev_it;
4829 depth_type const prev_depth = getDepth(prev_it);
4830 if (labeltype == prev_par.layout().labeltype) {
4831 if (prev_depth < min_depth)
4832 return prev_par.itemdepth + 1;
4833 if (prev_depth == min_depth)
4834 return prev_par.itemdepth;
4836 min_depth = min(min_depth, prev_depth);
4837 // small optimization: if we are at depth 0, we won't
4838 // find anything else
4839 if (prev_depth == 0)
4845 static bool needEnumCounterReset(ParIterator const & it)
4847 Paragraph const & par = *it;
4848 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4849 depth_type const cur_depth = par.getDepth();
4850 ParIterator prev_it = it;
4851 while (prev_it.pit()) {
4852 --prev_it.top().pit();
4853 Paragraph const & prev_par = *prev_it;
4854 if (prev_par.getDepth() <= cur_depth)
4855 return prev_par.layout().name() != par.layout().name();
4857 // start of nested inset: reset
4862 // set the label of a paragraph. This includes the counters.
4863 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4865 BufferParams const & bp = owner_->masterBuffer()->params();
4866 DocumentClass const & textclass = bp.documentClass();
4867 Paragraph & par = it.paragraph();
4868 Layout const & layout = par.layout();
4869 Counters & counters = textclass.counters();
4871 if (par.params().startOfAppendix()) {
4872 // We want to reset the counter corresponding to toplevel sectioning
4873 Layout const & lay = textclass.getTOCLayout();
4874 docstring const cnt = lay.counter;
4876 counters.reset(cnt);
4877 counters.appendix(true);
4879 par.params().appendix(counters.appendix());
4881 // Compute the item depth of the paragraph
4882 par.itemdepth = getItemDepth(it);
4884 if (layout.margintype == MARGIN_MANUAL) {
4885 if (par.params().labelWidthString().empty())
4886 par.params().labelWidthString(par.expandLabel(layout, bp));
4887 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4888 // we do not need to do anything here, since the empty case is
4889 // handled during export.
4891 par.params().labelWidthString(docstring());
4894 switch(layout.labeltype) {
4895 case LABEL_ITEMIZE: {
4896 // At some point of time we should do something more
4897 // clever here, like:
4898 // par.params().labelString(
4899 // bp.user_defined_bullet(par.itemdepth).getText());
4900 // for now, use a simple hardcoded label
4901 docstring itemlabel;
4902 switch (par.itemdepth) {
4904 itemlabel = char_type(0x2022);
4907 itemlabel = char_type(0x2013);
4910 itemlabel = char_type(0x2217);
4913 itemlabel = char_type(0x2219); // or 0x00b7
4916 par.params().labelString(itemlabel);
4920 case LABEL_ENUMERATE: {
4921 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4923 switch (par.itemdepth) {
4932 enumcounter += "iv";
4935 // not a valid enumdepth...
4939 // Increase the master counter?
4940 if (layout.stepmastercounter && needEnumCounterReset(it))
4941 counters.stepMaster(enumcounter, utype);
4943 // Maybe we have to reset the enumeration counter.
4944 if (!layout.resumecounter && needEnumCounterReset(it))
4945 counters.reset(enumcounter);
4946 counters.step(enumcounter, utype);
4948 string const & lang = par.getParLanguage(bp)->code();
4949 par.params().labelString(counters.theCounter(enumcounter, lang));
4954 case LABEL_SENSITIVE: {
4955 string const & type = counters.current_float();
4956 docstring full_label;
4958 full_label = owner_->B_("Senseless!!! ");
4960 docstring name = owner_->B_(textclass.floats().getType(type).name());
4961 if (counters.hasCounter(from_utf8(type))) {
4962 string const & lang = par.getParLanguage(bp)->code();
4963 counters.step(from_utf8(type), utype);
4964 full_label = bformat(from_ascii("%1$s %2$s:"),
4966 counters.theCounter(from_utf8(type), lang));
4968 full_label = bformat(from_ascii("%1$s #:"), name);
4970 par.params().labelString(full_label);
4974 case LABEL_NO_LABEL:
4975 par.params().labelString(docstring());
4979 case LABEL_CENTERED:
4980 case LABEL_STATIC: {
4981 docstring const & lcounter = layout.counter;
4982 if (!lcounter.empty()) {
4983 if (layout.toclevel <= bp.secnumdepth
4984 && (layout.latextype != LATEX_ENVIRONMENT
4985 || it.text()->isFirstInSequence(it.pit()))) {
4986 if (counters.hasCounter(lcounter))
4987 counters.step(lcounter, utype);
4988 par.params().labelString(par.expandLabel(layout, bp));
4990 par.params().labelString(docstring());
4992 par.params().labelString(par.expandLabel(layout, bp));
4998 par.params().labelString(par.expandLabel(layout, bp));
5003 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5005 // LASSERT: Is it safe to continue here, or should we just return?
5006 LASSERT(parit.pit() == 0, /**/);
5008 // Set the position of the text in the buffer to be able
5009 // to resolve macros in it.
5010 parit.text()->setMacrocontextPosition(parit);
5012 depth_type maxdepth = 0;
5013 pit_type const lastpit = parit.lastpit();
5014 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5015 // reduce depth if necessary
5016 if (parit->params().depth() > maxdepth) {
5017 /** FIXME: this function is const, but
5018 * nevertheless it modifies the buffer. To be
5019 * cleaner, one should modify the buffer in
5020 * another function, which is actually
5021 * non-const. This would however be costly in
5022 * terms of code duplication.
5024 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
5025 parit->params().depth(maxdepth);
5027 maxdepth = parit->getMaxDepthAfter();
5029 if (utype == OutputUpdate) {
5030 // track the active counters
5031 // we have to do this for the master buffer, since the local
5032 // buffer isn't tracking anything.
5033 masterBuffer()->params().documentClass().counters().
5034 setActiveLayout(parit->layout());
5037 // set the counter for this paragraph
5038 d->setLabel(parit, utype);
5040 // update change-tracking flag
5041 parit->addChangesToBuffer(*this);
5044 InsetList::const_iterator iit = parit->insetList().begin();
5045 InsetList::const_iterator end = parit->insetList().end();
5046 for (; iit != end; ++iit) {
5047 parit.pos() = iit->pos;
5048 iit->inset->updateBuffer(parit, utype);
5054 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5055 WordLangTuple & word_lang, docstring_list & suggestions) const
5059 suggestions.clear();
5060 word_lang = WordLangTuple();
5061 bool const to_end = to.empty();
5062 DocIterator const end = to_end ? doc_iterator_end(this) : to;
5063 // OK, we start from here.
5064 for (; from != end; from.forwardPos()) {
5065 // This skips all insets with spell check disabled.
5066 while (!from.allowSpellCheck()) {
5070 // If from is at the end of the document (which is possible
5071 // when "from" was changed above) LyX will crash later otherwise.
5072 if (from.atEnd() || (!to_end && from >= end))
5075 from.paragraph().spellCheck();
5076 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5077 if (SpellChecker::misspelled(res)) {
5081 // Do not increase progress when from == to, otherwise the word
5082 // count will be wrong.
5092 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5094 bool inword = false;
5099 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5100 if (!dit.inTexted()) {
5105 Paragraph const & par = dit.paragraph();
5106 pos_type const pos = dit.pos();
5108 // Copied and adapted from isWordSeparator() in Paragraph
5109 if (pos == dit.lastpos()) {
5112 Inset const * ins = par.getInset(pos);
5113 if (ins && skipNoOutput && !ins->producesOutput()) {
5116 // stop if end of range was skipped
5117 if (!to.atEnd() && dit >= to)
5120 } else if (!par.isDeleted(pos)) {
5121 if (par.isWordSeparator(pos))
5127 if (ins && ins->isLetter())
5129 else if (ins && ins->isSpace())
5132 char_type const c = par.getChar(pos);
5133 if (isPrintableNonspace(c))
5135 else if (isSpace(c))
5145 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5147 d->updateStatistics(from, to, skipNoOutput);
5151 int Buffer::wordCount() const
5153 return d->wordCount();
5157 int Buffer::charCount(bool with_blanks) const
5159 return d->charCount(with_blanks);
5163 Buffer::ReadStatus Buffer::reload()
5166 // c.f. bug http://www.lyx.org/trac/ticket/6587
5167 removeAutosaveFile();
5168 // e.g., read-only status could have changed due to version control
5169 d->filename.refresh();
5170 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5172 // clear parent. this will get reset if need be.
5174 ReadStatus const status = loadLyXFile();
5175 if (status == ReadSuccess) {
5180 message(bformat(_("Document %1$s reloaded."), disp_fn));
5183 message(bformat(_("Could not reload document %1$s."), disp_fn));
5193 bool Buffer::saveAs(FileName const & fn)
5195 FileName const old_name = fileName();
5196 FileName const old_auto = getAutosaveFileName();
5197 bool const old_unnamed = isUnnamed();
5198 bool success = true;
5199 d->old_position = filePath();
5206 // bring the autosave file with us, just in case.
5207 moveAutosaveFile(old_auto);
5208 // validate version control data and
5209 // correct buffer title
5210 lyxvc().file_found_hook(fileName());
5212 // the file has now been saved to the new location.
5213 // we need to check that the locations of child buffers
5215 checkChildBuffers();
5216 checkMasterBuffer();
5219 // reset the old filename and unnamed state
5220 setFileName(old_name);
5221 setUnnamed(old_unnamed);
5225 d->old_position.clear();
5230 void Buffer::checkChildBuffers()
5232 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5233 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5234 for (; it != en; ++it) {
5235 DocIterator dit = it->second;
5236 Buffer * cbuf = const_cast<Buffer *>(it->first);
5237 if (!cbuf || !theBufferList().isLoaded(cbuf))
5239 Inset * inset = dit.nextInset();
5240 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5241 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5242 docstring const & incfile = inset_inc->getParam("filename");
5243 string oldloc = cbuf->absFileName();
5244 string newloc = makeAbsPath(to_utf8(incfile),
5245 onlyPath(absFileName())).absFileName();
5246 if (oldloc == newloc)
5248 // the location of the child file is incorrect.
5250 inset_inc->setChildBuffer(0);
5252 // invalidate cache of children
5253 d->children_positions.clear();
5254 d->position_to_children.clear();
5258 // If a child has been saved under a different name/path, it might have been
5259 // orphaned. Therefore the master needs to be reset (bug 8161).
5260 void Buffer::checkMasterBuffer()
5262 Buffer const * const master = masterBuffer();
5266 // necessary to re-register the child (bug 5873)
5267 // FIXME: clean up updateMacros (here, only
5268 // child registering is needed).
5269 master->updateMacros();
5270 // (re)set master as master buffer, but only
5271 // if we are a real child
5272 if (master->isChild(this))
5279 string Buffer::includedFilePath(string const & name, string const & ext) const
5281 if (d->old_position.empty() ||
5282 equivalent(FileName(d->old_position), FileName(filePath())))
5285 bool isabsolute = FileName::isAbsolute(name);
5286 // both old_position and filePath() end with a path separator
5287 string absname = isabsolute ? name : d->old_position + name;
5289 // if old_position is set to origin, we need to do the equivalent of
5290 // getReferencedFileName() (see readDocument())
5291 if (!isabsolute && d->old_position == params().origin) {
5292 FileName const test(addExtension(filePath() + name, ext));
5294 absname = filePath() + name;
5297 if (!FileName(addExtension(absname, ext)).exists())
5301 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5303 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5304 from_utf8(filePath())));
5308 void Buffer::setChangesPresent(bool b) const
5310 d->tracked_changes_present_ = b;
5314 bool Buffer::areChangesPresent() const
5316 return d->tracked_changes_present_;
5320 void Buffer::updateChangesPresent() const
5322 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5323 setChangesPresent(false);
5324 ParConstIterator it = par_iterator_begin();
5325 ParConstIterator const end = par_iterator_end();
5326 for (; !areChangesPresent() && it != end; ++it)
5327 it->addChangesToBuffer(*this);
5331 void Buffer::Impl::refreshFileMonitor()
5333 if (file_monitor_ && file_monitor_->filename() == filename.absFileName())
5334 return file_monitor_->refresh();
5336 // The previous file monitor is invalid
5337 // This also destroys the previous file monitor and all its connections
5338 file_monitor_ = FileSystemWatcher::monitor(filename);
5339 fileExternallyModified(false);
5340 // file_monitor_ will be destroyed with *this, so it is not going to call a
5341 // destroyed object method.
5342 file_monitor_->connect([this](){ fileExternallyModified(true); });
5346 void Buffer::Impl::fileExternallyModified(bool modified) const
5349 lyx_clean = bak_clean = false;
5350 externally_modified_ = modified;
5352 wa_->updateTitles();
5356 bool Buffer::notifiesExternalModification() const
5358 return d->isExternallyModified();
5362 void Buffer::clearExternalModification() const
5364 d->fileExternallyModified(false);