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/FileName.h"
95 #include "support/FileNameList.h"
96 #include "support/filetools.h"
97 #include "support/ForkedCalls.h"
98 #include "support/gettext.h"
99 #include "support/gzstream.h"
100 #include "support/lstrings.h"
101 #include "support/lyxalgo.h"
102 #include "support/mutex.h"
103 #include "support/os.h"
104 #include "support/Package.h"
105 #include "support/PathChanger.h"
106 #include "support/Systemcall.h"
107 #include "support/TempFile.h"
108 #include "support/textutils.h"
109 #include "support/types.h"
111 #include "support/bind.h"
123 using namespace lyx::support;
124 using namespace lyx::graphics;
128 namespace Alert = frontend::Alert;
129 namespace os = support::os;
133 int const LYX_FORMAT = LYX_FORMAT_LYX;
135 typedef map<string, bool> DepClean;
136 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
141 // A storehouse for the cloned buffers.
142 list<CloneList *> cloned_buffers;
148 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
152 delete preview_loader_;
160 /// search for macro in local (buffer) table or in children
161 MacroData const * getBufferMacro(docstring const & name,
162 DocIterator const & pos) const;
164 /// Update macro table starting with position of it \param it in some
166 void updateMacros(DocIterator & it, DocIterator & scope);
168 void setLabel(ParIterator & it, UpdateType utype) const;
170 /** If we have branches that use the file suffix
171 feature, return the file name with suffix appended.
173 support::FileName exportFileName() const;
180 mutable TexRow texrow;
182 /// need to regenerate .tex?
186 mutable bool lyx_clean;
188 /// is autosave needed?
189 mutable bool bak_clean;
191 /// is this an unnamed file (New...)?
194 /// is this an internal bufffer?
195 bool internal_buffer;
200 /// name of the file the buffer is associated with.
203 /** Set to true only when the file is fully loaded.
204 * Used to prevent the premature generation of previews
205 * and by the citation inset.
207 bool file_fully_loaded;
209 /// original format of loaded file
212 /// if the file was originally loaded from an older format, do
213 /// we need to back it up still?
214 bool need_format_backup;
216 /// Ignore the parent (e.g. when exporting a child standalone)?
220 mutable TocBackend toc_backend;
225 ScopeMacro(DocIterator const & s, MacroData const & m)
226 : scope(s), macro(m) {}
230 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
231 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
232 /// map from the macro name to the position map,
233 /// which maps the macro definition position to the scope and the MacroData.
234 NamePositionScopeMacroMap macros;
235 /// This seem to change the way Buffer::getMacro() works
236 mutable bool macro_lock;
238 /// positions of child buffers in the buffer
239 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer() : buffer(0) {}
242 ScopeBuffer(DocIterator const & s, Buffer const * b)
243 : scope(s), buffer(b) {}
245 Buffer const * buffer;
247 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
248 /// position of children buffers in this buffer
249 BufferPositionMap children_positions;
250 /// map from children inclusion positions to their scope and their buffer
251 PositionScopeBufferMap position_to_children;
253 /// Contains the old buffer filePath() while saving-as, or the
254 /// directory where the document was last saved while loading.
257 /** Keeps track of the path of local layout files.
258 * If possible, it is always relative to the buffer path.
259 * Empty for layouts in system or user directory.
261 string layout_position;
263 /// Container for all sort of Buffer dependant errors.
264 map<string, ErrorList> errorLists;
266 /// timestamp and checksum used to test if the file has been externally
267 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
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::FileNameList 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_;
380 /// So we can force access via the accessors.
381 mutable Buffer const * parent_buffer;
390 /// Creates the per buffer temporary directory
391 static FileName createBufferTmpDir()
393 // FIXME This would be the ideal application for a TempDir class (like
394 // TempFile but for directories)
399 Mutex::Locker locker(&mutex);
400 counter = convert<string>(count++);
402 // We are in our own directory. Why bother to mangle name?
403 // In fact I wrote this code to circumvent a problematic behaviour
404 // (bug?) of EMX mkstemp().
405 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
408 if (!tmpfl.createDirectory(0777)) {
409 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
410 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
411 from_utf8(tmpfl.absFileName())));
417 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
418 Buffer const * cloned_buffer)
419 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
420 internal_buffer(false), read_only(readonly_), filename(file),
421 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
422 ignore_parent(false), toc_backend(owner), macro_lock(false), timestamp_(0),
423 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
424 bibfile_cache_valid_(false), cite_labels_valid_(false), preview_error_(false),
425 inset(0), preview_loader_(0), cloned_buffer_(cloned_buffer),
426 clone_list_(0), doing_export(false), parent_buffer(0),
427 word_count_(0), char_count_(0), blank_count_(0)
429 if (!cloned_buffer_) {
430 temppath = createBufferTmpDir();
431 lyxvc.setBuffer(owner_);
433 wa_ = new frontend::WorkAreaManager;
436 temppath = cloned_buffer_->d->temppath;
437 file_fully_loaded = true;
438 params = cloned_buffer_->d->params;
439 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
440 bibinfo_ = cloned_buffer_->d->bibinfo_;
441 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
442 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
443 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
444 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
445 unnamed = cloned_buffer_->d->unnamed;
446 internal_buffer = cloned_buffer_->d->internal_buffer;
447 layout_position = cloned_buffer_->d->layout_position;
448 preview_file_ = cloned_buffer_->d->preview_file_;
449 preview_format_ = cloned_buffer_->d->preview_format_;
450 preview_error_ = cloned_buffer_->d->preview_error_;
451 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
455 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
456 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
458 LYXERR(Debug::INFO, "Buffer::Buffer()");
460 d->inset = new InsetText(*cloned_buffer->d->inset);
461 d->inset->setBuffer(*this);
462 // FIXME: optimize this loop somewhat, maybe by creating a new
463 // general recursive Inset::setId().
464 DocIterator it = doc_iterator_begin(this);
465 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
466 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
467 it.paragraph().setId(cloned_it.paragraph().id());
469 d->inset = new InsetText(this);
470 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
476 LYXERR(Debug::INFO, "Buffer::~Buffer()");
477 // here the buffer should take care that it is
478 // saved properly, before it goes into the void.
480 // GuiView already destroyed
484 // No need to do additional cleanups for internal buffer.
490 // this is in case of recursive includes: we won't try to delete
491 // ourselves as a child.
492 d->clone_list_->erase(this);
493 // loop over children
494 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
495 Impl::BufferPositionMap::iterator end = d->children_positions.end();
496 for (; it != end; ++it) {
497 Buffer * child = const_cast<Buffer *>(it->first);
498 if (d->clone_list_->erase(child))
501 // if we're the master buffer, then we should get rid of the list
504 // If this is not empty, we have leaked something. Worse, one of the
505 // children still has a reference to this list. But we will try to
506 // continue, rather than shut down.
507 LATTEST(d->clone_list_->empty());
508 list<CloneList *>::iterator it =
509 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
510 if (it == cloned_buffers.end()) {
511 // We will leak in this case, but it is safe to continue.
514 cloned_buffers.erase(it);
515 delete d->clone_list_;
517 // FIXME Do we really need to do this right before we delete d?
518 // clear references to children in macro tables
519 d->children_positions.clear();
520 d->position_to_children.clear();
522 // loop over children
523 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
524 Impl::BufferPositionMap::iterator end = d->children_positions.end();
525 for (; it != end; ++it) {
526 Buffer * child = const_cast<Buffer *>(it->first);
527 if (theBufferList().isLoaded(child)) {
528 if (theBufferList().isOthersChild(this, child))
531 theBufferList().release(child);
536 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
537 msg += emergencyWrite();
538 Alert::warning(_("Attempting to close changed document!"), msg);
541 // FIXME Do we really need to do this right before we delete d?
542 // clear references to children in macro tables
543 d->children_positions.clear();
544 d->position_to_children.clear();
546 if (!d->temppath.destroyDirectory()) {
547 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
548 from_utf8(d->temppath.absFileName())));
557 Buffer * Buffer::cloneFromMaster() const
560 cloned_buffers.push_back(new CloneList);
561 CloneList * clones = cloned_buffers.back();
563 masterBuffer()->cloneWithChildren(bufmap, clones);
565 // make sure we got cloned
566 BufferMap::const_iterator bit = bufmap.find(this);
567 LASSERT(bit != bufmap.end(), return 0);
568 Buffer * cloned_buffer = bit->second;
570 return cloned_buffer;
574 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
576 // have we already been cloned?
577 if (bufmap.find(this) != bufmap.end())
580 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
582 // The clone needs its own DocumentClass, since running updateBuffer() will
583 // modify it, and we would otherwise be sharing it with the original Buffer.
584 buffer_clone->params().makeDocumentClass(true);
586 cap::switchBetweenClasses(
587 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
588 static_cast<InsetText &>(buffer_clone->inset()), el);
590 bufmap[this] = buffer_clone;
591 clones->insert(buffer_clone);
592 buffer_clone->d->clone_list_ = clones;
593 buffer_clone->d->macro_lock = true;
594 buffer_clone->d->children_positions.clear();
596 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
597 // math macro caches need to be rethought and simplified.
598 // I am not sure wether we should handle Buffer cloning here or in BufferList.
599 // Right now BufferList knows nothing about buffer clones.
600 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
601 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
602 for (; it != end; ++it) {
603 DocIterator dit = it->first.clone(buffer_clone);
604 dit.setBuffer(buffer_clone);
605 Buffer * child = const_cast<Buffer *>(it->second.buffer);
607 child->cloneWithChildren(bufmap, clones);
608 BufferMap::iterator const bit = bufmap.find(child);
609 LASSERT(bit != bufmap.end(), continue);
610 Buffer * child_clone = bit->second;
612 Inset * inset = dit.nextInset();
613 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
614 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
615 inset_inc->setChildBuffer(child_clone);
616 child_clone->d->setParent(buffer_clone);
617 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
618 buffer_clone->setChild(dit, child_clone);
620 buffer_clone->d->macro_lock = false;
625 Buffer * Buffer::cloneBufferOnly() const {
626 cloned_buffers.push_back(new CloneList);
627 CloneList * clones = cloned_buffers.back();
628 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
630 // The clone needs its own DocumentClass, since running updateBuffer() will
631 // modify it, and we would otherwise be sharing it with the original Buffer.
632 buffer_clone->params().makeDocumentClass(true);
634 cap::switchBetweenClasses(
635 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
636 static_cast<InsetText &>(buffer_clone->inset()), el);
638 clones->insert(buffer_clone);
639 buffer_clone->d->clone_list_ = clones;
641 // we won't be cloning the children
642 buffer_clone->d->children_positions.clear();
647 bool Buffer::isClone() const
649 return d->cloned_buffer_;
653 void Buffer::changed(bool update_metrics) const
656 d->wa_->redrawAll(update_metrics);
660 frontend::WorkAreaManager & Buffer::workAreaManager() const
667 Text & Buffer::text() const
669 return d->inset->text();
673 Inset & Buffer::inset() const
679 BufferParams & Buffer::params()
685 BufferParams const & Buffer::params() const
691 BufferParams const & Buffer::masterParams() const
693 if (masterBuffer() == this)
696 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
697 // Copy child authors to the params. We need those pointers.
698 AuthorList const & child_authors = params().authors();
699 AuthorList::Authors::const_iterator it = child_authors.begin();
700 for (; it != child_authors.end(); ++it)
701 mparams.authors().record(*it);
706 double Buffer::fontScalingFactor() const
708 return isExporting() ? 75.0 * params().html_math_img_scale
709 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
713 ParagraphList & Buffer::paragraphs()
715 return text().paragraphs();
719 ParagraphList const & Buffer::paragraphs() const
721 return text().paragraphs();
725 LyXVC & Buffer::lyxvc()
731 LyXVC const & Buffer::lyxvc() const
737 string const Buffer::temppath() const
739 return d->temppath.absFileName();
743 TexRow & Buffer::texrow()
749 TexRow const & Buffer::texrow() const
755 TocBackend & Buffer::tocBackend() const
757 return d->toc_backend;
761 Undo & Buffer::undo()
767 void Buffer::setChild(DocIterator const & dit, Buffer * child)
769 d->children_positions[child] = dit;
773 string Buffer::latexName(bool const no_path) const
775 FileName latex_name =
776 makeLatexName(d->exportFileName());
777 return no_path ? latex_name.onlyFileName()
778 : latex_name.absFileName();
782 FileName Buffer::Impl::exportFileName() const
784 docstring const branch_suffix =
785 params.branchlist().getFileNameSuffix();
786 if (branch_suffix.empty())
789 string const name = filename.onlyFileNameWithoutExt()
790 + to_utf8(branch_suffix);
791 FileName res(filename.onlyPath().absFileName() + "/" + name);
792 res.changeExtension(filename.extension());
798 string Buffer::logName(LogType * type) const
800 string const filename = latexName(false);
802 if (filename.empty()) {
808 string const path = temppath();
810 FileName const fname(addName(temppath(),
811 onlyFileName(changeExtension(filename,
814 // FIXME: how do we know this is the name of the build log?
815 FileName const bname(
816 addName(path, onlyFileName(
817 changeExtension(filename,
818 formats.extension(params().bufferFormat()) + ".out"))));
820 // Also consider the master buffer log file
821 FileName masterfname = fname;
822 LogType mtype = latexlog;
823 if (masterBuffer() != this) {
824 string const mlogfile = masterBuffer()->logName(&mtype);
825 masterfname = FileName(mlogfile);
828 // If no Latex log or Build log is newer, show Build log
829 if (bname.exists() &&
830 ((!fname.exists() && !masterfname.exists())
831 || (fname.lastModified() < bname.lastModified()
832 && masterfname.lastModified() < bname.lastModified()))) {
833 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
836 return bname.absFileName();
837 // If we have a newer master file log or only a master log, show this
838 } else if (fname != masterfname
839 && (!fname.exists() && (masterfname.exists()
840 || fname.lastModified() < masterfname.lastModified()))) {
841 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
844 return masterfname.absFileName();
846 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
849 return fname.absFileName();
853 void Buffer::setReadonly(bool const flag)
855 if (d->read_only != flag) {
862 void Buffer::setFileName(FileName const & fname)
864 bool const changed = fname != d->filename;
867 lyxvc().file_found_hook(fname);
868 setReadonly(d->filename.isReadOnly());
874 int Buffer::readHeader(Lexer & lex)
876 int unknown_tokens = 0;
878 int begin_header_line = -1;
880 // Initialize parameters that may be/go lacking in header:
881 params().branchlist().clear();
882 params().preamble.erase();
883 params().options.erase();
884 params().master.erase();
885 params().float_placement.erase();
886 params().paperwidth.erase();
887 params().paperheight.erase();
888 params().leftmargin.erase();
889 params().rightmargin.erase();
890 params().topmargin.erase();
891 params().bottommargin.erase();
892 params().headheight.erase();
893 params().headsep.erase();
894 params().footskip.erase();
895 params().columnsep.erase();
896 params().fonts_cjk.erase();
897 params().listings_params.clear();
898 params().clearLayoutModules();
899 params().clearRemovedModules();
900 params().clearIncludedChildren();
901 params().pdfoptions().clear();
902 params().indiceslist().clear();
903 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
904 params().isbackgroundcolor = false;
905 params().fontcolor = RGBColor(0, 0, 0);
906 params().isfontcolor = false;
907 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
908 params().boxbgcolor = RGBColor(0xFF, 0, 0);
909 params().html_latex_start.clear();
910 params().html_latex_end.clear();
911 params().html_math_img_scale = 1.0;
912 params().output_sync_macro.erase();
913 params().setLocalLayout(docstring(), false);
914 params().setLocalLayout(docstring(), true);
916 for (int i = 0; i < 4; ++i) {
917 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
918 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
921 ErrorList & errorList = d->errorLists["Parse"];
930 if (token == "\\end_header")
934 if (token == "\\begin_header") {
935 begin_header_line = line;
939 LYXERR(Debug::PARSER, "Handling document header token: `"
942 string const result =
943 params().readToken(lex, token, d->filename.onlyPath());
944 if (!result.empty()) {
945 if (token == "\\textclass") {
946 d->layout_position = result;
949 docstring const s = bformat(_("Unknown token: "
953 errorList.push_back(ErrorItem(_("Document header error"), s));
957 if (begin_header_line) {
958 docstring const s = _("\\begin_header is missing");
959 errorList.push_back(ErrorItem(_("Document header error"), s));
962 params().makeDocumentClass();
964 return unknown_tokens;
969 // changed to be public and have one parameter
970 // Returns true if "\end_document" is not read (Asger)
971 bool Buffer::readDocument(Lexer & lex)
973 ErrorList & errorList = d->errorLists["Parse"];
976 // remove dummy empty par
977 paragraphs().clear();
979 if (!lex.checkFor("\\begin_document")) {
980 docstring const s = _("\\begin_document is missing");
981 errorList.push_back(ErrorItem(_("Document header error"), s));
986 if (params().output_changes) {
987 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
988 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
989 LaTeXFeatures::isAvailable("xcolor");
991 if (!dvipost && !xcolorulem) {
992 Alert::warning(_("Changes not shown in LaTeX output"),
993 _("Changes will not be highlighted in LaTeX output, "
994 "because neither dvipost nor xcolor/ulem are installed.\n"
995 "Please install these packages or redefine "
996 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
997 } else if (!xcolorulem) {
998 Alert::warning(_("Changes not shown in LaTeX output"),
999 _("Changes will not be highlighted in LaTeX output "
1000 "when using pdflatex, because xcolor and ulem are not installed.\n"
1001 "Please install both packages or redefine "
1002 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1006 if (!parent() && !params().master.empty()) {
1007 FileName const master_file = makeAbsPath(params().master,
1008 onlyPath(absFileName()));
1009 if (isLyXFileName(master_file.absFileName())) {
1011 checkAndLoadLyXFile(master_file, true);
1013 // necessary e.g. after a reload
1014 // to re-register the child (bug 5873)
1015 // FIXME: clean up updateMacros (here, only
1016 // child registering is needed).
1017 master->updateMacros();
1018 // set master as master buffer, but only
1019 // if we are a real child
1020 if (master->isChild(this))
1022 // if the master is not fully loaded
1023 // it is probably just loading this
1024 // child. No warning needed then.
1025 else if (master->isFullyLoaded())
1026 LYXERR0("The master '"
1028 << "' assigned to this document ("
1030 << ") does not include "
1031 "this document. Ignoring the master assignment.");
1036 // assure we have a default index
1037 params().indiceslist().addDefault(B_("Index"));
1040 if (FileName::isAbsolute(params().origin))
1041 d->old_position = params().origin;
1043 d->old_position = filePath();
1044 bool const res = text().read(lex, errorList, d->inset);
1045 d->old_position.clear();
1047 // inform parent buffer about local macros
1049 Buffer const * pbuf = parent();
1050 UserMacroSet::const_iterator cit = usermacros.begin();
1051 UserMacroSet::const_iterator end = usermacros.end();
1052 for (; cit != end; ++cit)
1053 pbuf->usermacros.insert(*cit);
1057 updateMacroInstances(InternalUpdate);
1062 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1064 Format const * fmt = formats.getFormat(format);
1067 // It is important to use the correct extension here, since some
1068 // converters create a wrong output file otherwise (e.g. html2latex)
1069 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1070 FileName const name(tempfile.name());
1071 ofdocstream os(name.toFilesystemEncoding().c_str());
1072 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1073 bool const success = !(os << contents).fail();
1076 bool converted = false;
1078 params().compressed = false;
1080 // remove dummy empty par
1081 paragraphs().clear();
1083 converted = importFile(format, name, errorList);
1092 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1094 if (!theConverters().isReachable(format, "lyx"))
1097 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1098 FileName const lyx(tempfile.name());
1099 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1100 return readFile(lyx) == ReadSuccess;
1106 bool Buffer::readString(string const & s)
1108 params().compressed = false;
1111 istringstream is(s);
1113 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1114 FileName const fn = tempfile.name();
1117 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1119 if (success && file_format != LYX_FORMAT) {
1120 // We need to call lyx2lyx, so write the input to a file
1121 ofstream os(fn.toFilesystemEncoding().c_str());
1124 // lyxvc in readFile
1125 if (readFile(fn) != ReadSuccess)
1129 if (readDocument(lex))
1135 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1139 if (!lex.setFile(fname)) {
1140 Alert::error(_("File Not Found"),
1141 bformat(_("Unable to open file `%1$s'."),
1142 from_utf8(fn.absFileName())));
1143 return ReadFileNotFound;
1147 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1148 if (ret_plf != ReadSuccess)
1151 if (file_format != LYX_FORMAT) {
1153 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1154 if (ret_clf != ReadSuccess)
1156 ret_clf = readFile(tmpFile);
1157 if (ret_clf == ReadSuccess) {
1158 d->file_format = file_format;
1159 d->need_format_backup = true;
1164 // FIXME: InsetInfo needs to know whether the file is under VCS
1165 // during the parse process, so this has to be done before.
1166 lyxvc().file_found_hook(d->filename);
1168 if (readDocument(lex)) {
1169 Alert::error(_("Document format failure"),
1170 bformat(_("%1$s ended unexpectedly, which means"
1171 " that it is probably corrupted."),
1172 from_utf8(fn.absFileName())));
1173 return ReadDocumentFailure;
1176 d->file_fully_loaded = true;
1177 d->read_only = !d->filename.isWritable();
1178 params().compressed = formats.isZippedFile(d->filename);
1184 bool Buffer::isFullyLoaded() const
1186 return d->file_fully_loaded;
1190 void Buffer::setFullyLoaded(bool value)
1192 d->file_fully_loaded = value;
1196 bool Buffer::lastPreviewError() const
1198 return d->preview_error_;
1202 PreviewLoader * Buffer::loader() const
1204 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1206 if (!d->preview_loader_)
1207 d->preview_loader_ = new PreviewLoader(*this);
1208 return d->preview_loader_;
1212 void Buffer::removePreviews() const
1214 delete d->preview_loader_;
1215 d->preview_loader_ = 0;
1219 void Buffer::updatePreviews() const
1221 PreviewLoader * ploader = loader();
1225 InsetIterator it = inset_iterator_begin(*d->inset);
1226 InsetIterator const end = inset_iterator_end(*d->inset);
1227 for (; it != end; ++it)
1228 it->addPreview(it, *ploader);
1230 ploader->startLoading();
1234 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1235 FileName const & fn, int & file_format) const
1237 if(!lex.checkFor("\\lyxformat")) {
1238 Alert::error(_("Document format failure"),
1239 bformat(_("%1$s is not a readable LyX document."),
1240 from_utf8(fn.absFileName())));
1241 return ReadNoLyXFormat;
1247 // LyX formats 217 and earlier were written as 2.17. This corresponds
1248 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1249 // these cases. See also: www.lyx.org/trac/changeset/1313.
1250 size_t dot = tmp_format.find_first_of(".,");
1251 if (dot != string::npos)
1252 tmp_format.erase(dot, 1);
1254 file_format = convert<int>(tmp_format);
1259 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1260 FileName & tmpfile, int from_format)
1262 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1263 tempfile.setAutoRemove(false);
1264 tmpfile = tempfile.name();
1265 if(tmpfile.empty()) {
1266 Alert::error(_("Conversion failed"),
1267 bformat(_("%1$s is from a different"
1268 " version of LyX, but a temporary"
1269 " file for converting it could"
1270 " not be created."),
1271 from_utf8(fn.absFileName())));
1272 return LyX2LyXNoTempFile;
1275 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1276 if (lyx2lyx.empty()) {
1277 Alert::error(_("Conversion script not found"),
1278 bformat(_("%1$s is from a different"
1279 " version of LyX, but the"
1280 " conversion script lyx2lyx"
1281 " could not be found."),
1282 from_utf8(fn.absFileName())));
1283 return LyX2LyXNotFound;
1287 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1288 ostringstream command;
1289 command << os::python()
1290 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1291 << " -t " << convert<string>(LYX_FORMAT)
1292 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1293 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1294 string const command_str = command.str();
1296 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1298 cmd_ret const ret = runCommand(command_str);
1299 if (ret.first != 0) {
1300 if (from_format < LYX_FORMAT) {
1301 Alert::error(_("Conversion script failed"),
1302 bformat(_("%1$s is from an older version"
1303 " of LyX and the lyx2lyx script"
1304 " failed to convert it."),
1305 from_utf8(fn.absFileName())));
1306 return LyX2LyXOlderFormat;
1308 Alert::error(_("Conversion script failed"),
1309 bformat(_("%1$s is from a newer version"
1310 " of LyX and the lyx2lyx script"
1311 " failed to convert it."),
1312 from_utf8(fn.absFileName())));
1313 return LyX2LyXNewerFormat;
1320 FileName Buffer::getBackupName() const {
1321 FileName const & fn = fileName();
1322 string const fname = fn.onlyFileNameWithoutExt();
1323 string const fext = fn.extension() + "~";
1324 string const fpath = lyxrc.backupdir_path.empty() ?
1325 fn.onlyPath().absFileName() :
1326 lyxrc.backupdir_path;
1327 string const fform = convert<string>(d->file_format);
1328 string const backname = fname + "-lyxformat-" + fform;
1329 FileName backup(addName(fpath, addExtension(backname, fext)));
1331 // limit recursion, just in case
1333 unsigned long orig_checksum = 0;
1334 while (backup.exists() && v < 100) {
1335 if (orig_checksum == 0)
1336 orig_checksum = fn.checksum();
1337 unsigned long new_checksum = backup.checksum();
1338 if (orig_checksum == new_checksum) {
1339 LYXERR(Debug::FILES, "Not backing up " << fn <<
1340 "since " << backup << "has the same checksum.");
1341 // a bit of a hack, but we have to check this anyway
1342 // below, and setting this is simpler than introducing
1343 // a special boolean for this purpose.
1347 string const newbackname = backname + "-" + convert<string>(v);
1348 backup.set(addName(fpath, addExtension(newbackname, fext)));
1351 return v < 100 ? backup : FileName();
1355 // Should probably be moved to somewhere else: BufferView? GuiView?
1356 bool Buffer::save() const
1358 docstring const file = makeDisplayPath(absFileName(), 20);
1359 d->filename.refresh();
1361 // check the read-only status before moving the file as a backup
1362 if (d->filename.exists()) {
1363 bool const read_only = !d->filename.isWritable();
1365 Alert::warning(_("File is read-only"),
1366 bformat(_("The file %1$s cannot be written because it "
1367 "is marked as read-only."), file));
1372 // ask if the disk file has been externally modified (use checksum method)
1373 if (fileName().exists() && isExternallyModified(checksum_method)) {
1375 bformat(_("Document %1$s has been externally modified. "
1376 "Are you sure you want to overwrite this file?"), file);
1377 int const ret = Alert::prompt(_("Overwrite modified file?"),
1378 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1383 // We don't need autosaves in the immediate future. (Asger)
1384 resetAutosaveTimers();
1386 // if the file does not yet exist, none of the backup activity
1387 // that follows is necessary
1388 if (!fileName().exists()) {
1389 if (!writeFile(fileName()))
1395 // we first write the file to a new name, then move it to its
1396 // proper location once that has been done successfully. that
1397 // way we preserve the original file if something goes wrong.
1398 string const justname = fileName().onlyFileNameWithoutExt();
1399 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1400 justname + "-XXXXXX.lyx");
1401 bool const symlink = fileName().isSymLink();
1403 tempfile->setAutoRemove(false);
1405 FileName savefile(tempfile->name());
1406 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1407 if (!writeFile(savefile))
1410 // we will set this to false if we fail
1411 bool made_backup = true;
1413 FileName backupName;
1414 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1416 if (d->need_format_backup)
1417 backupName = getBackupName();
1419 // If we for some reason failed to find a backup name in case of
1420 // a format change, this will still set one. It's the best we can
1422 if (backupName.empty()) {
1423 backupName.set(fileName().absFileName() + "~");
1424 if (!lyxrc.backupdir_path.empty()) {
1425 string const mangledName =
1426 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1427 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1431 LYXERR(Debug::FILES, "Backing up original file to " <<
1432 backupName.absFileName());
1433 // Except file is symlink do not copy because of #6587.
1434 // Hard links have bad luck.
1435 made_backup = symlink ?
1436 fileName().copyTo(backupName):
1437 fileName().moveTo(backupName);
1440 Alert::error(_("Backup failure"),
1441 bformat(_("Cannot create backup file %1$s.\n"
1442 "Please check whether the directory exists and is writable."),
1443 from_utf8(backupName.absFileName())));
1444 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1445 } else if (d->need_format_backup) {
1446 // the original file has been backed up successfully, so we
1447 // will not need to do that again
1448 d->need_format_backup = false;
1452 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1453 // Only do this if tempfile is not in autoremove mode
1456 // If we have no symlink, we can simply rename the temp file.
1457 // Otherwise, we need to copy it so the symlink stays intact.
1458 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1459 savefile.moveTo(fileName()))
1461 // saveCheckSum() was already called by writeFile(), but the
1462 // time stamp is invalidated by copying/moving
1465 if (d->file_format != LYX_FORMAT)
1466 // the file associated with this buffer is now in the current format
1467 d->file_format = LYX_FORMAT;
1470 // else we saved the file, but failed to move it to the right location.
1472 if (needBackup && made_backup && !symlink) {
1473 // the original file was moved to some new location, so it will look
1474 // to the user as if it was deleted. (see bug #9234.) we could try
1475 // to restore it, but that would basically mean trying to do again
1476 // what we just failed to do. better to leave things as they are.
1477 Alert::error(_("Write failure"),
1478 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1479 "But LyX could not move it to:\n %2$s.\n"
1480 "Your original file has been backed up to:\n %3$s"),
1481 from_utf8(savefile.absFileName()),
1482 from_utf8(fileName().absFileName()),
1483 from_utf8(backupName.absFileName())));
1485 // either we did not try to make a backup, or else we tried and failed,
1486 // or else the original file was a symlink, in which case it was copied,
1487 // not moved. so the original file is intact.
1488 Alert::error(_("Write failure"),
1489 bformat(_("Cannot move saved file to:\n %1$s.\n"
1490 "But the file has successfully been saved as:\n %2$s."),
1491 from_utf8(fileName().absFileName()),
1492 from_utf8(savefile.absFileName())));
1498 bool Buffer::writeFile(FileName const & fname) const
1500 if (d->read_only && fname == d->filename)
1503 bool retval = false;
1505 docstring const str = bformat(_("Saving document %1$s..."),
1506 makeDisplayPath(fname.absFileName()));
1509 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1511 if (params().compressed) {
1512 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1513 retval = ofs && write(ofs);
1515 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1516 retval = ofs && write(ofs);
1520 message(str + _(" could not write file!"));
1525 // removeAutosaveFile();
1528 message(str + _(" done."));
1534 docstring Buffer::emergencyWrite()
1536 // No need to save if the buffer has not changed.
1540 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1542 docstring user_message = bformat(
1543 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1545 // We try to save three places:
1546 // 1) Same place as document. Unless it is an unnamed doc.
1548 string s = absFileName();
1551 if (writeFile(FileName(s))) {
1553 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1554 return user_message;
1556 user_message += " " + _("Save failed! Trying again...\n");
1560 // 2) In HOME directory.
1561 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1563 lyxerr << ' ' << s << endl;
1564 if (writeFile(FileName(s))) {
1566 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1567 return user_message;
1570 user_message += " " + _("Save failed! Trying yet again...\n");
1572 // 3) In "/tmp" directory.
1573 // MakeAbsPath to prepend the current
1574 // drive letter on OS/2
1575 s = addName(package().temp_dir().absFileName(), absFileName());
1577 lyxerr << ' ' << s << endl;
1578 if (writeFile(FileName(s))) {
1580 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1581 return user_message;
1584 user_message += " " + _("Save failed! Bummer. Document is lost.");
1587 return user_message;
1591 bool Buffer::write(ostream & ofs) const
1594 // Use the standard "C" locale for file output.
1595 ofs.imbue(locale::classic());
1598 // The top of the file should not be written by params().
1600 // write out a comment in the top of the file
1601 // Important: Keep the version formatting in sync with lyx2lyx and
1602 // tex2lyx (bug 7951)
1603 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1604 << " created this file. For more info see http://www.lyx.org/\n"
1605 << "\\lyxformat " << LYX_FORMAT << "\n"
1606 << "\\begin_document\n";
1608 /// For each author, set 'used' to true if there is a change
1609 /// by this author in the document; otherwise set it to 'false'.
1610 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1611 AuthorList::Authors::const_iterator a_end = params().authors().end();
1612 for (; a_it != a_end; ++a_it)
1613 a_it->setUsed(false);
1615 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1616 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1617 for ( ; it != end; ++it)
1618 it->checkAuthors(params().authors());
1620 // now write out the buffer parameters.
1621 ofs << "\\begin_header\n";
1622 params().writeFile(ofs, this);
1623 ofs << "\\end_header\n";
1626 ofs << "\n\\begin_body\n";
1628 ofs << "\n\\end_body\n";
1630 // Write marker that shows file is complete
1631 ofs << "\\end_document" << endl;
1633 // Shouldn't really be needed....
1636 // how to check if close went ok?
1637 // Following is an attempt... (BE 20001011)
1639 // good() returns false if any error occurred, including some
1640 // formatting error.
1641 // bad() returns true if something bad happened in the buffer,
1642 // which should include file system full errors.
1647 lyxerr << "File was not closed properly." << endl;
1654 bool Buffer::makeLaTeXFile(FileName const & fname,
1655 string const & original_path,
1656 OutputParams const & runparams_in,
1657 OutputWhat output) const
1659 OutputParams runparams = runparams_in;
1661 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1662 // Check here, because the "flavor" is not known in BufferParams::encoding()
1663 // (power users can override this safety measure selecting "utf8-plain").
1664 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1665 && (runparams.encoding->name() != "utf8-plain"))
1666 runparams.encoding = encodings.fromLyXName("ascii");
1668 string const encoding = runparams.encoding->iconvName();
1669 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1672 try { ofs.reset(encoding); }
1673 catch (iconv_codecvt_facet_exception const & e) {
1674 lyxerr << "Caught iconv exception: " << e.what() << endl;
1675 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1676 "verify that the support software for your encoding (%1$s) is "
1677 "properly installed"), from_ascii(encoding)));
1680 if (!openFileWrite(ofs, fname))
1683 ErrorList & errorList = d->errorLists["Export"];
1685 bool failed_export = false;
1688 // make sure we are ready to export
1689 // this needs to be done before we validate
1690 // FIXME Do we need to do this all the time? I.e., in children
1691 // of a master we are exporting?
1693 updateMacroInstances(OutputUpdate);
1696 writeLaTeXSource(os, original_path, runparams, output);
1698 catch (EncodingException const & e) {
1699 docstring const failed(1, e.failed_char);
1701 oss << "0x" << hex << e.failed_char << dec;
1702 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1703 " (code point %2$s)"),
1704 failed, from_utf8(oss.str()));
1705 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1706 "representable in the chosen encoding.\n"
1707 "Changing the document encoding to utf8 could help."),
1708 {e.par_id, e.pos}, {e.par_id, e.pos + 1}));
1709 failed_export = true;
1711 catch (iconv_codecvt_facet_exception const & e) {
1712 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1714 failed_export = true;
1716 catch (exception const & e) {
1717 errorList.push_back(ErrorItem(_("conversion failed"),
1719 failed_export = true;
1722 lyxerr << "Caught some really weird exception..." << endl;
1726 d->texrow = move(os.texrow());
1730 failed_export = true;
1731 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1734 if (runparams_in.silent)
1738 return !failed_export;
1742 void Buffer::writeLaTeXSource(otexstream & os,
1743 string const & original_path,
1744 OutputParams const & runparams_in,
1745 OutputWhat output) const
1747 // The child documents, if any, shall be already loaded at this point.
1749 OutputParams runparams = runparams_in;
1751 // XeTeX with TeX fonts is only safe with ASCII encoding,
1752 // Check here, because the "flavor" is not known in BufferParams::encoding()
1753 // (power users can override this safety measure selecting "utf8-plain").
1754 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1755 && (runparams.encoding->name() != "utf8-plain"))
1756 runparams.encoding = encodings.fromLyXName("ascii");
1757 // FIXME: when only the current paragraph is shown, this is ignored
1758 // (or not reached) and characters encodable in the current
1759 // encoding are not converted to ASCII-representation.
1761 // If we are compiling a file standalone, even if this is the
1762 // child of some other buffer, let's cut the link here, so the
1763 // file is really independent and no concurring settings from
1764 // the master (e.g. branch state) interfere (see #8100).
1765 if (!runparams.is_child)
1766 d->ignore_parent = true;
1768 // Classify the unicode characters appearing in math insets
1769 BufferEncodings::initUnicodeMath(*this);
1771 // validate the buffer.
1772 LYXERR(Debug::LATEX, " Validating buffer...");
1773 LaTeXFeatures features(*this, params(), runparams);
1775 // This is only set once per document (in master)
1776 if (!runparams.is_child)
1777 runparams.use_polyglossia = features.usePolyglossia();
1778 LYXERR(Debug::LATEX, " Buffer validation done.");
1780 bool const output_preamble =
1781 output == FullSource || output == OnlyPreamble;
1782 bool const output_body =
1783 output == FullSource || output == OnlyBody;
1785 // The starting paragraph of the coming rows is the
1786 // first paragraph of the document. (Asger)
1787 if (output_preamble && runparams.nice) {
1788 os << "%% LyX " << lyx_version << " created this file. "
1789 "For more info, see http://www.lyx.org/.\n"
1790 "%% Do not edit unless you really know what "
1793 LYXERR(Debug::INFO, "lyx document header finished");
1795 // There are a few differences between nice LaTeX and usual files:
1796 // usual files have \batchmode and special input@path to allow
1797 // inclusion of figures specified by an explicitly relative path
1798 // (i.e., a path starting with './' or '../') with either \input or
1799 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1800 // input@path is set when the actual parameter original_path is set.
1801 // This is done for usual tex-file, but not for nice-latex-file.
1802 // (Matthias 250696)
1803 // Note that input@path is only needed for something the user does
1804 // in the preamble, included .tex files or ERT, files included by
1805 // LyX work without it.
1806 if (output_preamble) {
1807 if (!runparams.nice) {
1808 // code for usual, NOT nice-latex-file
1809 os << "\\batchmode\n"; // changed from \nonstopmode
1811 if (!original_path.empty()) {
1813 // We don't know the encoding of inputpath
1814 docstring const inputpath = from_utf8(original_path);
1815 docstring uncodable_glyphs;
1816 Encoding const * const enc = runparams.encoding;
1818 for (size_t n = 0; n < inputpath.size(); ++n) {
1819 if (!enc->encodable(inputpath[n])) {
1820 docstring const glyph(1, inputpath[n]);
1821 LYXERR0("Uncodable character '"
1823 << "' in input path!");
1824 uncodable_glyphs += glyph;
1829 // warn user if we found uncodable glyphs.
1830 if (!uncodable_glyphs.empty()) {
1831 frontend::Alert::warning(
1832 _("Uncodable character in file path"),
1834 _("The path of your document\n"
1836 "contains glyphs that are unknown "
1837 "in the current document encoding "
1838 "(namely %2$s). This may result in "
1839 "incomplete output, unless "
1840 "TEXINPUTS contains the document "
1841 "directory and you don't use "
1842 "explicitly relative paths (i.e., "
1843 "paths starting with './' or "
1844 "'../') in the preamble or in ERT."
1845 "\n\nIn case of problems, choose "
1846 "an appropriate document encoding\n"
1847 "(such as utf8) or change the "
1849 inputpath, uncodable_glyphs));
1852 support::latex_path(original_path);
1853 if (contains(docdir, '#')) {
1854 docdir = subst(docdir, "#", "\\#");
1855 os << "\\catcode`\\#=11"
1856 "\\def\\#{#}\\catcode`\\#=6\n";
1858 if (contains(docdir, '%')) {
1859 docdir = subst(docdir, "%", "\\%");
1860 os << "\\catcode`\\%=11"
1861 "\\def\\%{%}\\catcode`\\%=14\n";
1863 os << "\\makeatletter\n"
1864 << "\\def\\input@path{{"
1866 << "\\makeatother\n";
1870 // get parent macros (if this buffer has a parent) which will be
1871 // written at the document begin further down.
1872 MacroSet parentMacros;
1873 listParentMacros(parentMacros, features);
1875 // Write the preamble
1876 runparams.use_babel = params().writeLaTeX(os, features,
1877 d->filename.onlyPath());
1879 if (!runparams.dryrun && features.hasPolyglossiaExclusiveLanguages()
1880 && !features.hasOnlyPolyglossiaLanguages()) {
1883 vector<string> bll = features.getBabelExclusiveLanguages();
1884 vector<string> pll = features.getPolyglossiaExclusiveLanguages();
1887 for (vector<string>::const_iterator it = bll.begin(); it != bll.end(); ++it) {
1892 blangs = bll.size() > 1 ?
1893 support::bformat(_("The languages %1$s are only supported by Babel."), langs)
1894 : support::bformat(_("The language %1$s is only supported by Babel."), langs);
1898 for (vector<string>::const_iterator it = pll.begin(); it != pll.end(); ++it) {
1903 plangs = pll.size() > 1 ?
1904 support::bformat(_("The languages %1$s are only supported by Polyglossia."), langs)
1905 : support::bformat(_("The language %1$s is only supported by Polyglossia."), langs);
1906 if (!blangs.empty())
1910 frontend::Alert::warning(
1911 _("Incompatible Languages!"),
1913 _("You cannot use the following languages "
1914 "together in one LaTeX document because "
1915 "they require conflicting language packages:\n"
1920 // Japanese might be required only in some children of a document,
1921 // but once required, we must keep use_japanese true.
1922 runparams.use_japanese |= features.isRequired("japanese");
1925 // Restore the parenthood if needed
1926 if (!runparams.is_child)
1927 d->ignore_parent = false;
1932 // mark the beginning of the body to separate it from InPreamble insets
1933 os.texrow().start(TexRow::beginDocument());
1934 os << "\\begin{document}\n";
1936 // mark the start of a new paragraph by simulating a newline,
1937 // so that os.afterParbreak() returns true at document start
1940 // output the parent macros
1941 MacroSet::iterator it = parentMacros.begin();
1942 MacroSet::iterator end = parentMacros.end();
1943 for (; it != end; ++it) {
1944 int num_lines = (*it)->write(os.os(), true);
1945 os.texrow().newlines(num_lines);
1948 } // output_preamble
1950 LYXERR(Debug::INFO, "preamble finished, now the body.");
1953 latexParagraphs(*this, text(), os, runparams);
1955 // Restore the parenthood if needed
1956 if (!runparams.is_child)
1957 d->ignore_parent = false;
1959 // add this just in case after all the paragraphs
1962 if (output_preamble) {
1963 os << "\\end{document}\n";
1964 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1966 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1968 runparams_in.encoding = runparams.encoding;
1970 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1971 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1975 void Buffer::makeDocBookFile(FileName const & fname,
1976 OutputParams const & runparams,
1977 OutputWhat output) const
1979 LYXERR(Debug::LATEX, "makeDocBookFile...");
1982 if (!openFileWrite(ofs, fname))
1985 // make sure we are ready to export
1986 // this needs to be done before we validate
1988 updateMacroInstances(OutputUpdate);
1990 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1994 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1998 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1999 OutputParams const & runparams,
2000 OutputWhat output) const
2002 LaTeXFeatures features(*this, params(), runparams);
2007 DocumentClass const & tclass = params().documentClass();
2008 string const & top_element = tclass.latexname();
2010 bool const output_preamble =
2011 output == FullSource || output == OnlyPreamble;
2012 bool const output_body =
2013 output == FullSource || output == OnlyBody;
2015 if (output_preamble) {
2016 if (runparams.flavor == OutputParams::XML)
2017 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2020 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
2023 if (! tclass.class_header().empty())
2024 os << from_ascii(tclass.class_header());
2025 else if (runparams.flavor == OutputParams::XML)
2026 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
2027 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
2029 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
2031 docstring preamble = params().preamble;
2032 if (runparams.flavor != OutputParams::XML ) {
2033 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
2034 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
2035 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
2036 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
2039 string const name = runparams.nice
2040 ? changeExtension(absFileName(), ".sgml") : fname;
2041 preamble += features.getIncludedFiles(name);
2042 preamble += features.getLyXSGMLEntities();
2044 if (!preamble.empty()) {
2045 os << "\n [ " << preamble << " ]";
2051 string top = top_element;
2053 if (runparams.flavor == OutputParams::XML)
2054 top += params().language->code();
2056 top += params().language->code().substr(0, 2);
2059 if (!params().options.empty()) {
2061 top += params().options;
2064 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2065 << " file was created by LyX " << lyx_version
2066 << "\n See http://www.lyx.org/ for more information -->\n";
2068 params().documentClass().counters().reset();
2070 sgml::openTag(os, top);
2072 docbookParagraphs(text(), *this, os, runparams);
2073 sgml::closeTag(os, top_element);
2078 void Buffer::makeLyXHTMLFile(FileName const & fname,
2079 OutputParams const & runparams) const
2081 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2084 if (!openFileWrite(ofs, fname))
2087 // make sure we are ready to export
2088 // this has to be done before we validate
2089 updateBuffer(UpdateMaster, OutputUpdate);
2090 updateMacroInstances(OutputUpdate);
2092 writeLyXHTMLSource(ofs, runparams, FullSource);
2096 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2100 void Buffer::writeLyXHTMLSource(odocstream & os,
2101 OutputParams const & runparams,
2102 OutputWhat output) const
2104 LaTeXFeatures features(*this, params(), runparams);
2106 d->bibinfo_.makeCitationLabels(*this);
2108 bool const output_preamble =
2109 output == FullSource || output == OnlyPreamble;
2110 bool const output_body =
2111 output == FullSource || output == OnlyBody || output == IncludedFile;
2113 if (output_preamble) {
2114 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2115 << "<!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"
2116 // FIXME Language should be set properly.
2117 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2119 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2120 // FIXME Presumably need to set this right
2121 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2123 docstring const & doctitle = features.htmlTitle();
2125 << (doctitle.empty() ?
2126 from_ascii("LyX Document") :
2127 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2130 docstring styles = features.getTClassHTMLPreamble();
2131 if (!styles.empty())
2132 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2134 styles = features.getPreambleSnippets().str;
2135 if (!styles.empty())
2136 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2138 // we will collect CSS information in a stream, and then output it
2139 // either here, as part of the header, or else in a separate file.
2140 odocstringstream css;
2141 styles = features.getCSSSnippets();
2142 if (!styles.empty())
2143 css << "/* LyX Provided Styles */\n" << styles << '\n';
2145 styles = features.getTClassHTMLStyles();
2146 if (!styles.empty())
2147 css << "/* Layout-provided Styles */\n" << styles << '\n';
2149 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2150 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2151 if (needfg || needbg) {
2152 css << "\nbody {\n";
2155 << from_ascii(X11hexname(params().fontcolor))
2158 css << " background-color: "
2159 << from_ascii(X11hexname(params().backgroundcolor))
2164 docstring const dstyles = css.str();
2165 if (!dstyles.empty()) {
2166 bool written = false;
2167 if (params().html_css_as_file) {
2168 // open a file for CSS info
2170 string const fcssname = addName(temppath(), "docstyle.css");
2171 FileName const fcssfile = FileName(fcssname);
2172 if (openFileWrite(ocss, fcssfile)) {
2176 // write link to header
2177 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2179 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2182 // we are here if the CSS is supposed to be written to the header
2183 // or if we failed to write it to an external file.
2185 os << "<style type='text/css'>\n"
2194 bool const output_body_tag = (output != IncludedFile);
2195 if (output_body_tag)
2196 os << "<body dir=\"auto\">\n";
2198 if (output != IncludedFile)
2199 // if we're an included file, the counters are in the master.
2200 params().documentClass().counters().reset();
2201 xhtmlParagraphs(text(), *this, xs, runparams);
2202 if (output_body_tag)
2206 if (output_preamble)
2211 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2212 // Other flags: -wall -v0 -x
2213 int Buffer::runChktex()
2217 // get LaTeX-Filename
2218 FileName const path(temppath());
2219 string const name = addName(path.absFileName(), latexName());
2220 string const org_path = filePath();
2222 PathChanger p(path); // path to LaTeX file
2223 message(_("Running chktex..."));
2225 // Generate the LaTeX file if neccessary
2226 OutputParams runparams(¶ms().encoding());
2227 runparams.flavor = OutputParams::LATEX;
2228 runparams.nice = false;
2229 runparams.linelen = lyxrc.plaintext_linelen;
2230 makeLaTeXFile(FileName(name), org_path, runparams);
2233 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2234 int const res = chktex.run(terr); // run chktex
2237 Alert::error(_("chktex failure"),
2238 _("Could not run chktex successfully."));
2240 ErrorList & errlist = d->errorLists["ChkTeX"];
2242 bufferErrors(terr, errlist);
2247 if (runparams.silent)
2248 d->errorLists["ChkTeX"].clear();
2256 void Buffer::validate(LaTeXFeatures & features) const
2258 // Validate the buffer params, but not for included
2259 // files, since they also use the parent buffer's
2261 if (!features.runparams().is_child)
2262 params().validate(features);
2264 for (Paragraph const & p : paragraphs())
2265 p.validate(features);
2267 if (lyxerr.debugging(Debug::LATEX)) {
2268 features.showStruct();
2273 void Buffer::getLabelList(vector<docstring> & list) const
2275 // If this is a child document, use the master's list instead.
2277 masterBuffer()->getLabelList(list);
2282 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2283 Toc::const_iterator toc_it = toc->begin();
2284 Toc::const_iterator end = toc->end();
2285 for (; toc_it != end; ++toc_it) {
2286 if (toc_it->depth() == 0)
2287 list.push_back(toc_it->str());
2292 void Buffer::updateBibfilesCache(UpdateScope scope) const
2294 // FIXME This is probably unnecssary, given where we call this.
2295 // If this is a child document, use the parent's cache instead.
2296 if (parent() && scope != UpdateChildOnly) {
2297 masterBuffer()->updateBibfilesCache();
2301 d->bibfiles_cache_.clear();
2302 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2303 if (it->lyxCode() == BIBTEX_CODE) {
2304 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2305 support::FileNameList const bibfiles = inset.getBibFiles();
2306 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2309 } else if (it->lyxCode() == INCLUDE_CODE) {
2310 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2311 Buffer const * const incbuf = inset.getChildBuffer();
2314 support::FileNameList const & bibfiles =
2315 incbuf->getBibfilesCache(UpdateChildOnly);
2316 if (!bibfiles.empty()) {
2317 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2323 d->bibfile_cache_valid_ = true;
2324 d->bibinfo_cache_valid_ = false;
2325 d->cite_labels_valid_ = false;
2329 void Buffer::invalidateBibinfoCache() const
2331 d->bibinfo_cache_valid_ = false;
2332 d->cite_labels_valid_ = false;
2333 // also invalidate the cache for the parent buffer
2334 Buffer const * const pbuf = d->parent();
2336 pbuf->invalidateBibinfoCache();
2340 void Buffer::invalidateBibfileCache() const
2342 d->bibfile_cache_valid_ = false;
2343 d->bibinfo_cache_valid_ = false;
2344 d->cite_labels_valid_ = false;
2345 // also invalidate the cache for the parent buffer
2346 Buffer const * const pbuf = d->parent();
2348 pbuf->invalidateBibfileCache();
2352 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2354 // FIXME This is probably unnecessary, given where we call this.
2355 // If this is a child document, use the master's cache instead.
2356 Buffer const * const pbuf = masterBuffer();
2357 if (pbuf != this && scope != UpdateChildOnly)
2358 return pbuf->getBibfilesCache();
2360 if (!d->bibfile_cache_valid_)
2361 this->updateBibfilesCache(scope);
2363 return d->bibfiles_cache_;
2367 BiblioInfo const & Buffer::masterBibInfo() const
2369 Buffer const * const tmp = masterBuffer();
2371 return tmp->masterBibInfo();
2376 void Buffer::checkIfBibInfoCacheIsValid() const
2378 // use the master's cache
2379 Buffer const * const tmp = masterBuffer();
2381 tmp->checkIfBibInfoCacheIsValid();
2385 // compare the cached timestamps with the actual ones.
2386 FileNameList const & bibfiles_cache = getBibfilesCache();
2387 FileNameList::const_iterator ei = bibfiles_cache.begin();
2388 FileNameList::const_iterator en = bibfiles_cache.end();
2389 for (; ei != en; ++ ei) {
2390 time_t lastw = ei->lastModified();
2391 time_t prevw = d->bibfile_status_[*ei];
2392 if (lastw != prevw) {
2393 d->bibinfo_cache_valid_ = false;
2394 d->cite_labels_valid_ = false;
2395 d->bibfile_status_[*ei] = lastw;
2401 void Buffer::reloadBibInfoCache() const
2403 // use the master's cache
2404 Buffer const * const tmp = masterBuffer();
2406 tmp->reloadBibInfoCache();
2410 checkIfBibInfoCacheIsValid();
2411 if (d->bibinfo_cache_valid_)
2414 d->bibinfo_.clear();
2416 d->bibinfo_cache_valid_ = true;
2420 void Buffer::collectBibKeys() const
2422 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2423 it->collectBibKeys(it);
2427 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2429 Buffer const * tmp = masterBuffer();
2430 BiblioInfo & masterbi = (tmp == this) ?
2431 d->bibinfo_ : tmp->d->bibinfo_;
2432 masterbi.mergeBiblioInfo(bi);
2436 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2438 Buffer const * tmp = masterBuffer();
2439 BiblioInfo & masterbi = (tmp == this) ?
2440 d->bibinfo_ : tmp->d->bibinfo_;
2445 void Buffer::makeCitationLabels() const
2447 Buffer const * const master = masterBuffer();
2448 return d->bibinfo_.makeCitationLabels(*master);
2452 bool Buffer::citeLabelsValid() const
2454 return masterBuffer()->d->cite_labels_valid_;
2458 void Buffer::removeBiblioTempFiles() const
2460 // We remove files that contain LaTeX commands specific to the
2461 // particular bibliographic style being used, in order to avoid
2462 // LaTeX errors when we switch style.
2463 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2464 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2465 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2466 aux_file.removeFile();
2467 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2468 bbl_file.removeFile();
2469 // Also for the parent buffer
2470 Buffer const * const pbuf = parent();
2472 pbuf->removeBiblioTempFiles();
2476 bool Buffer::isDepClean(string const & name) const
2478 DepClean::const_iterator const it = d->dep_clean.find(name);
2479 if (it == d->dep_clean.end())
2485 void Buffer::markDepClean(string const & name)
2487 d->dep_clean[name] = true;
2491 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2494 // FIXME? if there is an Buffer LFUN that can be dispatched even
2495 // if internal, put a switch '(cmd.action)' here.
2501 switch (cmd.action()) {
2503 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2504 flag.setOnOff(isReadonly());
2507 // FIXME: There is need for a command-line import.
2508 //case LFUN_BUFFER_IMPORT:
2510 case LFUN_BUFFER_AUTO_SAVE:
2513 case LFUN_BUFFER_EXPORT_CUSTOM:
2514 // FIXME: Nothing to check here?
2517 case LFUN_BUFFER_EXPORT: {
2518 docstring const arg = cmd.argument();
2519 if (arg == "custom") {
2523 string format = to_utf8(arg);
2524 size_t pos = format.find(' ');
2525 if (pos != string::npos)
2526 format = format.substr(0, pos);
2527 enable = params().isExportable(format, false);
2529 flag.message(bformat(
2530 _("Don't know how to export to format: %1$s"), arg));
2534 case LFUN_BUFFER_CHKTEX:
2535 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2538 case LFUN_BUILD_PROGRAM:
2539 enable = params().isExportable("program", false);
2542 case LFUN_BRANCH_ACTIVATE:
2543 case LFUN_BRANCH_DEACTIVATE:
2544 case LFUN_BRANCH_MASTER_ACTIVATE:
2545 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2546 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2547 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2548 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2549 : params().branchlist();
2550 docstring const branchName = cmd.argument();
2551 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2555 case LFUN_BRANCH_ADD:
2556 case LFUN_BRANCHES_RENAME:
2557 // if no Buffer is present, then of course we won't be called!
2560 case LFUN_BUFFER_LANGUAGE:
2561 enable = !isReadonly();
2564 case LFUN_BUFFER_VIEW_CACHE:
2565 (d->preview_file_).refresh();
2566 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2569 case LFUN_CHANGES_TRACK:
2570 flag.setEnabled(true);
2571 flag.setOnOff(params().track_changes);
2574 case LFUN_CHANGES_OUTPUT:
2575 flag.setEnabled(true);
2576 flag.setOnOff(params().output_changes);
2579 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2580 flag.setOnOff(params().compressed);
2584 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2585 flag.setOnOff(params().output_sync);
2592 flag.setEnabled(enable);
2597 void Buffer::dispatch(string const & command, DispatchResult & result)
2599 return dispatch(lyxaction.lookupFunc(command), result);
2603 // NOTE We can end up here even if we have no GUI, because we are called
2604 // by LyX::exec to handled command-line requests. So we may need to check
2605 // whether we have a GUI or not. The boolean use_gui holds this information.
2606 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2609 // FIXME? if there is an Buffer LFUN that can be dispatched even
2610 // if internal, put a switch '(cmd.action())' here.
2611 dr.dispatched(false);
2614 string const argument = to_utf8(func.argument());
2615 // We'll set this back to false if need be.
2616 bool dispatched = true;
2617 undo().beginUndoGroup();
2619 switch (func.action()) {
2620 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2621 if (lyxvc().inUse()) {
2622 string log = lyxvc().toggleReadOnly();
2627 setReadonly(!isReadonly());
2630 case LFUN_BUFFER_EXPORT: {
2631 ExportStatus const status = doExport(argument, false);
2632 dr.setError(status != ExportSuccess);
2633 if (status != ExportSuccess)
2634 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2639 case LFUN_BUILD_PROGRAM: {
2640 ExportStatus const status = doExport("program", true);
2641 dr.setError(status != ExportSuccess);
2642 if (status != ExportSuccess)
2643 dr.setMessage(_("Error generating literate programming code."));
2647 case LFUN_BUFFER_CHKTEX:
2651 case LFUN_BUFFER_EXPORT_CUSTOM: {
2653 string command = split(argument, format_name, ' ');
2654 Format const * format = formats.getFormat(format_name);
2656 lyxerr << "Format \"" << format_name
2657 << "\" not recognized!"
2662 // The name of the file created by the conversion process
2665 // Output to filename
2666 if (format->name() == "lyx") {
2667 string const latexname = latexName(false);
2668 filename = changeExtension(latexname,
2669 format->extension());
2670 filename = addName(temppath(), filename);
2672 if (!writeFile(FileName(filename)))
2676 doExport(format_name, true, filename);
2679 // Substitute $$FName for filename
2680 if (!contains(command, "$$FName"))
2681 command = "( " + command + " ) < $$FName";
2682 command = subst(command, "$$FName", filename);
2684 // Execute the command in the background
2686 call.startscript(Systemcall::DontWait, command,
2687 filePath(), layoutPos());
2691 // FIXME: There is need for a command-line import.
2693 case LFUN_BUFFER_IMPORT:
2698 case LFUN_BUFFER_AUTO_SAVE:
2700 resetAutosaveTimers();
2703 case LFUN_BRANCH_ACTIVATE:
2704 case LFUN_BRANCH_DEACTIVATE:
2705 case LFUN_BRANCH_MASTER_ACTIVATE:
2706 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2707 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2708 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2709 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2712 docstring const branch_name = func.argument();
2713 // the case without a branch name is handled elsewhere
2714 if (branch_name.empty()) {
2718 Branch * branch = buf->params().branchlist().find(branch_name);
2720 LYXERR0("Branch " << branch_name << " does not exist.");
2722 docstring const msg =
2723 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2727 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2728 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2729 if (branch->isSelected() != activate) {
2730 buf->undo().recordUndoBufferParams(CursorData());
2731 branch->setSelected(activate);
2733 dr.screenUpdate(Update::Force);
2734 dr.forceBufferUpdate();
2739 case LFUN_BRANCH_ADD: {
2740 docstring branch_name = func.argument();
2741 if (branch_name.empty()) {
2745 BranchList & branch_list = params().branchlist();
2746 vector<docstring> const branches =
2747 getVectorFromString(branch_name, branch_list.separator());
2749 for (vector<docstring>::const_iterator it = branches.begin();
2750 it != branches.end(); ++it) {
2752 Branch * branch = branch_list.find(branch_name);
2754 LYXERR0("Branch " << branch_name << " already exists.");
2758 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2760 undo().recordUndoBufferParams(CursorData());
2761 branch_list.add(branch_name);
2762 branch = branch_list.find(branch_name);
2763 string const x11hexname = X11hexname(branch->color());
2764 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2765 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2767 dr.screenUpdate(Update::Force);
2775 case LFUN_BRANCHES_RENAME: {
2776 if (func.argument().empty())
2779 docstring const oldname = from_utf8(func.getArg(0));
2780 docstring const newname = from_utf8(func.getArg(1));
2781 InsetIterator it = inset_iterator_begin(inset());
2782 InsetIterator const end = inset_iterator_end(inset());
2783 bool success = false;
2784 for (; it != end; ++it) {
2785 if (it->lyxCode() == BRANCH_CODE) {
2786 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2787 if (ins.branch() == oldname) {
2788 undo().recordUndo(CursorData(it));
2789 ins.rename(newname);
2794 if (it->lyxCode() == INCLUDE_CODE) {
2795 // get buffer of external file
2796 InsetInclude const & ins =
2797 static_cast<InsetInclude const &>(*it);
2798 Buffer * child = ins.getChildBuffer();
2801 child->dispatch(func, dr);
2806 dr.screenUpdate(Update::Force);
2807 dr.forceBufferUpdate();
2812 case LFUN_BUFFER_VIEW_CACHE:
2813 if (!formats.view(*this, d->preview_file_,
2814 d->preview_format_))
2815 dr.setMessage(_("Error viewing the output file."));
2818 case LFUN_CHANGES_TRACK:
2819 if (params().save_transient_properties)
2820 undo().recordUndoBufferParams(CursorData());
2821 params().track_changes = !params().track_changes;
2822 if (!params().track_changes)
2823 dr.forceChangesUpdate();
2826 case LFUN_CHANGES_OUTPUT:
2827 if (params().save_transient_properties)
2828 undo().recordUndoBufferParams(CursorData());
2829 params().output_changes = !params().output_changes;
2830 if (params().output_changes) {
2831 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2832 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2833 LaTeXFeatures::isAvailable("xcolor");
2835 if (!dvipost && !xcolorulem) {
2836 Alert::warning(_("Changes not shown in LaTeX output"),
2837 _("Changes will not be highlighted in LaTeX output, "
2838 "because neither dvipost nor xcolor/ulem are installed.\n"
2839 "Please install these packages or redefine "
2840 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2841 } else if (!xcolorulem) {
2842 Alert::warning(_("Changes not shown in LaTeX output"),
2843 _("Changes will not be highlighted in LaTeX output "
2844 "when using pdflatex, because xcolor and ulem are not installed.\n"
2845 "Please install both packages or redefine "
2846 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2851 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2852 // turn compression on/off
2853 undo().recordUndoBufferParams(CursorData());
2854 params().compressed = !params().compressed;
2857 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2858 undo().recordUndoBufferParams(CursorData());
2859 params().output_sync = !params().output_sync;
2866 dr.dispatched(dispatched);
2867 undo().endUndoGroup();
2871 void Buffer::changeLanguage(Language const * from, Language const * to)
2873 LASSERT(from, return);
2874 LASSERT(to, return);
2876 for_each(par_iterator_begin(),
2878 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2882 bool Buffer::isMultiLingual() const
2884 ParConstIterator end = par_iterator_end();
2885 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2886 if (it->isMultiLingual(params()))
2893 std::set<Language const *> Buffer::getLanguages() const
2895 std::set<Language const *> languages;
2896 getLanguages(languages);
2901 void Buffer::getLanguages(std::set<Language const *> & languages) const
2903 ParConstIterator end = par_iterator_end();
2904 // add the buffer language, even if it's not actively used
2905 languages.insert(language());
2906 // iterate over the paragraphs
2907 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2908 it->getLanguages(languages);
2910 ListOfBuffers clist = getDescendents();
2911 ListOfBuffers::const_iterator cit = clist.begin();
2912 ListOfBuffers::const_iterator const cen = clist.end();
2913 for (; cit != cen; ++cit)
2914 (*cit)->getLanguages(languages);
2918 DocIterator Buffer::getParFromID(int const id) const
2920 Buffer * buf = const_cast<Buffer *>(this);
2922 // This means non-existent
2923 return doc_iterator_end(buf);
2925 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2926 if (it.paragraph().id() == id)
2929 return doc_iterator_end(buf);
2933 bool Buffer::hasParWithID(int const id) const
2935 return !getParFromID(id).atEnd();
2939 ParIterator Buffer::par_iterator_begin()
2941 return ParIterator(doc_iterator_begin(this));
2945 ParIterator Buffer::par_iterator_end()
2947 return ParIterator(doc_iterator_end(this));
2951 ParConstIterator Buffer::par_iterator_begin() const
2953 return ParConstIterator(doc_iterator_begin(this));
2957 ParConstIterator Buffer::par_iterator_end() const
2959 return ParConstIterator(doc_iterator_end(this));
2963 Language const * Buffer::language() const
2965 return params().language;
2969 docstring const Buffer::B_(string const & l10n) const
2971 return params().B_(l10n);
2975 bool Buffer::isClean() const
2977 return d->lyx_clean;
2981 bool Buffer::isExternallyModified(CheckMethod method) const
2983 LASSERT(d->filename.exists(), return false);
2984 // if method == timestamp, check timestamp before checksum
2985 return (method == checksum_method
2986 || d->timestamp_ != d->filename.lastModified())
2987 && d->checksum_ != d->filename.checksum();
2991 void Buffer::saveCheckSum() const
2993 FileName const & file = d->filename;
2996 if (file.exists()) {
2997 d->timestamp_ = file.lastModified();
2998 d->checksum_ = file.checksum();
3000 // in the case of save to a new file.
3007 void Buffer::markClean() const
3009 if (!d->lyx_clean) {
3010 d->lyx_clean = true;
3013 // if the .lyx file has been saved, we don't need an
3015 d->bak_clean = true;
3016 d->undo_.markDirty();
3020 void Buffer::setUnnamed(bool flag)
3026 bool Buffer::isUnnamed() const
3033 /// Don't check unnamed, here: isInternal() is used in
3034 /// newBuffer(), where the unnamed flag has not been set by anyone
3035 /// yet. Also, for an internal buffer, there should be no need for
3036 /// retrieving fileName() nor for checking if it is unnamed or not.
3037 bool Buffer::isInternal() const
3039 return d->internal_buffer;
3043 void Buffer::setInternal(bool flag)
3045 d->internal_buffer = flag;
3049 void Buffer::markDirty()
3052 d->lyx_clean = false;
3055 d->bak_clean = false;
3057 DepClean::iterator it = d->dep_clean.begin();
3058 DepClean::const_iterator const end = d->dep_clean.end();
3060 for (; it != end; ++it)
3065 FileName Buffer::fileName() const
3071 string Buffer::absFileName() const
3073 return d->filename.absFileName();
3077 string Buffer::filePath() const
3079 string const abs = d->filename.onlyPath().absFileName();
3082 int last = abs.length() - 1;
3084 return abs[last] == '/' ? abs : abs + '/';
3088 DocFileName Buffer::getReferencedFileName(string const & fn) const
3091 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3092 result.set(fn, filePath());
3094 // filePath() ends with a path separator
3095 FileName const test(filePath() + fn);
3097 result.set(fn, filePath());
3099 result.set(fn, params().origin);
3106 string Buffer::layoutPos() const
3108 return d->layout_position;
3112 void Buffer::setLayoutPos(string const & path)
3115 d->layout_position.clear();
3119 LATTEST(FileName::isAbsolute(path));
3121 d->layout_position =
3122 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3124 if (d->layout_position.empty())
3125 d->layout_position = ".";
3129 bool Buffer::isReadonly() const
3131 return d->read_only;
3135 void Buffer::setParent(Buffer const * buffer)
3137 // Avoids recursive include.
3138 d->setParent(buffer == this ? 0 : buffer);
3143 Buffer const * Buffer::parent() const
3149 ListOfBuffers Buffer::allRelatives() const
3151 ListOfBuffers lb = masterBuffer()->getDescendents();
3152 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3157 Buffer const * Buffer::masterBuffer() const
3159 // FIXME Should be make sure we are not in some kind
3160 // of recursive include? A -> B -> A will crash this.
3161 Buffer const * const pbuf = d->parent();
3165 return pbuf->masterBuffer();
3169 bool Buffer::isChild(Buffer * child) const
3171 return d->children_positions.find(child) != d->children_positions.end();
3175 DocIterator Buffer::firstChildPosition(Buffer const * child)
3177 Impl::BufferPositionMap::iterator it;
3178 it = d->children_positions.find(child);
3179 if (it == d->children_positions.end())
3180 return DocIterator(this);
3185 bool Buffer::hasChildren() const
3187 return !d->children_positions.empty();
3191 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3193 // loop over children
3194 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3195 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3196 for (; it != end; ++it) {
3197 Buffer * child = const_cast<Buffer *>(it->first);
3199 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3200 if (bit != clist.end())
3202 clist.push_back(child);
3204 // there might be grandchildren
3205 child->collectChildren(clist, true);
3210 ListOfBuffers Buffer::getChildren() const
3213 collectChildren(v, false);
3214 // Make sure we have not included ourselves.
3215 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3216 if (bit != v.end()) {
3217 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3224 ListOfBuffers Buffer::getDescendents() const
3227 collectChildren(v, true);
3228 // Make sure we have not included ourselves.
3229 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3230 if (bit != v.end()) {
3231 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3238 template<typename M>
3239 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3244 typename M::const_iterator it = m.lower_bound(x);
3245 if (it == m.begin())
3253 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3254 DocIterator const & pos) const
3256 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3258 // if paragraphs have no macro context set, pos will be empty
3262 // we haven't found anything yet
3263 DocIterator bestPos = owner_->par_iterator_begin();
3264 MacroData const * bestData = 0;
3266 // find macro definitions for name
3267 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3268 if (nameIt != macros.end()) {
3269 // find last definition in front of pos or at pos itself
3270 PositionScopeMacroMap::const_iterator it
3271 = greatest_below(nameIt->second, pos);
3272 if (it != nameIt->second.end()) {
3274 // scope ends behind pos?
3275 if (pos < it->second.scope) {
3276 // Looks good, remember this. If there
3277 // is no external macro behind this,
3278 // we found the right one already.
3279 bestPos = it->first;
3280 bestData = &it->second.macro;
3284 // try previous macro if there is one
3285 if (it == nameIt->second.begin())
3292 // find macros in included files
3293 PositionScopeBufferMap::const_iterator it
3294 = greatest_below(position_to_children, pos);
3295 if (it == position_to_children.end())
3296 // no children before
3300 // do we know something better (i.e. later) already?
3301 if (it->first < bestPos )
3304 // scope ends behind pos?
3305 if (pos < it->second.scope
3306 && (cloned_buffer_ ||
3307 theBufferList().isLoaded(it->second.buffer))) {
3308 // look for macro in external file
3310 MacroData const * data
3311 = it->second.buffer->getMacro(name, false);
3314 bestPos = it->first;
3320 // try previous file if there is one
3321 if (it == position_to_children.begin())
3326 // return the best macro we have found
3331 MacroData const * Buffer::getMacro(docstring const & name,
3332 DocIterator const & pos, bool global) const
3337 // query buffer macros
3338 MacroData const * data = d->getBufferMacro(name, pos);
3342 // If there is a master buffer, query that
3343 Buffer const * const pbuf = d->parent();
3345 d->macro_lock = true;
3346 MacroData const * macro = pbuf->getMacro(
3347 name, *this, false);
3348 d->macro_lock = false;
3354 data = MacroTable::globalMacros().get(name);
3363 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3365 // set scope end behind the last paragraph
3366 DocIterator scope = par_iterator_begin();
3367 scope.pit() = scope.lastpit() + 1;
3369 return getMacro(name, scope, global);
3373 MacroData const * Buffer::getMacro(docstring const & name,
3374 Buffer const & child, bool global) const
3376 // look where the child buffer is included first
3377 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3378 if (it == d->children_positions.end())
3381 // check for macros at the inclusion position
3382 return getMacro(name, it->second, global);
3386 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3388 pit_type const lastpit = it.lastpit();
3390 // look for macros in each paragraph
3391 while (it.pit() <= lastpit) {
3392 Paragraph & par = it.paragraph();
3394 // iterate over the insets of the current paragraph
3395 InsetList const & insets = par.insetList();
3396 InsetList::const_iterator iit = insets.begin();
3397 InsetList::const_iterator end = insets.end();
3398 for (; iit != end; ++iit) {
3399 it.pos() = iit->pos;
3401 // is it a nested text inset?
3402 if (iit->inset->asInsetText()) {
3403 // Inset needs its own scope?
3404 InsetText const * itext = iit->inset->asInsetText();
3405 bool newScope = itext->isMacroScope();
3407 // scope which ends just behind the inset
3408 DocIterator insetScope = it;
3411 // collect macros in inset
3412 it.push_back(CursorSlice(*iit->inset));
3413 updateMacros(it, newScope ? insetScope : scope);
3418 if (iit->inset->asInsetTabular()) {
3419 CursorSlice slice(*iit->inset);
3420 size_t const numcells = slice.nargs();
3421 for (; slice.idx() < numcells; slice.forwardIdx()) {
3422 it.push_back(slice);
3423 updateMacros(it, scope);
3429 // is it an external file?
3430 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3431 // get buffer of external file
3432 InsetInclude const & inset =
3433 static_cast<InsetInclude const &>(*iit->inset);
3435 Buffer * child = inset.getChildBuffer();
3440 // register its position, but only when it is
3441 // included first in the buffer
3442 if (children_positions.find(child) ==
3443 children_positions.end())
3444 children_positions[child] = it;
3446 // register child with its scope
3447 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3451 InsetMath * im = iit->inset->asInsetMath();
3452 if (doing_export && im) {
3453 InsetMathHull * hull = im->asHullInset();
3455 hull->recordLocation(it);
3458 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3462 MathMacroTemplate & macroTemplate =
3463 *iit->inset->asInsetMath()->asMacroTemplate();
3464 MacroContext mc(owner_, it);
3465 macroTemplate.updateToContext(mc);
3468 bool valid = macroTemplate.validMacro();
3469 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3470 // then the BufferView's cursor will be invalid in
3471 // some cases which leads to crashes.
3476 // FIXME (Abdel), I don't understand why we pass 'it' here
3477 // instead of 'macroTemplate' defined above... is this correct?
3478 macros[macroTemplate.name()][it] =
3479 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3489 void Buffer::updateMacros() const
3494 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3496 // start with empty table
3498 d->children_positions.clear();
3499 d->position_to_children.clear();
3501 // Iterate over buffer, starting with first paragraph
3502 // The scope must be bigger than any lookup DocIterator
3503 // later. For the global lookup, lastpit+1 is used, hence
3504 // we use lastpit+2 here.
3505 DocIterator it = par_iterator_begin();
3506 DocIterator outerScope = it;
3507 outerScope.pit() = outerScope.lastpit() + 2;
3508 d->updateMacros(it, outerScope);
3512 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3514 InsetIterator it = inset_iterator_begin(inset());
3515 InsetIterator const end = inset_iterator_end(inset());
3516 for (; it != end; ++it) {
3517 if (it->lyxCode() == BRANCH_CODE) {
3518 InsetBranch & br = static_cast<InsetBranch &>(*it);
3519 docstring const name = br.branch();
3520 if (!from_master && !params().branchlist().find(name))
3521 result.push_back(name);
3522 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3523 result.push_back(name);
3526 if (it->lyxCode() == INCLUDE_CODE) {
3527 // get buffer of external file
3528 InsetInclude const & ins =
3529 static_cast<InsetInclude const &>(*it);
3530 Buffer * child = ins.getChildBuffer();
3533 child->getUsedBranches(result, true);
3536 // remove duplicates
3541 void Buffer::updateMacroInstances(UpdateType utype) const
3543 LYXERR(Debug::MACROS, "updateMacroInstances for "
3544 << d->filename.onlyFileName());
3545 DocIterator it = doc_iterator_begin(this);
3547 DocIterator const end = doc_iterator_end(this);
3548 for (; it != end; it.forwardInset()) {
3549 // look for MathData cells in InsetMathNest insets
3550 InsetMath * minset = it.nextInset()->asInsetMath();
3554 // update macro in all cells of the InsetMathNest
3555 DocIterator::idx_type n = minset->nargs();
3556 MacroContext mc = MacroContext(this, it);
3557 for (DocIterator::idx_type i = 0; i < n; ++i) {
3558 MathData & data = minset->cell(i);
3559 data.updateMacros(0, mc, utype, 0);
3565 void Buffer::listMacroNames(MacroNameSet & macros) const
3570 d->macro_lock = true;
3572 // loop over macro names
3573 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3574 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3575 for (; nameIt != nameEnd; ++nameIt)
3576 macros.insert(nameIt->first);
3578 // loop over children
3579 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3580 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3581 for (; it != end; ++it)
3582 it->first->listMacroNames(macros);
3585 Buffer const * const pbuf = d->parent();
3587 pbuf->listMacroNames(macros);
3589 d->macro_lock = false;
3593 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3595 Buffer const * const pbuf = d->parent();
3600 pbuf->listMacroNames(names);
3603 MacroNameSet::iterator it = names.begin();
3604 MacroNameSet::iterator end = names.end();
3605 for (; it != end; ++it) {
3607 MacroData const * data =
3608 pbuf->getMacro(*it, *this, false);
3610 macros.insert(data);
3612 // we cannot access the original MathMacroTemplate anymore
3613 // here to calls validate method. So we do its work here manually.
3614 // FIXME: somehow make the template accessible here.
3615 if (data->optionals() > 0)
3616 features.require("xargs");
3622 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3625 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3627 RefCache::iterator it = d->ref_cache_.find(label);
3628 if (it != d->ref_cache_.end())
3629 return it->second.second;
3631 static InsetLabel const * dummy_il = 0;
3632 static References const dummy_refs = References();
3633 it = d->ref_cache_.insert(
3634 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3635 return it->second.second;
3639 Buffer::References const & Buffer::references(docstring const & label) const
3641 return const_cast<Buffer *>(this)->getReferenceCache(label);
3645 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3647 References & refs = getReferenceCache(label);
3648 refs.push_back(make_pair(inset, it));
3652 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3654 masterBuffer()->d->ref_cache_[label].first = il;
3658 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3660 return masterBuffer()->d->ref_cache_[label].first;
3664 void Buffer::clearReferenceCache() const
3667 d->ref_cache_.clear();
3671 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3673 //FIXME: This does not work for child documents yet.
3674 reloadBibInfoCache();
3676 // Check if the label 'from' appears more than once
3677 BiblioInfo const & keys = masterBibInfo();
3678 BiblioInfo::const_iterator bit = keys.begin();
3679 BiblioInfo::const_iterator bend = keys.end();
3680 vector<docstring> labels;
3682 for (; bit != bend; ++bit)
3684 labels.push_back(bit->first);
3686 if (count(labels.begin(), labels.end(), from) > 1)
3689 string const paramName = "key";
3690 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3691 if (it->lyxCode() != CITE_CODE)
3693 InsetCommand * inset = it->asInsetCommand();
3694 docstring const oldValue = inset->getParam(paramName);
3695 if (oldValue == from)
3696 inset->setParam(paramName, to);
3700 // returns NULL if id-to-row conversion is unsupported
3701 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3702 pit_type par_begin, pit_type par_end,
3703 OutputWhat output, bool master) const
3705 unique_ptr<TexRow> texrow;
3706 OutputParams runparams(¶ms().encoding());
3707 runparams.nice = true;
3708 runparams.flavor = params().getOutputFlavor(format);
3709 runparams.linelen = lyxrc.plaintext_linelen;
3710 // No side effect of file copying and image conversion
3711 runparams.dryrun = true;
3713 if (output == CurrentParagraph) {
3714 runparams.par_begin = par_begin;
3715 runparams.par_end = par_end;
3716 if (par_begin + 1 == par_end) {
3718 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3722 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3723 convert<docstring>(par_begin),
3724 convert<docstring>(par_end - 1))
3727 // output paragraphs
3728 if (runparams.flavor == OutputParams::LYX) {
3729 Paragraph const & par = text().paragraphs()[par_begin];
3731 depth_type dt = par.getDepth();
3732 par.write(ods, params(), dt);
3733 os << from_utf8(ods.str());
3734 } else if (runparams.flavor == OutputParams::HTML) {
3736 setMathFlavor(runparams);
3737 xhtmlParagraphs(text(), *this, xs, runparams);
3738 } else if (runparams.flavor == OutputParams::TEXT) {
3740 // FIXME Handles only one paragraph, unlike the others.
3741 // Probably should have some routine with a signature like them.
3742 writePlaintextParagraph(*this,
3743 text().paragraphs()[par_begin], os, runparams, dummy);
3744 } else if (params().isDocBook()) {
3745 docbookParagraphs(text(), *this, os, runparams);
3747 // If we are previewing a paragraph, even if this is the
3748 // child of some other buffer, let's cut the link here,
3749 // so that no concurring settings from the master
3750 // (e.g. branch state) interfere (see #8101).
3752 d->ignore_parent = true;
3753 // We need to validate the Buffer params' features here
3754 // in order to know if we should output polyglossia
3755 // macros (instead of babel macros)
3756 LaTeXFeatures features(*this, params(), runparams);
3758 runparams.use_polyglossia = features.usePolyglossia();
3759 // latex or literate
3762 ots.texrow().newlines(2);
3764 latexParagraphs(*this, text(), ots, runparams);
3765 texrow = ots.releaseTexRow();
3767 // Restore the parenthood
3769 d->ignore_parent = false;
3773 if (output == FullSource)
3774 os << _("Preview source code");
3775 else if (output == OnlyPreamble)
3776 os << _("Preview preamble");
3777 else if (output == OnlyBody)
3778 os << _("Preview body");
3780 if (runparams.flavor == OutputParams::LYX) {
3782 if (output == FullSource)
3784 else if (output == OnlyPreamble)
3785 params().writeFile(ods, this);
3786 else if (output == OnlyBody)
3788 os << from_utf8(ods.str());
3789 } else if (runparams.flavor == OutputParams::HTML) {
3790 writeLyXHTMLSource(os, runparams, output);
3791 } else if (runparams.flavor == OutputParams::TEXT) {
3792 if (output == OnlyPreamble) {
3793 os << "% "<< _("Plain text does not have a preamble.");
3795 writePlaintextFile(*this, os, runparams);
3796 } else if (params().isDocBook()) {
3797 writeDocBookSource(os, absFileName(), runparams, output);
3799 // latex or literate
3802 ots.texrow().newlines(2);
3804 runparams.is_child = true;
3805 writeLaTeXSource(ots, string(), runparams, output);
3806 texrow = ots.releaseTexRow();
3813 ErrorList & Buffer::errorList(string const & type) const
3815 return d->errorLists[type];
3819 void Buffer::updateTocItem(std::string const & type,
3820 DocIterator const & dit) const
3823 d->gui_->updateTocItem(type, dit);
3827 void Buffer::structureChanged() const
3830 d->gui_->structureChanged();
3834 void Buffer::errors(string const & err, bool from_master) const
3837 d->gui_->errors(err, from_master);
3841 void Buffer::message(docstring const & msg) const
3844 d->gui_->message(msg);
3848 void Buffer::setBusy(bool on) const
3851 d->gui_->setBusy(on);
3855 void Buffer::updateTitles() const
3858 d->wa_->updateTitles();
3862 void Buffer::resetAutosaveTimers() const
3865 d->gui_->resetAutosaveTimers();
3869 bool Buffer::hasGuiDelegate() const
3875 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3884 class AutoSaveBuffer : public ForkedProcess {
3887 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3888 : buffer_(buffer), fname_(fname) {}
3890 virtual shared_ptr<ForkedProcess> clone() const
3892 return make_shared<AutoSaveBuffer>(*this);
3897 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3898 from_utf8(fname_.absFileName())));
3899 return run(DontWait);
3903 virtual int generateChild();
3905 Buffer const & buffer_;
3910 int AutoSaveBuffer::generateChild()
3912 #if defined(__APPLE__)
3913 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3914 * We should use something else like threads.
3916 * Since I do not know how to determine at run time what is the OS X
3917 * version, I just disable forking altogether for now (JMarc)
3919 pid_t const pid = -1;
3921 // tmp_ret will be located (usually) in /tmp
3922 // will that be a problem?
3923 // Note that this calls ForkedCalls::fork(), so it's
3924 // ok cross-platform.
3925 pid_t const pid = fork();
3926 // If you want to debug the autosave
3927 // you should set pid to -1, and comment out the fork.
3928 if (pid != 0 && pid != -1)
3932 // pid = -1 signifies that lyx was unable
3933 // to fork. But we will do the save
3935 bool failed = false;
3936 TempFile tempfile("lyxautoXXXXXX.lyx");
3937 tempfile.setAutoRemove(false);
3938 FileName const tmp_ret = tempfile.name();
3939 if (!tmp_ret.empty()) {
3940 if (!buffer_.writeFile(tmp_ret))
3942 else if (!tmp_ret.moveTo(fname_))
3948 // failed to write/rename tmp_ret so try writing direct
3949 if (!buffer_.writeFile(fname_)) {
3950 // It is dangerous to do this in the child,
3951 // but safe in the parent, so...
3952 if (pid == -1) // emit message signal.
3953 buffer_.message(_("Autosave failed!"));
3957 if (pid == 0) // we are the child so...
3966 FileName Buffer::getEmergencyFileName() const
3968 return FileName(d->filename.absFileName() + ".emergency");
3972 FileName Buffer::getAutosaveFileName() const
3974 // if the document is unnamed try to save in the backup dir, else
3975 // in the default document path, and as a last try in the filePath,
3976 // which will most often be the temporary directory
3979 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3980 : lyxrc.backupdir_path;
3981 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3984 string const fname = "#" + d->filename.onlyFileName() + "#";
3986 return makeAbsPath(fname, fpath);
3990 void Buffer::removeAutosaveFile() const
3992 FileName const f = getAutosaveFileName();
3998 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
4000 FileName const newauto = getAutosaveFileName();
4002 if (newauto != oldauto && oldauto.exists())
4003 if (!oldauto.moveTo(newauto))
4004 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4008 bool Buffer::autoSave() const
4010 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4011 if (buf->d->bak_clean || isReadonly())
4014 message(_("Autosaving current document..."));
4015 buf->d->bak_clean = true;
4017 FileName const fname = getAutosaveFileName();
4018 LASSERT(d->cloned_buffer_, return false);
4020 // If this buffer is cloned, we assume that
4021 // we are running in a separate thread already.
4022 TempFile tempfile("lyxautoXXXXXX.lyx");
4023 tempfile.setAutoRemove(false);
4024 FileName const tmp_ret = tempfile.name();
4025 if (!tmp_ret.empty()) {
4027 // assume successful write of tmp_ret
4028 if (tmp_ret.moveTo(fname))
4031 // failed to write/rename tmp_ret so try writing direct
4032 return writeFile(fname);
4036 void Buffer::setExportStatus(bool e) const
4038 d->doing_export = e;
4039 ListOfBuffers clist = getDescendents();
4040 ListOfBuffers::const_iterator cit = clist.begin();
4041 ListOfBuffers::const_iterator const cen = clist.end();
4042 for (; cit != cen; ++cit)
4043 (*cit)->d->doing_export = e;
4047 bool Buffer::isExporting() const
4049 return d->doing_export;
4053 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4057 return doExport(target, put_in_tempdir, result_file);
4060 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4061 string & result_file) const
4063 bool const update_unincluded =
4064 params().maintain_unincluded_children
4065 && !params().getIncludedChildren().empty();
4067 // (1) export with all included children (omit \includeonly)
4068 if (update_unincluded) {
4069 ExportStatus const status =
4070 doExport(target, put_in_tempdir, true, result_file);
4071 if (status != ExportSuccess)
4074 // (2) export with included children only
4075 return doExport(target, put_in_tempdir, false, result_file);
4079 void Buffer::setMathFlavor(OutputParams & op) const
4081 switch (params().html_math_output) {
4082 case BufferParams::MathML:
4083 op.math_flavor = OutputParams::MathAsMathML;
4085 case BufferParams::HTML:
4086 op.math_flavor = OutputParams::MathAsHTML;
4088 case BufferParams::Images:
4089 op.math_flavor = OutputParams::MathAsImages;
4091 case BufferParams::LaTeX:
4092 op.math_flavor = OutputParams::MathAsLaTeX;
4098 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4099 bool includeall, string & result_file) const
4101 LYXERR(Debug::FILES, "target=" << target);
4102 OutputParams runparams(¶ms().encoding());
4103 string format = target;
4104 string dest_filename;
4105 size_t pos = target.find(' ');
4106 if (pos != string::npos) {
4107 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4108 format = target.substr(0, pos);
4109 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4110 FileName(dest_filename).onlyPath().createPath();
4111 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4113 MarkAsExporting exporting(this);
4114 string backend_format;
4115 runparams.flavor = OutputParams::LATEX;
4116 runparams.linelen = lyxrc.plaintext_linelen;
4117 runparams.includeall = includeall;
4118 vector<string> backs = params().backends();
4119 Converters converters = theConverters();
4120 bool need_nice_file = false;
4121 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4122 // Get shortest path to format
4123 converters.buildGraph();
4124 Graph::EdgePath path;
4125 for (vector<string>::const_iterator it = backs.begin();
4126 it != backs.end(); ++it) {
4127 Graph::EdgePath p = converters.getPath(*it, format);
4128 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4129 backend_format = *it;
4134 if (!put_in_tempdir) {
4135 // Only show this alert if this is an export to a non-temporary
4136 // file (not for previewing).
4137 Alert::error(_("Couldn't export file"), bformat(
4138 _("No information for exporting the format %1$s."),
4139 formats.prettyName(format)));
4141 return ExportNoPathToFormat;
4143 runparams.flavor = converters.getFlavor(path, this);
4144 Graph::EdgePath::const_iterator it = path.begin();
4145 Graph::EdgePath::const_iterator en = path.end();
4146 for (; it != en; ++it)
4147 if (theConverters().get(*it).nice()) {
4148 need_nice_file = true;
4153 backend_format = format;
4154 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4155 // FIXME: Don't hardcode format names here, but use a flag
4156 if (backend_format == "pdflatex")
4157 runparams.flavor = OutputParams::PDFLATEX;
4158 else if (backend_format == "luatex")
4159 runparams.flavor = OutputParams::LUATEX;
4160 else if (backend_format == "dviluatex")
4161 runparams.flavor = OutputParams::DVILUATEX;
4162 else if (backend_format == "xetex")
4163 runparams.flavor = OutputParams::XETEX;
4166 string filename = latexName(false);
4167 filename = addName(temppath(), filename);
4168 filename = changeExtension(filename,
4169 formats.extension(backend_format));
4170 LYXERR(Debug::FILES, "filename=" << filename);
4172 // Plain text backend
4173 if (backend_format == "text") {
4174 runparams.flavor = OutputParams::TEXT;
4175 writePlaintextFile(*this, FileName(filename), runparams);
4178 else if (backend_format == "xhtml") {
4179 runparams.flavor = OutputParams::HTML;
4180 setMathFlavor(runparams);
4181 makeLyXHTMLFile(FileName(filename), runparams);
4182 } else if (backend_format == "lyx")
4183 writeFile(FileName(filename));
4185 else if (params().isDocBook()) {
4186 runparams.nice = !put_in_tempdir;
4187 makeDocBookFile(FileName(filename), runparams);
4190 else if (backend_format == format || need_nice_file) {
4191 runparams.nice = true;
4192 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4193 if (d->cloned_buffer_)
4194 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4197 } else if (!lyxrc.tex_allows_spaces
4198 && contains(filePath(), ' ')) {
4199 Alert::error(_("File name error"),
4200 _("The directory path to the document cannot contain spaces."));
4201 return ExportTexPathHasSpaces;
4203 runparams.nice = false;
4204 bool const success = makeLaTeXFile(
4205 FileName(filename), filePath(), runparams);
4206 if (d->cloned_buffer_)
4207 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4212 string const error_type = (format == "program")
4213 ? "Build" : params().bufferFormat();
4214 ErrorList & error_list = d->errorLists[error_type];
4215 string const ext = formats.extension(format);
4216 FileName const tmp_result_file(changeExtension(filename, ext));
4217 bool const success = converters.convert(this, FileName(filename),
4218 tmp_result_file, FileName(absFileName()), backend_format, format,
4221 // Emit the signal to show the error list or copy it back to the
4222 // cloned Buffer so that it can be emitted afterwards.
4223 if (format != backend_format) {
4224 if (runparams.silent)
4226 else if (d->cloned_buffer_)
4227 d->cloned_buffer_->d->errorLists[error_type] =
4228 d->errorLists[error_type];
4231 // also to the children, in case of master-buffer-view
4232 ListOfBuffers clist = getDescendents();
4233 ListOfBuffers::const_iterator cit = clist.begin();
4234 ListOfBuffers::const_iterator const cen = clist.end();
4235 for (; cit != cen; ++cit) {
4236 if (runparams.silent)
4237 (*cit)->d->errorLists[error_type].clear();
4238 else if (d->cloned_buffer_) {
4239 // Enable reverse search by copying back the
4240 // texrow object to the cloned buffer.
4241 // FIXME: this is not thread safe.
4242 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4243 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4244 (*cit)->d->errorLists[error_type];
4246 (*cit)->errors(error_type, true);
4250 if (d->cloned_buffer_) {
4251 // Enable reverse dvi or pdf to work by copying back the texrow
4252 // object to the cloned buffer.
4253 // FIXME: There is a possibility of concurrent access to texrow
4254 // here from the main GUI thread that should be securized.
4255 d->cloned_buffer_->d->texrow = d->texrow;
4256 string const error_type = params().bufferFormat();
4257 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4261 if (put_in_tempdir) {
4262 result_file = tmp_result_file.absFileName();
4263 return success ? ExportSuccess : ExportConverterError;
4266 if (dest_filename.empty())
4267 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4269 result_file = dest_filename;
4270 // We need to copy referenced files (e. g. included graphics
4271 // if format == "dvi") to the result dir.
4272 vector<ExportedFile> const files =
4273 runparams.exportdata->externalFiles(format);
4274 string const dest = runparams.export_folder.empty() ?
4275 onlyPath(result_file) : runparams.export_folder;
4276 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4277 : force_overwrite == ALL_FILES;
4278 CopyStatus status = use_force ? FORCE : SUCCESS;
4280 vector<ExportedFile>::const_iterator it = files.begin();
4281 vector<ExportedFile>::const_iterator const en = files.end();
4282 for (; it != en && status != CANCEL; ++it) {
4283 string const fmt = formats.getFormatFromFile(it->sourceName);
4284 string fixedName = it->exportName;
4285 if (!runparams.export_folder.empty()) {
4286 // Relative pathnames starting with ../ will be sanitized
4287 // if exporting to a different folder
4288 while (fixedName.substr(0, 3) == "../")
4289 fixedName = fixedName.substr(3, fixedName.length() - 3);
4291 FileName fixedFileName = makeAbsPath(fixedName, dest);
4292 fixedFileName.onlyPath().createPath();
4293 status = copyFile(fmt, it->sourceName,
4295 it->exportName, status == FORCE,
4296 runparams.export_folder.empty());
4299 if (status == CANCEL) {
4300 message(_("Document export cancelled."));
4301 return ExportCancel;
4304 if (tmp_result_file.exists()) {
4305 // Finally copy the main file
4306 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4307 : force_overwrite != NO_FILES;
4308 if (status == SUCCESS && use_force)
4310 status = copyFile(format, tmp_result_file,
4311 FileName(result_file), result_file,
4313 if (status == CANCEL) {
4314 message(_("Document export cancelled."));
4315 return ExportCancel;
4317 message(bformat(_("Document exported as %1$s "
4319 formats.prettyName(format),
4320 makeDisplayPath(result_file)));
4323 // This must be a dummy converter like fax (bug 1888)
4324 message(bformat(_("Document exported as %1$s"),
4325 formats.prettyName(format)));
4328 return success ? ExportSuccess : ExportConverterError;
4332 Buffer::ExportStatus Buffer::preview(string const & format) const
4334 bool const update_unincluded =
4335 params().maintain_unincluded_children
4336 && !params().getIncludedChildren().empty();
4337 return preview(format, update_unincluded);
4341 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4343 MarkAsExporting exporting(this);
4345 // (1) export with all included children (omit \includeonly)
4347 ExportStatus const status = doExport(format, true, true, result_file);
4348 if (status != ExportSuccess)
4351 // (2) export with included children only
4352 ExportStatus const status = doExport(format, true, false, result_file);
4353 FileName const previewFile(result_file);
4355 Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4356 theimpl->preview_file_ = previewFile;
4357 theimpl->preview_format_ = format;
4358 theimpl->preview_error_ = (status != ExportSuccess);
4360 if (status != ExportSuccess)
4363 if (previewFile.exists())
4364 return formats.view(*this, previewFile, format) ?
4365 PreviewSuccess : PreviewError;
4367 // Successful export but no output file?
4368 // Probably a bug in error detection.
4369 LATTEST(status != ExportSuccess);
4374 Buffer::ReadStatus Buffer::extractFromVC()
4376 bool const found = LyXVC::file_not_found_hook(d->filename);
4378 return ReadFileNotFound;
4379 if (!d->filename.isReadableFile())
4385 Buffer::ReadStatus Buffer::loadEmergency()
4387 FileName const emergencyFile = getEmergencyFileName();
4388 if (!emergencyFile.exists()
4389 || emergencyFile.lastModified() <= d->filename.lastModified())
4390 return ReadFileNotFound;
4392 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4393 docstring const text = bformat(_("An emergency save of the document "
4394 "%1$s exists.\n\nRecover emergency save?"), file);
4396 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4397 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4403 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4404 bool const success = (ret_llf == ReadSuccess);
4407 Alert::warning(_("File is read-only"),
4408 bformat(_("An emergency file is successfully loaded, "
4409 "but the original file %1$s is marked read-only. "
4410 "Please make sure to save the document as a different "
4411 "file."), from_utf8(d->filename.absFileName())));
4414 lyxvc().file_found_hook(d->filename);
4415 str = _("Document was successfully recovered.");
4417 str = _("Document was NOT successfully recovered.");
4418 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4419 makeDisplayPath(emergencyFile.absFileName()));
4421 int const del_emerg =
4422 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4423 _("&Remove"), _("&Keep"));
4424 if (del_emerg == 0) {
4425 emergencyFile.removeFile();
4427 Alert::warning(_("Emergency file deleted"),
4428 _("Do not forget to save your file now!"), true);
4430 return success ? ReadSuccess : ReadEmergencyFailure;
4433 int const del_emerg =
4434 Alert::prompt(_("Delete emergency file?"),
4435 _("Remove emergency file now?"), 1, 1,
4436 _("&Remove"), _("&Keep"));
4438 emergencyFile.removeFile();
4439 return ReadOriginal;
4449 Buffer::ReadStatus Buffer::loadAutosave()
4451 // Now check if autosave file is newer.
4452 FileName const autosaveFile = getAutosaveFileName();
4453 if (!autosaveFile.exists()
4454 || autosaveFile.lastModified() <= d->filename.lastModified())
4455 return ReadFileNotFound;
4457 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4458 docstring const text = bformat(_("The backup of the document %1$s "
4459 "is newer.\n\nLoad the backup instead?"), file);
4460 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4461 _("&Load backup"), _("Load &original"), _("&Cancel"));
4466 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4467 // the file is not saved if we load the autosave file.
4468 if (ret_llf == ReadSuccess) {
4470 Alert::warning(_("File is read-only"),
4471 bformat(_("A backup file is successfully loaded, "
4472 "but the original file %1$s is marked read-only. "
4473 "Please make sure to save the document as a "
4475 from_utf8(d->filename.absFileName())));
4478 lyxvc().file_found_hook(d->filename);
4481 return ReadAutosaveFailure;
4484 // Here we delete the autosave
4485 autosaveFile.removeFile();
4486 return ReadOriginal;
4494 Buffer::ReadStatus Buffer::loadLyXFile()
4496 if (!d->filename.isReadableFile()) {
4497 ReadStatus const ret_rvc = extractFromVC();
4498 if (ret_rvc != ReadSuccess)
4502 ReadStatus const ret_re = loadEmergency();
4503 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4506 ReadStatus const ret_ra = loadAutosave();
4507 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4510 return loadThisLyXFile(d->filename);
4514 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4516 return readFile(fn);
4520 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4522 for (auto const & err : terr) {
4523 TexRow::TextEntry start, end = TexRow::text_none;
4524 int errorRow = err.error_in_line;
4525 Buffer const * buf = 0;
4527 if (err.child_name.empty())
4528 tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4530 // The error occurred in a child
4531 for (Buffer const * child : getDescendents()) {
4532 string const child_name =
4533 DocFileName(changeExtension(child->absFileName(), "tex")).
4535 if (err.child_name != child_name)
4537 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4538 if (!TexRow::isNone(start)) {
4539 buf = d->cloned_buffer_
4540 ? child->d->cloned_buffer_->d->owner_
4547 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4553 void Buffer::setBuffersForInsets() const
4555 inset().setBuffer(const_cast<Buffer &>(*this));
4559 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4561 LBUFERR(!text().paragraphs().empty());
4563 // Use the master text class also for child documents
4564 Buffer const * const master = masterBuffer();
4565 DocumentClass const & textclass = master->params().documentClass();
4567 // do this only if we are the top-level Buffer
4568 if (master == this) {
4569 textclass.counters().reset(from_ascii("bibitem"));
4570 reloadBibInfoCache();
4573 // keep the buffers to be children in this set. If the call from the
4574 // master comes back we can see which of them were actually seen (i.e.
4575 // via an InsetInclude). The remaining ones in the set need still be updated.
4576 static std::set<Buffer const *> bufToUpdate;
4577 if (scope == UpdateMaster) {
4578 // If this is a child document start with the master
4579 if (master != this) {
4580 bufToUpdate.insert(this);
4581 master->updateBuffer(UpdateMaster, utype);
4582 // If the master buffer has no gui associated with it, then the TocModel is
4583 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4584 // (bug 5699). The same happens if the master buffer is open in a different
4585 // window. This test catches both possibilities.
4586 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4587 // There remains a problem here: If there is another child open in yet a third
4588 // window, that TOC is not updated. So some more general solution is needed at
4590 if (master->d->gui_ != d->gui_)
4593 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4594 if (bufToUpdate.find(this) == bufToUpdate.end())
4598 // start over the counters in the master
4599 textclass.counters().reset();
4602 // update will be done below for this buffer
4603 bufToUpdate.erase(this);
4605 // update all caches
4606 clearReferenceCache();
4608 setChangesPresent(false);
4610 Buffer & cbuf = const_cast<Buffer &>(*this);
4613 ParIterator parit = cbuf.par_iterator_begin();
4614 updateBuffer(parit, utype);
4617 // TocBackend update will be done later.
4620 d->bibinfo_cache_valid_ = true;
4621 d->cite_labels_valid_ = true;
4623 cbuf.tocBackend().update(true, utype);
4624 if (scope == UpdateMaster)
4625 cbuf.structureChanged();
4629 static depth_type getDepth(DocIterator const & it)
4631 depth_type depth = 0;
4632 for (size_t i = 0 ; i < it.depth() ; ++i)
4633 if (!it[i].inset().inMathed())
4634 depth += it[i].paragraph().getDepth() + 1;
4635 // remove 1 since the outer inset does not count
4636 // we should have at least one non-math inset, so
4637 // depth should nevery be 0. but maybe it is worth
4638 // marking this, just in case.
4640 // coverity[INTEGER_OVERFLOW]
4644 static depth_type getItemDepth(ParIterator const & it)
4646 Paragraph const & par = *it;
4647 LabelType const labeltype = par.layout().labeltype;
4649 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4652 // this will hold the lowest depth encountered up to now.
4653 depth_type min_depth = getDepth(it);
4654 ParIterator prev_it = it;
4657 --prev_it.top().pit();
4659 // start of nested inset: go to outer par
4661 if (prev_it.empty()) {
4662 // start of document: nothing to do
4667 // We search for the first paragraph with same label
4668 // that is not more deeply nested.
4669 Paragraph & prev_par = *prev_it;
4670 depth_type const prev_depth = getDepth(prev_it);
4671 if (labeltype == prev_par.layout().labeltype) {
4672 if (prev_depth < min_depth)
4673 return prev_par.itemdepth + 1;
4674 if (prev_depth == min_depth)
4675 return prev_par.itemdepth;
4677 min_depth = min(min_depth, prev_depth);
4678 // small optimization: if we are at depth 0, we won't
4679 // find anything else
4680 if (prev_depth == 0)
4686 static bool needEnumCounterReset(ParIterator const & it)
4688 Paragraph const & par = *it;
4689 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4690 depth_type const cur_depth = par.getDepth();
4691 ParIterator prev_it = it;
4692 while (prev_it.pit()) {
4693 --prev_it.top().pit();
4694 Paragraph const & prev_par = *prev_it;
4695 if (prev_par.getDepth() <= cur_depth)
4696 return prev_par.layout().name() != par.layout().name();
4698 // start of nested inset: reset
4703 // set the label of a paragraph. This includes the counters.
4704 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4706 BufferParams const & bp = owner_->masterBuffer()->params();
4707 DocumentClass const & textclass = bp.documentClass();
4708 Paragraph & par = it.paragraph();
4709 Layout const & layout = par.layout();
4710 Counters & counters = textclass.counters();
4712 if (par.params().startOfAppendix()) {
4713 // We want to reset the counter corresponding to toplevel sectioning
4714 Layout const & lay = textclass.getTOCLayout();
4715 docstring const cnt = lay.counter;
4717 counters.reset(cnt);
4718 counters.appendix(true);
4720 par.params().appendix(counters.appendix());
4722 // Compute the item depth of the paragraph
4723 par.itemdepth = getItemDepth(it);
4725 if (layout.margintype == MARGIN_MANUAL) {
4726 if (par.params().labelWidthString().empty())
4727 par.params().labelWidthString(par.expandLabel(layout, bp));
4728 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4729 // we do not need to do anything here, since the empty case is
4730 // handled during export.
4732 par.params().labelWidthString(docstring());
4735 switch(layout.labeltype) {
4736 case LABEL_ITEMIZE: {
4737 // At some point of time we should do something more
4738 // clever here, like:
4739 // par.params().labelString(
4740 // bp.user_defined_bullet(par.itemdepth).getText());
4741 // for now, use a simple hardcoded label
4742 docstring itemlabel;
4743 switch (par.itemdepth) {
4745 itemlabel = char_type(0x2022);
4748 itemlabel = char_type(0x2013);
4751 itemlabel = char_type(0x2217);
4754 itemlabel = char_type(0x2219); // or 0x00b7
4757 par.params().labelString(itemlabel);
4761 case LABEL_ENUMERATE: {
4762 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4764 switch (par.itemdepth) {
4773 enumcounter += "iv";
4776 // not a valid enumdepth...
4780 // Increase the master counter?
4781 if (layout.stepmastercounter && needEnumCounterReset(it))
4782 counters.stepMaster(enumcounter, utype);
4784 // Maybe we have to reset the enumeration counter.
4785 if (!layout.resumecounter && needEnumCounterReset(it))
4786 counters.reset(enumcounter);
4787 counters.step(enumcounter, utype);
4789 string const & lang = par.getParLanguage(bp)->code();
4790 par.params().labelString(counters.theCounter(enumcounter, lang));
4795 case LABEL_SENSITIVE: {
4796 string const & type = counters.current_float();
4797 docstring full_label;
4799 full_label = owner_->B_("Senseless!!! ");
4801 docstring name = owner_->B_(textclass.floats().getType(type).name());
4802 if (counters.hasCounter(from_utf8(type))) {
4803 string const & lang = par.getParLanguage(bp)->code();
4804 counters.step(from_utf8(type), utype);
4805 full_label = bformat(from_ascii("%1$s %2$s:"),
4807 counters.theCounter(from_utf8(type), lang));
4809 full_label = bformat(from_ascii("%1$s #:"), name);
4811 par.params().labelString(full_label);
4815 case LABEL_NO_LABEL:
4816 par.params().labelString(docstring());
4820 case LABEL_CENTERED:
4821 case LABEL_STATIC: {
4822 docstring const & lcounter = layout.counter;
4823 if (!lcounter.empty()) {
4824 if (layout.toclevel <= bp.secnumdepth
4825 && (layout.latextype != LATEX_ENVIRONMENT
4826 || it.text()->isFirstInSequence(it.pit()))) {
4827 if (counters.hasCounter(lcounter))
4828 counters.step(lcounter, utype);
4829 par.params().labelString(par.expandLabel(layout, bp));
4831 par.params().labelString(docstring());
4833 par.params().labelString(par.expandLabel(layout, bp));
4839 par.params().labelString(par.expandLabel(layout, bp));
4844 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4846 // LASSERT: Is it safe to continue here, or should we just return?
4847 LASSERT(parit.pit() == 0, /**/);
4849 // Set the position of the text in the buffer to be able
4850 // to resolve macros in it.
4851 parit.text()->setMacrocontextPosition(parit);
4853 depth_type maxdepth = 0;
4854 pit_type const lastpit = parit.lastpit();
4855 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4856 // reduce depth if necessary
4857 if (parit->params().depth() > maxdepth) {
4858 /** FIXME: this function is const, but
4859 * nevertheless it modifies the buffer. To be
4860 * cleaner, one should modify the buffer in
4861 * another function, which is actually
4862 * non-const. This would however be costly in
4863 * terms of code duplication.
4865 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4866 parit->params().depth(maxdepth);
4868 maxdepth = parit->getMaxDepthAfter();
4870 if (utype == OutputUpdate) {
4871 // track the active counters
4872 // we have to do this for the master buffer, since the local
4873 // buffer isn't tracking anything.
4874 masterBuffer()->params().documentClass().counters().
4875 setActiveLayout(parit->layout());
4878 // set the counter for this paragraph
4879 d->setLabel(parit, utype);
4881 // update change-tracking flag
4882 parit->addChangesToBuffer(*this);
4885 InsetList::const_iterator iit = parit->insetList().begin();
4886 InsetList::const_iterator end = parit->insetList().end();
4887 for (; iit != end; ++iit) {
4888 parit.pos() = iit->pos;
4889 iit->inset->updateBuffer(parit, utype);
4895 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4896 WordLangTuple & word_lang, docstring_list & suggestions) const
4900 suggestions.clear();
4901 word_lang = WordLangTuple();
4902 bool const to_end = to.empty();
4903 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4904 // OK, we start from here.
4905 for (; from != end; from.forwardPos()) {
4906 // This skips all insets with spell check disabled.
4907 while (!from.allowSpellCheck()) {
4911 // If from is at the end of the document (which is possible
4912 // when "from" was changed above) LyX will crash later otherwise.
4913 if (from.atEnd() || (!to_end && from >= end))
4916 from.paragraph().spellCheck();
4917 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4918 if (SpellChecker::misspelled(res)) {
4922 // Do not increase progress when from == to, otherwise the word
4923 // count will be wrong.
4933 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4935 bool inword = false;
4940 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4941 if (!dit.inTexted()) {
4946 Paragraph const & par = dit.paragraph();
4947 pos_type const pos = dit.pos();
4949 // Copied and adapted from isWordSeparator() in Paragraph
4950 if (pos == dit.lastpos()) {
4953 Inset const * ins = par.getInset(pos);
4954 if (ins && skipNoOutput && !ins->producesOutput()) {
4957 // stop if end of range was skipped
4958 if (!to.atEnd() && dit >= to)
4961 } else if (!par.isDeleted(pos)) {
4962 if (par.isWordSeparator(pos))
4968 if (ins && ins->isLetter())
4970 else if (ins && ins->isSpace())
4973 char_type const c = par.getChar(pos);
4974 if (isPrintableNonspace(c))
4976 else if (isSpace(c))
4986 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4988 d->updateStatistics(from, to, skipNoOutput);
4992 int Buffer::wordCount() const
4994 return d->wordCount();
4998 int Buffer::charCount(bool with_blanks) const
5000 return d->charCount(with_blanks);
5004 Buffer::ReadStatus Buffer::reload()
5007 // c.f. bug http://www.lyx.org/trac/ticket/6587
5008 removeAutosaveFile();
5009 // e.g., read-only status could have changed due to version control
5010 d->filename.refresh();
5011 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5013 // clear parent. this will get reset if need be.
5015 ReadStatus const status = loadLyXFile();
5016 if (status == ReadSuccess) {
5021 message(bformat(_("Document %1$s reloaded."), disp_fn));
5024 message(bformat(_("Could not reload document %1$s."), disp_fn));
5034 bool Buffer::saveAs(FileName const & fn)
5036 FileName const old_name = fileName();
5037 FileName const old_auto = getAutosaveFileName();
5038 bool const old_unnamed = isUnnamed();
5039 bool success = true;
5040 d->old_position = filePath();
5047 // bring the autosave file with us, just in case.
5048 moveAutosaveFile(old_auto);
5049 // validate version control data and
5050 // correct buffer title
5051 lyxvc().file_found_hook(fileName());
5053 // the file has now been saved to the new location.
5054 // we need to check that the locations of child buffers
5056 checkChildBuffers();
5057 checkMasterBuffer();
5060 // reset the old filename and unnamed state
5061 setFileName(old_name);
5062 setUnnamed(old_unnamed);
5066 d->old_position.clear();
5071 void Buffer::checkChildBuffers()
5073 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5074 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5075 for (; it != en; ++it) {
5076 DocIterator dit = it->second;
5077 Buffer * cbuf = const_cast<Buffer *>(it->first);
5078 if (!cbuf || !theBufferList().isLoaded(cbuf))
5080 Inset * inset = dit.nextInset();
5081 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5082 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5083 docstring const & incfile = inset_inc->getParam("filename");
5084 string oldloc = cbuf->absFileName();
5085 string newloc = makeAbsPath(to_utf8(incfile),
5086 onlyPath(absFileName())).absFileName();
5087 if (oldloc == newloc)
5089 // the location of the child file is incorrect.
5091 inset_inc->setChildBuffer(0);
5093 // invalidate cache of children
5094 d->children_positions.clear();
5095 d->position_to_children.clear();
5099 // If a child has been saved under a different name/path, it might have been
5100 // orphaned. Therefore the master needs to be reset (bug 8161).
5101 void Buffer::checkMasterBuffer()
5103 Buffer const * const master = masterBuffer();
5107 // necessary to re-register the child (bug 5873)
5108 // FIXME: clean up updateMacros (here, only
5109 // child registering is needed).
5110 master->updateMacros();
5111 // (re)set master as master buffer, but only
5112 // if we are a real child
5113 if (master->isChild(this))
5120 string Buffer::includedFilePath(string const & name, string const & ext) const
5122 if (d->old_position.empty() ||
5123 equivalent(FileName(d->old_position), FileName(filePath())))
5126 bool isabsolute = FileName::isAbsolute(name);
5127 // both old_position and filePath() end with a path separator
5128 string absname = isabsolute ? name : d->old_position + name;
5130 // if old_position is set to origin, we need to do the equivalent of
5131 // getReferencedFileName() (see readDocument())
5132 if (!isabsolute && d->old_position == params().origin) {
5133 FileName const test(addExtension(filePath() + name, ext));
5135 absname = filePath() + name;
5138 if (!FileName(addExtension(absname, ext)).exists())
5142 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5144 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5145 from_utf8(filePath())));
5149 void Buffer::setChangesPresent(bool b) const
5151 d->tracked_changes_present_ = b;
5155 bool Buffer::areChangesPresent() const
5157 return d->tracked_changes_present_;
5161 void Buffer::updateChangesPresent() const
5163 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5164 setChangesPresent(false);
5165 ParConstIterator it = par_iterator_begin();
5166 ParConstIterator const end = par_iterator_end();
5167 for (; !areChangesPresent() && it != end; ++it)
5168 it->addChangesToBuffer(*this);