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"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
139 // A storehouse for the cloned buffers.
140 list<CloneList *> cloned_buffers;
146 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
150 delete preview_loader_;
158 /// search for macro in local (buffer) table or in children
159 MacroData const * getBufferMacro(docstring const & name,
160 DocIterator const & pos) const;
162 /// Update macro table starting with position of it \param it in some
164 void updateMacros(DocIterator & it, DocIterator & scope);
166 void setLabel(ParIterator & it, UpdateType utype) const;
168 /** If we have branches that use the file suffix
169 feature, return the file name with suffix appended.
171 support::FileName exportFileName() const;
178 mutable TexRow texrow;
180 /// need to regenerate .tex?
184 mutable bool lyx_clean;
186 /// is autosave needed?
187 mutable bool bak_clean;
189 /// is this an unnamed file (New...)?
192 /// is this an internal bufffer?
193 bool internal_buffer;
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
207 /// original format of loaded file
210 /// if the file was originally loaded from an older format, do
211 /// we need to back it up still?
212 bool need_format_backup;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
223 ScopeMacro(DocIterator const & s, MacroData const & m)
224 : scope(s), macro(m) {}
228 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
229 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
230 /// map from the macro name to the position map,
231 /// which maps the macro definition position to the scope and the MacroData.
232 NamePositionScopeMacroMap macros;
233 /// This seem to change the way Buffer::getMacro() works
234 mutable bool macro_lock;
236 /// positions of child buffers in the buffer
237 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
239 ScopeBuffer() : buffer(0) {}
240 ScopeBuffer(DocIterator const & s, Buffer const * b)
241 : scope(s), buffer(b) {}
243 Buffer const * buffer;
245 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
246 /// position of children buffers in this buffer
247 BufferPositionMap children_positions;
248 /// map from children inclusion positions to their scope and their buffer
249 PositionScopeBufferMap position_to_children;
251 /// Contains the old buffer filePath() while saving-as, or the
252 /// directory where the document was last saved while loading.
255 /** Keeps track of the path of local layout files.
256 * If possible, it is always relative to the buffer path.
257 * Empty for layouts in system or user directory.
259 string layout_position;
261 /// Container for all sort of Buffer dependant errors.
262 map<string, ErrorList> errorLists;
264 /// timestamp and checksum used to test if the file has been externally
265 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
267 unsigned long checksum_;
270 frontend::WorkAreaManager * wa_;
272 frontend::GuiBufferDelegate * gui_;
277 /// A cache for the bibfiles (including bibfiles of loaded child
278 /// documents), needed for appropriate update of natbib labels.
279 mutable support::FileNameList bibfiles_cache_;
281 // FIXME The caching mechanism could be improved. At present, we have a
282 // cache for each Buffer, that caches all the bibliography info for that
283 // Buffer. A more efficient solution would be to have a global cache per
284 // file, and then to construct the Buffer's bibinfo from that.
285 /// A cache for bibliography info
286 mutable BiblioInfo bibinfo_;
287 /// whether the bibinfo cache is valid
288 mutable bool bibinfo_cache_valid_;
289 /// whether the bibfile cache is valid
290 mutable bool bibfile_cache_valid_;
291 /// Cache of timestamps of .bib files
292 map<FileName, time_t> bibfile_status_;
293 /// Indicates whether the bibinfo has changed since the last time
294 /// we ran updateBuffer(), i.e., whether citation labels may need
296 mutable bool cite_labels_valid_;
298 /// These two hold the file name and format, written to by
299 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
300 FileName preview_file_;
301 string preview_format_;
302 /// If there was an error when previewing, on the next preview we do
303 /// a fresh compile (e.g. in case the user installed a package that
307 mutable RefCache ref_cache_;
309 /// our Text that should be wrapped in an InsetText
313 PreviewLoader * preview_loader_;
315 /// This is here to force the test to be done whenever parent_buffer
317 Buffer const * parent() const
319 // ignore_parent temporarily "orphans" a buffer
320 // (e.g. if a child is compiled standalone)
323 // if parent_buffer is not loaded, then it has been unloaded,
324 // which means that parent_buffer is an invalid pointer. So we
325 // set it to null in that case.
326 // however, the BufferList doesn't know about cloned buffers, so
327 // they will always be regarded as unloaded. in that case, we hope
329 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
331 return parent_buffer;
335 void setParent(Buffer const * pb)
337 if (parent_buffer == pb)
340 if (!cloned_buffer_ && parent_buffer && pb)
341 LYXERR0("Warning: a buffer should not have two parents!");
343 if (!cloned_buffer_ && parent_buffer) {
344 parent_buffer->invalidateBibfileCache();
345 parent_buffer->invalidateBibinfoCache();
349 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
350 /// This one is useful for preview detached in a thread.
351 Buffer const * cloned_buffer_;
353 CloneList * clone_list_;
354 /// are we in the process of exporting this buffer?
355 mutable bool doing_export;
357 /// compute statistics
358 /// \p from initial position
359 /// \p to points to the end position
360 void updateStatistics(DocIterator & from, DocIterator & to,
361 bool skipNoOutput = true);
362 /// statistics accessor functions
363 int wordCount() const
367 int charCount(bool with_blanks) const
370 + (with_blanks ? blank_count_ : 0);
373 // does the buffer contain tracked changes? (if so, we automatically
374 // display the review toolbar, for instance)
375 mutable bool tracked_changes_present_;
378 /// So we can force access via the accessors.
379 mutable Buffer const * parent_buffer;
388 /// Creates the per buffer temporary directory
389 static FileName createBufferTmpDir()
391 // FIXME This would be the ideal application for a TempDir class (like
392 // TempFile but for directories)
397 Mutex::Locker locker(&mutex);
398 counter = convert<string>(count++);
400 // We are in our own directory. Why bother to mangle name?
401 // In fact I wrote this code to circumvent a problematic behaviour
402 // (bug?) of EMX mkstemp().
403 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
406 if (!tmpfl.createDirectory(0777)) {
407 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
408 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
409 from_utf8(tmpfl.absFileName())));
415 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
416 Buffer const * cloned_buffer)
417 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
418 internal_buffer(false), read_only(readonly_), filename(file),
419 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
420 ignore_parent(false), toc_backend(owner), macro_lock(false), timestamp_(0),
421 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
422 bibfile_cache_valid_(false), cite_labels_valid_(false), inset(0),
423 preview_loader_(0), cloned_buffer_(cloned_buffer), clone_list_(0),
424 doing_export(false), parent_buffer(0),
425 word_count_(0), char_count_(0), blank_count_(0)
427 if (!cloned_buffer_) {
428 temppath = createBufferTmpDir();
429 lyxvc.setBuffer(owner_);
431 wa_ = new frontend::WorkAreaManager;
434 temppath = cloned_buffer_->d->temppath;
435 file_fully_loaded = true;
436 params = cloned_buffer_->d->params;
437 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
438 bibinfo_ = cloned_buffer_->d->bibinfo_;
439 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
440 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
441 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
442 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
443 unnamed = cloned_buffer_->d->unnamed;
444 internal_buffer = cloned_buffer_->d->internal_buffer;
445 layout_position = cloned_buffer_->d->layout_position;
446 preview_file_ = cloned_buffer_->d->preview_file_;
447 preview_format_ = cloned_buffer_->d->preview_format_;
448 preview_error_ = cloned_buffer_->d->preview_error_;
449 tracked_changes_present_ = cloned_buffer_->d->tracked_changes_present_;
453 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
454 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
456 LYXERR(Debug::INFO, "Buffer::Buffer()");
458 d->inset = new InsetText(*cloned_buffer->d->inset);
459 d->inset->setBuffer(*this);
460 // FIXME: optimize this loop somewhat, maybe by creating a new
461 // general recursive Inset::setId().
462 DocIterator it = doc_iterator_begin(this);
463 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
464 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
465 it.paragraph().setId(cloned_it.paragraph().id());
467 d->inset = new InsetText(this);
468 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
474 LYXERR(Debug::INFO, "Buffer::~Buffer()");
475 // here the buffer should take care that it is
476 // saved properly, before it goes into the void.
478 // GuiView already destroyed
482 // No need to do additional cleanups for internal buffer.
488 // this is in case of recursive includes: we won't try to delete
489 // ourselves as a child.
490 d->clone_list_->erase(this);
491 // loop over children
492 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
493 Impl::BufferPositionMap::iterator end = d->children_positions.end();
494 for (; it != end; ++it) {
495 Buffer * child = const_cast<Buffer *>(it->first);
496 if (d->clone_list_->erase(child))
499 // if we're the master buffer, then we should get rid of the list
502 // If this is not empty, we have leaked something. Worse, one of the
503 // children still has a reference to this list. But we will try to
504 // continue, rather than shut down.
505 LATTEST(d->clone_list_->empty());
506 list<CloneList *>::iterator it =
507 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
508 if (it == cloned_buffers.end()) {
509 // We will leak in this case, but it is safe to continue.
512 cloned_buffers.erase(it);
513 delete d->clone_list_;
515 // FIXME Do we really need to do this right before we delete d?
516 // clear references to children in macro tables
517 d->children_positions.clear();
518 d->position_to_children.clear();
520 // loop over children
521 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
522 Impl::BufferPositionMap::iterator end = d->children_positions.end();
523 for (; it != end; ++it) {
524 Buffer * child = const_cast<Buffer *>(it->first);
525 if (theBufferList().isLoaded(child)) {
526 if (theBufferList().isOthersChild(this, child))
529 theBufferList().release(child);
534 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
535 msg += emergencyWrite();
536 Alert::warning(_("Attempting to close changed document!"), msg);
539 // FIXME Do we really need to do this right before we delete d?
540 // clear references to children in macro tables
541 d->children_positions.clear();
542 d->position_to_children.clear();
544 if (!d->temppath.destroyDirectory()) {
545 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
546 from_utf8(d->temppath.absFileName())));
555 Buffer * Buffer::cloneFromMaster() const
558 cloned_buffers.push_back(new CloneList);
559 CloneList * clones = cloned_buffers.back();
561 masterBuffer()->cloneWithChildren(bufmap, clones);
563 // make sure we got cloned
564 BufferMap::const_iterator bit = bufmap.find(this);
565 LASSERT(bit != bufmap.end(), return 0);
566 Buffer * cloned_buffer = bit->second;
568 return cloned_buffer;
572 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
574 // have we already been cloned?
575 if (bufmap.find(this) != bufmap.end())
578 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
580 // The clone needs its own DocumentClass, since running updateBuffer() will
581 // modify it, and we would otherwise be sharing it with the original Buffer.
582 buffer_clone->params().makeDocumentClass(true);
584 cap::switchBetweenClasses(
585 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
586 static_cast<InsetText &>(buffer_clone->inset()), el);
588 bufmap[this] = buffer_clone;
589 clones->insert(buffer_clone);
590 buffer_clone->d->clone_list_ = clones;
591 buffer_clone->d->macro_lock = true;
592 buffer_clone->d->children_positions.clear();
594 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
595 // math macro caches need to be rethought and simplified.
596 // I am not sure wether we should handle Buffer cloning here or in BufferList.
597 // Right now BufferList knows nothing about buffer clones.
598 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
599 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
600 for (; it != end; ++it) {
601 DocIterator dit = it->first.clone(buffer_clone);
602 dit.setBuffer(buffer_clone);
603 Buffer * child = const_cast<Buffer *>(it->second.buffer);
605 child->cloneWithChildren(bufmap, clones);
606 BufferMap::iterator const bit = bufmap.find(child);
607 LASSERT(bit != bufmap.end(), continue);
608 Buffer * child_clone = bit->second;
610 Inset * inset = dit.nextInset();
611 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
612 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
613 inset_inc->setChildBuffer(child_clone);
614 child_clone->d->setParent(buffer_clone);
615 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
616 buffer_clone->setChild(dit, child_clone);
618 buffer_clone->d->macro_lock = false;
623 Buffer * Buffer::cloneBufferOnly() const {
624 cloned_buffers.push_back(new CloneList);
625 CloneList * clones = cloned_buffers.back();
626 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
628 // The clone needs its own DocumentClass, since running updateBuffer() will
629 // modify it, and we would otherwise be sharing it with the original Buffer.
630 buffer_clone->params().makeDocumentClass(true);
632 cap::switchBetweenClasses(
633 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
634 static_cast<InsetText &>(buffer_clone->inset()), el);
636 clones->insert(buffer_clone);
637 buffer_clone->d->clone_list_ = clones;
639 // we won't be cloning the children
640 buffer_clone->d->children_positions.clear();
645 bool Buffer::isClone() const
647 return d->cloned_buffer_;
651 void Buffer::changed(bool update_metrics) const
654 d->wa_->redrawAll(update_metrics);
658 frontend::WorkAreaManager & Buffer::workAreaManager() const
665 Text & Buffer::text() const
667 return d->inset->text();
671 Inset & Buffer::inset() const
677 BufferParams & Buffer::params()
683 BufferParams const & Buffer::params() const
689 BufferParams const & Buffer::masterParams() const
691 if (masterBuffer() == this)
694 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
695 // Copy child authors to the params. We need those pointers.
696 AuthorList const & child_authors = params().authors();
697 AuthorList::Authors::const_iterator it = child_authors.begin();
698 for (; it != child_authors.end(); ++it)
699 mparams.authors().record(*it);
704 double Buffer::fontScalingFactor() const
706 return isExporting() ? 75.0 * params().html_math_img_scale
707 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
711 ParagraphList & Buffer::paragraphs()
713 return text().paragraphs();
717 ParagraphList const & Buffer::paragraphs() const
719 return text().paragraphs();
723 LyXVC & Buffer::lyxvc()
729 LyXVC const & Buffer::lyxvc() const
735 string const Buffer::temppath() const
737 return d->temppath.absFileName();
741 TexRow & Buffer::texrow()
747 TexRow const & Buffer::texrow() const
753 TocBackend & Buffer::tocBackend() const
755 return d->toc_backend;
759 Undo & Buffer::undo()
765 void Buffer::setChild(DocIterator const & dit, Buffer * child)
767 d->children_positions[child] = dit;
771 string Buffer::latexName(bool const no_path) const
773 FileName latex_name =
774 makeLatexName(d->exportFileName());
775 return no_path ? latex_name.onlyFileName()
776 : latex_name.absFileName();
780 FileName Buffer::Impl::exportFileName() const
782 docstring const branch_suffix =
783 params.branchlist().getFileNameSuffix();
784 if (branch_suffix.empty())
787 string const name = filename.onlyFileNameWithoutExt()
788 + to_utf8(branch_suffix);
789 FileName res(filename.onlyPath().absFileName() + "/" + name);
790 res.changeExtension(filename.extension());
796 string Buffer::logName(LogType * type) const
798 string const filename = latexName(false);
800 if (filename.empty()) {
806 string const path = temppath();
808 FileName const fname(addName(temppath(),
809 onlyFileName(changeExtension(filename,
812 // FIXME: how do we know this is the name of the build log?
813 FileName const bname(
814 addName(path, onlyFileName(
815 changeExtension(filename,
816 formats.extension(params().bufferFormat()) + ".out"))));
818 // Also consider the master buffer log file
819 FileName masterfname = fname;
820 LogType mtype = latexlog;
821 if (masterBuffer() != this) {
822 string const mlogfile = masterBuffer()->logName(&mtype);
823 masterfname = FileName(mlogfile);
826 // If no Latex log or Build log is newer, show Build log
827 if (bname.exists() &&
828 ((!fname.exists() && !masterfname.exists())
829 || (fname.lastModified() < bname.lastModified()
830 && masterfname.lastModified() < bname.lastModified()))) {
831 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
834 return bname.absFileName();
835 // If we have a newer master file log or only a master log, show this
836 } else if (fname != masterfname
837 && (!fname.exists() && (masterfname.exists()
838 || fname.lastModified() < masterfname.lastModified()))) {
839 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
842 return masterfname.absFileName();
844 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
847 return fname.absFileName();
851 void Buffer::setReadonly(bool const flag)
853 if (d->read_only != flag) {
860 void Buffer::setFileName(FileName const & fname)
862 bool const changed = fname != d->filename;
865 lyxvc().file_found_hook(fname);
866 setReadonly(d->filename.isReadOnly());
872 int Buffer::readHeader(Lexer & lex)
874 int unknown_tokens = 0;
876 int begin_header_line = -1;
878 // Initialize parameters that may be/go lacking in header:
879 params().branchlist().clear();
880 params().preamble.erase();
881 params().options.erase();
882 params().master.erase();
883 params().float_placement.erase();
884 params().paperwidth.erase();
885 params().paperheight.erase();
886 params().leftmargin.erase();
887 params().rightmargin.erase();
888 params().topmargin.erase();
889 params().bottommargin.erase();
890 params().headheight.erase();
891 params().headsep.erase();
892 params().footskip.erase();
893 params().columnsep.erase();
894 params().fonts_cjk.erase();
895 params().listings_params.clear();
896 params().clearLayoutModules();
897 params().clearRemovedModules();
898 params().clearIncludedChildren();
899 params().pdfoptions().clear();
900 params().indiceslist().clear();
901 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
902 params().isbackgroundcolor = false;
903 params().fontcolor = RGBColor(0, 0, 0);
904 params().isfontcolor = false;
905 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
906 params().boxbgcolor = RGBColor(0xFF, 0, 0);
907 params().html_latex_start.clear();
908 params().html_latex_end.clear();
909 params().html_math_img_scale = 1.0;
910 params().output_sync_macro.erase();
911 params().setLocalLayout(string(), false);
912 params().setLocalLayout(string(), true);
914 for (int i = 0; i < 4; ++i) {
915 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
916 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
919 ErrorList & errorList = d->errorLists["Parse"];
928 if (token == "\\end_header")
932 if (token == "\\begin_header") {
933 begin_header_line = line;
937 LYXERR(Debug::PARSER, "Handling document header token: `"
940 string const result =
941 params().readToken(lex, token, d->filename.onlyPath());
942 if (!result.empty()) {
943 if (token == "\\textclass") {
944 d->layout_position = result;
947 docstring const s = bformat(_("Unknown token: "
951 errorList.push_back(ErrorItem(_("Document header error"),
956 if (begin_header_line) {
957 docstring const s = _("\\begin_header is missing");
958 errorList.push_back(ErrorItem(_("Document header error"),
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"),
987 if (params().output_changes) {
988 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
989 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
990 LaTeXFeatures::isAvailable("xcolor");
992 if (!dvipost && !xcolorulem) {
993 Alert::warning(_("Changes not shown in LaTeX output"),
994 _("Changes will not be highlighted in LaTeX output, "
995 "because neither dvipost nor xcolor/ulem are installed.\n"
996 "Please install these packages or redefine "
997 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
998 } else if (!xcolorulem) {
999 Alert::warning(_("Changes not shown in LaTeX output"),
1000 _("Changes will not be highlighted in LaTeX output "
1001 "when using pdflatex, because xcolor and ulem are not installed.\n"
1002 "Please install both packages or redefine "
1003 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1007 if (!parent() && !params().master.empty()) {
1008 FileName const master_file = makeAbsPath(params().master,
1009 onlyPath(absFileName()));
1010 if (isLyXFileName(master_file.absFileName())) {
1012 checkAndLoadLyXFile(master_file, true);
1014 // necessary e.g. after a reload
1015 // to re-register the child (bug 5873)
1016 // FIXME: clean up updateMacros (here, only
1017 // child registering is needed).
1018 master->updateMacros();
1019 // set master as master buffer, but only
1020 // if we are a real child
1021 if (master->isChild(this))
1023 // if the master is not fully loaded
1024 // it is probably just loading this
1025 // child. No warning needed then.
1026 else if (master->isFullyLoaded())
1027 LYXERR0("The master '"
1029 << "' assigned to this document ("
1031 << ") does not include "
1032 "this document. Ignoring the master assignment.");
1037 // assure we have a default index
1038 params().indiceslist().addDefault(B_("Index"));
1041 if (FileName::isAbsolute(params().origin))
1042 d->old_position = params().origin;
1044 d->old_position = filePath();
1045 bool const res = text().read(lex, errorList, d->inset);
1046 d->old_position.clear();
1048 // inform parent buffer about local macros
1050 Buffer const * pbuf = parent();
1051 UserMacroSet::const_iterator cit = usermacros.begin();
1052 UserMacroSet::const_iterator end = usermacros.end();
1053 for (; cit != end; ++cit)
1054 pbuf->usermacros.insert(*cit);
1058 updateMacroInstances(InternalUpdate);
1063 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1065 Format const * fmt = formats.getFormat(format);
1068 // It is important to use the correct extension here, since some
1069 // converters create a wrong output file otherwise (e.g. html2latex)
1070 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1071 FileName const name(tempfile.name());
1072 ofdocstream os(name.toFilesystemEncoding().c_str());
1073 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1074 bool const success = !(os << contents).fail();
1077 bool converted = false;
1079 params().compressed = false;
1081 // remove dummy empty par
1082 paragraphs().clear();
1084 converted = importFile(format, name, errorList);
1093 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1095 if (!theConverters().isReachable(format, "lyx"))
1098 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1099 FileName const lyx(tempfile.name());
1100 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1101 return readFile(lyx) == ReadSuccess;
1107 bool Buffer::readString(string const & s)
1109 params().compressed = false;
1112 istringstream is(s);
1114 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1115 FileName const fn = tempfile.name();
1118 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1120 if (success && file_format != LYX_FORMAT) {
1121 // We need to call lyx2lyx, so write the input to a file
1122 ofstream os(fn.toFilesystemEncoding().c_str());
1125 // lyxvc in readFile
1126 if (readFile(fn) != ReadSuccess)
1130 if (readDocument(lex))
1136 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1140 if (!lex.setFile(fname)) {
1141 Alert::error(_("File Not Found"),
1142 bformat(_("Unable to open file `%1$s'."),
1143 from_utf8(fn.absFileName())));
1144 return ReadFileNotFound;
1148 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1149 if (ret_plf != ReadSuccess)
1152 if (file_format != LYX_FORMAT) {
1154 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1155 if (ret_clf != ReadSuccess)
1157 ret_clf = readFile(tmpFile);
1158 if (ret_clf == ReadSuccess) {
1159 d->file_format = file_format;
1160 d->need_format_backup = true;
1165 // FIXME: InsetInfo needs to know whether the file is under VCS
1166 // during the parse process, so this has to be done before.
1167 lyxvc().file_found_hook(d->filename);
1169 if (readDocument(lex)) {
1170 Alert::error(_("Document format failure"),
1171 bformat(_("%1$s ended unexpectedly, which means"
1172 " that it is probably corrupted."),
1173 from_utf8(fn.absFileName())));
1174 return ReadDocumentFailure;
1177 d->file_fully_loaded = true;
1178 d->read_only = !d->filename.isWritable();
1179 params().compressed = formats.isZippedFile(d->filename);
1185 bool Buffer::isFullyLoaded() const
1187 return d->file_fully_loaded;
1191 void Buffer::setFullyLoaded(bool value)
1193 d->file_fully_loaded = value;
1197 bool Buffer::lastPreviewError() const
1199 return d->preview_error_;
1203 PreviewLoader * Buffer::loader() const
1205 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1207 if (!d->preview_loader_)
1208 d->preview_loader_ = new PreviewLoader(*this);
1209 return d->preview_loader_;
1213 void Buffer::removePreviews() const
1215 delete d->preview_loader_;
1216 d->preview_loader_ = 0;
1220 void Buffer::updatePreviews() const
1222 PreviewLoader * ploader = loader();
1226 InsetIterator it = inset_iterator_begin(*d->inset);
1227 InsetIterator const end = inset_iterator_end(*d->inset);
1228 for (; it != end; ++it)
1229 it->addPreview(it, *ploader);
1231 ploader->startLoading();
1235 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1236 FileName const & fn, int & file_format) const
1238 if(!lex.checkFor("\\lyxformat")) {
1239 Alert::error(_("Document format failure"),
1240 bformat(_("%1$s is not a readable LyX document."),
1241 from_utf8(fn.absFileName())));
1242 return ReadNoLyXFormat;
1248 // LyX formats 217 and earlier were written as 2.17. This corresponds
1249 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1250 // these cases. See also: www.lyx.org/trac/changeset/1313.
1251 size_t dot = tmp_format.find_first_of(".,");
1252 if (dot != string::npos)
1253 tmp_format.erase(dot, 1);
1255 file_format = convert<int>(tmp_format);
1260 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1261 FileName & tmpfile, int from_format)
1263 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1264 tempfile.setAutoRemove(false);
1265 tmpfile = tempfile.name();
1266 if(tmpfile.empty()) {
1267 Alert::error(_("Conversion failed"),
1268 bformat(_("%1$s is from a different"
1269 " version of LyX, but a temporary"
1270 " file for converting it could"
1271 " not be created."),
1272 from_utf8(fn.absFileName())));
1273 return LyX2LyXNoTempFile;
1276 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1277 if (lyx2lyx.empty()) {
1278 Alert::error(_("Conversion script not found"),
1279 bformat(_("%1$s is from a different"
1280 " version of LyX, but the"
1281 " conversion script lyx2lyx"
1282 " could not be found."),
1283 from_utf8(fn.absFileName())));
1284 return LyX2LyXNotFound;
1288 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1289 ostringstream command;
1290 command << os::python()
1291 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1292 << " -t " << convert<string>(LYX_FORMAT)
1293 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1294 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1295 string const command_str = command.str();
1297 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1299 cmd_ret const ret = runCommand(command_str);
1300 if (ret.first != 0) {
1301 if (from_format < LYX_FORMAT) {
1302 Alert::error(_("Conversion script failed"),
1303 bformat(_("%1$s is from an older version"
1304 " of LyX and the lyx2lyx script"
1305 " failed to convert it."),
1306 from_utf8(fn.absFileName())));
1307 return LyX2LyXOlderFormat;
1309 Alert::error(_("Conversion script failed"),
1310 bformat(_("%1$s is from a newer version"
1311 " of LyX and the lyx2lyx script"
1312 " failed to convert it."),
1313 from_utf8(fn.absFileName())));
1314 return LyX2LyXNewerFormat;
1321 FileName Buffer::getBackupName() const {
1322 FileName const & fn = fileName();
1323 string const fname = fn.onlyFileNameWithoutExt();
1324 string const fext = fn.extension();
1325 string const fpath = lyxrc.backupdir_path.empty() ?
1326 fn.onlyPath().absFileName() :
1327 lyxrc.backupdir_path;
1328 string const fform = convert<string>(d->file_format);
1329 string const backname = fname + "-lyxformat-" + fform;
1330 FileName backup(addName(fpath, addExtension(backname, fext)));
1332 // limit recursion, just in case
1334 unsigned long orig_checksum = 0;
1335 while (backup.exists() && v < 100) {
1336 if (orig_checksum == 0)
1337 orig_checksum = fn.checksum();
1338 unsigned long new_checksum = backup.checksum();
1339 if (orig_checksum == new_checksum) {
1340 LYXERR(Debug::FILES, "Not backing up " << fn <<
1341 "since " << backup << "has the same checksum.");
1342 // a bit of a hack, but we have to check this anyway
1343 // below, and setting this is simpler than introducing
1344 // a special boolean for this purpose.
1348 string const newbackname = backname + "-" + convert<string>(v);
1349 backup.set(addName(fpath, addExtension(newbackname, fext)));
1352 return v < 100 ? backup : FileName();
1356 // Should probably be moved to somewhere else: BufferView? GuiView?
1357 bool Buffer::save() const
1359 docstring const file = makeDisplayPath(absFileName(), 20);
1360 d->filename.refresh();
1362 // check the read-only status before moving the file as a backup
1363 if (d->filename.exists()) {
1364 bool const read_only = !d->filename.isWritable();
1366 Alert::warning(_("File is read-only"),
1367 bformat(_("The file %1$s cannot be written because it "
1368 "is marked as read-only."), file));
1373 // ask if the disk file has been externally modified (use checksum method)
1374 if (fileName().exists() && isExternallyModified(checksum_method)) {
1376 bformat(_("Document %1$s has been externally modified. "
1377 "Are you sure you want to overwrite this file?"), file);
1378 int const ret = Alert::prompt(_("Overwrite modified file?"),
1379 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1384 // We don't need autosaves in the immediate future. (Asger)
1385 resetAutosaveTimers();
1387 // if the file does not yet exist, none of the backup activity
1388 // that follows is necessary
1389 if (!fileName().exists()) {
1390 if (!writeFile(fileName()))
1396 // we first write the file to a new name, then move it to its
1397 // proper location once that has been done successfully. that
1398 // way we preserve the original file if something goes wrong.
1399 string const justname = fileName().onlyFileNameWithoutExt();
1400 auto tempfile = make_unique<TempFile>(fileName().onlyPath(),
1401 justname + "-XXXXXX.lyx");
1402 bool const symlink = fileName().isSymLink();
1404 tempfile->setAutoRemove(false);
1406 FileName savefile(tempfile->name());
1407 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1408 if (!writeFile(savefile))
1411 // we will set this to false if we fail
1412 bool made_backup = true;
1414 FileName backupName;
1415 bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1417 if (d->need_format_backup)
1418 backupName = getBackupName();
1420 // If we for some reason failed to find a backup name in case of
1421 // a format change, this will still set one. It's the best we can
1423 if (backupName.empty()) {
1424 backupName.set(fileName().absFileName() + "~");
1425 if (!lyxrc.backupdir_path.empty()) {
1426 string const mangledName =
1427 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1428 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1432 LYXERR(Debug::FILES, "Backing up original file to " <<
1433 backupName.absFileName());
1434 // Except file is symlink do not copy because of #6587.
1435 // Hard links have bad luck.
1436 made_backup = symlink ?
1437 fileName().copyTo(backupName):
1438 fileName().moveTo(backupName);
1441 Alert::error(_("Backup failure"),
1442 bformat(_("Cannot create backup file %1$s.\n"
1443 "Please check whether the directory exists and is writable."),
1444 from_utf8(backupName.absFileName())));
1445 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1446 } else if (d->need_format_backup) {
1447 // the original file has been backed up successfully, so we
1448 // will not need to do that again
1449 d->need_format_backup = false;
1453 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1454 // Only do this if tempfile is not in autoremove mode
1457 // If we have no symlink, we can simply rename the temp file.
1458 // Otherwise, we need to copy it so the symlink stays intact.
1459 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1460 savefile.moveTo(fileName()))
1462 // saveCheckSum() was already called by writeFile(), but the
1463 // time stamp is invalidated by copying/moving
1466 if (d->file_format != LYX_FORMAT)
1467 // the file associated with this buffer is now in the current format
1468 d->file_format = LYX_FORMAT;
1471 // else we saved the file, but failed to move it to the right location.
1473 if (needBackup && made_backup && !symlink) {
1474 // the original file was moved to some new location, so it will look
1475 // to the user as if it was deleted. (see bug #9234.) we could try
1476 // to restore it, but that would basically mean trying to do again
1477 // what we just failed to do. better to leave things as they are.
1478 Alert::error(_("Write failure"),
1479 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1480 "But LyX could not move it to:\n %2$s.\n"
1481 "Your original file has been backed up to:\n %3$s"),
1482 from_utf8(savefile.absFileName()),
1483 from_utf8(fileName().absFileName()),
1484 from_utf8(backupName.absFileName())));
1486 // either we did not try to make a backup, or else we tried and failed,
1487 // or else the original file was a symlink, in which case it was copied,
1488 // not moved. so the original file is intact.
1489 Alert::error(_("Write failure"),
1490 bformat(_("Cannot move saved file to:\n %1$s.\n"
1491 "But the file has successfully been saved as:\n %2$s."),
1492 from_utf8(fileName().absFileName()),
1493 from_utf8(savefile.absFileName())));
1499 bool Buffer::writeFile(FileName const & fname) const
1501 if (d->read_only && fname == d->filename)
1504 bool retval = false;
1506 docstring const str = bformat(_("Saving document %1$s..."),
1507 makeDisplayPath(fname.absFileName()));
1510 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1512 if (params().compressed) {
1513 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1514 retval = ofs && write(ofs);
1516 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1517 retval = ofs && write(ofs);
1521 message(str + _(" could not write file!"));
1526 // removeAutosaveFile();
1529 message(str + _(" done."));
1535 docstring Buffer::emergencyWrite()
1537 // No need to save if the buffer has not changed.
1541 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1543 docstring user_message = bformat(
1544 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1546 // We try to save three places:
1547 // 1) Same place as document. Unless it is an unnamed doc.
1549 string s = absFileName();
1552 if (writeFile(FileName(s))) {
1554 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1555 return user_message;
1557 user_message += " " + _("Save failed! Trying again...\n");
1561 // 2) In HOME directory.
1562 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1564 lyxerr << ' ' << s << endl;
1565 if (writeFile(FileName(s))) {
1567 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1568 return user_message;
1571 user_message += " " + _("Save failed! Trying yet again...\n");
1573 // 3) In "/tmp" directory.
1574 // MakeAbsPath to prepend the current
1575 // drive letter on OS/2
1576 s = addName(package().temp_dir().absFileName(), absFileName());
1578 lyxerr << ' ' << s << endl;
1579 if (writeFile(FileName(s))) {
1581 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1582 return user_message;
1585 user_message += " " + _("Save failed! Bummer. Document is lost.");
1588 return user_message;
1592 bool Buffer::write(ostream & ofs) const
1595 // Use the standard "C" locale for file output.
1596 ofs.imbue(locale::classic());
1599 // The top of the file should not be written by params().
1601 // write out a comment in the top of the file
1602 // Important: Keep the version formatting in sync with lyx2lyx and
1603 // tex2lyx (bug 7951)
1604 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1605 << " created this file. For more info see http://www.lyx.org/\n"
1606 << "\\lyxformat " << LYX_FORMAT << "\n"
1607 << "\\begin_document\n";
1609 /// For each author, set 'used' to true if there is a change
1610 /// by this author in the document; otherwise set it to 'false'.
1611 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1612 AuthorList::Authors::const_iterator a_end = params().authors().end();
1613 for (; a_it != a_end; ++a_it)
1614 a_it->setUsed(false);
1616 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1617 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1618 for ( ; it != end; ++it)
1619 it->checkAuthors(params().authors());
1621 // now write out the buffer parameters.
1622 ofs << "\\begin_header\n";
1623 params().writeFile(ofs, this);
1624 ofs << "\\end_header\n";
1627 ofs << "\n\\begin_body\n";
1629 ofs << "\n\\end_body\n";
1631 // Write marker that shows file is complete
1632 ofs << "\\end_document" << endl;
1634 // Shouldn't really be needed....
1637 // how to check if close went ok?
1638 // Following is an attempt... (BE 20001011)
1640 // good() returns false if any error occurred, including some
1641 // formatting error.
1642 // bad() returns true if something bad happened in the buffer,
1643 // which should include file system full errors.
1648 lyxerr << "File was not closed properly." << endl;
1655 bool Buffer::makeLaTeXFile(FileName const & fname,
1656 string const & original_path,
1657 OutputParams const & runparams_in,
1658 OutputWhat output) const
1660 OutputParams runparams = runparams_in;
1662 // XeTeX with TeX fonts is only safe with ASCII encoding (see also #9740),
1663 // Check here, because the "flavor" is not known in BufferParams::encoding()
1664 // (power users can override this safety measure selecting "utf8-plain").
1665 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX)
1666 && (runparams.encoding->name() != "utf8-plain"))
1667 runparams.encoding = encodings.fromLyXName("ascii");
1669 string const encoding = runparams.encoding->iconvName();
1670 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1673 try { ofs.reset(encoding); }
1674 catch (iconv_codecvt_facet_exception const & e) {
1675 lyxerr << "Caught iconv exception: " << e.what() << endl;
1676 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1677 "verify that the support software for your encoding (%1$s) is "
1678 "properly installed"), from_ascii(encoding)));
1681 if (!openFileWrite(ofs, fname))
1684 ErrorList & errorList = d->errorLists["Export"];
1686 bool failed_export = false;
1687 otexstream os(ofs, d->texrow);
1689 // make sure we are ready to export
1690 // this needs to be done before we validate
1691 // FIXME Do we need to do this all the time? I.e., in children
1692 // of a master we are exporting?
1694 updateMacroInstances(OutputUpdate);
1697 os.texrow().reset();
1698 writeLaTeXSource(os, original_path, runparams, output);
1700 catch (EncodingException const & e) {
1701 docstring const failed(1, e.failed_char);
1703 oss << "0x" << hex << e.failed_char << dec;
1704 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1705 " (code point %2$s)"),
1706 failed, from_utf8(oss.str()));
1707 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1708 "representable in the chosen encoding.\n"
1709 "Changing the document encoding to utf8 could help."),
1710 e.par_id, e.pos, e.pos + 1));
1711 failed_export = true;
1713 catch (iconv_codecvt_facet_exception const & e) {
1714 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1715 _(e.what()), -1, 0, 0));
1716 failed_export = true;
1718 catch (exception const & e) {
1719 errorList.push_back(ErrorItem(_("conversion failed"),
1720 _(e.what()), -1, 0, 0));
1721 failed_export = true;
1724 lyxerr << "Caught some really weird exception..." << endl;
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 // Japanese might be required only in some children of a document,
1880 // but once required, we must keep use_japanese true.
1881 runparams.use_japanese |= features.isRequired("japanese");
1884 // Restore the parenthood if needed
1885 if (!runparams.is_child)
1886 d->ignore_parent = false;
1891 os << "\\begin{document}\n";
1893 // output the parent macros
1894 MacroSet::iterator it = parentMacros.begin();
1895 MacroSet::iterator end = parentMacros.end();
1896 for (; it != end; ++it) {
1897 int num_lines = (*it)->write(os.os(), true);
1898 os.texrow().newlines(num_lines);
1901 } // output_preamble
1903 os.texrow().start(paragraphs().begin()->id(), 0);
1905 LYXERR(Debug::INFO, "preamble finished, now the body.");
1908 latexParagraphs(*this, text(), os, runparams);
1910 // Restore the parenthood if needed
1911 if (!runparams.is_child)
1912 d->ignore_parent = false;
1914 // add this just in case after all the paragraphs
1917 if (output_preamble) {
1918 os << "\\end{document}\n";
1919 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1921 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1923 runparams_in.encoding = runparams.encoding;
1925 os.texrow().finalize();
1927 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1928 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1932 void Buffer::makeDocBookFile(FileName const & fname,
1933 OutputParams const & runparams,
1934 OutputWhat output) const
1936 LYXERR(Debug::LATEX, "makeDocBookFile...");
1939 if (!openFileWrite(ofs, fname))
1942 // make sure we are ready to export
1943 // this needs to be done before we validate
1945 updateMacroInstances(OutputUpdate);
1947 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1951 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1955 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1956 OutputParams const & runparams,
1957 OutputWhat output) const
1959 LaTeXFeatures features(*this, params(), runparams);
1962 d->texrow.reset(false);
1964 DocumentClass const & tclass = params().documentClass();
1965 string const & top_element = tclass.latexname();
1967 bool const output_preamble =
1968 output == FullSource || output == OnlyPreamble;
1969 bool const output_body =
1970 output == FullSource || output == OnlyBody;
1972 if (output_preamble) {
1973 if (runparams.flavor == OutputParams::XML)
1974 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1977 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1980 if (! tclass.class_header().empty())
1981 os << from_ascii(tclass.class_header());
1982 else if (runparams.flavor == OutputParams::XML)
1983 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1984 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1986 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1988 docstring preamble = from_utf8(params().preamble);
1989 if (runparams.flavor != OutputParams::XML ) {
1990 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1991 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1992 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1993 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1996 string const name = runparams.nice
1997 ? changeExtension(absFileName(), ".sgml") : fname;
1998 preamble += features.getIncludedFiles(name);
1999 preamble += features.getLyXSGMLEntities();
2001 if (!preamble.empty()) {
2002 os << "\n [ " << preamble << " ]";
2008 string top = top_element;
2010 if (runparams.flavor == OutputParams::XML)
2011 top += params().language->code();
2013 top += params().language->code().substr(0, 2);
2016 if (!params().options.empty()) {
2018 top += params().options;
2021 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2022 << " file was created by LyX " << lyx_version
2023 << "\n See http://www.lyx.org/ for more information -->\n";
2025 params().documentClass().counters().reset();
2027 sgml::openTag(os, top);
2029 docbookParagraphs(text(), *this, os, runparams);
2030 sgml::closeTag(os, top_element);
2035 void Buffer::makeLyXHTMLFile(FileName const & fname,
2036 OutputParams const & runparams) const
2038 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2041 if (!openFileWrite(ofs, fname))
2044 // make sure we are ready to export
2045 // this has to be done before we validate
2046 updateBuffer(UpdateMaster, OutputUpdate);
2047 updateMacroInstances(OutputUpdate);
2049 writeLyXHTMLSource(ofs, runparams, FullSource);
2053 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2057 void Buffer::writeLyXHTMLSource(odocstream & os,
2058 OutputParams const & runparams,
2059 OutputWhat output) const
2061 LaTeXFeatures features(*this, params(), runparams);
2063 d->bibinfo_.makeCitationLabels(*this);
2065 bool const output_preamble =
2066 output == FullSource || output == OnlyPreamble;
2067 bool const output_body =
2068 output == FullSource || output == OnlyBody || output == IncludedFile;
2070 if (output_preamble) {
2071 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2072 << "<!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"
2073 // FIXME Language should be set properly.
2074 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2076 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2077 // FIXME Presumably need to set this right
2078 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2080 docstring const & doctitle = features.htmlTitle();
2082 << (doctitle.empty() ?
2083 from_ascii("LyX Document") :
2084 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2087 docstring styles = features.getTClassHTMLPreamble();
2088 if (!styles.empty())
2089 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2091 styles = from_utf8(features.getPreambleSnippets());
2092 if (!styles.empty())
2093 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2095 // we will collect CSS information in a stream, and then output it
2096 // either here, as part of the header, or else in a separate file.
2097 odocstringstream css;
2098 styles = from_utf8(features.getCSSSnippets());
2099 if (!styles.empty())
2100 css << "/* LyX Provided Styles */\n" << styles << '\n';
2102 styles = features.getTClassHTMLStyles();
2103 if (!styles.empty())
2104 css << "/* Layout-provided Styles */\n" << styles << '\n';
2106 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2107 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2108 if (needfg || needbg) {
2109 css << "\nbody {\n";
2112 << from_ascii(X11hexname(params().fontcolor))
2115 css << " background-color: "
2116 << from_ascii(X11hexname(params().backgroundcolor))
2121 docstring const dstyles = css.str();
2122 if (!dstyles.empty()) {
2123 bool written = false;
2124 if (params().html_css_as_file) {
2125 // open a file for CSS info
2127 string const fcssname = addName(temppath(), "docstyle.css");
2128 FileName const fcssfile = FileName(fcssname);
2129 if (openFileWrite(ocss, fcssfile)) {
2133 // write link to header
2134 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2136 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2139 // we are here if the CSS is supposed to be written to the header
2140 // or if we failed to write it to an external file.
2142 os << "<style type='text/css'>\n"
2151 bool const output_body_tag = (output != IncludedFile);
2152 if (output_body_tag)
2155 if (output != IncludedFile)
2156 // if we're an included file, the counters are in the master.
2157 params().documentClass().counters().reset();
2158 xhtmlParagraphs(text(), *this, xs, runparams);
2159 if (output_body_tag)
2163 if (output_preamble)
2168 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2169 // Other flags: -wall -v0 -x
2170 int Buffer::runChktex()
2174 // get LaTeX-Filename
2175 FileName const path(temppath());
2176 string const name = addName(path.absFileName(), latexName());
2177 string const org_path = filePath();
2179 PathChanger p(path); // path to LaTeX file
2180 message(_("Running chktex..."));
2182 // Generate the LaTeX file if neccessary
2183 OutputParams runparams(¶ms().encoding());
2184 runparams.flavor = OutputParams::LATEX;
2185 runparams.nice = false;
2186 runparams.linelen = lyxrc.plaintext_linelen;
2187 makeLaTeXFile(FileName(name), org_path, runparams);
2190 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2191 int const res = chktex.run(terr); // run chktex
2194 Alert::error(_("chktex failure"),
2195 _("Could not run chktex successfully."));
2197 ErrorList & errlist = d->errorLists["ChkTeX"];
2199 bufferErrors(terr, errlist);
2204 if (runparams.silent)
2205 d->errorLists["ChkTeX"].clear();
2213 void Buffer::validate(LaTeXFeatures & features) const
2215 // Validate the buffer params, but not for included
2216 // files, since they also use the parent buffer's
2218 if (!features.runparams().is_child)
2219 params().validate(features);
2221 for_each(paragraphs().begin(), paragraphs().end(),
2222 bind(&Paragraph::validate, _1, ref(features)));
2224 if (lyxerr.debugging(Debug::LATEX)) {
2225 features.showStruct();
2230 void Buffer::getLabelList(vector<docstring> & list) const
2232 // If this is a child document, use the master's list instead.
2234 masterBuffer()->getLabelList(list);
2239 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2240 Toc::const_iterator toc_it = toc->begin();
2241 Toc::const_iterator end = toc->end();
2242 for (; toc_it != end; ++toc_it) {
2243 if (toc_it->depth() == 0)
2244 list.push_back(toc_it->str());
2249 void Buffer::updateBibfilesCache(UpdateScope scope) const
2251 // FIXME This is probably unnecssary, given where we call this.
2252 // If this is a child document, use the parent's cache instead.
2253 if (parent() && scope != UpdateChildOnly) {
2254 masterBuffer()->updateBibfilesCache();
2258 d->bibfiles_cache_.clear();
2259 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2260 if (it->lyxCode() == BIBTEX_CODE) {
2261 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2262 support::FileNameList const bibfiles = inset.getBibFiles();
2263 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2266 } else if (it->lyxCode() == INCLUDE_CODE) {
2267 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2268 Buffer const * const incbuf = inset.getChildBuffer();
2271 support::FileNameList const & bibfiles =
2272 incbuf->getBibfilesCache(UpdateChildOnly);
2273 if (!bibfiles.empty()) {
2274 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2280 d->bibfile_cache_valid_ = true;
2281 d->bibinfo_cache_valid_ = false;
2282 d->cite_labels_valid_ = false;
2286 void Buffer::invalidateBibinfoCache() const
2288 d->bibinfo_cache_valid_ = false;
2289 d->cite_labels_valid_ = false;
2290 // also invalidate the cache for the parent buffer
2291 Buffer const * const pbuf = d->parent();
2293 pbuf->invalidateBibinfoCache();
2297 void Buffer::invalidateBibfileCache() const
2299 d->bibfile_cache_valid_ = false;
2300 d->bibinfo_cache_valid_ = false;
2301 d->cite_labels_valid_ = false;
2302 // also invalidate the cache for the parent buffer
2303 Buffer const * const pbuf = d->parent();
2305 pbuf->invalidateBibfileCache();
2309 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2311 // FIXME This is probably unnecessary, given where we call this.
2312 // If this is a child document, use the master's cache instead.
2313 Buffer const * const pbuf = masterBuffer();
2314 if (pbuf != this && scope != UpdateChildOnly)
2315 return pbuf->getBibfilesCache();
2317 if (!d->bibfile_cache_valid_)
2318 this->updateBibfilesCache(scope);
2320 return d->bibfiles_cache_;
2324 BiblioInfo const & Buffer::masterBibInfo() const
2326 Buffer const * const tmp = masterBuffer();
2328 return tmp->masterBibInfo();
2333 void Buffer::checkIfBibInfoCacheIsValid() const
2335 // use the master's cache
2336 Buffer const * const tmp = masterBuffer();
2338 tmp->checkIfBibInfoCacheIsValid();
2342 // compare the cached timestamps with the actual ones.
2343 FileNameList const & bibfiles_cache = getBibfilesCache();
2344 FileNameList::const_iterator ei = bibfiles_cache.begin();
2345 FileNameList::const_iterator en = bibfiles_cache.end();
2346 for (; ei != en; ++ ei) {
2347 time_t lastw = ei->lastModified();
2348 time_t prevw = d->bibfile_status_[*ei];
2349 if (lastw != prevw) {
2350 d->bibinfo_cache_valid_ = false;
2351 d->cite_labels_valid_ = false;
2352 d->bibfile_status_[*ei] = lastw;
2358 void Buffer::reloadBibInfoCache() const
2360 // use the master's cache
2361 Buffer const * const tmp = masterBuffer();
2363 tmp->reloadBibInfoCache();
2367 checkIfBibInfoCacheIsValid();
2368 if (d->bibinfo_cache_valid_)
2371 d->bibinfo_.clear();
2373 d->bibinfo_cache_valid_ = true;
2377 void Buffer::collectBibKeys() const
2379 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2380 it->collectBibKeys(it);
2384 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2386 Buffer const * tmp = masterBuffer();
2387 BiblioInfo & masterbi = (tmp == this) ?
2388 d->bibinfo_ : tmp->d->bibinfo_;
2389 masterbi.mergeBiblioInfo(bi);
2393 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2395 Buffer const * tmp = masterBuffer();
2396 BiblioInfo & masterbi = (tmp == this) ?
2397 d->bibinfo_ : tmp->d->bibinfo_;
2402 void Buffer::makeCitationLabels() const
2404 Buffer const * const master = masterBuffer();
2405 return d->bibinfo_.makeCitationLabels(*master);
2409 bool Buffer::citeLabelsValid() const
2411 return masterBuffer()->d->cite_labels_valid_;
2415 void Buffer::removeBiblioTempFiles() const
2417 // We remove files that contain LaTeX commands specific to the
2418 // particular bibliographic style being used, in order to avoid
2419 // LaTeX errors when we switch style.
2420 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2421 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2422 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2423 aux_file.removeFile();
2424 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2425 bbl_file.removeFile();
2426 // Also for the parent buffer
2427 Buffer const * const pbuf = parent();
2429 pbuf->removeBiblioTempFiles();
2433 bool Buffer::isDepClean(string const & name) const
2435 DepClean::const_iterator const it = d->dep_clean.find(name);
2436 if (it == d->dep_clean.end())
2442 void Buffer::markDepClean(string const & name)
2444 d->dep_clean[name] = true;
2448 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2451 // FIXME? if there is an Buffer LFUN that can be dispatched even
2452 // if internal, put a switch '(cmd.action)' here.
2458 switch (cmd.action()) {
2460 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2461 flag.setOnOff(isReadonly());
2464 // FIXME: There is need for a command-line import.
2465 //case LFUN_BUFFER_IMPORT:
2467 case LFUN_BUFFER_AUTO_SAVE:
2470 case LFUN_BUFFER_EXPORT_CUSTOM:
2471 // FIXME: Nothing to check here?
2474 case LFUN_BUFFER_EXPORT: {
2475 docstring const arg = cmd.argument();
2476 if (arg == "custom") {
2480 string format = to_utf8(arg);
2481 size_t pos = format.find(' ');
2482 if (pos != string::npos)
2483 format = format.substr(0, pos);
2484 enable = params().isExportable(format);
2486 flag.message(bformat(
2487 _("Don't know how to export to format: %1$s"), arg));
2491 case LFUN_BUFFER_CHKTEX:
2492 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2495 case LFUN_BUILD_PROGRAM:
2496 enable = params().isExportable("program");
2499 case LFUN_BRANCH_ACTIVATE:
2500 case LFUN_BRANCH_DEACTIVATE:
2501 case LFUN_BRANCH_MASTER_ACTIVATE:
2502 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2503 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2504 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2505 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2506 : params().branchlist();
2507 docstring const branchName = cmd.argument();
2508 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2512 case LFUN_BRANCH_ADD:
2513 case LFUN_BRANCHES_RENAME:
2514 // if no Buffer is present, then of course we won't be called!
2517 case LFUN_BUFFER_LANGUAGE:
2518 enable = !isReadonly();
2521 case LFUN_BUFFER_VIEW_CACHE:
2522 (d->preview_file_).refresh();
2523 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2526 case LFUN_CHANGES_TRACK:
2527 flag.setEnabled(true);
2528 flag.setOnOff(params().track_changes);
2531 case LFUN_CHANGES_OUTPUT:
2532 flag.setEnabled(true);
2533 flag.setOnOff(params().output_changes);
2536 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2537 flag.setOnOff(params().compressed);
2541 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2542 flag.setOnOff(params().output_sync);
2549 flag.setEnabled(enable);
2554 void Buffer::dispatch(string const & command, DispatchResult & result)
2556 return dispatch(lyxaction.lookupFunc(command), result);
2560 // NOTE We can end up here even if we have no GUI, because we are called
2561 // by LyX::exec to handled command-line requests. So we may need to check
2562 // whether we have a GUI or not. The boolean use_gui holds this information.
2563 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2566 // FIXME? if there is an Buffer LFUN that can be dispatched even
2567 // if internal, put a switch '(cmd.action())' here.
2568 dr.dispatched(false);
2571 string const argument = to_utf8(func.argument());
2572 // We'll set this back to false if need be.
2573 bool dispatched = true;
2574 undo().beginUndoGroup();
2576 switch (func.action()) {
2577 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2578 if (lyxvc().inUse()) {
2579 string log = lyxvc().toggleReadOnly();
2584 setReadonly(!isReadonly());
2587 case LFUN_BUFFER_EXPORT: {
2588 ExportStatus const status = doExport(argument, false);
2589 dr.setError(status != ExportSuccess);
2590 if (status != ExportSuccess)
2591 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2596 case LFUN_BUILD_PROGRAM: {
2597 ExportStatus const status = doExport("program", true);
2598 dr.setError(status != ExportSuccess);
2599 if (status != ExportSuccess)
2600 dr.setMessage(_("Error generating literate programming code."));
2604 case LFUN_BUFFER_CHKTEX:
2608 case LFUN_BUFFER_EXPORT_CUSTOM: {
2610 string command = split(argument, format_name, ' ');
2611 Format const * format = formats.getFormat(format_name);
2613 lyxerr << "Format \"" << format_name
2614 << "\" not recognized!"
2619 // The name of the file created by the conversion process
2622 // Output to filename
2623 if (format->name() == "lyx") {
2624 string const latexname = latexName(false);
2625 filename = changeExtension(latexname,
2626 format->extension());
2627 filename = addName(temppath(), filename);
2629 if (!writeFile(FileName(filename)))
2633 doExport(format_name, true, filename);
2636 // Substitute $$FName for filename
2637 if (!contains(command, "$$FName"))
2638 command = "( " + command + " ) < $$FName";
2639 command = subst(command, "$$FName", filename);
2641 // Execute the command in the background
2643 call.startscript(Systemcall::DontWait, command,
2644 filePath(), layoutPos());
2648 // FIXME: There is need for a command-line import.
2650 case LFUN_BUFFER_IMPORT:
2655 case LFUN_BUFFER_AUTO_SAVE:
2657 resetAutosaveTimers();
2660 case LFUN_BRANCH_ACTIVATE:
2661 case LFUN_BRANCH_DEACTIVATE:
2662 case LFUN_BRANCH_MASTER_ACTIVATE:
2663 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2664 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2665 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2666 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2669 docstring const branch_name = func.argument();
2670 // the case without a branch name is handled elsewhere
2671 if (branch_name.empty()) {
2675 Branch * branch = buf->params().branchlist().find(branch_name);
2677 LYXERR0("Branch " << branch_name << " does not exist.");
2679 docstring const msg =
2680 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2684 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2685 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2686 if (branch->isSelected() != activate) {
2687 buf->undo().recordUndoBufferParams(CursorData());
2688 branch->setSelected(activate);
2690 dr.screenUpdate(Update::Force);
2691 dr.forceBufferUpdate();
2696 case LFUN_BRANCH_ADD: {
2697 docstring branch_name = func.argument();
2698 if (branch_name.empty()) {
2702 BranchList & branch_list = params().branchlist();
2703 vector<docstring> const branches =
2704 getVectorFromString(branch_name, branch_list.separator());
2706 for (vector<docstring>::const_iterator it = branches.begin();
2707 it != branches.end(); ++it) {
2709 Branch * branch = branch_list.find(branch_name);
2711 LYXERR0("Branch " << branch_name << " already exists.");
2715 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2717 undo().recordUndoBufferParams(CursorData());
2718 branch_list.add(branch_name);
2719 branch = branch_list.find(branch_name);
2720 string const x11hexname = X11hexname(branch->color());
2721 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2722 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2724 dr.screenUpdate(Update::Force);
2732 case LFUN_BRANCHES_RENAME: {
2733 if (func.argument().empty())
2736 docstring const oldname = from_utf8(func.getArg(0));
2737 docstring const newname = from_utf8(func.getArg(1));
2738 InsetIterator it = inset_iterator_begin(inset());
2739 InsetIterator const end = inset_iterator_end(inset());
2740 bool success = false;
2741 for (; it != end; ++it) {
2742 if (it->lyxCode() == BRANCH_CODE) {
2743 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2744 if (ins.branch() == oldname) {
2745 undo().recordUndo(CursorData(it));
2746 ins.rename(newname);
2751 if (it->lyxCode() == INCLUDE_CODE) {
2752 // get buffer of external file
2753 InsetInclude const & ins =
2754 static_cast<InsetInclude const &>(*it);
2755 Buffer * child = ins.getChildBuffer();
2758 child->dispatch(func, dr);
2763 dr.screenUpdate(Update::Force);
2764 dr.forceBufferUpdate();
2769 case LFUN_BUFFER_VIEW_CACHE:
2770 if (!formats.view(*this, d->preview_file_,
2771 d->preview_format_))
2772 dr.setMessage(_("Error viewing the output file."));
2775 case LFUN_CHANGES_TRACK:
2776 if (params().save_transient_properties)
2777 undo().recordUndoBufferParams(CursorData());
2778 params().track_changes = !params().track_changes;
2779 if (!params().track_changes)
2780 dr.forceChangesUpdate();
2783 case LFUN_CHANGES_OUTPUT:
2784 if (params().save_transient_properties)
2785 undo().recordUndoBufferParams(CursorData());
2786 params().output_changes = !params().output_changes;
2787 if (params().output_changes) {
2788 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2789 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2790 LaTeXFeatures::isAvailable("xcolor");
2792 if (!dvipost && !xcolorulem) {
2793 Alert::warning(_("Changes not shown in LaTeX output"),
2794 _("Changes will not be highlighted in LaTeX output, "
2795 "because neither dvipost nor xcolor/ulem are installed.\n"
2796 "Please install these packages or redefine "
2797 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2798 } else if (!xcolorulem) {
2799 Alert::warning(_("Changes not shown in LaTeX output"),
2800 _("Changes will not be highlighted in LaTeX output "
2801 "when using pdflatex, because xcolor and ulem are not installed.\n"
2802 "Please install both packages or redefine "
2803 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2808 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2809 // turn compression on/off
2810 undo().recordUndoBufferParams(CursorData());
2811 params().compressed = !params().compressed;
2814 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2815 undo().recordUndoBufferParams(CursorData());
2816 params().output_sync = !params().output_sync;
2823 dr.dispatched(dispatched);
2824 undo().endUndoGroup();
2828 void Buffer::changeLanguage(Language const * from, Language const * to)
2830 LASSERT(from, return);
2831 LASSERT(to, return);
2833 for_each(par_iterator_begin(),
2835 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2839 bool Buffer::isMultiLingual() const
2841 ParConstIterator end = par_iterator_end();
2842 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2843 if (it->isMultiLingual(params()))
2850 std::set<Language const *> Buffer::getLanguages() const
2852 std::set<Language const *> languages;
2853 getLanguages(languages);
2858 void Buffer::getLanguages(std::set<Language const *> & languages) const
2860 ParConstIterator end = par_iterator_end();
2861 // add the buffer language, even if it's not actively used
2862 languages.insert(language());
2863 // iterate over the paragraphs
2864 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2865 it->getLanguages(languages);
2867 ListOfBuffers clist = getDescendents();
2868 ListOfBuffers::const_iterator cit = clist.begin();
2869 ListOfBuffers::const_iterator const cen = clist.end();
2870 for (; cit != cen; ++cit)
2871 (*cit)->getLanguages(languages);
2875 DocIterator Buffer::getParFromID(int const id) const
2877 Buffer * buf = const_cast<Buffer *>(this);
2879 // John says this is called with id == -1 from undo
2880 lyxerr << "getParFromID(), id: " << id << endl;
2881 return doc_iterator_end(buf);
2884 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2885 if (it.paragraph().id() == id)
2888 return doc_iterator_end(buf);
2892 bool Buffer::hasParWithID(int const id) const
2894 return !getParFromID(id).atEnd();
2898 ParIterator Buffer::par_iterator_begin()
2900 return ParIterator(doc_iterator_begin(this));
2904 ParIterator Buffer::par_iterator_end()
2906 return ParIterator(doc_iterator_end(this));
2910 ParConstIterator Buffer::par_iterator_begin() const
2912 return ParConstIterator(doc_iterator_begin(this));
2916 ParConstIterator Buffer::par_iterator_end() const
2918 return ParConstIterator(doc_iterator_end(this));
2922 Language const * Buffer::language() const
2924 return params().language;
2928 docstring const Buffer::B_(string const & l10n) const
2930 return params().B_(l10n);
2934 bool Buffer::isClean() const
2936 return d->lyx_clean;
2940 bool Buffer::isExternallyModified(CheckMethod method) const
2942 LASSERT(d->filename.exists(), return false);
2943 // if method == timestamp, check timestamp before checksum
2944 return (method == checksum_method
2945 || d->timestamp_ != d->filename.lastModified())
2946 && d->checksum_ != d->filename.checksum();
2950 void Buffer::saveCheckSum() const
2952 FileName const & file = d->filename;
2955 if (file.exists()) {
2956 d->timestamp_ = file.lastModified();
2957 d->checksum_ = file.checksum();
2959 // in the case of save to a new file.
2966 void Buffer::markClean() const
2968 if (!d->lyx_clean) {
2969 d->lyx_clean = true;
2972 // if the .lyx file has been saved, we don't need an
2974 d->bak_clean = true;
2975 d->undo_.markDirty();
2979 void Buffer::setUnnamed(bool flag)
2985 bool Buffer::isUnnamed() const
2992 /// Don't check unnamed, here: isInternal() is used in
2993 /// newBuffer(), where the unnamed flag has not been set by anyone
2994 /// yet. Also, for an internal buffer, there should be no need for
2995 /// retrieving fileName() nor for checking if it is unnamed or not.
2996 bool Buffer::isInternal() const
2998 return d->internal_buffer;
3002 void Buffer::setInternal(bool flag)
3004 d->internal_buffer = flag;
3008 void Buffer::markDirty()
3011 d->lyx_clean = false;
3014 d->bak_clean = false;
3016 DepClean::iterator it = d->dep_clean.begin();
3017 DepClean::const_iterator const end = d->dep_clean.end();
3019 for (; it != end; ++it)
3024 FileName Buffer::fileName() const
3030 string Buffer::absFileName() const
3032 return d->filename.absFileName();
3036 string Buffer::filePath() const
3038 string const abs = d->filename.onlyPath().absFileName();
3041 int last = abs.length() - 1;
3043 return abs[last] == '/' ? abs : abs + '/';
3047 DocFileName Buffer::getReferencedFileName(string const & fn) const
3050 if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3051 result.set(fn, filePath());
3053 // filePath() ends with a path separator
3054 FileName const test(filePath() + fn);
3056 result.set(fn, filePath());
3058 result.set(fn, params().origin);
3065 string Buffer::layoutPos() const
3067 return d->layout_position;
3071 void Buffer::setLayoutPos(string const & path)
3074 d->layout_position.clear();
3078 LATTEST(FileName::isAbsolute(path));
3080 d->layout_position =
3081 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3083 if (d->layout_position.empty())
3084 d->layout_position = ".";
3088 bool Buffer::isReadonly() const
3090 return d->read_only;
3094 void Buffer::setParent(Buffer const * buffer)
3096 // Avoids recursive include.
3097 d->setParent(buffer == this ? 0 : buffer);
3102 Buffer const * Buffer::parent() const
3108 ListOfBuffers Buffer::allRelatives() const
3110 ListOfBuffers lb = masterBuffer()->getDescendents();
3111 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3116 Buffer const * Buffer::masterBuffer() const
3118 // FIXME Should be make sure we are not in some kind
3119 // of recursive include? A -> B -> A will crash this.
3120 Buffer const * const pbuf = d->parent();
3124 return pbuf->masterBuffer();
3128 bool Buffer::isChild(Buffer * child) const
3130 return d->children_positions.find(child) != d->children_positions.end();
3134 DocIterator Buffer::firstChildPosition(Buffer const * child)
3136 Impl::BufferPositionMap::iterator it;
3137 it = d->children_positions.find(child);
3138 if (it == d->children_positions.end())
3139 return DocIterator(this);
3144 bool Buffer::hasChildren() const
3146 return !d->children_positions.empty();
3150 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3152 // loop over children
3153 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3154 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3155 for (; it != end; ++it) {
3156 Buffer * child = const_cast<Buffer *>(it->first);
3158 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3159 if (bit != clist.end())
3161 clist.push_back(child);
3163 // there might be grandchildren
3164 child->collectChildren(clist, true);
3169 ListOfBuffers Buffer::getChildren() const
3172 collectChildren(v, false);
3173 // Make sure we have not included ourselves.
3174 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3175 if (bit != v.end()) {
3176 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3183 ListOfBuffers Buffer::getDescendents() const
3186 collectChildren(v, true);
3187 // Make sure we have not included ourselves.
3188 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3189 if (bit != v.end()) {
3190 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3197 template<typename M>
3198 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3203 typename M::const_iterator it = m.lower_bound(x);
3204 if (it == m.begin())
3212 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3213 DocIterator const & pos) const
3215 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3217 // if paragraphs have no macro context set, pos will be empty
3221 // we haven't found anything yet
3222 DocIterator bestPos = owner_->par_iterator_begin();
3223 MacroData const * bestData = 0;
3225 // find macro definitions for name
3226 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3227 if (nameIt != macros.end()) {
3228 // find last definition in front of pos or at pos itself
3229 PositionScopeMacroMap::const_iterator it
3230 = greatest_below(nameIt->second, pos);
3231 if (it != nameIt->second.end()) {
3233 // scope ends behind pos?
3234 if (pos < it->second.scope) {
3235 // Looks good, remember this. If there
3236 // is no external macro behind this,
3237 // we found the right one already.
3238 bestPos = it->first;
3239 bestData = &it->second.macro;
3243 // try previous macro if there is one
3244 if (it == nameIt->second.begin())
3251 // find macros in included files
3252 PositionScopeBufferMap::const_iterator it
3253 = greatest_below(position_to_children, pos);
3254 if (it == position_to_children.end())
3255 // no children before
3259 // do we know something better (i.e. later) already?
3260 if (it->first < bestPos )
3263 // scope ends behind pos?
3264 if (pos < it->second.scope
3265 && (cloned_buffer_ ||
3266 theBufferList().isLoaded(it->second.buffer))) {
3267 // look for macro in external file
3269 MacroData const * data
3270 = it->second.buffer->getMacro(name, false);
3273 bestPos = it->first;
3279 // try previous file if there is one
3280 if (it == position_to_children.begin())
3285 // return the best macro we have found
3290 MacroData const * Buffer::getMacro(docstring const & name,
3291 DocIterator const & pos, bool global) const
3296 // query buffer macros
3297 MacroData const * data = d->getBufferMacro(name, pos);
3301 // If there is a master buffer, query that
3302 Buffer const * const pbuf = d->parent();
3304 d->macro_lock = true;
3305 MacroData const * macro = pbuf->getMacro(
3306 name, *this, false);
3307 d->macro_lock = false;
3313 data = MacroTable::globalMacros().get(name);
3322 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3324 // set scope end behind the last paragraph
3325 DocIterator scope = par_iterator_begin();
3326 scope.pit() = scope.lastpit() + 1;
3328 return getMacro(name, scope, global);
3332 MacroData const * Buffer::getMacro(docstring const & name,
3333 Buffer const & child, bool global) const
3335 // look where the child buffer is included first
3336 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3337 if (it == d->children_positions.end())
3340 // check for macros at the inclusion position
3341 return getMacro(name, it->second, global);
3345 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3347 pit_type const lastpit = it.lastpit();
3349 // look for macros in each paragraph
3350 while (it.pit() <= lastpit) {
3351 Paragraph & par = it.paragraph();
3353 // iterate over the insets of the current paragraph
3354 InsetList const & insets = par.insetList();
3355 InsetList::const_iterator iit = insets.begin();
3356 InsetList::const_iterator end = insets.end();
3357 for (; iit != end; ++iit) {
3358 it.pos() = iit->pos;
3360 // is it a nested text inset?
3361 if (iit->inset->asInsetText()) {
3362 // Inset needs its own scope?
3363 InsetText const * itext = iit->inset->asInsetText();
3364 bool newScope = itext->isMacroScope();
3366 // scope which ends just behind the inset
3367 DocIterator insetScope = it;
3370 // collect macros in inset
3371 it.push_back(CursorSlice(*iit->inset));
3372 updateMacros(it, newScope ? insetScope : scope);
3377 if (iit->inset->asInsetTabular()) {
3378 CursorSlice slice(*iit->inset);
3379 size_t const numcells = slice.nargs();
3380 for (; slice.idx() < numcells; slice.forwardIdx()) {
3381 it.push_back(slice);
3382 updateMacros(it, scope);
3388 // is it an external file?
3389 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3390 // get buffer of external file
3391 InsetInclude const & inset =
3392 static_cast<InsetInclude const &>(*iit->inset);
3394 Buffer * child = inset.getChildBuffer();
3399 // register its position, but only when it is
3400 // included first in the buffer
3401 if (children_positions.find(child) ==
3402 children_positions.end())
3403 children_positions[child] = it;
3405 // register child with its scope
3406 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3410 InsetMath * im = iit->inset->asInsetMath();
3411 if (doing_export && im) {
3412 InsetMathHull * hull = im->asHullInset();
3414 hull->recordLocation(it);
3417 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3421 MathMacroTemplate & macroTemplate =
3422 *iit->inset->asInsetMath()->asMacroTemplate();
3423 MacroContext mc(owner_, it);
3424 macroTemplate.updateToContext(mc);
3427 bool valid = macroTemplate.validMacro();
3428 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3429 // then the BufferView's cursor will be invalid in
3430 // some cases which leads to crashes.
3435 // FIXME (Abdel), I don't understand why we pass 'it' here
3436 // instead of 'macroTemplate' defined above... is this correct?
3437 macros[macroTemplate.name()][it] =
3438 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3448 void Buffer::updateMacros() const
3453 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3455 // start with empty table
3457 d->children_positions.clear();
3458 d->position_to_children.clear();
3460 // Iterate over buffer, starting with first paragraph
3461 // The scope must be bigger than any lookup DocIterator
3462 // later. For the global lookup, lastpit+1 is used, hence
3463 // we use lastpit+2 here.
3464 DocIterator it = par_iterator_begin();
3465 DocIterator outerScope = it;
3466 outerScope.pit() = outerScope.lastpit() + 2;
3467 d->updateMacros(it, outerScope);
3471 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3473 InsetIterator it = inset_iterator_begin(inset());
3474 InsetIterator const end = inset_iterator_end(inset());
3475 for (; it != end; ++it) {
3476 if (it->lyxCode() == BRANCH_CODE) {
3477 InsetBranch & br = static_cast<InsetBranch &>(*it);
3478 docstring const name = br.branch();
3479 if (!from_master && !params().branchlist().find(name))
3480 result.push_back(name);
3481 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3482 result.push_back(name);
3485 if (it->lyxCode() == INCLUDE_CODE) {
3486 // get buffer of external file
3487 InsetInclude const & ins =
3488 static_cast<InsetInclude const &>(*it);
3489 Buffer * child = ins.getChildBuffer();
3492 child->getUsedBranches(result, true);
3495 // remove duplicates
3500 void Buffer::updateMacroInstances(UpdateType utype) const
3502 LYXERR(Debug::MACROS, "updateMacroInstances for "
3503 << d->filename.onlyFileName());
3504 DocIterator it = doc_iterator_begin(this);
3506 DocIterator const end = doc_iterator_end(this);
3507 for (; it != end; it.forwardInset()) {
3508 // look for MathData cells in InsetMathNest insets
3509 InsetMath * minset = it.nextInset()->asInsetMath();
3513 // update macro in all cells of the InsetMathNest
3514 DocIterator::idx_type n = minset->nargs();
3515 MacroContext mc = MacroContext(this, it);
3516 for (DocIterator::idx_type i = 0; i < n; ++i) {
3517 MathData & data = minset->cell(i);
3518 data.updateMacros(0, mc, utype);
3524 void Buffer::listMacroNames(MacroNameSet & macros) const
3529 d->macro_lock = true;
3531 // loop over macro names
3532 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3533 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3534 for (; nameIt != nameEnd; ++nameIt)
3535 macros.insert(nameIt->first);
3537 // loop over children
3538 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3539 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3540 for (; it != end; ++it)
3541 it->first->listMacroNames(macros);
3544 Buffer const * const pbuf = d->parent();
3546 pbuf->listMacroNames(macros);
3548 d->macro_lock = false;
3552 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3554 Buffer const * const pbuf = d->parent();
3559 pbuf->listMacroNames(names);
3562 MacroNameSet::iterator it = names.begin();
3563 MacroNameSet::iterator end = names.end();
3564 for (; it != end; ++it) {
3566 MacroData const * data =
3567 pbuf->getMacro(*it, *this, false);
3569 macros.insert(data);
3571 // we cannot access the original MathMacroTemplate anymore
3572 // here to calls validate method. So we do its work here manually.
3573 // FIXME: somehow make the template accessible here.
3574 if (data->optionals() > 0)
3575 features.require("xargs");
3581 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3584 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3586 RefCache::iterator it = d->ref_cache_.find(label);
3587 if (it != d->ref_cache_.end())
3588 return it->second.second;
3590 static InsetLabel const * dummy_il = 0;
3591 static References const dummy_refs = References();
3592 it = d->ref_cache_.insert(
3593 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3594 return it->second.second;
3598 Buffer::References const & Buffer::references(docstring const & label) const
3600 return const_cast<Buffer *>(this)->getReferenceCache(label);
3604 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3606 References & refs = getReferenceCache(label);
3607 refs.push_back(make_pair(inset, it));
3611 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3613 masterBuffer()->d->ref_cache_[label].first = il;
3617 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3619 return masterBuffer()->d->ref_cache_[label].first;
3623 void Buffer::clearReferenceCache() const
3626 d->ref_cache_.clear();
3630 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3632 //FIXME: This does not work for child documents yet.
3633 reloadBibInfoCache();
3635 // Check if the label 'from' appears more than once
3636 BiblioInfo const & keys = masterBibInfo();
3637 BiblioInfo::const_iterator bit = keys.begin();
3638 BiblioInfo::const_iterator bend = keys.end();
3639 vector<docstring> labels;
3641 for (; bit != bend; ++bit)
3643 labels.push_back(bit->first);
3645 if (count(labels.begin(), labels.end(), from) > 1)
3648 string const paramName = "key";
3649 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3650 if (it->lyxCode() != CITE_CODE)
3652 InsetCommand * inset = it->asInsetCommand();
3653 docstring const oldValue = inset->getParam(paramName);
3654 if (oldValue == from)
3655 inset->setParam(paramName, to);
3659 // returns NULL if id-to-row conversion is unsupported
3660 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3661 pit_type par_begin, pit_type par_end,
3662 OutputWhat output, bool master) const
3664 unique_ptr<TexRow> texrow;
3665 OutputParams runparams(¶ms().encoding());
3666 runparams.nice = true;
3667 runparams.flavor = params().getOutputFlavor(format);
3668 runparams.linelen = lyxrc.plaintext_linelen;
3669 // No side effect of file copying and image conversion
3670 runparams.dryrun = true;
3672 if (output == CurrentParagraph) {
3673 runparams.par_begin = par_begin;
3674 runparams.par_end = par_end;
3675 if (par_begin + 1 == par_end) {
3677 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3681 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3682 convert<docstring>(par_begin),
3683 convert<docstring>(par_end - 1))
3686 // output paragraphs
3687 if (runparams.flavor == OutputParams::LYX) {
3688 Paragraph const & par = text().paragraphs()[par_begin];
3690 depth_type dt = par.getDepth();
3691 par.write(ods, params(), dt);
3692 os << from_utf8(ods.str());
3693 } else if (runparams.flavor == OutputParams::HTML) {
3695 setMathFlavor(runparams);
3696 xhtmlParagraphs(text(), *this, xs, runparams);
3697 } else if (runparams.flavor == OutputParams::TEXT) {
3699 // FIXME Handles only one paragraph, unlike the others.
3700 // Probably should have some routine with a signature like them.
3701 writePlaintextParagraph(*this,
3702 text().paragraphs()[par_begin], os, runparams, dummy);
3703 } else if (params().isDocBook()) {
3704 docbookParagraphs(text(), *this, os, runparams);
3706 // If we are previewing a paragraph, even if this is the
3707 // child of some other buffer, let's cut the link here,
3708 // so that no concurring settings from the master
3709 // (e.g. branch state) interfere (see #8101).
3711 d->ignore_parent = true;
3712 // We need to validate the Buffer params' features here
3713 // in order to know if we should output polyglossia
3714 // macros (instead of babel macros)
3715 LaTeXFeatures features(*this, params(), runparams);
3716 params().validate(features);
3717 runparams.use_polyglossia = features.usePolyglossia();
3718 texrow = make_unique<TexRow>();
3721 // latex or literate
3722 otexstream ots(os, *texrow);
3725 latexParagraphs(*this, text(), ots, runparams);
3728 // Restore the parenthood
3730 d->ignore_parent = false;
3734 if (output == FullSource)
3735 os << _("Preview source code");
3736 else if (output == OnlyPreamble)
3737 os << _("Preview preamble");
3738 else if (output == OnlyBody)
3739 os << _("Preview body");
3741 if (runparams.flavor == OutputParams::LYX) {
3743 if (output == FullSource)
3745 else if (output == OnlyPreamble)
3746 params().writeFile(ods, this);
3747 else if (output == OnlyBody)
3749 os << from_utf8(ods.str());
3750 } else if (runparams.flavor == OutputParams::HTML) {
3751 writeLyXHTMLSource(os, runparams, output);
3752 } else if (runparams.flavor == OutputParams::TEXT) {
3753 if (output == OnlyPreamble) {
3754 os << "% "<< _("Plain text does not have a preamble.");
3756 writePlaintextFile(*this, os, runparams);
3757 } else if (params().isDocBook()) {
3758 writeDocBookSource(os, absFileName(), runparams, output);
3760 // latex or literate
3761 texrow = make_unique<TexRow>();
3764 otexstream ots(os, *texrow);
3766 runparams.is_child = true;
3767 writeLaTeXSource(ots, string(), runparams, output);
3775 ErrorList & Buffer::errorList(string const & type) const
3777 return d->errorLists[type];
3781 void Buffer::updateTocItem(std::string const & type,
3782 DocIterator const & dit) const
3785 d->gui_->updateTocItem(type, dit);
3789 void Buffer::structureChanged() const
3792 d->gui_->structureChanged();
3796 void Buffer::errors(string const & err, bool from_master) const
3799 d->gui_->errors(err, from_master);
3803 void Buffer::message(docstring const & msg) const
3806 d->gui_->message(msg);
3810 void Buffer::setBusy(bool on) const
3813 d->gui_->setBusy(on);
3817 void Buffer::updateTitles() const
3820 d->wa_->updateTitles();
3824 void Buffer::resetAutosaveTimers() const
3827 d->gui_->resetAutosaveTimers();
3831 bool Buffer::hasGuiDelegate() const
3837 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3846 class AutoSaveBuffer : public ForkedProcess {
3849 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3850 : buffer_(buffer), fname_(fname) {}
3852 virtual shared_ptr<ForkedProcess> clone() const
3854 return make_shared<AutoSaveBuffer>(*this);
3859 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3860 from_utf8(fname_.absFileName())));
3861 return run(DontWait);
3865 virtual int generateChild();
3867 Buffer const & buffer_;
3872 int AutoSaveBuffer::generateChild()
3874 #if defined(__APPLE__)
3875 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3876 * We should use something else like threads.
3878 * Since I do not know how to determine at run time what is the OS X
3879 * version, I just disable forking altogether for now (JMarc)
3881 pid_t const pid = -1;
3883 // tmp_ret will be located (usually) in /tmp
3884 // will that be a problem?
3885 // Note that this calls ForkedCalls::fork(), so it's
3886 // ok cross-platform.
3887 pid_t const pid = fork();
3888 // If you want to debug the autosave
3889 // you should set pid to -1, and comment out the fork.
3890 if (pid != 0 && pid != -1)
3894 // pid = -1 signifies that lyx was unable
3895 // to fork. But we will do the save
3897 bool failed = false;
3898 TempFile tempfile("lyxautoXXXXXX.lyx");
3899 tempfile.setAutoRemove(false);
3900 FileName const tmp_ret = tempfile.name();
3901 if (!tmp_ret.empty()) {
3902 if (!buffer_.writeFile(tmp_ret))
3904 else if (!tmp_ret.moveTo(fname_))
3910 // failed to write/rename tmp_ret so try writing direct
3911 if (!buffer_.writeFile(fname_)) {
3912 // It is dangerous to do this in the child,
3913 // but safe in the parent, so...
3914 if (pid == -1) // emit message signal.
3915 buffer_.message(_("Autosave failed!"));
3919 if (pid == 0) // we are the child so...
3928 FileName Buffer::getEmergencyFileName() const
3930 return FileName(d->filename.absFileName() + ".emergency");
3934 FileName Buffer::getAutosaveFileName() const
3936 // if the document is unnamed try to save in the backup dir, else
3937 // in the default document path, and as a last try in the filePath,
3938 // which will most often be the temporary directory
3941 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3942 : lyxrc.backupdir_path;
3943 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3946 string const fname = "#" + d->filename.onlyFileName() + "#";
3948 return makeAbsPath(fname, fpath);
3952 void Buffer::removeAutosaveFile() const
3954 FileName const f = getAutosaveFileName();
3960 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3962 FileName const newauto = getAutosaveFileName();
3964 if (newauto != oldauto && oldauto.exists())
3965 if (!oldauto.moveTo(newauto))
3966 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3970 bool Buffer::autoSave() const
3972 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3973 if (buf->d->bak_clean || isReadonly())
3976 message(_("Autosaving current document..."));
3977 buf->d->bak_clean = true;
3979 FileName const fname = getAutosaveFileName();
3980 LASSERT(d->cloned_buffer_, return false);
3982 // If this buffer is cloned, we assume that
3983 // we are running in a separate thread already.
3984 TempFile tempfile("lyxautoXXXXXX.lyx");
3985 tempfile.setAutoRemove(false);
3986 FileName const tmp_ret = tempfile.name();
3987 if (!tmp_ret.empty()) {
3989 // assume successful write of tmp_ret
3990 if (tmp_ret.moveTo(fname))
3993 // failed to write/rename tmp_ret so try writing direct
3994 return writeFile(fname);
3998 void Buffer::setExportStatus(bool e) const
4000 d->doing_export = e;
4001 ListOfBuffers clist = getDescendents();
4002 ListOfBuffers::const_iterator cit = clist.begin();
4003 ListOfBuffers::const_iterator const cen = clist.end();
4004 for (; cit != cen; ++cit)
4005 (*cit)->d->doing_export = e;
4009 bool Buffer::isExporting() const
4011 return d->doing_export;
4015 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4019 return doExport(target, put_in_tempdir, result_file);
4022 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4023 string & result_file) const
4025 bool const update_unincluded =
4026 params().maintain_unincluded_children
4027 && !params().getIncludedChildren().empty();
4029 // (1) export with all included children (omit \includeonly)
4030 if (update_unincluded) {
4031 ExportStatus const status =
4032 doExport(target, put_in_tempdir, true, result_file);
4033 if (status != ExportSuccess)
4036 // (2) export with included children only
4037 return doExport(target, put_in_tempdir, false, result_file);
4041 void Buffer::setMathFlavor(OutputParams & op) const
4043 switch (params().html_math_output) {
4044 case BufferParams::MathML:
4045 op.math_flavor = OutputParams::MathAsMathML;
4047 case BufferParams::HTML:
4048 op.math_flavor = OutputParams::MathAsHTML;
4050 case BufferParams::Images:
4051 op.math_flavor = OutputParams::MathAsImages;
4053 case BufferParams::LaTeX:
4054 op.math_flavor = OutputParams::MathAsLaTeX;
4060 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4061 bool includeall, string & result_file) const
4063 LYXERR(Debug::FILES, "target=" << target);
4064 OutputParams runparams(¶ms().encoding());
4065 string format = target;
4066 string dest_filename;
4067 size_t pos = target.find(' ');
4068 if (pos != string::npos) {
4069 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4070 format = target.substr(0, pos);
4071 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4072 FileName(dest_filename).onlyPath().createPath();
4073 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4075 MarkAsExporting exporting(this);
4076 string backend_format;
4077 runparams.flavor = OutputParams::LATEX;
4078 runparams.linelen = lyxrc.plaintext_linelen;
4079 runparams.includeall = includeall;
4080 vector<string> backs = params().backends();
4081 Converters converters = theConverters();
4082 bool need_nice_file = false;
4083 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4084 // Get shortest path to format
4085 converters.buildGraph();
4086 Graph::EdgePath path;
4087 for (vector<string>::const_iterator it = backs.begin();
4088 it != backs.end(); ++it) {
4089 Graph::EdgePath p = converters.getPath(*it, format);
4090 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4091 backend_format = *it;
4096 if (!put_in_tempdir) {
4097 // Only show this alert if this is an export to a non-temporary
4098 // file (not for previewing).
4099 Alert::error(_("Couldn't export file"), bformat(
4100 _("No information for exporting the format %1$s."),
4101 formats.prettyName(format)));
4103 return ExportNoPathToFormat;
4105 runparams.flavor = converters.getFlavor(path, this);
4106 Graph::EdgePath::const_iterator it = path.begin();
4107 Graph::EdgePath::const_iterator en = path.end();
4108 for (; it != en; ++it)
4109 if (theConverters().get(*it).nice()) {
4110 need_nice_file = true;
4115 backend_format = format;
4116 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4117 // FIXME: Don't hardcode format names here, but use a flag
4118 if (backend_format == "pdflatex")
4119 runparams.flavor = OutputParams::PDFLATEX;
4120 else if (backend_format == "luatex")
4121 runparams.flavor = OutputParams::LUATEX;
4122 else if (backend_format == "dviluatex")
4123 runparams.flavor = OutputParams::DVILUATEX;
4124 else if (backend_format == "xetex")
4125 runparams.flavor = OutputParams::XETEX;
4128 string filename = latexName(false);
4129 filename = addName(temppath(), filename);
4130 filename = changeExtension(filename,
4131 formats.extension(backend_format));
4132 LYXERR(Debug::FILES, "filename=" << filename);
4134 // Plain text backend
4135 if (backend_format == "text") {
4136 runparams.flavor = OutputParams::TEXT;
4137 writePlaintextFile(*this, FileName(filename), runparams);
4140 else if (backend_format == "xhtml") {
4141 runparams.flavor = OutputParams::HTML;
4142 setMathFlavor(runparams);
4143 makeLyXHTMLFile(FileName(filename), runparams);
4144 } else if (backend_format == "lyx")
4145 writeFile(FileName(filename));
4147 else if (params().isDocBook()) {
4148 runparams.nice = !put_in_tempdir;
4149 makeDocBookFile(FileName(filename), runparams);
4152 else if (backend_format == format || need_nice_file) {
4153 runparams.nice = true;
4154 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4155 if (d->cloned_buffer_)
4156 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4159 } else if (!lyxrc.tex_allows_spaces
4160 && contains(filePath(), ' ')) {
4161 Alert::error(_("File name error"),
4162 _("The directory path to the document cannot contain spaces."));
4163 return ExportTexPathHasSpaces;
4165 runparams.nice = false;
4166 bool const success = makeLaTeXFile(
4167 FileName(filename), filePath(), runparams);
4168 if (d->cloned_buffer_)
4169 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4174 string const error_type = (format == "program")
4175 ? "Build" : params().bufferFormat();
4176 ErrorList & error_list = d->errorLists[error_type];
4177 string const ext = formats.extension(format);
4178 FileName const tmp_result_file(changeExtension(filename, ext));
4179 bool const success = converters.convert(this, FileName(filename),
4180 tmp_result_file, FileName(absFileName()), backend_format, format,
4183 // Emit the signal to show the error list or copy it back to the
4184 // cloned Buffer so that it can be emitted afterwards.
4185 if (format != backend_format) {
4186 if (runparams.silent)
4188 else if (d->cloned_buffer_)
4189 d->cloned_buffer_->d->errorLists[error_type] =
4190 d->errorLists[error_type];
4193 // also to the children, in case of master-buffer-view
4194 ListOfBuffers clist = getDescendents();
4195 ListOfBuffers::const_iterator cit = clist.begin();
4196 ListOfBuffers::const_iterator const cen = clist.end();
4197 for (; cit != cen; ++cit) {
4198 if (runparams.silent)
4199 (*cit)->d->errorLists[error_type].clear();
4200 else if (d->cloned_buffer_) {
4201 // Enable reverse search by copying back the
4202 // texrow object to the cloned buffer.
4203 // FIXME: this is not thread safe.
4204 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4205 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4206 (*cit)->d->errorLists[error_type];
4208 (*cit)->errors(error_type, true);
4212 if (d->cloned_buffer_) {
4213 // Enable reverse dvi or pdf to work by copying back the texrow
4214 // object to the cloned buffer.
4215 // FIXME: There is a possibility of concurrent access to texrow
4216 // here from the main GUI thread that should be securized.
4217 d->cloned_buffer_->d->texrow = d->texrow;
4218 string const error_type = params().bufferFormat();
4219 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4223 if (put_in_tempdir) {
4224 result_file = tmp_result_file.absFileName();
4225 return success ? ExportSuccess : ExportConverterError;
4228 if (dest_filename.empty())
4229 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4231 result_file = dest_filename;
4232 // We need to copy referenced files (e. g. included graphics
4233 // if format == "dvi") to the result dir.
4234 vector<ExportedFile> const files =
4235 runparams.exportdata->externalFiles(format);
4236 string const dest = runparams.export_folder.empty() ?
4237 onlyPath(result_file) : runparams.export_folder;
4238 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4239 : force_overwrite == ALL_FILES;
4240 CopyStatus status = use_force ? FORCE : SUCCESS;
4242 vector<ExportedFile>::const_iterator it = files.begin();
4243 vector<ExportedFile>::const_iterator const en = files.end();
4244 for (; it != en && status != CANCEL; ++it) {
4245 string const fmt = formats.getFormatFromFile(it->sourceName);
4246 string fixedName = it->exportName;
4247 if (!runparams.export_folder.empty()) {
4248 // Relative pathnames starting with ../ will be sanitized
4249 // if exporting to a different folder
4250 while (fixedName.substr(0, 3) == "../")
4251 fixedName = fixedName.substr(3, fixedName.length() - 3);
4253 FileName fixedFileName = makeAbsPath(fixedName, dest);
4254 fixedFileName.onlyPath().createPath();
4255 status = copyFile(fmt, it->sourceName,
4257 it->exportName, status == FORCE,
4258 runparams.export_folder.empty());
4261 if (status == CANCEL) {
4262 message(_("Document export cancelled."));
4263 return ExportCancel;
4266 if (tmp_result_file.exists()) {
4267 // Finally copy the main file
4268 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4269 : force_overwrite != NO_FILES;
4270 if (status == SUCCESS && use_force)
4272 status = copyFile(format, tmp_result_file,
4273 FileName(result_file), result_file,
4275 if (status == CANCEL) {
4276 message(_("Document export cancelled."));
4277 return ExportCancel;
4279 message(bformat(_("Document exported as %1$s "
4281 formats.prettyName(format),
4282 makeDisplayPath(result_file)));
4285 // This must be a dummy converter like fax (bug 1888)
4286 message(bformat(_("Document exported as %1$s"),
4287 formats.prettyName(format)));
4290 return success ? ExportSuccess : ExportConverterError;
4294 Buffer::ExportStatus Buffer::preview(string const & format) const
4296 bool const update_unincluded =
4297 params().maintain_unincluded_children
4298 && !params().getIncludedChildren().empty();
4299 return preview(format, update_unincluded);
4303 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4305 MarkAsExporting exporting(this);
4307 // (1) export with all included children (omit \includeonly)
4309 ExportStatus const status = doExport(format, true, true, result_file);
4310 if (status != ExportSuccess)
4313 // (2) export with included children only
4314 ExportStatus const status = doExport(format, true, false, result_file);
4315 FileName const previewFile(result_file);
4317 LATTEST (isClone());
4318 d->cloned_buffer_->d->preview_file_ = previewFile;
4319 d->cloned_buffer_->d->preview_format_ = format;
4320 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4322 if (status != ExportSuccess)
4324 if (previewFile.exists()) {
4325 if (!formats.view(*this, previewFile, format))
4326 return PreviewError;
4328 return PreviewSuccess;
4331 // Successful export but no output file?
4332 // Probably a bug in error detection.
4333 LATTEST (status != ExportSuccess);
4340 Buffer::ReadStatus Buffer::extractFromVC()
4342 bool const found = LyXVC::file_not_found_hook(d->filename);
4344 return ReadFileNotFound;
4345 if (!d->filename.isReadableFile())
4351 Buffer::ReadStatus Buffer::loadEmergency()
4353 FileName const emergencyFile = getEmergencyFileName();
4354 if (!emergencyFile.exists()
4355 || emergencyFile.lastModified() <= d->filename.lastModified())
4356 return ReadFileNotFound;
4358 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4359 docstring const text = bformat(_("An emergency save of the document "
4360 "%1$s exists.\n\nRecover emergency save?"), file);
4362 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4363 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4369 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4370 bool const success = (ret_llf == ReadSuccess);
4373 Alert::warning(_("File is read-only"),
4374 bformat(_("An emergency file is successfully loaded, "
4375 "but the original file %1$s is marked read-only. "
4376 "Please make sure to save the document as a different "
4377 "file."), from_utf8(d->filename.absFileName())));
4380 lyxvc().file_found_hook(d->filename);
4381 str = _("Document was successfully recovered.");
4383 str = _("Document was NOT successfully recovered.");
4384 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4385 makeDisplayPath(emergencyFile.absFileName()));
4387 int const del_emerg =
4388 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4389 _("&Remove"), _("&Keep"));
4390 if (del_emerg == 0) {
4391 emergencyFile.removeFile();
4393 Alert::warning(_("Emergency file deleted"),
4394 _("Do not forget to save your file now!"), true);
4396 return success ? ReadSuccess : ReadEmergencyFailure;
4399 int const del_emerg =
4400 Alert::prompt(_("Delete emergency file?"),
4401 _("Remove emergency file now?"), 1, 1,
4402 _("&Remove"), _("&Keep"));
4404 emergencyFile.removeFile();
4405 return ReadOriginal;
4415 Buffer::ReadStatus Buffer::loadAutosave()
4417 // Now check if autosave file is newer.
4418 FileName const autosaveFile = getAutosaveFileName();
4419 if (!autosaveFile.exists()
4420 || autosaveFile.lastModified() <= d->filename.lastModified())
4421 return ReadFileNotFound;
4423 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4424 docstring const text = bformat(_("The backup of the document %1$s "
4425 "is newer.\n\nLoad the backup instead?"), file);
4426 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4427 _("&Load backup"), _("Load &original"), _("&Cancel"));
4432 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4433 // the file is not saved if we load the autosave file.
4434 if (ret_llf == ReadSuccess) {
4436 Alert::warning(_("File is read-only"),
4437 bformat(_("A backup file is successfully loaded, "
4438 "but the original file %1$s is marked read-only. "
4439 "Please make sure to save the document as a "
4441 from_utf8(d->filename.absFileName())));
4444 lyxvc().file_found_hook(d->filename);
4447 return ReadAutosaveFailure;
4450 // Here we delete the autosave
4451 autosaveFile.removeFile();
4452 return ReadOriginal;
4460 Buffer::ReadStatus Buffer::loadLyXFile()
4462 if (!d->filename.isReadableFile()) {
4463 ReadStatus const ret_rvc = extractFromVC();
4464 if (ret_rvc != ReadSuccess)
4468 ReadStatus const ret_re = loadEmergency();
4469 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4472 ReadStatus const ret_ra = loadAutosave();
4473 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4476 return loadThisLyXFile(d->filename);
4480 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4482 return readFile(fn);
4486 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4488 TeXErrors::Errors::const_iterator it = terr.begin();
4489 TeXErrors::Errors::const_iterator end = terr.end();
4490 ListOfBuffers clist = getDescendents();
4491 ListOfBuffers::const_iterator cen = clist.end();
4493 for (; it != end; ++it) {
4496 int errorRow = it->error_in_line;
4497 Buffer const * buf = 0;
4499 if (it->child_name.empty())
4500 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4502 // The error occurred in a child
4503 ListOfBuffers::const_iterator cit = clist.begin();
4504 for (; cit != cen; ++cit) {
4505 string const child_name =
4506 DocFileName(changeExtension(
4507 (*cit)->absFileName(), "tex")).
4509 if (it->child_name != child_name)
4511 (*cit)->d->texrow.getIdFromRow(errorRow,
4512 id_start, pos_start);
4513 if (id_start != -1) {
4514 buf = d->cloned_buffer_
4515 ? (*cit)->d->cloned_buffer_->d->owner_
4516 : (*cit)->d->owner_;
4527 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4528 } while (found && id_start == id_end && pos_start == pos_end);
4530 if (id_start != id_end) {
4531 // Next registered position is outside the inset where
4532 // the error occurred, so signal end-of-paragraph
4536 errorList.push_back(ErrorItem(it->error_desc,
4537 it->error_text, id_start, pos_start, pos_end, buf));
4542 void Buffer::setBuffersForInsets() const
4544 inset().setBuffer(const_cast<Buffer &>(*this));
4548 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4550 LBUFERR(!text().paragraphs().empty());
4552 // Use the master text class also for child documents
4553 Buffer const * const master = masterBuffer();
4554 DocumentClass const & textclass = master->params().documentClass();
4556 // do this only if we are the top-level Buffer
4557 if (master == this) {
4558 textclass.counters().reset(from_ascii("bibitem"));
4559 reloadBibInfoCache();
4562 // keep the buffers to be children in this set. If the call from the
4563 // master comes back we can see which of them were actually seen (i.e.
4564 // via an InsetInclude). The remaining ones in the set need still be updated.
4565 static std::set<Buffer const *> bufToUpdate;
4566 if (scope == UpdateMaster) {
4567 // If this is a child document start with the master
4568 if (master != this) {
4569 bufToUpdate.insert(this);
4570 master->updateBuffer(UpdateMaster, utype);
4571 // If the master buffer has no gui associated with it, then the TocModel is
4572 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4573 // (bug 5699). The same happens if the master buffer is open in a different
4574 // window. This test catches both possibilities.
4575 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4576 // There remains a problem here: If there is another child open in yet a third
4577 // window, that TOC is not updated. So some more general solution is needed at
4579 if (master->d->gui_ != d->gui_)
4582 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4583 if (bufToUpdate.find(this) == bufToUpdate.end())
4587 // start over the counters in the master
4588 textclass.counters().reset();
4591 // update will be done below for this buffer
4592 bufToUpdate.erase(this);
4594 // update all caches
4595 clearReferenceCache();
4597 setChangesPresent(false);
4599 Buffer & cbuf = const_cast<Buffer &>(*this);
4602 ParIterator parit = cbuf.par_iterator_begin();
4603 updateBuffer(parit, utype);
4606 // TocBackend update will be done later.
4609 d->bibinfo_cache_valid_ = true;
4610 d->cite_labels_valid_ = true;
4612 cbuf.tocBackend().update(true, utype);
4613 if (scope == UpdateMaster)
4614 cbuf.structureChanged();
4618 static depth_type getDepth(DocIterator const & it)
4620 depth_type depth = 0;
4621 for (size_t i = 0 ; i < it.depth() ; ++i)
4622 if (!it[i].inset().inMathed())
4623 depth += it[i].paragraph().getDepth() + 1;
4624 // remove 1 since the outer inset does not count
4625 // we should have at least one non-math inset, so
4626 // depth should nevery be 0. but maybe it is worth
4627 // marking this, just in case.
4629 // coverity[INTEGER_OVERFLOW]
4633 static depth_type getItemDepth(ParIterator const & it)
4635 Paragraph const & par = *it;
4636 LabelType const labeltype = par.layout().labeltype;
4638 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4641 // this will hold the lowest depth encountered up to now.
4642 depth_type min_depth = getDepth(it);
4643 ParIterator prev_it = it;
4646 --prev_it.top().pit();
4648 // start of nested inset: go to outer par
4650 if (prev_it.empty()) {
4651 // start of document: nothing to do
4656 // We search for the first paragraph with same label
4657 // that is not more deeply nested.
4658 Paragraph & prev_par = *prev_it;
4659 depth_type const prev_depth = getDepth(prev_it);
4660 if (labeltype == prev_par.layout().labeltype) {
4661 if (prev_depth < min_depth)
4662 return prev_par.itemdepth + 1;
4663 if (prev_depth == min_depth)
4664 return prev_par.itemdepth;
4666 min_depth = min(min_depth, prev_depth);
4667 // small optimization: if we are at depth 0, we won't
4668 // find anything else
4669 if (prev_depth == 0)
4675 static bool needEnumCounterReset(ParIterator const & it)
4677 Paragraph const & par = *it;
4678 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4679 depth_type const cur_depth = par.getDepth();
4680 ParIterator prev_it = it;
4681 while (prev_it.pit()) {
4682 --prev_it.top().pit();
4683 Paragraph const & prev_par = *prev_it;
4684 if (prev_par.getDepth() <= cur_depth)
4685 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4687 // start of nested inset: reset
4692 // set the label of a paragraph. This includes the counters.
4693 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4695 BufferParams const & bp = owner_->masterBuffer()->params();
4696 DocumentClass const & textclass = bp.documentClass();
4697 Paragraph & par = it.paragraph();
4698 Layout const & layout = par.layout();
4699 Counters & counters = textclass.counters();
4701 if (par.params().startOfAppendix()) {
4702 // We want to reset the counter corresponding to toplevel sectioning
4703 Layout const & lay = textclass.getTOCLayout();
4704 docstring const cnt = lay.counter;
4706 counters.reset(cnt);
4707 counters.appendix(true);
4709 par.params().appendix(counters.appendix());
4711 // Compute the item depth of the paragraph
4712 par.itemdepth = getItemDepth(it);
4714 if (layout.margintype == MARGIN_MANUAL) {
4715 if (par.params().labelWidthString().empty())
4716 par.params().labelWidthString(par.expandLabel(layout, bp));
4717 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4718 // we do not need to do anything here, since the empty case is
4719 // handled during export.
4721 par.params().labelWidthString(docstring());
4724 switch(layout.labeltype) {
4725 case LABEL_ITEMIZE: {
4726 // At some point of time we should do something more
4727 // clever here, like:
4728 // par.params().labelString(
4729 // bp.user_defined_bullet(par.itemdepth).getText());
4730 // for now, use a simple hardcoded label
4731 docstring itemlabel;
4732 switch (par.itemdepth) {
4734 itemlabel = char_type(0x2022);
4737 itemlabel = char_type(0x2013);
4740 itemlabel = char_type(0x2217);
4743 itemlabel = char_type(0x2219); // or 0x00b7
4746 par.params().labelString(itemlabel);
4750 case LABEL_ENUMERATE: {
4751 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4753 switch (par.itemdepth) {
4762 enumcounter += "iv";
4765 // not a valid enumdepth...
4769 // Maybe we have to reset the enumeration counter.
4770 if (needEnumCounterReset(it))
4771 counters.reset(enumcounter);
4772 counters.step(enumcounter, utype);
4774 string const & lang = par.getParLanguage(bp)->code();
4775 par.params().labelString(counters.theCounter(enumcounter, lang));
4780 case LABEL_SENSITIVE: {
4781 string const & type = counters.current_float();
4782 docstring full_label;
4784 full_label = owner_->B_("Senseless!!! ");
4786 docstring name = owner_->B_(textclass.floats().getType(type).name());
4787 if (counters.hasCounter(from_utf8(type))) {
4788 string const & lang = par.getParLanguage(bp)->code();
4789 counters.step(from_utf8(type), utype);
4790 full_label = bformat(from_ascii("%1$s %2$s:"),
4792 counters.theCounter(from_utf8(type), lang));
4794 full_label = bformat(from_ascii("%1$s #:"), name);
4796 par.params().labelString(full_label);
4800 case LABEL_NO_LABEL:
4801 par.params().labelString(docstring());
4805 case LABEL_CENTERED:
4806 case LABEL_STATIC: {
4807 docstring const & lcounter = layout.counter;
4808 if (!lcounter.empty()) {
4809 if (layout.toclevel <= bp.secnumdepth
4810 && (layout.latextype != LATEX_ENVIRONMENT
4811 || it.text()->isFirstInSequence(it.pit()))) {
4812 if (counters.hasCounter(lcounter))
4813 counters.step(lcounter, utype);
4814 par.params().labelString(par.expandLabel(layout, bp));
4816 par.params().labelString(docstring());
4818 par.params().labelString(par.expandLabel(layout, bp));
4824 par.params().labelString(par.expandLabel(layout, bp));
4829 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4831 // LASSERT: Is it safe to continue here, or should we just return?
4832 LASSERT(parit.pit() == 0, /**/);
4834 // Set the position of the text in the buffer to be able
4835 // to resolve macros in it.
4836 parit.text()->setMacrocontextPosition(parit);
4838 depth_type maxdepth = 0;
4839 pit_type const lastpit = parit.lastpit();
4840 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4841 // reduce depth if necessary
4842 if (parit->params().depth() > maxdepth) {
4843 /** FIXME: this function is const, but
4844 * nevertheless it modifies the buffer. To be
4845 * cleaner, one should modify the buffer in
4846 * another function, which is actually
4847 * non-const. This would however be costly in
4848 * terms of code duplication.
4850 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4851 parit->params().depth(maxdepth);
4853 maxdepth = parit->getMaxDepthAfter();
4855 if (utype == OutputUpdate) {
4856 // track the active counters
4857 // we have to do this for the master buffer, since the local
4858 // buffer isn't tracking anything.
4859 masterBuffer()->params().documentClass().counters().
4860 setActiveLayout(parit->layout());
4863 // set the counter for this paragraph
4864 d->setLabel(parit, utype);
4866 // update change-tracking flag
4867 parit->addChangesToBuffer(*this);
4870 InsetList::const_iterator iit = parit->insetList().begin();
4871 InsetList::const_iterator end = parit->insetList().end();
4872 for (; iit != end; ++iit) {
4873 parit.pos() = iit->pos;
4874 iit->inset->updateBuffer(parit, utype);
4880 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4881 WordLangTuple & word_lang, docstring_list & suggestions) const
4885 suggestions.clear();
4886 word_lang = WordLangTuple();
4887 bool const to_end = to.empty();
4888 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4889 // OK, we start from here.
4890 for (; from != end; from.forwardPos()) {
4891 // This skips all insets with spell check disabled.
4892 while (!from.allowSpellCheck()) {
4896 // If from is at the end of the document (which is possible
4897 // when "from" was changed above) LyX will crash later otherwise.
4898 if (from.atEnd() || (!to_end && from >= end))
4901 from.paragraph().spellCheck();
4902 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4903 if (SpellChecker::misspelled(res)) {
4907 // Do not increase progress when from == to, otherwise the word
4908 // count will be wrong.
4918 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4920 bool inword = false;
4925 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4926 if (!dit.inTexted()) {
4931 Paragraph const & par = dit.paragraph();
4932 pos_type const pos = dit.pos();
4934 // Copied and adapted from isWordSeparator() in Paragraph
4935 if (pos == dit.lastpos()) {
4938 Inset const * ins = par.getInset(pos);
4939 if (ins && skipNoOutput && !ins->producesOutput()) {
4942 // stop if end of range was skipped
4943 if (!to.atEnd() && dit >= to)
4946 } else if (!par.isDeleted(pos)) {
4947 if (par.isWordSeparator(pos))
4953 if (ins && ins->isLetter())
4955 else if (ins && ins->isSpace())
4958 char_type const c = par.getChar(pos);
4959 if (isPrintableNonspace(c))
4961 else if (isSpace(c))
4971 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4973 d->updateStatistics(from, to, skipNoOutput);
4977 int Buffer::wordCount() const
4979 return d->wordCount();
4983 int Buffer::charCount(bool with_blanks) const
4985 return d->charCount(with_blanks);
4989 Buffer::ReadStatus Buffer::reload()
4992 // c.f. bug http://www.lyx.org/trac/ticket/6587
4993 removeAutosaveFile();
4994 // e.g., read-only status could have changed due to version control
4995 d->filename.refresh();
4996 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4998 // clear parent. this will get reset if need be.
5000 ReadStatus const status = loadLyXFile();
5001 if (status == ReadSuccess) {
5006 message(bformat(_("Document %1$s reloaded."), disp_fn));
5009 message(bformat(_("Could not reload document %1$s."), disp_fn));
5019 bool Buffer::saveAs(FileName const & fn)
5021 FileName const old_name = fileName();
5022 FileName const old_auto = getAutosaveFileName();
5023 bool const old_unnamed = isUnnamed();
5024 bool success = true;
5025 d->old_position = filePath();
5032 // bring the autosave file with us, just in case.
5033 moveAutosaveFile(old_auto);
5034 // validate version control data and
5035 // correct buffer title
5036 lyxvc().file_found_hook(fileName());
5038 // the file has now been saved to the new location.
5039 // we need to check that the locations of child buffers
5041 checkChildBuffers();
5042 checkMasterBuffer();
5045 // reset the old filename and unnamed state
5046 setFileName(old_name);
5047 setUnnamed(old_unnamed);
5051 d->old_position.clear();
5056 void Buffer::checkChildBuffers()
5058 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5059 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5060 for (; it != en; ++it) {
5061 DocIterator dit = it->second;
5062 Buffer * cbuf = const_cast<Buffer *>(it->first);
5063 if (!cbuf || !theBufferList().isLoaded(cbuf))
5065 Inset * inset = dit.nextInset();
5066 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5067 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5068 docstring const & incfile = inset_inc->getParam("filename");
5069 string oldloc = cbuf->absFileName();
5070 string newloc = makeAbsPath(to_utf8(incfile),
5071 onlyPath(absFileName())).absFileName();
5072 if (oldloc == newloc)
5074 // the location of the child file is incorrect.
5076 inset_inc->setChildBuffer(0);
5078 // invalidate cache of children
5079 d->children_positions.clear();
5080 d->position_to_children.clear();
5084 // If a child has been saved under a different name/path, it might have been
5085 // orphaned. Therefore the master needs to be reset (bug 8161).
5086 void Buffer::checkMasterBuffer()
5088 Buffer const * const master = masterBuffer();
5092 // necessary to re-register the child (bug 5873)
5093 // FIXME: clean up updateMacros (here, only
5094 // child registering is needed).
5095 master->updateMacros();
5096 // (re)set master as master buffer, but only
5097 // if we are a real child
5098 if (master->isChild(this))
5105 string Buffer::includedFilePath(string const & name, string const & ext) const
5107 if (d->old_position.empty() ||
5108 equivalent(FileName(d->old_position), FileName(filePath())))
5111 bool isabsolute = FileName::isAbsolute(name);
5112 // both old_position and filePath() end with a path separator
5113 string absname = isabsolute ? name : d->old_position + name;
5115 // if old_position is set to origin, we need to do the equivalent of
5116 // getReferencedFileName() (see readDocument())
5117 if (!isabsolute && d->old_position == params().origin) {
5118 FileName const test(addExtension(filePath() + name, ext));
5120 absname = filePath() + name;
5123 if (!FileName(addExtension(absname, ext)).exists())
5127 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5129 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5130 from_utf8(filePath())));
5134 void Buffer::setChangesPresent(bool b) const
5136 d->tracked_changes_present_ = b;
5140 bool Buffer::areChangesPresent() const
5142 return d->tracked_changes_present_;
5146 void Buffer::updateChangesPresent() const
5148 LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5149 setChangesPresent(false);
5150 ParConstIterator it = par_iterator_begin();
5151 ParConstIterator const end = par_iterator_end();
5152 for (; !areChangesPresent() && it != end; ++it)
5153 it->addChangesToBuffer(*this);