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"
110 #include "support/shared_ptr.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;
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);
374 /// So we can force access via the accessors.
375 mutable Buffer const * parent_buffer;
384 /// Creates the per buffer temporary directory
385 static FileName createBufferTmpDir()
387 // FIXME This would be the ideal application for a TempDir class (like
388 // TempFile but for directories)
393 Mutex::Locker locker(&mutex);
394 counter = convert<string>(count++);
396 // We are in our own directory. Why bother to mangle name?
397 // In fact I wrote this code to circumvent a problematic behaviour
398 // (bug?) of EMX mkstemp().
399 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
402 if (!tmpfl.createDirectory(0777)) {
403 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
404 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
405 from_utf8(tmpfl.absFileName())));
411 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
412 Buffer const * cloned_buffer)
413 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
414 internal_buffer(false), read_only(readonly_), filename(file),
415 file_fully_loaded(false), file_format(LYX_FORMAT), need_format_backup(false),
416 ignore_parent(false), toc_backend(owner), macro_lock(false), timestamp_(0),
417 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
418 bibfile_cache_valid_(false), cite_labels_valid_(false), inset(0),
419 preview_loader_(0), cloned_buffer_(cloned_buffer), clone_list_(0),
420 doing_export(false), parent_buffer(0),
421 word_count_(0), char_count_(0), blank_count_(0)
423 if (!cloned_buffer_) {
424 temppath = createBufferTmpDir();
425 lyxvc.setBuffer(owner_);
427 wa_ = new frontend::WorkAreaManager;
430 temppath = cloned_buffer_->d->temppath;
431 file_fully_loaded = true;
432 params = cloned_buffer_->d->params;
433 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
434 bibinfo_ = cloned_buffer_->d->bibinfo_;
435 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
436 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
437 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
438 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
439 unnamed = cloned_buffer_->d->unnamed;
440 internal_buffer = cloned_buffer_->d->internal_buffer;
441 layout_position = cloned_buffer_->d->layout_position;
442 preview_file_ = cloned_buffer_->d->preview_file_;
443 preview_format_ = cloned_buffer_->d->preview_format_;
444 preview_error_ = cloned_buffer_->d->preview_error_;
448 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
449 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
451 LYXERR(Debug::INFO, "Buffer::Buffer()");
453 d->inset = new InsetText(*cloned_buffer->d->inset);
454 d->inset->setBuffer(*this);
455 // FIXME: optimize this loop somewhat, maybe by creating a new
456 // general recursive Inset::setId().
457 DocIterator it = doc_iterator_begin(this);
458 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
459 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
460 it.paragraph().setId(cloned_it.paragraph().id());
462 d->inset = new InsetText(this);
463 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
469 LYXERR(Debug::INFO, "Buffer::~Buffer()");
470 // here the buffer should take care that it is
471 // saved properly, before it goes into the void.
473 // GuiView already destroyed
477 // No need to do additional cleanups for internal buffer.
483 // this is in case of recursive includes: we won't try to delete
484 // ourselves as a child.
485 d->clone_list_->erase(this);
486 // loop over children
487 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
488 Impl::BufferPositionMap::iterator end = d->children_positions.end();
489 for (; it != end; ++it) {
490 Buffer * child = const_cast<Buffer *>(it->first);
491 if (d->clone_list_->erase(child))
494 // if we're the master buffer, then we should get rid of the list
497 // If this is not empty, we have leaked something. Worse, one of the
498 // children still has a reference to this list. But we will try to
499 // continue, rather than shut down.
500 LATTEST(d->clone_list_->empty());
501 list<CloneList *>::iterator it =
502 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
503 if (it == cloned_buffers.end()) {
504 // We will leak in this case, but it is safe to continue.
507 cloned_buffers.erase(it);
508 delete d->clone_list_;
510 // FIXME Do we really need to do this right before we delete d?
511 // clear references to children in macro tables
512 d->children_positions.clear();
513 d->position_to_children.clear();
515 // loop over children
516 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
517 Impl::BufferPositionMap::iterator end = d->children_positions.end();
518 for (; it != end; ++it) {
519 Buffer * child = const_cast<Buffer *>(it->first);
520 if (theBufferList().isLoaded(child))
521 theBufferList().releaseChild(this, child);
525 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
526 msg += emergencyWrite();
527 Alert::warning(_("Attempting to close changed document!"), msg);
530 // FIXME Do we really need to do this right before we delete d?
531 // clear references to children in macro tables
532 d->children_positions.clear();
533 d->position_to_children.clear();
535 if (!d->temppath.destroyDirectory()) {
536 LYXERR0(bformat(_("Could not remove the temporary directory %1$s"),
537 from_utf8(d->temppath.absFileName())));
546 Buffer * Buffer::cloneFromMaster() const
549 cloned_buffers.push_back(new CloneList);
550 CloneList * clones = cloned_buffers.back();
552 masterBuffer()->cloneWithChildren(bufmap, clones);
554 // make sure we got cloned
555 BufferMap::const_iterator bit = bufmap.find(this);
556 LASSERT(bit != bufmap.end(), return 0);
557 Buffer * cloned_buffer = bit->second;
559 return cloned_buffer;
563 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
565 // have we already been cloned?
566 if (bufmap.find(this) != bufmap.end())
569 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
571 // The clone needs its own DocumentClass, since running updateBuffer() will
572 // modify it, and we would otherwise be sharing it with the original Buffer.
573 buffer_clone->params().makeDocumentClass(true);
575 cap::switchBetweenClasses(
576 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
577 static_cast<InsetText &>(buffer_clone->inset()), el);
579 bufmap[this] = buffer_clone;
580 clones->insert(buffer_clone);
581 buffer_clone->d->clone_list_ = clones;
582 buffer_clone->d->macro_lock = true;
583 buffer_clone->d->children_positions.clear();
585 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
586 // math macro caches need to be rethought and simplified.
587 // I am not sure wether we should handle Buffer cloning here or in BufferList.
588 // Right now BufferList knows nothing about buffer clones.
589 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
590 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
591 for (; it != end; ++it) {
592 DocIterator dit = it->first.clone(buffer_clone);
593 dit.setBuffer(buffer_clone);
594 Buffer * child = const_cast<Buffer *>(it->second.buffer);
596 child->cloneWithChildren(bufmap, clones);
597 BufferMap::iterator const bit = bufmap.find(child);
598 LASSERT(bit != bufmap.end(), continue);
599 Buffer * child_clone = bit->second;
601 Inset * inset = dit.nextInset();
602 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
603 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
604 inset_inc->setChildBuffer(child_clone);
605 child_clone->d->setParent(buffer_clone);
606 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
607 buffer_clone->setChild(dit, child_clone);
609 buffer_clone->d->macro_lock = false;
614 Buffer * Buffer::cloneBufferOnly() const {
615 cloned_buffers.push_back(new CloneList);
616 CloneList * clones = cloned_buffers.back();
617 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
619 // The clone needs its own DocumentClass, since running updateBuffer() will
620 // modify it, and we would otherwise be sharing it with the original Buffer.
621 buffer_clone->params().makeDocumentClass(true);
623 cap::switchBetweenClasses(
624 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
625 static_cast<InsetText &>(buffer_clone->inset()), el);
627 clones->insert(buffer_clone);
628 buffer_clone->d->clone_list_ = clones;
630 // we won't be cloning the children
631 buffer_clone->d->children_positions.clear();
636 bool Buffer::isClone() const
638 return d->cloned_buffer_;
642 void Buffer::changed(bool update_metrics) const
645 d->wa_->redrawAll(update_metrics);
649 frontend::WorkAreaManager & Buffer::workAreaManager() const
656 Text & Buffer::text() const
658 return d->inset->text();
662 Inset & Buffer::inset() const
668 BufferParams & Buffer::params()
674 BufferParams const & Buffer::params() const
680 BufferParams const & Buffer::masterParams() const
682 if (masterBuffer() == this)
685 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
686 // Copy child authors to the params. We need those pointers.
687 AuthorList const & child_authors = params().authors();
688 AuthorList::Authors::const_iterator it = child_authors.begin();
689 for (; it != child_authors.end(); ++it)
690 mparams.authors().record(*it);
695 double Buffer::fontScalingFactor() const
697 return isExporting() ? 75.0 * params().html_math_img_scale
698 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
702 ParagraphList & Buffer::paragraphs()
704 return text().paragraphs();
708 ParagraphList const & Buffer::paragraphs() const
710 return text().paragraphs();
714 LyXVC & Buffer::lyxvc()
720 LyXVC const & Buffer::lyxvc() const
726 string const Buffer::temppath() const
728 return d->temppath.absFileName();
732 TexRow & Buffer::texrow()
738 TexRow const & Buffer::texrow() const
744 TocBackend & Buffer::tocBackend() const
746 return d->toc_backend;
750 Undo & Buffer::undo()
756 void Buffer::setChild(DocIterator const & dit, Buffer * child)
758 d->children_positions[child] = dit;
762 string Buffer::latexName(bool const no_path) const
764 FileName latex_name =
765 makeLatexName(d->exportFileName());
766 return no_path ? latex_name.onlyFileName()
767 : latex_name.absFileName();
771 FileName Buffer::Impl::exportFileName() const
773 docstring const branch_suffix =
774 params.branchlist().getFileNameSuffix();
775 if (branch_suffix.empty())
778 string const name = filename.onlyFileNameWithoutExt()
779 + to_utf8(branch_suffix);
780 FileName res(filename.onlyPath().absFileName() + "/" + name);
781 res.changeExtension(filename.extension());
787 string Buffer::logName(LogType * type) const
789 string const filename = latexName(false);
791 if (filename.empty()) {
797 string const path = temppath();
799 FileName const fname(addName(temppath(),
800 onlyFileName(changeExtension(filename,
803 // FIXME: how do we know this is the name of the build log?
804 FileName const bname(
805 addName(path, onlyFileName(
806 changeExtension(filename,
807 formats.extension(params().bufferFormat()) + ".out"))));
809 // Also consider the master buffer log file
810 FileName masterfname = fname;
811 LogType mtype = latexlog;
812 if (masterBuffer() != this) {
813 string const mlogfile = masterBuffer()->logName(&mtype);
814 masterfname = FileName(mlogfile);
817 // If no Latex log or Build log is newer, show Build log
818 if (bname.exists() &&
819 ((!fname.exists() && !masterfname.exists())
820 || (fname.lastModified() < bname.lastModified()
821 && masterfname.lastModified() < bname.lastModified()))) {
822 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
825 return bname.absFileName();
826 // If we have a newer master file log or only a master log, show this
827 } else if (fname != masterfname
828 && (!fname.exists() && (masterfname.exists()
829 || fname.lastModified() < masterfname.lastModified()))) {
830 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
833 return masterfname.absFileName();
835 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
838 return fname.absFileName();
842 void Buffer::setReadonly(bool const flag)
844 if (d->read_only != flag) {
851 void Buffer::setFileName(FileName const & fname)
853 bool const changed = fname != d->filename;
856 lyxvc().file_found_hook(fname);
857 setReadonly(d->filename.isReadOnly());
863 int Buffer::readHeader(Lexer & lex)
865 int unknown_tokens = 0;
867 int begin_header_line = -1;
869 // Initialize parameters that may be/go lacking in header:
870 params().branchlist().clear();
871 params().preamble.erase();
872 params().options.erase();
873 params().master.erase();
874 params().float_placement.erase();
875 params().paperwidth.erase();
876 params().paperheight.erase();
877 params().leftmargin.erase();
878 params().rightmargin.erase();
879 params().topmargin.erase();
880 params().bottommargin.erase();
881 params().headheight.erase();
882 params().headsep.erase();
883 params().footskip.erase();
884 params().columnsep.erase();
885 params().fonts_cjk.erase();
886 params().listings_params.clear();
887 params().clearLayoutModules();
888 params().clearRemovedModules();
889 params().clearIncludedChildren();
890 params().pdfoptions().clear();
891 params().indiceslist().clear();
892 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
893 params().isbackgroundcolor = false;
894 params().fontcolor = RGBColor(0, 0, 0);
895 params().isfontcolor = false;
896 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
897 params().boxbgcolor = RGBColor(0xFF, 0, 0);
898 params().html_latex_start.clear();
899 params().html_latex_end.clear();
900 params().html_math_img_scale = 1.0;
901 params().output_sync_macro.erase();
902 params().setLocalLayout(string(), false);
903 params().setLocalLayout(string(), true);
905 for (int i = 0; i < 4; ++i) {
906 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
907 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
910 ErrorList & errorList = d->errorLists["Parse"];
919 if (token == "\\end_header")
923 if (token == "\\begin_header") {
924 begin_header_line = line;
928 LYXERR(Debug::PARSER, "Handling document header token: `"
931 string const result =
932 params().readToken(lex, token, d->filename.onlyPath());
933 if (!result.empty()) {
934 if (token == "\\textclass") {
935 d->layout_position = result;
938 docstring const s = bformat(_("Unknown token: "
942 errorList.push_back(ErrorItem(_("Document header error"),
947 if (begin_header_line) {
948 docstring const s = _("\\begin_header is missing");
949 errorList.push_back(ErrorItem(_("Document header error"),
953 params().makeDocumentClass();
955 return unknown_tokens;
960 // changed to be public and have one parameter
961 // Returns true if "\end_document" is not read (Asger)
962 bool Buffer::readDocument(Lexer & lex)
964 ErrorList & errorList = d->errorLists["Parse"];
967 // remove dummy empty par
968 paragraphs().clear();
970 if (!lex.checkFor("\\begin_document")) {
971 docstring const s = _("\\begin_document is missing");
972 errorList.push_back(ErrorItem(_("Document header error"),
978 if (params().output_changes) {
979 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
980 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
981 LaTeXFeatures::isAvailable("xcolor");
983 if (!dvipost && !xcolorulem) {
984 Alert::warning(_("Changes not shown in LaTeX output"),
985 _("Changes will not be highlighted in LaTeX output, "
986 "because neither dvipost nor xcolor/ulem are installed.\n"
987 "Please install these packages or redefine "
988 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
989 } else if (!xcolorulem) {
990 Alert::warning(_("Changes not shown in LaTeX output"),
991 _("Changes will not be highlighted in LaTeX output "
992 "when using pdflatex, because xcolor and ulem are not installed.\n"
993 "Please install both packages or redefine "
994 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
998 if (!parent() && !params().master.empty()) {
999 FileName const master_file = makeAbsPath(params().master,
1000 onlyPath(absFileName()));
1001 if (isLyXFileName(master_file.absFileName())) {
1003 checkAndLoadLyXFile(master_file, true);
1005 // necessary e.g. after a reload
1006 // to re-register the child (bug 5873)
1007 // FIXME: clean up updateMacros (here, only
1008 // child registering is needed).
1009 master->updateMacros();
1010 // set master as master buffer, but only
1011 // if we are a real child
1012 if (master->isChild(this))
1014 // if the master is not fully loaded
1015 // it is probably just loading this
1016 // child. No warning needed then.
1017 else if (master->isFullyLoaded())
1018 LYXERR0("The master '"
1020 << "' assigned to this document ("
1022 << ") does not include "
1023 "this document. Ignoring the master assignment.");
1028 // assure we have a default index
1029 params().indiceslist().addDefault(B_("Index"));
1032 d->old_position = originFilePath();
1033 bool const res = text().read(lex, errorList, d->inset);
1034 d->old_position.clear();
1036 // inform parent buffer about local macros
1038 Buffer const * pbuf = parent();
1039 UserMacroSet::const_iterator cit = usermacros.begin();
1040 UserMacroSet::const_iterator end = usermacros.end();
1041 for (; cit != end; ++cit)
1042 pbuf->usermacros.insert(*cit);
1046 updateMacroInstances(InternalUpdate);
1051 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1053 Format const * fmt = formats.getFormat(format);
1056 // It is important to use the correct extension here, since some
1057 // converters create a wrong output file otherwise (e.g. html2latex)
1058 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1059 FileName const name(tempfile.name());
1060 ofdocstream os(name.toFilesystemEncoding().c_str());
1061 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1062 bool const success = !(os << contents).fail();
1065 bool converted = false;
1067 params().compressed = false;
1069 // remove dummy empty par
1070 paragraphs().clear();
1072 converted = importFile(format, name, errorList);
1081 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1083 if (!theConverters().isReachable(format, "lyx"))
1086 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1087 FileName const lyx(tempfile.name());
1088 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1089 return readFile(lyx) == ReadSuccess;
1095 bool Buffer::readString(string const & s)
1097 params().compressed = false;
1100 istringstream is(s);
1102 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1103 FileName const fn = tempfile.name();
1106 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1108 if (success && file_format != LYX_FORMAT) {
1109 // We need to call lyx2lyx, so write the input to a file
1110 ofstream os(fn.toFilesystemEncoding().c_str());
1113 // lyxvc in readFile
1114 if (readFile(fn) != ReadSuccess)
1118 if (readDocument(lex))
1124 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1128 if (!lex.setFile(fname)) {
1129 Alert::error(_("File Not Found"),
1130 bformat(_("Unable to open file `%1$s'."),
1131 from_utf8(fn.absFileName())));
1132 return ReadFileNotFound;
1136 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1137 if (ret_plf != ReadSuccess)
1140 if (file_format != LYX_FORMAT) {
1142 ReadStatus ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1143 if (ret_clf != ReadSuccess)
1145 ret_clf = readFile(tmpFile);
1146 if (ret_clf == ReadSuccess) {
1147 d->file_format = file_format;
1148 d->need_format_backup = true;
1153 // FIXME: InsetInfo needs to know whether the file is under VCS
1154 // during the parse process, so this has to be done before.
1155 lyxvc().file_found_hook(d->filename);
1157 if (readDocument(lex)) {
1158 Alert::error(_("Document format failure"),
1159 bformat(_("%1$s ended unexpectedly, which means"
1160 " that it is probably corrupted."),
1161 from_utf8(fn.absFileName())));
1162 return ReadDocumentFailure;
1165 d->file_fully_loaded = true;
1166 d->read_only = !d->filename.isWritable();
1167 params().compressed = formats.isZippedFile(d->filename);
1173 bool Buffer::isFullyLoaded() const
1175 return d->file_fully_loaded;
1179 void Buffer::setFullyLoaded(bool value)
1181 d->file_fully_loaded = value;
1185 bool Buffer::lastPreviewError() const
1187 return d->preview_error_;
1191 PreviewLoader * Buffer::loader() const
1193 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1195 if (!d->preview_loader_)
1196 d->preview_loader_ = new PreviewLoader(*this);
1197 return d->preview_loader_;
1201 void Buffer::removePreviews() const
1203 delete d->preview_loader_;
1204 d->preview_loader_ = 0;
1208 void Buffer::updatePreviews() const
1210 PreviewLoader * ploader = loader();
1214 InsetIterator it = inset_iterator_begin(*d->inset);
1215 InsetIterator const end = inset_iterator_end(*d->inset);
1216 for (; it != end; ++it)
1217 it->addPreview(it, *ploader);
1219 ploader->startLoading();
1223 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1224 FileName const & fn, int & file_format) const
1226 if(!lex.checkFor("\\lyxformat")) {
1227 Alert::error(_("Document format failure"),
1228 bformat(_("%1$s is not a readable LyX document."),
1229 from_utf8(fn.absFileName())));
1230 return ReadNoLyXFormat;
1236 // LyX formats 217 and earlier were written as 2.17. This corresponds
1237 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1238 // these cases. See also: www.lyx.org/trac/changeset/1313.
1239 size_t dot = tmp_format.find_first_of(".,");
1240 if (dot != string::npos)
1241 tmp_format.erase(dot, 1);
1243 file_format = convert<int>(tmp_format);
1248 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1249 FileName & tmpfile, int from_format)
1251 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1252 tempfile.setAutoRemove(false);
1253 tmpfile = tempfile.name();
1254 if(tmpfile.empty()) {
1255 Alert::error(_("Conversion failed"),
1256 bformat(_("%1$s is from a different"
1257 " version of LyX, but a temporary"
1258 " file for converting it could"
1259 " not be created."),
1260 from_utf8(fn.absFileName())));
1261 return LyX2LyXNoTempFile;
1264 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1265 if (lyx2lyx.empty()) {
1266 Alert::error(_("Conversion script not found"),
1267 bformat(_("%1$s is from a different"
1268 " version of LyX, but the"
1269 " conversion script lyx2lyx"
1270 " could not be found."),
1271 from_utf8(fn.absFileName())));
1272 return LyX2LyXNotFound;
1276 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1277 ostringstream command;
1278 command << os::python()
1279 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1280 << " -t " << convert<string>(LYX_FORMAT)
1281 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1282 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1283 string const command_str = command.str();
1285 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1287 cmd_ret const ret = runCommand(command_str);
1288 if (ret.first != 0) {
1289 if (from_format < LYX_FORMAT) {
1290 Alert::error(_("Conversion script failed"),
1291 bformat(_("%1$s is from an older version"
1292 " of LyX and the lyx2lyx script"
1293 " failed to convert it."),
1294 from_utf8(fn.absFileName())));
1295 return LyX2LyXOlderFormat;
1297 Alert::error(_("Conversion script failed"),
1298 bformat(_("%1$s is from a newer version"
1299 " of LyX and the lyx2lyx script"
1300 " failed to convert it."),
1301 from_utf8(fn.absFileName())));
1302 return LyX2LyXNewerFormat;
1309 string Buffer::getBackupName() const {
1310 FileName const & fn = fileName();
1311 string const fname = fn.onlyFileNameWithoutExt();
1312 string const fext = fn.extension();
1313 string const fpath = lyxrc.backupdir_path.empty() ?
1314 fn.onlyPath().absFileName() :
1315 lyxrc.backupdir_path;
1316 string const fform = convert<string>(d->file_format);
1317 string const backname = fname + "-" + fform;
1318 FileName backup(addName(fpath, addExtension(backname, fext)));
1320 // limit recursion, just in case
1322 unsigned long orig_checksum = 0;
1323 while (backup.exists() && v < 100) {
1324 if (orig_checksum == 0)
1325 orig_checksum = fn.checksum();
1326 unsigned long new_checksum = backup.checksum();
1327 if (orig_checksum == new_checksum) {
1328 LYXERR(Debug::FILES, "Not backing up " << fn <<
1329 "since " << backup << "has the same checksum.");
1330 // a bit of a hack, but we have to check this anyway
1331 // below, and setting this is simpler than introducing
1332 // a special boolean for this purpose.
1336 string newbackname = backname + "-" + convert<string>(v);
1337 backup.set(addName(fpath, addExtension(newbackname, fext)));
1340 return v < 100 ? backup.onlyFileName() : "";
1344 // Should probably be moved to somewhere else: BufferView? GuiView?
1345 bool Buffer::save() const
1347 docstring const file = makeDisplayPath(absFileName(), 20);
1348 d->filename.refresh();
1350 // check the read-only status before moving the file as a backup
1351 if (d->filename.exists()) {
1352 bool const read_only = !d->filename.isWritable();
1354 Alert::warning(_("File is read-only"),
1355 bformat(_("The file %1$s cannot be written because it "
1356 "is marked as read-only."), file));
1361 // ask if the disk file has been externally modified (use checksum method)
1362 if (fileName().exists() && isExternallyModified(checksum_method)) {
1364 bformat(_("Document %1$s has been externally modified. "
1365 "Are you sure you want to overwrite this file?"), file);
1366 int const ret = Alert::prompt(_("Overwrite modified file?"),
1367 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1372 // We don't need autosaves in the immediate future. (Asger)
1373 resetAutosaveTimers();
1375 // if the file does not yet exist, none of the backup activity
1376 // that follows is necessary
1377 if (!fileName().exists()) {
1378 if (!writeFile(fileName()))
1384 // we first write the file to a new name, then move it to its
1385 // proper location once that has been done successfully. that
1386 // way we preserve the original file if something goes wrong.
1387 string const justname = fileName().onlyFileNameWithoutExt();
1388 boost::scoped_ptr<TempFile>
1389 tempfile(new TempFile(fileName().onlyPath(),
1390 justname + "-XXXXXX.lyx"));
1391 bool const symlink = fileName().isSymLink();
1393 tempfile->setAutoRemove(false);
1395 FileName savefile(tempfile->name());
1396 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1397 if (!writeFile(savefile))
1400 // we will set this to false if we fail
1401 bool made_backup = true;
1403 FileName backupName;
1404 if (lyxrc.make_backup || d->need_format_backup) {
1405 if (d->need_format_backup) {
1406 string backup_name = getBackupName();
1407 if (!backup_name.empty())
1408 backupName.set(backup_name);
1411 // If we for some reason failed to find a backup name in case of
1412 // a format change, this will still set one. It's the best we can
1414 if (backupName.empty()) {
1415 backupName.set(fileName().absFileName() + "~");
1416 if (!lyxrc.backupdir_path.empty()) {
1417 string const mangledName =
1418 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1419 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1423 LYXERR(Debug::FILES, "Backing up original file to " <<
1424 backupName.absFileName());
1425 // Except file is symlink do not copy because of #6587.
1426 // Hard links have bad luck.
1427 made_backup = symlink ?
1428 fileName().copyTo(backupName):
1429 fileName().moveTo(backupName);
1432 Alert::error(_("Backup failure"),
1433 bformat(_("Cannot create backup file %1$s.\n"
1434 "Please check whether the directory exists and is writable."),
1435 from_utf8(backupName.absFileName())));
1436 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1437 } else if (d->need_format_backup) {
1438 // the original file has been backed up successfully, so we
1439 // will not need to do that again
1440 d->need_format_backup = false;
1444 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1445 // Only do this if tempfile is not in autoremove mode
1448 // If we have no symlink, we can simply rename the temp file.
1449 // Otherwise, we need to copy it so the symlink stays intact.
1450 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1451 savefile.moveTo(fileName()))
1453 // saveCheckSum() was already called by writeFile(), but the
1454 // time stamp is invalidated by copying/moving
1457 if (d->file_format != LYX_FORMAT)
1458 // the file associated with this buffer is now in the current format
1459 d->file_format = LYX_FORMAT;
1462 // else we saved the file, but failed to move it to the right location.
1464 if (lyxrc.make_backup && made_backup && !symlink) {
1465 // the original file was moved to filename.lyx~, so it will look
1466 // to the user as if it was deleted. (see bug #9234.) we could try
1467 // to restore it, but that would basically mean trying to do again
1468 // what we just failed to do. better to leave things as they are.
1469 Alert::error(_("Write failure"),
1470 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1471 "But LyX could not move it to:\n %2$s.\n"
1472 "Your original file has been backed up to:\n %3$s"),
1473 from_utf8(savefile.absFileName()),
1474 from_utf8(fileName().absFileName()),
1475 from_utf8(backupName.absFileName())));
1477 // either we did not try to make a backup, or else we tried and failed,
1478 // or else the original file was a symlink, in which case it was copied,
1479 // not moved. so the original file is intact.
1480 Alert::error(_("Write failure"),
1481 bformat(_("Cannot move saved file to:\n %1$s.\n"
1482 "But the file has successfully been saved as:\n %2$s."),
1483 from_utf8(fileName().absFileName()),
1484 from_utf8(savefile.absFileName())));
1490 bool Buffer::writeFile(FileName const & fname) const
1492 if (d->read_only && fname == d->filename)
1495 bool retval = false;
1497 docstring const str = bformat(_("Saving document %1$s..."),
1498 makeDisplayPath(fname.absFileName()));
1501 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1503 if (params().compressed) {
1504 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1505 retval = ofs && write(ofs);
1507 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1508 retval = ofs && write(ofs);
1512 message(str + _(" could not write file!"));
1517 // removeAutosaveFile();
1520 message(str + _(" done."));
1526 docstring Buffer::emergencyWrite()
1528 // No need to save if the buffer has not changed.
1532 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1534 docstring user_message = bformat(
1535 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1537 // We try to save three places:
1538 // 1) Same place as document. Unless it is an unnamed doc.
1540 string s = absFileName();
1543 if (writeFile(FileName(s))) {
1545 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1546 return user_message;
1548 user_message += " " + _("Save failed! Trying again...\n");
1552 // 2) In HOME directory.
1553 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1555 lyxerr << ' ' << s << endl;
1556 if (writeFile(FileName(s))) {
1558 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1559 return user_message;
1562 user_message += " " + _("Save failed! Trying yet again...\n");
1564 // 3) In "/tmp" directory.
1565 // MakeAbsPath to prepend the current
1566 // drive letter on OS/2
1567 s = addName(package().temp_dir().absFileName(), absFileName());
1569 lyxerr << ' ' << s << endl;
1570 if (writeFile(FileName(s))) {
1572 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1573 return user_message;
1576 user_message += " " + _("Save failed! Bummer. Document is lost.");
1579 return user_message;
1583 bool Buffer::write(ostream & ofs) const
1586 // Use the standard "C" locale for file output.
1587 ofs.imbue(locale::classic());
1590 // The top of the file should not be written by params().
1592 // write out a comment in the top of the file
1593 // Important: Keep the version formatting in sync with lyx2lyx and
1594 // tex2lyx (bug 7951)
1595 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1596 << " created this file. For more info see http://www.lyx.org/\n"
1597 << "\\lyxformat " << LYX_FORMAT << "\n"
1598 << "\\begin_document\n";
1600 /// For each author, set 'used' to true if there is a change
1601 /// by this author in the document; otherwise set it to 'false'.
1602 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1603 AuthorList::Authors::const_iterator a_end = params().authors().end();
1604 for (; a_it != a_end; ++a_it)
1605 a_it->setUsed(false);
1607 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1608 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1609 for ( ; it != end; ++it)
1610 it->checkAuthors(params().authors());
1612 // now write out the buffer parameters.
1613 ofs << "\\begin_header\n";
1614 params().writeFile(ofs, this);
1615 ofs << "\\end_header\n";
1618 ofs << "\n\\begin_body\n";
1620 ofs << "\n\\end_body\n";
1622 // Write marker that shows file is complete
1623 ofs << "\\end_document" << endl;
1625 // Shouldn't really be needed....
1628 // how to check if close went ok?
1629 // Following is an attempt... (BE 20001011)
1631 // good() returns false if any error occurred, including some
1632 // formatting error.
1633 // bad() returns true if something bad happened in the buffer,
1634 // which should include file system full errors.
1639 lyxerr << "File was not closed properly." << endl;
1646 bool Buffer::makeLaTeXFile(FileName const & fname,
1647 string const & original_path,
1648 OutputParams const & runparams_in,
1649 OutputWhat output) const
1651 OutputParams runparams = runparams_in;
1653 // XeTeX with TeX fonts is only safe with ASCII encoding,
1654 // but the "flavor" is not known in BufferParams::encoding().
1655 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1656 runparams.encoding = encodings.fromLyXName("ascii");
1658 string const encoding = runparams.encoding->iconvName();
1659 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1662 try { ofs.reset(encoding); }
1663 catch (iconv_codecvt_facet_exception const & e) {
1664 lyxerr << "Caught iconv exception: " << e.what() << endl;
1665 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1666 "verify that the support software for your encoding (%1$s) is "
1667 "properly installed"), from_ascii(encoding)));
1670 if (!openFileWrite(ofs, fname))
1673 ErrorList & errorList = d->errorLists["Export"];
1675 bool failed_export = false;
1676 otexstream os(ofs, d->texrow);
1678 // make sure we are ready to export
1679 // this needs to be done before we validate
1680 // FIXME Do we need to do this all the time? I.e., in children
1681 // of a master we are exporting?
1683 updateMacroInstances(OutputUpdate);
1686 os.texrow().reset();
1687 writeLaTeXSource(os, original_path, runparams, output);
1689 catch (EncodingException const & e) {
1690 docstring const failed(1, e.failed_char);
1692 oss << "0x" << hex << e.failed_char << dec;
1693 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1694 " (code point %2$s)"),
1695 failed, from_utf8(oss.str()));
1696 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1697 "representable in the chosen encoding.\n"
1698 "Changing the document encoding to utf8 could help."),
1699 e.par_id, e.pos, e.pos + 1));
1700 failed_export = true;
1702 catch (iconv_codecvt_facet_exception const & e) {
1703 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1704 _(e.what()), -1, 0, 0));
1705 failed_export = true;
1707 catch (exception const & e) {
1708 errorList.push_back(ErrorItem(_("conversion failed"),
1709 _(e.what()), -1, 0, 0));
1710 failed_export = true;
1713 lyxerr << "Caught some really weird exception..." << endl;
1719 failed_export = true;
1720 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1723 if (runparams_in.silent)
1727 return !failed_export;
1731 void Buffer::writeLaTeXSource(otexstream & os,
1732 string const & original_path,
1733 OutputParams const & runparams_in,
1734 OutputWhat output) const
1736 // The child documents, if any, shall be already loaded at this point.
1738 OutputParams runparams = runparams_in;
1740 // XeTeX with TeX fonts is only safe with ASCII encoding,
1741 // but the "flavor" is not known in BufferParams::encoding().
1742 if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1743 runparams.encoding = encodings.fromLyXName("ascii");
1744 // FIXME: when only the current paragraph is shown, this is ignored
1745 // (or not reached) and characters encodable in the current
1746 // encoding are not converted to ASCII-representation.
1748 // If we are compiling a file standalone, even if this is the
1749 // child of some other buffer, let's cut the link here, so the
1750 // file is really independent and no concurring settings from
1751 // the master (e.g. branch state) interfere (see #8100).
1752 if (!runparams.is_child)
1753 d->ignore_parent = true;
1755 // Classify the unicode characters appearing in math insets
1756 BufferEncodings::initUnicodeMath(*this);
1758 // validate the buffer.
1759 LYXERR(Debug::LATEX, " Validating buffer...");
1760 LaTeXFeatures features(*this, params(), runparams);
1762 // This is only set once per document (in master)
1763 if (!runparams.is_child)
1764 runparams.use_polyglossia = features.usePolyglossia();
1765 LYXERR(Debug::LATEX, " Buffer validation done.");
1767 bool const output_preamble =
1768 output == FullSource || output == OnlyPreamble;
1769 bool const output_body =
1770 output == FullSource || output == OnlyBody;
1772 // The starting paragraph of the coming rows is the
1773 // first paragraph of the document. (Asger)
1774 if (output_preamble && runparams.nice) {
1775 os << "%% LyX " << lyx_version << " created this file. "
1776 "For more info, see http://www.lyx.org/.\n"
1777 "%% Do not edit unless you really know what "
1780 LYXERR(Debug::INFO, "lyx document header finished");
1782 // There are a few differences between nice LaTeX and usual files:
1783 // usual files have \batchmode and special input@path to allow
1784 // inclusion of figures specified by an explicitly relative path
1785 // (i.e., a path starting with './' or '../') with either \input or
1786 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1787 // input@path is set when the actual parameter original_path is set.
1788 // This is done for usual tex-file, but not for nice-latex-file.
1789 // (Matthias 250696)
1790 // Note that input@path is only needed for something the user does
1791 // in the preamble, included .tex files or ERT, files included by
1792 // LyX work without it.
1793 if (output_preamble) {
1794 if (!runparams.nice) {
1795 // code for usual, NOT nice-latex-file
1796 os << "\\batchmode\n"; // changed from \nonstopmode
1798 if (!original_path.empty()) {
1800 // We don't know the encoding of inputpath
1801 docstring const inputpath = from_utf8(original_path);
1802 docstring uncodable_glyphs;
1803 Encoding const * const enc = runparams.encoding;
1805 for (size_t n = 0; n < inputpath.size(); ++n) {
1806 if (!enc->encodable(inputpath[n])) {
1807 docstring const glyph(1, inputpath[n]);
1808 LYXERR0("Uncodable character '"
1810 << "' in input path!");
1811 uncodable_glyphs += glyph;
1816 // warn user if we found uncodable glyphs.
1817 if (!uncodable_glyphs.empty()) {
1818 frontend::Alert::warning(
1819 _("Uncodable character in file path"),
1821 _("The path of your document\n"
1823 "contains glyphs that are unknown "
1824 "in the current document encoding "
1825 "(namely %2$s). This may result in "
1826 "incomplete output, unless "
1827 "TEXINPUTS contains the document "
1828 "directory and you don't use "
1829 "explicitly relative paths (i.e., "
1830 "paths starting with './' or "
1831 "'../') in the preamble or in ERT."
1832 "\n\nIn case of problems, choose "
1833 "an appropriate document encoding\n"
1834 "(such as utf8) or change the "
1836 inputpath, uncodable_glyphs));
1839 support::latex_path(original_path);
1840 if (contains(docdir, '#')) {
1841 docdir = subst(docdir, "#", "\\#");
1842 os << "\\catcode`\\#=11"
1843 "\\def\\#{#}\\catcode`\\#=6\n";
1845 if (contains(docdir, '%')) {
1846 docdir = subst(docdir, "%", "\\%");
1847 os << "\\catcode`\\%=11"
1848 "\\def\\%{%}\\catcode`\\%=14\n";
1850 os << "\\makeatletter\n"
1851 << "\\def\\input@path{{"
1853 << "\\makeatother\n";
1857 // get parent macros (if this buffer has a parent) which will be
1858 // written at the document begin further down.
1859 MacroSet parentMacros;
1860 listParentMacros(parentMacros, features);
1862 // Write the preamble
1863 runparams.use_babel = params().writeLaTeX(os, features,
1864 d->filename.onlyPath());
1866 // Japanese might be required only in some children of a document,
1867 // but once required, we must keep use_japanese true.
1868 runparams.use_japanese |= features.isRequired("japanese");
1871 // Restore the parenthood if needed
1872 if (!runparams.is_child)
1873 d->ignore_parent = false;
1878 os << "\\begin{document}\n";
1880 // output the parent macros
1881 MacroSet::iterator it = parentMacros.begin();
1882 MacroSet::iterator end = parentMacros.end();
1883 for (; it != end; ++it) {
1884 int num_lines = (*it)->write(os.os(), true);
1885 os.texrow().newlines(num_lines);
1888 } // output_preamble
1890 os.texrow().start(paragraphs().begin()->id(), 0);
1892 LYXERR(Debug::INFO, "preamble finished, now the body.");
1895 latexParagraphs(*this, text(), os, runparams);
1897 // Restore the parenthood if needed
1898 if (!runparams.is_child)
1899 d->ignore_parent = false;
1901 // add this just in case after all the paragraphs
1904 if (output_preamble) {
1905 os << "\\end{document}\n";
1906 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1908 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1910 runparams_in.encoding = runparams.encoding;
1912 os.texrow().finalize();
1914 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1915 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1919 void Buffer::makeDocBookFile(FileName const & fname,
1920 OutputParams const & runparams,
1921 OutputWhat output) const
1923 LYXERR(Debug::LATEX, "makeDocBookFile...");
1926 if (!openFileWrite(ofs, fname))
1929 // make sure we are ready to export
1930 // this needs to be done before we validate
1932 updateMacroInstances(OutputUpdate);
1934 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1938 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1942 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1943 OutputParams const & runparams,
1944 OutputWhat output) const
1946 LaTeXFeatures features(*this, params(), runparams);
1949 d->texrow.reset(false);
1951 DocumentClass const & tclass = params().documentClass();
1952 string const & top_element = tclass.latexname();
1954 bool const output_preamble =
1955 output == FullSource || output == OnlyPreamble;
1956 bool const output_body =
1957 output == FullSource || output == OnlyBody;
1959 if (output_preamble) {
1960 if (runparams.flavor == OutputParams::XML)
1961 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1964 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1967 if (! tclass.class_header().empty())
1968 os << from_ascii(tclass.class_header());
1969 else if (runparams.flavor == OutputParams::XML)
1970 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1971 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1973 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1975 docstring preamble = from_utf8(params().preamble);
1976 if (runparams.flavor != OutputParams::XML ) {
1977 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1978 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1979 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1980 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1983 string const name = runparams.nice
1984 ? changeExtension(absFileName(), ".sgml") : fname;
1985 preamble += features.getIncludedFiles(name);
1986 preamble += features.getLyXSGMLEntities();
1988 if (!preamble.empty()) {
1989 os << "\n [ " << preamble << " ]";
1995 string top = top_element;
1997 if (runparams.flavor == OutputParams::XML)
1998 top += params().language->code();
2000 top += params().language->code().substr(0, 2);
2003 if (!params().options.empty()) {
2005 top += params().options;
2008 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2009 << " file was created by LyX " << lyx_version
2010 << "\n See http://www.lyx.org/ for more information -->\n";
2012 params().documentClass().counters().reset();
2014 sgml::openTag(os, top);
2016 docbookParagraphs(text(), *this, os, runparams);
2017 sgml::closeTag(os, top_element);
2022 void Buffer::makeLyXHTMLFile(FileName const & fname,
2023 OutputParams const & runparams) const
2025 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2028 if (!openFileWrite(ofs, fname))
2031 // make sure we are ready to export
2032 // this has to be done before we validate
2033 updateBuffer(UpdateMaster, OutputUpdate);
2034 updateMacroInstances(OutputUpdate);
2036 writeLyXHTMLSource(ofs, runparams, FullSource);
2040 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2044 void Buffer::writeLyXHTMLSource(odocstream & os,
2045 OutputParams const & runparams,
2046 OutputWhat output) const
2048 LaTeXFeatures features(*this, params(), runparams);
2050 d->bibinfo_.makeCitationLabels(*this);
2052 bool const output_preamble =
2053 output == FullSource || output == OnlyPreamble;
2054 bool const output_body =
2055 output == FullSource || output == OnlyBody || output == IncludedFile;
2057 if (output_preamble) {
2058 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2059 << "<!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"
2060 // FIXME Language should be set properly.
2061 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2063 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2064 // FIXME Presumably need to set this right
2065 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2067 docstring const & doctitle = features.htmlTitle();
2069 << (doctitle.empty() ?
2070 from_ascii("LyX Document") :
2071 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2074 docstring styles = features.getTClassHTMLPreamble();
2075 if (!styles.empty())
2076 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2078 styles = from_utf8(features.getPreambleSnippets());
2079 if (!styles.empty())
2080 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2082 // we will collect CSS information in a stream, and then output it
2083 // either here, as part of the header, or else in a separate file.
2084 odocstringstream css;
2085 styles = from_utf8(features.getCSSSnippets());
2086 if (!styles.empty())
2087 css << "/* LyX Provided Styles */\n" << styles << '\n';
2089 styles = features.getTClassHTMLStyles();
2090 if (!styles.empty())
2091 css << "/* Layout-provided Styles */\n" << styles << '\n';
2093 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2094 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2095 if (needfg || needbg) {
2096 css << "\nbody {\n";
2099 << from_ascii(X11hexname(params().fontcolor))
2102 css << " background-color: "
2103 << from_ascii(X11hexname(params().backgroundcolor))
2108 docstring const dstyles = css.str();
2109 if (!dstyles.empty()) {
2110 bool written = false;
2111 if (params().html_css_as_file) {
2112 // open a file for CSS info
2114 string const fcssname = addName(temppath(), "docstyle.css");
2115 FileName const fcssfile = FileName(fcssname);
2116 if (openFileWrite(ocss, fcssfile)) {
2120 // write link to header
2121 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2123 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2126 // we are here if the CSS is supposed to be written to the header
2127 // or if we failed to write it to an external file.
2129 os << "<style type='text/css'>\n"
2138 bool const output_body_tag = (output != IncludedFile);
2139 if (output_body_tag)
2142 if (output != IncludedFile)
2143 // if we're an included file, the counters are in the master.
2144 params().documentClass().counters().reset();
2145 xhtmlParagraphs(text(), *this, xs, runparams);
2146 if (output_body_tag)
2150 if (output_preamble)
2155 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2156 // Other flags: -wall -v0 -x
2157 int Buffer::runChktex()
2161 // get LaTeX-Filename
2162 FileName const path(temppath());
2163 string const name = addName(path.absFileName(), latexName());
2164 string const org_path = filePath();
2166 PathChanger p(path); // path to LaTeX file
2167 message(_("Running chktex..."));
2169 // Generate the LaTeX file if neccessary
2170 OutputParams runparams(¶ms().encoding());
2171 runparams.flavor = OutputParams::LATEX;
2172 runparams.nice = false;
2173 runparams.linelen = lyxrc.plaintext_linelen;
2174 makeLaTeXFile(FileName(name), org_path, runparams);
2177 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2178 int const res = chktex.run(terr); // run chktex
2181 Alert::error(_("chktex failure"),
2182 _("Could not run chktex successfully."));
2184 ErrorList & errlist = d->errorLists["ChkTeX"];
2186 bufferErrors(terr, errlist);
2191 if (runparams.silent)
2192 d->errorLists["ChkTeX"].clear();
2200 void Buffer::validate(LaTeXFeatures & features) const
2202 // Validate the buffer params, but not for included
2203 // files, since they also use the parent buffer's
2205 if (!features.runparams().is_child)
2206 params().validate(features);
2208 for_each(paragraphs().begin(), paragraphs().end(),
2209 bind(&Paragraph::validate, _1, ref(features)));
2211 if (lyxerr.debugging(Debug::LATEX)) {
2212 features.showStruct();
2217 void Buffer::getLabelList(vector<docstring> & list) const
2219 // If this is a child document, use the master's list instead.
2221 masterBuffer()->getLabelList(list);
2226 shared_ptr<Toc> toc = d->toc_backend.toc("label");
2227 TocIterator toc_it = toc->begin();
2228 TocIterator end = toc->end();
2229 for (; toc_it != end; ++toc_it) {
2230 if (toc_it->depth() == 0)
2231 list.push_back(toc_it->str());
2236 void Buffer::updateBibfilesCache(UpdateScope scope) const
2238 // FIXME This is probably unnecssary, given where we call this.
2239 // If this is a child document, use the parent's cache instead.
2240 if (parent() && scope != UpdateChildOnly) {
2241 masterBuffer()->updateBibfilesCache();
2245 d->bibfiles_cache_.clear();
2246 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2247 if (it->lyxCode() == BIBTEX_CODE) {
2248 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2249 support::FileNameList const bibfiles = inset.getBibFiles();
2250 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2253 } else if (it->lyxCode() == INCLUDE_CODE) {
2254 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2255 Buffer const * const incbuf = inset.getChildBuffer();
2258 support::FileNameList const & bibfiles =
2259 incbuf->getBibfilesCache(UpdateChildOnly);
2260 if (!bibfiles.empty()) {
2261 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2267 d->bibfile_cache_valid_ = true;
2268 d->bibinfo_cache_valid_ = false;
2269 d->cite_labels_valid_ = false;
2273 void Buffer::invalidateBibinfoCache() const
2275 d->bibinfo_cache_valid_ = false;
2276 d->cite_labels_valid_ = false;
2277 // also invalidate the cache for the parent buffer
2278 Buffer const * const pbuf = d->parent();
2280 pbuf->invalidateBibinfoCache();
2284 void Buffer::invalidateBibfileCache() const
2286 d->bibfile_cache_valid_ = false;
2287 d->bibinfo_cache_valid_ = false;
2288 d->cite_labels_valid_ = false;
2289 // also invalidate the cache for the parent buffer
2290 Buffer const * const pbuf = d->parent();
2292 pbuf->invalidateBibfileCache();
2296 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2298 // FIXME This is probably unnecessary, given where we call this.
2299 // If this is a child document, use the master's cache instead.
2300 Buffer const * const pbuf = masterBuffer();
2301 if (pbuf != this && scope != UpdateChildOnly)
2302 return pbuf->getBibfilesCache();
2304 if (!d->bibfile_cache_valid_)
2305 this->updateBibfilesCache(scope);
2307 return d->bibfiles_cache_;
2311 BiblioInfo const & Buffer::masterBibInfo() const
2313 Buffer const * const tmp = masterBuffer();
2315 return tmp->masterBibInfo();
2320 void Buffer::checkIfBibInfoCacheIsValid() const
2322 // use the master's cache
2323 Buffer const * const tmp = masterBuffer();
2325 tmp->checkIfBibInfoCacheIsValid();
2329 // compare the cached timestamps with the actual ones.
2330 FileNameList const & bibfiles_cache = getBibfilesCache();
2331 FileNameList::const_iterator ei = bibfiles_cache.begin();
2332 FileNameList::const_iterator en = bibfiles_cache.end();
2333 for (; ei != en; ++ ei) {
2334 time_t lastw = ei->lastModified();
2335 time_t prevw = d->bibfile_status_[*ei];
2336 if (lastw != prevw) {
2337 d->bibinfo_cache_valid_ = false;
2338 d->cite_labels_valid_ = false;
2339 d->bibfile_status_[*ei] = lastw;
2345 void Buffer::reloadBibInfoCache() const
2347 // use the master's cache
2348 Buffer const * const tmp = masterBuffer();
2350 tmp->reloadBibInfoCache();
2354 checkIfBibInfoCacheIsValid();
2355 if (d->bibinfo_cache_valid_)
2358 d->bibinfo_.clear();
2360 d->bibinfo_cache_valid_ = true;
2364 void Buffer::collectBibKeys() const
2366 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2367 it->collectBibKeys(it);
2371 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2373 Buffer const * tmp = masterBuffer();
2374 BiblioInfo & masterbi = (tmp == this) ?
2375 d->bibinfo_ : tmp->d->bibinfo_;
2376 masterbi.mergeBiblioInfo(bi);
2380 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2382 Buffer const * tmp = masterBuffer();
2383 BiblioInfo & masterbi = (tmp == this) ?
2384 d->bibinfo_ : tmp->d->bibinfo_;
2389 void Buffer::makeCitationLabels() const
2391 Buffer const * const master = masterBuffer();
2392 return d->bibinfo_.makeCitationLabels(*master);
2396 bool Buffer::citeLabelsValid() const
2398 return masterBuffer()->d->cite_labels_valid_;
2402 void Buffer::removeBiblioTempFiles() const
2404 // We remove files that contain LaTeX commands specific to the
2405 // particular bibliographic style being used, in order to avoid
2406 // LaTeX errors when we switch style.
2407 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2408 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2409 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2410 aux_file.removeFile();
2411 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2412 bbl_file.removeFile();
2413 // Also for the parent buffer
2414 Buffer const * const pbuf = parent();
2416 pbuf->removeBiblioTempFiles();
2420 bool Buffer::isDepClean(string const & name) const
2422 DepClean::const_iterator const it = d->dep_clean.find(name);
2423 if (it == d->dep_clean.end())
2429 void Buffer::markDepClean(string const & name)
2431 d->dep_clean[name] = true;
2435 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2438 // FIXME? if there is an Buffer LFUN that can be dispatched even
2439 // if internal, put a switch '(cmd.action)' here.
2445 switch (cmd.action()) {
2447 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2448 flag.setOnOff(isReadonly());
2451 // FIXME: There is need for a command-line import.
2452 //case LFUN_BUFFER_IMPORT:
2454 case LFUN_BUFFER_AUTO_SAVE:
2457 case LFUN_BUFFER_EXPORT_CUSTOM:
2458 // FIXME: Nothing to check here?
2461 case LFUN_BUFFER_EXPORT: {
2462 docstring const arg = cmd.argument();
2463 if (arg == "custom") {
2467 string format = to_utf8(arg);
2468 size_t pos = format.find(' ');
2469 if (pos != string::npos)
2470 format = format.substr(0, pos);
2471 enable = params().isExportable(format);
2473 flag.message(bformat(
2474 _("Don't know how to export to format: %1$s"), arg));
2478 case LFUN_BUFFER_CHKTEX:
2479 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2482 case LFUN_BUILD_PROGRAM:
2483 enable = params().isExportable("program");
2486 case LFUN_BRANCH_ACTIVATE:
2487 case LFUN_BRANCH_DEACTIVATE:
2488 case LFUN_BRANCH_MASTER_ACTIVATE:
2489 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2490 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2491 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2492 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2493 : params().branchlist();
2494 docstring const branchName = cmd.argument();
2495 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2499 case LFUN_BRANCH_ADD:
2500 case LFUN_BRANCHES_RENAME:
2501 // if no Buffer is present, then of course we won't be called!
2504 case LFUN_BUFFER_LANGUAGE:
2505 enable = !isReadonly();
2508 case LFUN_BUFFER_VIEW_CACHE:
2509 (d->preview_file_).refresh();
2510 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2513 case LFUN_CHANGES_TRACK:
2514 flag.setEnabled(true);
2515 flag.setOnOff(params().track_changes);
2518 case LFUN_CHANGES_OUTPUT:
2519 flag.setEnabled(true);
2520 flag.setOnOff(params().output_changes);
2523 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2524 flag.setOnOff(params().compressed);
2528 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2529 flag.setOnOff(params().output_sync);
2536 flag.setEnabled(enable);
2541 void Buffer::dispatch(string const & command, DispatchResult & result)
2543 return dispatch(lyxaction.lookupFunc(command), result);
2547 // NOTE We can end up here even if we have no GUI, because we are called
2548 // by LyX::exec to handled command-line requests. So we may need to check
2549 // whether we have a GUI or not. The boolean use_gui holds this information.
2550 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2553 // FIXME? if there is an Buffer LFUN that can be dispatched even
2554 // if internal, put a switch '(cmd.action())' here.
2555 dr.dispatched(false);
2558 string const argument = to_utf8(func.argument());
2559 // We'll set this back to false if need be.
2560 bool dispatched = true;
2561 undo().beginUndoGroup();
2563 switch (func.action()) {
2564 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2565 if (lyxvc().inUse()) {
2566 string log = lyxvc().toggleReadOnly();
2571 setReadonly(!isReadonly());
2574 case LFUN_BUFFER_EXPORT: {
2575 ExportStatus const status = doExport(argument, false);
2576 dr.setError(status != ExportSuccess);
2577 if (status != ExportSuccess)
2578 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2583 case LFUN_BUILD_PROGRAM: {
2584 ExportStatus const status = doExport("program", true);
2585 dr.setError(status != ExportSuccess);
2586 if (status != ExportSuccess)
2587 dr.setMessage(_("Error generating literate programming code."));
2591 case LFUN_BUFFER_CHKTEX:
2595 case LFUN_BUFFER_EXPORT_CUSTOM: {
2597 string command = split(argument, format_name, ' ');
2598 Format const * format = formats.getFormat(format_name);
2600 lyxerr << "Format \"" << format_name
2601 << "\" not recognized!"
2606 // The name of the file created by the conversion process
2609 // Output to filename
2610 if (format->name() == "lyx") {
2611 string const latexname = latexName(false);
2612 filename = changeExtension(latexname,
2613 format->extension());
2614 filename = addName(temppath(), filename);
2616 if (!writeFile(FileName(filename)))
2620 doExport(format_name, true, filename);
2623 // Substitute $$FName for filename
2624 if (!contains(command, "$$FName"))
2625 command = "( " + command + " ) < $$FName";
2626 command = subst(command, "$$FName", filename);
2628 // Execute the command in the background
2630 call.startscript(Systemcall::DontWait, command,
2631 filePath(), layoutPos());
2635 // FIXME: There is need for a command-line import.
2637 case LFUN_BUFFER_IMPORT:
2642 case LFUN_BUFFER_AUTO_SAVE:
2644 resetAutosaveTimers();
2647 case LFUN_BRANCH_ACTIVATE:
2648 case LFUN_BRANCH_DEACTIVATE:
2649 case LFUN_BRANCH_MASTER_ACTIVATE:
2650 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2651 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2652 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2653 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2656 docstring const branch_name = func.argument();
2657 // the case without a branch name is handled elsewhere
2658 if (branch_name.empty()) {
2662 Branch * branch = buf->params().branchlist().find(branch_name);
2664 LYXERR0("Branch " << branch_name << " does not exist.");
2666 docstring const msg =
2667 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2671 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2672 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2673 if (branch->isSelected() != activate) {
2674 buf->undo().recordUndoBufferParams(CursorData());
2675 branch->setSelected(activate);
2677 dr.screenUpdate(Update::Force);
2678 dr.forceBufferUpdate();
2683 case LFUN_BRANCH_ADD: {
2684 docstring branch_name = func.argument();
2685 if (branch_name.empty()) {
2689 BranchList & branch_list = params().branchlist();
2690 vector<docstring> const branches =
2691 getVectorFromString(branch_name, branch_list.separator());
2693 for (vector<docstring>::const_iterator it = branches.begin();
2694 it != branches.end(); ++it) {
2696 Branch * branch = branch_list.find(branch_name);
2698 LYXERR0("Branch " << branch_name << " already exists.");
2702 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2704 undo().recordUndoBufferParams(CursorData());
2705 branch_list.add(branch_name);
2706 branch = branch_list.find(branch_name);
2707 string const x11hexname = X11hexname(branch->color());
2708 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2709 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2711 dr.screenUpdate(Update::Force);
2719 case LFUN_BRANCHES_RENAME: {
2720 if (func.argument().empty())
2723 docstring const oldname = from_utf8(func.getArg(0));
2724 docstring const newname = from_utf8(func.getArg(1));
2725 InsetIterator it = inset_iterator_begin(inset());
2726 InsetIterator const end = inset_iterator_end(inset());
2727 bool success = false;
2728 for (; it != end; ++it) {
2729 if (it->lyxCode() == BRANCH_CODE) {
2730 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2731 if (ins.branch() == oldname) {
2732 undo().recordUndo(CursorData(it));
2733 ins.rename(newname);
2738 if (it->lyxCode() == INCLUDE_CODE) {
2739 // get buffer of external file
2740 InsetInclude const & ins =
2741 static_cast<InsetInclude const &>(*it);
2742 Buffer * child = ins.getChildBuffer();
2745 child->dispatch(func, dr);
2750 dr.screenUpdate(Update::Force);
2751 dr.forceBufferUpdate();
2756 case LFUN_BUFFER_VIEW_CACHE:
2757 if (!formats.view(*this, d->preview_file_,
2758 d->preview_format_))
2759 dr.setMessage(_("Error viewing the output file."));
2762 case LFUN_CHANGES_TRACK:
2763 undo().recordUndoBufferParams(CursorData());
2764 params().track_changes = !params().track_changes;
2767 case LFUN_CHANGES_OUTPUT:
2768 undo().recordUndoBufferParams(CursorData());
2769 params().output_changes = !params().output_changes;
2770 if (params().output_changes) {
2771 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
2772 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2773 LaTeXFeatures::isAvailable("xcolor");
2775 if (!dvipost && !xcolorulem) {
2776 Alert::warning(_("Changes not shown in LaTeX output"),
2777 _("Changes will not be highlighted in LaTeX output, "
2778 "because neither dvipost nor xcolor/ulem are installed.\n"
2779 "Please install these packages or redefine "
2780 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2781 } else if (!xcolorulem) {
2782 Alert::warning(_("Changes not shown in LaTeX output"),
2783 _("Changes will not be highlighted in LaTeX output "
2784 "when using pdflatex, because xcolor and ulem are not installed.\n"
2785 "Please install both packages or redefine "
2786 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2791 case LFUN_BUFFER_TOGGLE_COMPRESSION:
2792 // turn compression on/off
2793 undo().recordUndoBufferParams(CursorData());
2794 params().compressed = !params().compressed;
2797 case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2798 undo().recordUndoBufferParams(CursorData());
2799 params().output_sync = !params().output_sync;
2806 dr.dispatched(dispatched);
2807 undo().endUndoGroup();
2811 void Buffer::changeLanguage(Language const * from, Language const * to)
2813 LASSERT(from, return);
2814 LASSERT(to, return);
2816 for_each(par_iterator_begin(),
2818 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2822 bool Buffer::isMultiLingual() const
2824 ParConstIterator end = par_iterator_end();
2825 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2826 if (it->isMultiLingual(params()))
2833 std::set<Language const *> Buffer::getLanguages() const
2835 std::set<Language const *> languages;
2836 getLanguages(languages);
2841 void Buffer::getLanguages(std::set<Language const *> & languages) const
2843 ParConstIterator end = par_iterator_end();
2844 // add the buffer language, even if it's not actively used
2845 languages.insert(language());
2846 // iterate over the paragraphs
2847 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2848 it->getLanguages(languages);
2850 ListOfBuffers clist = getDescendents();
2851 ListOfBuffers::const_iterator cit = clist.begin();
2852 ListOfBuffers::const_iterator const cen = clist.end();
2853 for (; cit != cen; ++cit)
2854 (*cit)->getLanguages(languages);
2858 DocIterator Buffer::getParFromID(int const id) const
2860 Buffer * buf = const_cast<Buffer *>(this);
2862 // John says this is called with id == -1 from undo
2863 lyxerr << "getParFromID(), id: " << id << endl;
2864 return doc_iterator_end(buf);
2867 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2868 if (it.paragraph().id() == id)
2871 return doc_iterator_end(buf);
2875 bool Buffer::hasParWithID(int const id) const
2877 return !getParFromID(id).atEnd();
2881 ParIterator Buffer::par_iterator_begin()
2883 return ParIterator(doc_iterator_begin(this));
2887 ParIterator Buffer::par_iterator_end()
2889 return ParIterator(doc_iterator_end(this));
2893 ParConstIterator Buffer::par_iterator_begin() const
2895 return ParConstIterator(doc_iterator_begin(this));
2899 ParConstIterator Buffer::par_iterator_end() const
2901 return ParConstIterator(doc_iterator_end(this));
2905 Language const * Buffer::language() const
2907 return params().language;
2911 docstring const Buffer::B_(string const & l10n) const
2913 return params().B_(l10n);
2917 bool Buffer::isClean() const
2919 return d->lyx_clean;
2923 bool Buffer::isExternallyModified(CheckMethod method) const
2925 LASSERT(d->filename.exists(), return false);
2926 // if method == timestamp, check timestamp before checksum
2927 return (method == checksum_method
2928 || d->timestamp_ != d->filename.lastModified())
2929 && d->checksum_ != d->filename.checksum();
2933 void Buffer::saveCheckSum() const
2935 FileName const & file = d->filename;
2938 if (file.exists()) {
2939 d->timestamp_ = file.lastModified();
2940 d->checksum_ = file.checksum();
2942 // in the case of save to a new file.
2949 void Buffer::markClean() const
2951 if (!d->lyx_clean) {
2952 d->lyx_clean = true;
2955 // if the .lyx file has been saved, we don't need an
2957 d->bak_clean = true;
2958 d->undo_.markDirty();
2962 void Buffer::setUnnamed(bool flag)
2968 bool Buffer::isUnnamed() const
2975 /// Don't check unnamed, here: isInternal() is used in
2976 /// newBuffer(), where the unnamed flag has not been set by anyone
2977 /// yet. Also, for an internal buffer, there should be no need for
2978 /// retrieving fileName() nor for checking if it is unnamed or not.
2979 bool Buffer::isInternal() const
2981 return d->internal_buffer;
2985 void Buffer::setInternal(bool flag)
2987 d->internal_buffer = flag;
2991 void Buffer::markDirty()
2994 d->lyx_clean = false;
2997 d->bak_clean = false;
2999 DepClean::iterator it = d->dep_clean.begin();
3000 DepClean::const_iterator const end = d->dep_clean.end();
3002 for (; it != end; ++it)
3007 FileName Buffer::fileName() const
3013 string Buffer::absFileName() const
3015 return d->filename.absFileName();
3019 string Buffer::filePath() const
3021 string const abs = d->filename.onlyPath().absFileName();
3024 int last = abs.length() - 1;
3026 return abs[last] == '/' ? abs : abs + '/';
3030 string Buffer::originFilePath() const
3032 if (FileName::isAbsolute(params().origin))
3033 return params().origin;
3039 string Buffer::layoutPos() const
3041 return d->layout_position;
3045 void Buffer::setLayoutPos(string const & path)
3048 d->layout_position.clear();
3052 LATTEST(FileName::isAbsolute(path));
3054 d->layout_position =
3055 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3057 if (d->layout_position.empty())
3058 d->layout_position = ".";
3062 bool Buffer::isReadonly() const
3064 return d->read_only;
3068 void Buffer::setParent(Buffer const * buffer)
3070 // Avoids recursive include.
3071 d->setParent(buffer == this ? 0 : buffer);
3076 Buffer const * Buffer::parent() const
3082 ListOfBuffers Buffer::allRelatives() const
3084 ListOfBuffers lb = masterBuffer()->getDescendents();
3085 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3090 Buffer const * Buffer::masterBuffer() const
3092 // FIXME Should be make sure we are not in some kind
3093 // of recursive include? A -> B -> A will crash this.
3094 Buffer const * const pbuf = d->parent();
3098 return pbuf->masterBuffer();
3102 bool Buffer::isChild(Buffer * child) const
3104 return d->children_positions.find(child) != d->children_positions.end();
3108 DocIterator Buffer::firstChildPosition(Buffer const * child)
3110 Impl::BufferPositionMap::iterator it;
3111 it = d->children_positions.find(child);
3112 if (it == d->children_positions.end())
3113 return DocIterator(this);
3118 bool Buffer::hasChildren() const
3120 return !d->children_positions.empty();
3124 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3126 // loop over children
3127 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3128 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3129 for (; it != end; ++it) {
3130 Buffer * child = const_cast<Buffer *>(it->first);
3132 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3133 if (bit != clist.end())
3135 clist.push_back(child);
3137 // there might be grandchildren
3138 child->collectChildren(clist, true);
3143 ListOfBuffers Buffer::getChildren() const
3146 collectChildren(v, false);
3147 // Make sure we have not included ourselves.
3148 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3149 if (bit != v.end()) {
3150 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3157 ListOfBuffers Buffer::getDescendents() const
3160 collectChildren(v, true);
3161 // Make sure we have not included ourselves.
3162 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3163 if (bit != v.end()) {
3164 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3171 template<typename M>
3172 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3177 typename M::const_iterator it = m.lower_bound(x);
3178 if (it == m.begin())
3186 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3187 DocIterator const & pos) const
3189 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3191 // if paragraphs have no macro context set, pos will be empty
3195 // we haven't found anything yet
3196 DocIterator bestPos = owner_->par_iterator_begin();
3197 MacroData const * bestData = 0;
3199 // find macro definitions for name
3200 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3201 if (nameIt != macros.end()) {
3202 // find last definition in front of pos or at pos itself
3203 PositionScopeMacroMap::const_iterator it
3204 = greatest_below(nameIt->second, pos);
3205 if (it != nameIt->second.end()) {
3207 // scope ends behind pos?
3208 if (pos < it->second.scope) {
3209 // Looks good, remember this. If there
3210 // is no external macro behind this,
3211 // we found the right one already.
3212 bestPos = it->first;
3213 bestData = &it->second.macro;
3217 // try previous macro if there is one
3218 if (it == nameIt->second.begin())
3225 // find macros in included files
3226 PositionScopeBufferMap::const_iterator it
3227 = greatest_below(position_to_children, pos);
3228 if (it == position_to_children.end())
3229 // no children before
3233 // do we know something better (i.e. later) already?
3234 if (it->first < bestPos )
3237 // scope ends behind pos?
3238 if (pos < it->second.scope
3239 && (cloned_buffer_ ||
3240 theBufferList().isLoaded(it->second.buffer))) {
3241 // look for macro in external file
3243 MacroData const * data
3244 = it->second.buffer->getMacro(name, false);
3247 bestPos = it->first;
3253 // try previous file if there is one
3254 if (it == position_to_children.begin())
3259 // return the best macro we have found
3264 MacroData const * Buffer::getMacro(docstring const & name,
3265 DocIterator const & pos, bool global) const
3270 // query buffer macros
3271 MacroData const * data = d->getBufferMacro(name, pos);
3275 // If there is a master buffer, query that
3276 Buffer const * const pbuf = d->parent();
3278 d->macro_lock = true;
3279 MacroData const * macro = pbuf->getMacro(
3280 name, *this, false);
3281 d->macro_lock = false;
3287 data = MacroTable::globalMacros().get(name);
3296 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3298 // set scope end behind the last paragraph
3299 DocIterator scope = par_iterator_begin();
3300 scope.pit() = scope.lastpit() + 1;
3302 return getMacro(name, scope, global);
3306 MacroData const * Buffer::getMacro(docstring const & name,
3307 Buffer const & child, bool global) const
3309 // look where the child buffer is included first
3310 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3311 if (it == d->children_positions.end())
3314 // check for macros at the inclusion position
3315 return getMacro(name, it->second, global);
3319 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3321 pit_type const lastpit = it.lastpit();
3323 // look for macros in each paragraph
3324 while (it.pit() <= lastpit) {
3325 Paragraph & par = it.paragraph();
3327 // iterate over the insets of the current paragraph
3328 InsetList const & insets = par.insetList();
3329 InsetList::const_iterator iit = insets.begin();
3330 InsetList::const_iterator end = insets.end();
3331 for (; iit != end; ++iit) {
3332 it.pos() = iit->pos;
3334 // is it a nested text inset?
3335 if (iit->inset->asInsetText()) {
3336 // Inset needs its own scope?
3337 InsetText const * itext = iit->inset->asInsetText();
3338 bool newScope = itext->isMacroScope();
3340 // scope which ends just behind the inset
3341 DocIterator insetScope = it;
3344 // collect macros in inset
3345 it.push_back(CursorSlice(*iit->inset));
3346 updateMacros(it, newScope ? insetScope : scope);
3351 if (iit->inset->asInsetTabular()) {
3352 CursorSlice slice(*iit->inset);
3353 size_t const numcells = slice.nargs();
3354 for (; slice.idx() < numcells; slice.forwardIdx()) {
3355 it.push_back(slice);
3356 updateMacros(it, scope);
3362 // is it an external file?
3363 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3364 // get buffer of external file
3365 InsetInclude const & inset =
3366 static_cast<InsetInclude const &>(*iit->inset);
3368 Buffer * child = inset.getChildBuffer();
3373 // register its position, but only when it is
3374 // included first in the buffer
3375 if (children_positions.find(child) ==
3376 children_positions.end())
3377 children_positions[child] = it;
3379 // register child with its scope
3380 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3384 InsetMath * im = iit->inset->asInsetMath();
3385 if (doing_export && im) {
3386 InsetMathHull * hull = im->asHullInset();
3388 hull->recordLocation(it);
3391 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3395 MathMacroTemplate & macroTemplate =
3396 *iit->inset->asInsetMath()->asMacroTemplate();
3397 MacroContext mc(owner_, it);
3398 macroTemplate.updateToContext(mc);
3401 bool valid = macroTemplate.validMacro();
3402 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3403 // then the BufferView's cursor will be invalid in
3404 // some cases which leads to crashes.
3409 // FIXME (Abdel), I don't understand why we pass 'it' here
3410 // instead of 'macroTemplate' defined above... is this correct?
3411 macros[macroTemplate.name()][it] =
3412 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3422 void Buffer::updateMacros() const
3427 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3429 // start with empty table
3431 d->children_positions.clear();
3432 d->position_to_children.clear();
3434 // Iterate over buffer, starting with first paragraph
3435 // The scope must be bigger than any lookup DocIterator
3436 // later. For the global lookup, lastpit+1 is used, hence
3437 // we use lastpit+2 here.
3438 DocIterator it = par_iterator_begin();
3439 DocIterator outerScope = it;
3440 outerScope.pit() = outerScope.lastpit() + 2;
3441 d->updateMacros(it, outerScope);
3445 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3447 InsetIterator it = inset_iterator_begin(inset());
3448 InsetIterator const end = inset_iterator_end(inset());
3449 for (; it != end; ++it) {
3450 if (it->lyxCode() == BRANCH_CODE) {
3451 InsetBranch & br = static_cast<InsetBranch &>(*it);
3452 docstring const name = br.branch();
3453 if (!from_master && !params().branchlist().find(name))
3454 result.push_back(name);
3455 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3456 result.push_back(name);
3459 if (it->lyxCode() == INCLUDE_CODE) {
3460 // get buffer of external file
3461 InsetInclude const & ins =
3462 static_cast<InsetInclude const &>(*it);
3463 Buffer * child = ins.getChildBuffer();
3466 child->getUsedBranches(result, true);
3469 // remove duplicates
3474 void Buffer::updateMacroInstances(UpdateType utype) const
3476 LYXERR(Debug::MACROS, "updateMacroInstances for "
3477 << d->filename.onlyFileName());
3478 DocIterator it = doc_iterator_begin(this);
3480 DocIterator const end = doc_iterator_end(this);
3481 for (; it != end; it.forwardInset()) {
3482 // look for MathData cells in InsetMathNest insets
3483 InsetMath * minset = it.nextInset()->asInsetMath();
3487 // update macro in all cells of the InsetMathNest
3488 DocIterator::idx_type n = minset->nargs();
3489 MacroContext mc = MacroContext(this, it);
3490 for (DocIterator::idx_type i = 0; i < n; ++i) {
3491 MathData & data = minset->cell(i);
3492 data.updateMacros(0, mc, utype);
3498 void Buffer::listMacroNames(MacroNameSet & macros) const
3503 d->macro_lock = true;
3505 // loop over macro names
3506 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3507 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3508 for (; nameIt != nameEnd; ++nameIt)
3509 macros.insert(nameIt->first);
3511 // loop over children
3512 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3513 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3514 for (; it != end; ++it)
3515 it->first->listMacroNames(macros);
3518 Buffer const * const pbuf = d->parent();
3520 pbuf->listMacroNames(macros);
3522 d->macro_lock = false;
3526 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3528 Buffer const * const pbuf = d->parent();
3533 pbuf->listMacroNames(names);
3536 MacroNameSet::iterator it = names.begin();
3537 MacroNameSet::iterator end = names.end();
3538 for (; it != end; ++it) {
3540 MacroData const * data =
3541 pbuf->getMacro(*it, *this, false);
3543 macros.insert(data);
3545 // we cannot access the original MathMacroTemplate anymore
3546 // here to calls validate method. So we do its work here manually.
3547 // FIXME: somehow make the template accessible here.
3548 if (data->optionals() > 0)
3549 features.require("xargs");
3555 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3558 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3560 RefCache::iterator it = d->ref_cache_.find(label);
3561 if (it != d->ref_cache_.end())
3562 return it->second.second;
3564 static InsetLabel const * dummy_il = 0;
3565 static References const dummy_refs = References();
3566 it = d->ref_cache_.insert(
3567 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3568 return it->second.second;
3572 Buffer::References const & Buffer::references(docstring const & label) const
3574 return const_cast<Buffer *>(this)->getReferenceCache(label);
3578 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3580 References & refs = getReferenceCache(label);
3581 refs.push_back(make_pair(inset, it));
3585 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3587 masterBuffer()->d->ref_cache_[label].first = il;
3591 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3593 return masterBuffer()->d->ref_cache_[label].first;
3597 void Buffer::clearReferenceCache() const
3600 d->ref_cache_.clear();
3604 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3606 //FIXME: This does not work for child documents yet.
3607 reloadBibInfoCache();
3609 // Check if the label 'from' appears more than once
3610 BiblioInfo const & keys = masterBibInfo();
3611 BiblioInfo::const_iterator bit = keys.begin();
3612 BiblioInfo::const_iterator bend = keys.end();
3613 vector<docstring> labels;
3615 for (; bit != bend; ++bit)
3617 labels.push_back(bit->first);
3619 if (count(labels.begin(), labels.end(), from) > 1)
3622 string const paramName = "key";
3623 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3624 if (it->lyxCode() != CITE_CODE)
3626 InsetCommand * inset = it->asInsetCommand();
3627 docstring const oldValue = inset->getParam(paramName);
3628 if (oldValue == from)
3629 inset->setParam(paramName, to);
3633 // returns NULL if id-to-row conversion is unsupported
3634 auto_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3635 pit_type par_begin, pit_type par_end,
3636 OutputWhat output, bool master) const
3638 auto_ptr<TexRow> texrow(NULL);
3639 OutputParams runparams(¶ms().encoding());
3640 runparams.nice = true;
3641 runparams.flavor = params().getOutputFlavor(format);
3642 runparams.linelen = lyxrc.plaintext_linelen;
3643 // No side effect of file copying and image conversion
3644 runparams.dryrun = true;
3646 if (output == CurrentParagraph) {
3647 runparams.par_begin = par_begin;
3648 runparams.par_end = par_end;
3649 if (par_begin + 1 == par_end) {
3651 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3655 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3656 convert<docstring>(par_begin),
3657 convert<docstring>(par_end - 1))
3660 // output paragraphs
3661 if (runparams.flavor == OutputParams::LYX) {
3662 Paragraph const & par = text().paragraphs()[par_begin];
3664 depth_type dt = par.getDepth();
3665 par.write(ods, params(), dt);
3666 os << from_utf8(ods.str());
3667 } else if (runparams.flavor == OutputParams::HTML) {
3669 setMathFlavor(runparams);
3670 xhtmlParagraphs(text(), *this, xs, runparams);
3671 } else if (runparams.flavor == OutputParams::TEXT) {
3673 // FIXME Handles only one paragraph, unlike the others.
3674 // Probably should have some routine with a signature like them.
3675 writePlaintextParagraph(*this,
3676 text().paragraphs()[par_begin], os, runparams, dummy);
3677 } else if (params().isDocBook()) {
3678 docbookParagraphs(text(), *this, os, runparams);
3680 // If we are previewing a paragraph, even if this is the
3681 // child of some other buffer, let's cut the link here,
3682 // so that no concurring settings from the master
3683 // (e.g. branch state) interfere (see #8101).
3685 d->ignore_parent = true;
3686 // We need to validate the Buffer params' features here
3687 // in order to know if we should output polyglossia
3688 // macros (instead of babel macros)
3689 LaTeXFeatures features(*this, params(), runparams);
3690 params().validate(features);
3691 runparams.use_polyglossia = features.usePolyglossia();
3692 texrow.reset(new TexRow());
3695 // latex or literate
3696 otexstream ots(os, *texrow);
3699 latexParagraphs(*this, text(), ots, runparams);
3702 // Restore the parenthood
3704 d->ignore_parent = false;
3708 if (output == FullSource)
3709 os << _("Preview source code");
3710 else if (output == OnlyPreamble)
3711 os << _("Preview preamble");
3712 else if (output == OnlyBody)
3713 os << _("Preview body");
3715 if (runparams.flavor == OutputParams::LYX) {
3717 if (output == FullSource)
3719 else if (output == OnlyPreamble)
3720 params().writeFile(ods, this);
3721 else if (output == OnlyBody)
3723 os << from_utf8(ods.str());
3724 } else if (runparams.flavor == OutputParams::HTML) {
3725 writeLyXHTMLSource(os, runparams, output);
3726 } else if (runparams.flavor == OutputParams::TEXT) {
3727 if (output == OnlyPreamble) {
3728 os << "% "<< _("Plain text does not have a preamble.");
3730 writePlaintextFile(*this, os, runparams);
3731 } else if (params().isDocBook()) {
3732 writeDocBookSource(os, absFileName(), runparams, output);
3734 // latex or literate
3735 texrow.reset(new TexRow());
3738 otexstream ots(os, *texrow);
3740 runparams.is_child = true;
3741 writeLaTeXSource(ots, string(), runparams, output);
3749 ErrorList & Buffer::errorList(string const & type) const
3751 return d->errorLists[type];
3755 void Buffer::updateTocItem(std::string const & type,
3756 DocIterator const & dit) const
3759 d->gui_->updateTocItem(type, dit);
3763 void Buffer::structureChanged() const
3766 d->gui_->structureChanged();
3770 void Buffer::errors(string const & err, bool from_master) const
3773 d->gui_->errors(err, from_master);
3777 void Buffer::message(docstring const & msg) const
3780 d->gui_->message(msg);
3784 void Buffer::setBusy(bool on) const
3787 d->gui_->setBusy(on);
3791 void Buffer::updateTitles() const
3794 d->wa_->updateTitles();
3798 void Buffer::resetAutosaveTimers() const
3801 d->gui_->resetAutosaveTimers();
3805 bool Buffer::hasGuiDelegate() const
3811 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3820 class AutoSaveBuffer : public ForkedProcess {
3823 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3824 : buffer_(buffer), fname_(fname) {}
3826 virtual shared_ptr<ForkedProcess> clone() const
3828 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3833 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3834 from_utf8(fname_.absFileName())));
3835 return run(DontWait);
3839 virtual int generateChild();
3841 Buffer const & buffer_;
3846 int AutoSaveBuffer::generateChild()
3848 #if defined(__APPLE__)
3849 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3850 * We should use something else like threads.
3852 * Since I do not know how to determine at run time what is the OS X
3853 * version, I just disable forking altogether for now (JMarc)
3855 pid_t const pid = -1;
3857 // tmp_ret will be located (usually) in /tmp
3858 // will that be a problem?
3859 // Note that this calls ForkedCalls::fork(), so it's
3860 // ok cross-platform.
3861 pid_t const pid = fork();
3862 // If you want to debug the autosave
3863 // you should set pid to -1, and comment out the fork.
3864 if (pid != 0 && pid != -1)
3868 // pid = -1 signifies that lyx was unable
3869 // to fork. But we will do the save
3871 bool failed = false;
3872 TempFile tempfile("lyxautoXXXXXX.lyx");
3873 tempfile.setAutoRemove(false);
3874 FileName const tmp_ret = tempfile.name();
3875 if (!tmp_ret.empty()) {
3876 if (!buffer_.writeFile(tmp_ret))
3878 else if (!tmp_ret.moveTo(fname_))
3884 // failed to write/rename tmp_ret so try writing direct
3885 if (!buffer_.writeFile(fname_)) {
3886 // It is dangerous to do this in the child,
3887 // but safe in the parent, so...
3888 if (pid == -1) // emit message signal.
3889 buffer_.message(_("Autosave failed!"));
3893 if (pid == 0) // we are the child so...
3902 FileName Buffer::getEmergencyFileName() const
3904 return FileName(d->filename.absFileName() + ".emergency");
3908 FileName Buffer::getAutosaveFileName() const
3910 // if the document is unnamed try to save in the backup dir, else
3911 // in the default document path, and as a last try in the filePath,
3912 // which will most often be the temporary directory
3915 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3916 : lyxrc.backupdir_path;
3917 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3920 string const fname = "#" + d->filename.onlyFileName() + "#";
3922 return makeAbsPath(fname, fpath);
3926 void Buffer::removeAutosaveFile() const
3928 FileName const f = getAutosaveFileName();
3934 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3936 FileName const newauto = getAutosaveFileName();
3938 if (newauto != oldauto && oldauto.exists())
3939 if (!oldauto.moveTo(newauto))
3940 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3944 bool Buffer::autoSave() const
3946 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3947 if (buf->d->bak_clean || isReadonly())
3950 message(_("Autosaving current document..."));
3951 buf->d->bak_clean = true;
3953 FileName const fname = getAutosaveFileName();
3954 LASSERT(d->cloned_buffer_, return false);
3956 // If this buffer is cloned, we assume that
3957 // we are running in a separate thread already.
3958 TempFile tempfile("lyxautoXXXXXX.lyx");
3959 tempfile.setAutoRemove(false);
3960 FileName const tmp_ret = tempfile.name();
3961 if (!tmp_ret.empty()) {
3963 // assume successful write of tmp_ret
3964 if (tmp_ret.moveTo(fname))
3967 // failed to write/rename tmp_ret so try writing direct
3968 return writeFile(fname);
3972 void Buffer::setExportStatus(bool e) const
3974 d->doing_export = e;
3975 ListOfBuffers clist = getDescendents();
3976 ListOfBuffers::const_iterator cit = clist.begin();
3977 ListOfBuffers::const_iterator const cen = clist.end();
3978 for (; cit != cen; ++cit)
3979 (*cit)->d->doing_export = e;
3983 bool Buffer::isExporting() const
3985 return d->doing_export;
3989 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3993 return doExport(target, put_in_tempdir, result_file);
3996 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3997 string & result_file) const
3999 bool const update_unincluded =
4000 params().maintain_unincluded_children
4001 && !params().getIncludedChildren().empty();
4003 // (1) export with all included children (omit \includeonly)
4004 if (update_unincluded) {
4005 ExportStatus const status =
4006 doExport(target, put_in_tempdir, true, result_file);
4007 if (status != ExportSuccess)
4010 // (2) export with included children only
4011 return doExport(target, put_in_tempdir, false, result_file);
4015 void Buffer::setMathFlavor(OutputParams & op) const
4017 switch (params().html_math_output) {
4018 case BufferParams::MathML:
4019 op.math_flavor = OutputParams::MathAsMathML;
4021 case BufferParams::HTML:
4022 op.math_flavor = OutputParams::MathAsHTML;
4024 case BufferParams::Images:
4025 op.math_flavor = OutputParams::MathAsImages;
4027 case BufferParams::LaTeX:
4028 op.math_flavor = OutputParams::MathAsLaTeX;
4034 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4035 bool includeall, string & result_file) const
4037 LYXERR(Debug::FILES, "target=" << target);
4038 OutputParams runparams(¶ms().encoding());
4039 string format = target;
4040 string dest_filename;
4041 size_t pos = target.find(' ');
4042 if (pos != string::npos) {
4043 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4044 format = target.substr(0, pos);
4045 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4046 FileName(dest_filename).onlyPath().createPath();
4047 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4049 MarkAsExporting exporting(this);
4050 string backend_format;
4051 runparams.flavor = OutputParams::LATEX;
4052 runparams.linelen = lyxrc.plaintext_linelen;
4053 runparams.includeall = includeall;
4054 vector<string> backs = params().backends();
4055 Converters converters = theConverters();
4056 bool need_nice_file = false;
4057 if (find(backs.begin(), backs.end(), format) == backs.end()) {
4058 // Get shortest path to format
4059 converters.buildGraph();
4060 Graph::EdgePath path;
4061 for (vector<string>::const_iterator it = backs.begin();
4062 it != backs.end(); ++it) {
4063 Graph::EdgePath p = converters.getPath(*it, format);
4064 if (!p.empty() && (path.empty() || p.size() < path.size())) {
4065 backend_format = *it;
4070 if (!put_in_tempdir) {
4071 // Only show this alert if this is an export to a non-temporary
4072 // file (not for previewing).
4073 Alert::error(_("Couldn't export file"), bformat(
4074 _("No information for exporting the format %1$s."),
4075 formats.prettyName(format)));
4077 return ExportNoPathToFormat;
4079 runparams.flavor = converters.getFlavor(path, this);
4080 Graph::EdgePath::const_iterator it = path.begin();
4081 Graph::EdgePath::const_iterator en = path.end();
4082 for (; it != en; ++it)
4083 if (theConverters().get(*it).nice()) {
4084 need_nice_file = true;
4089 backend_format = format;
4090 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4091 // FIXME: Don't hardcode format names here, but use a flag
4092 if (backend_format == "pdflatex")
4093 runparams.flavor = OutputParams::PDFLATEX;
4094 else if (backend_format == "luatex")
4095 runparams.flavor = OutputParams::LUATEX;
4096 else if (backend_format == "dviluatex")
4097 runparams.flavor = OutputParams::DVILUATEX;
4098 else if (backend_format == "xetex")
4099 runparams.flavor = OutputParams::XETEX;
4102 string filename = latexName(false);
4103 filename = addName(temppath(), filename);
4104 filename = changeExtension(filename,
4105 formats.extension(backend_format));
4106 LYXERR(Debug::FILES, "filename=" << filename);
4108 // Plain text backend
4109 if (backend_format == "text") {
4110 runparams.flavor = OutputParams::TEXT;
4111 writePlaintextFile(*this, FileName(filename), runparams);
4114 else if (backend_format == "xhtml") {
4115 runparams.flavor = OutputParams::HTML;
4116 setMathFlavor(runparams);
4117 makeLyXHTMLFile(FileName(filename), runparams);
4118 } else if (backend_format == "lyx")
4119 writeFile(FileName(filename));
4121 else if (params().isDocBook()) {
4122 runparams.nice = !put_in_tempdir;
4123 makeDocBookFile(FileName(filename), runparams);
4126 else if (backend_format == format || need_nice_file) {
4127 runparams.nice = true;
4128 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4129 if (d->cloned_buffer_)
4130 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4133 } else if (!lyxrc.tex_allows_spaces
4134 && contains(filePath(), ' ')) {
4135 Alert::error(_("File name error"),
4136 _("The directory path to the document cannot contain spaces."));
4137 return ExportTexPathHasSpaces;
4139 runparams.nice = false;
4140 bool const success = makeLaTeXFile(
4141 FileName(filename), filePath(), runparams);
4142 if (d->cloned_buffer_)
4143 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4148 string const error_type = (format == "program")
4149 ? "Build" : params().bufferFormat();
4150 ErrorList & error_list = d->errorLists[error_type];
4151 string const ext = formats.extension(format);
4152 FileName const tmp_result_file(changeExtension(filename, ext));
4153 bool const success = converters.convert(this, FileName(filename),
4154 tmp_result_file, FileName(absFileName()), backend_format, format,
4157 // Emit the signal to show the error list or copy it back to the
4158 // cloned Buffer so that it can be emitted afterwards.
4159 if (format != backend_format) {
4160 if (runparams.silent)
4162 else if (d->cloned_buffer_)
4163 d->cloned_buffer_->d->errorLists[error_type] =
4164 d->errorLists[error_type];
4167 // also to the children, in case of master-buffer-view
4168 ListOfBuffers clist = getDescendents();
4169 ListOfBuffers::const_iterator cit = clist.begin();
4170 ListOfBuffers::const_iterator const cen = clist.end();
4171 for (; cit != cen; ++cit) {
4172 if (runparams.silent)
4173 (*cit)->d->errorLists[error_type].clear();
4174 else if (d->cloned_buffer_) {
4175 // Enable reverse search by copying back the
4176 // texrow object to the cloned buffer.
4177 // FIXME: this is not thread safe.
4178 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4179 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4180 (*cit)->d->errorLists[error_type];
4182 (*cit)->errors(error_type, true);
4186 if (d->cloned_buffer_) {
4187 // Enable reverse dvi or pdf to work by copying back the texrow
4188 // object to the cloned buffer.
4189 // FIXME: There is a possibility of concurrent access to texrow
4190 // here from the main GUI thread that should be securized.
4191 d->cloned_buffer_->d->texrow = d->texrow;
4192 string const error_type = params().bufferFormat();
4193 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4197 if (put_in_tempdir) {
4198 result_file = tmp_result_file.absFileName();
4199 return success ? ExportSuccess : ExportConverterError;
4202 if (dest_filename.empty())
4203 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4205 result_file = dest_filename;
4206 // We need to copy referenced files (e. g. included graphics
4207 // if format == "dvi") to the result dir.
4208 vector<ExportedFile> const files =
4209 runparams.exportdata->externalFiles(format);
4210 string const dest = runparams.export_folder.empty() ?
4211 onlyPath(result_file) : runparams.export_folder;
4212 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4213 : force_overwrite == ALL_FILES;
4214 CopyStatus status = use_force ? FORCE : SUCCESS;
4216 vector<ExportedFile>::const_iterator it = files.begin();
4217 vector<ExportedFile>::const_iterator const en = files.end();
4218 for (; it != en && status != CANCEL; ++it) {
4219 string const fmt = formats.getFormatFromFile(it->sourceName);
4220 string fixedName = it->exportName;
4221 if (!runparams.export_folder.empty()) {
4222 // Relative pathnames starting with ../ will be sanitized
4223 // if exporting to a different folder
4224 while (fixedName.substr(0, 3) == "../")
4225 fixedName = fixedName.substr(3, fixedName.length() - 3);
4227 FileName fixedFileName = makeAbsPath(fixedName, dest);
4228 fixedFileName.onlyPath().createPath();
4229 status = copyFile(fmt, it->sourceName,
4231 it->exportName, status == FORCE,
4232 runparams.export_folder.empty());
4235 if (status == CANCEL) {
4236 message(_("Document export cancelled."));
4237 return ExportCancel;
4240 if (tmp_result_file.exists()) {
4241 // Finally copy the main file
4242 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4243 : force_overwrite != NO_FILES;
4244 if (status == SUCCESS && use_force)
4246 status = copyFile(format, tmp_result_file,
4247 FileName(result_file), result_file,
4249 if (status == CANCEL) {
4250 message(_("Document export cancelled."));
4251 return ExportCancel;
4253 message(bformat(_("Document exported as %1$s "
4255 formats.prettyName(format),
4256 makeDisplayPath(result_file)));
4259 // This must be a dummy converter like fax (bug 1888)
4260 message(bformat(_("Document exported as %1$s"),
4261 formats.prettyName(format)));
4264 return success ? ExportSuccess : ExportConverterError;
4268 Buffer::ExportStatus Buffer::preview(string const & format) const
4270 bool const update_unincluded =
4271 params().maintain_unincluded_children
4272 && !params().getIncludedChildren().empty();
4273 return preview(format, update_unincluded);
4277 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4279 MarkAsExporting exporting(this);
4281 // (1) export with all included children (omit \includeonly)
4283 ExportStatus const status = doExport(format, true, true, result_file);
4284 if (status != ExportSuccess)
4287 // (2) export with included children only
4288 ExportStatus const status = doExport(format, true, false, result_file);
4289 FileName const previewFile(result_file);
4291 LATTEST (isClone());
4292 d->cloned_buffer_->d->preview_file_ = previewFile;
4293 d->cloned_buffer_->d->preview_format_ = format;
4294 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4296 if (status != ExportSuccess)
4298 if (previewFile.exists()) {
4299 if (!formats.view(*this, previewFile, format))
4300 return PreviewError;
4302 return PreviewSuccess;
4305 // Successful export but no output file?
4306 // Probably a bug in error detection.
4307 LATTEST (status != ExportSuccess);
4314 Buffer::ReadStatus Buffer::extractFromVC()
4316 bool const found = LyXVC::file_not_found_hook(d->filename);
4318 return ReadFileNotFound;
4319 if (!d->filename.isReadableFile())
4325 Buffer::ReadStatus Buffer::loadEmergency()
4327 FileName const emergencyFile = getEmergencyFileName();
4328 if (!emergencyFile.exists()
4329 || emergencyFile.lastModified() <= d->filename.lastModified())
4330 return ReadFileNotFound;
4332 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4333 docstring const text = bformat(_("An emergency save of the document "
4334 "%1$s exists.\n\nRecover emergency save?"), file);
4336 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4337 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4343 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4344 bool const success = (ret_llf == ReadSuccess);
4347 Alert::warning(_("File is read-only"),
4348 bformat(_("An emergency file is successfully loaded, "
4349 "but the original file %1$s is marked read-only. "
4350 "Please make sure to save the document as a different "
4351 "file."), from_utf8(d->filename.absFileName())));
4354 lyxvc().file_found_hook(d->filename);
4355 str = _("Document was successfully recovered.");
4357 str = _("Document was NOT successfully recovered.");
4358 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4359 makeDisplayPath(emergencyFile.absFileName()));
4361 int const del_emerg =
4362 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4363 _("&Remove"), _("&Keep"));
4364 if (del_emerg == 0) {
4365 emergencyFile.removeFile();
4367 Alert::warning(_("Emergency file deleted"),
4368 _("Do not forget to save your file now!"), true);
4370 return success ? ReadSuccess : ReadEmergencyFailure;
4373 int const del_emerg =
4374 Alert::prompt(_("Delete emergency file?"),
4375 _("Remove emergency file now?"), 1, 1,
4376 _("&Remove"), _("&Keep"));
4378 emergencyFile.removeFile();
4379 return ReadOriginal;
4389 Buffer::ReadStatus Buffer::loadAutosave()
4391 // Now check if autosave file is newer.
4392 FileName const autosaveFile = getAutosaveFileName();
4393 if (!autosaveFile.exists()
4394 || autosaveFile.lastModified() <= d->filename.lastModified())
4395 return ReadFileNotFound;
4397 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4398 docstring const text = bformat(_("The backup of the document %1$s "
4399 "is newer.\n\nLoad the backup instead?"), file);
4400 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4401 _("&Load backup"), _("Load &original"), _("&Cancel"));
4406 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4407 // the file is not saved if we load the autosave file.
4408 if (ret_llf == ReadSuccess) {
4410 Alert::warning(_("File is read-only"),
4411 bformat(_("A backup file is successfully loaded, "
4412 "but the original file %1$s is marked read-only. "
4413 "Please make sure to save the document as a "
4415 from_utf8(d->filename.absFileName())));
4418 lyxvc().file_found_hook(d->filename);
4421 return ReadAutosaveFailure;
4424 // Here we delete the autosave
4425 autosaveFile.removeFile();
4426 return ReadOriginal;
4434 Buffer::ReadStatus Buffer::loadLyXFile()
4436 if (!d->filename.isReadableFile()) {
4437 ReadStatus const ret_rvc = extractFromVC();
4438 if (ret_rvc != ReadSuccess)
4442 ReadStatus const ret_re = loadEmergency();
4443 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4446 ReadStatus const ret_ra = loadAutosave();
4447 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4450 return loadThisLyXFile(d->filename);
4454 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4456 return readFile(fn);
4460 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4462 TeXErrors::Errors::const_iterator it = terr.begin();
4463 TeXErrors::Errors::const_iterator end = terr.end();
4464 ListOfBuffers clist = getDescendents();
4465 ListOfBuffers::const_iterator cen = clist.end();
4467 for (; it != end; ++it) {
4470 int errorRow = it->error_in_line;
4471 Buffer const * buf = 0;
4473 if (it->child_name.empty())
4474 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4476 // The error occurred in a child
4477 ListOfBuffers::const_iterator cit = clist.begin();
4478 for (; cit != cen; ++cit) {
4479 string const child_name =
4480 DocFileName(changeExtension(
4481 (*cit)->absFileName(), "tex")).
4483 if (it->child_name != child_name)
4485 (*cit)->d->texrow.getIdFromRow(errorRow,
4486 id_start, pos_start);
4487 if (id_start != -1) {
4488 buf = d->cloned_buffer_
4489 ? (*cit)->d->cloned_buffer_->d->owner_
4490 : (*cit)->d->owner_;
4501 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4502 } while (found && id_start == id_end && pos_start == pos_end);
4504 if (id_start != id_end) {
4505 // Next registered position is outside the inset where
4506 // the error occurred, so signal end-of-paragraph
4510 errorList.push_back(ErrorItem(it->error_desc,
4511 it->error_text, id_start, pos_start, pos_end, buf));
4516 void Buffer::setBuffersForInsets() const
4518 inset().setBuffer(const_cast<Buffer &>(*this));
4522 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4524 LBUFERR(!text().paragraphs().empty());
4526 // Use the master text class also for child documents
4527 Buffer const * const master = masterBuffer();
4528 DocumentClass const & textclass = master->params().documentClass();
4530 // do this only if we are the top-level Buffer
4531 if (master == this) {
4532 textclass.counters().reset(from_ascii("bibitem"));
4533 reloadBibInfoCache();
4536 // keep the buffers to be children in this set. If the call from the
4537 // master comes back we can see which of them were actually seen (i.e.
4538 // via an InsetInclude). The remaining ones in the set need still be updated.
4539 static std::set<Buffer const *> bufToUpdate;
4540 if (scope == UpdateMaster) {
4541 // If this is a child document start with the master
4542 if (master != this) {
4543 bufToUpdate.insert(this);
4544 master->updateBuffer(UpdateMaster, utype);
4545 // If the master buffer has no gui associated with it, then the TocModel is
4546 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4547 // (bug 5699). The same happens if the master buffer is open in a different
4548 // window. This test catches both possibilities.
4549 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4550 // There remains a problem here: If there is another child open in yet a third
4551 // window, that TOC is not updated. So some more general solution is needed at
4553 if (master->d->gui_ != d->gui_)
4556 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4557 if (bufToUpdate.find(this) == bufToUpdate.end())
4561 // start over the counters in the master
4562 textclass.counters().reset();
4565 // update will be done below for this buffer
4566 bufToUpdate.erase(this);
4568 // update all caches
4569 clearReferenceCache();
4572 Buffer & cbuf = const_cast<Buffer &>(*this);
4575 ParIterator parit = cbuf.par_iterator_begin();
4576 updateBuffer(parit, utype);
4579 // TocBackend update will be done later.
4582 d->bibinfo_cache_valid_ = true;
4583 d->cite_labels_valid_ = true;
4585 cbuf.tocBackend().update(true, utype);
4586 if (scope == UpdateMaster)
4587 cbuf.structureChanged();
4591 static depth_type getDepth(DocIterator const & it)
4593 depth_type depth = 0;
4594 for (size_t i = 0 ; i < it.depth() ; ++i)
4595 if (!it[i].inset().inMathed())
4596 depth += it[i].paragraph().getDepth() + 1;
4597 // remove 1 since the outer inset does not count
4601 static depth_type getItemDepth(ParIterator const & it)
4603 Paragraph const & par = *it;
4604 LabelType const labeltype = par.layout().labeltype;
4606 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4609 // this will hold the lowest depth encountered up to now.
4610 depth_type min_depth = getDepth(it);
4611 ParIterator prev_it = it;
4614 --prev_it.top().pit();
4616 // start of nested inset: go to outer par
4618 if (prev_it.empty()) {
4619 // start of document: nothing to do
4624 // We search for the first paragraph with same label
4625 // that is not more deeply nested.
4626 Paragraph & prev_par = *prev_it;
4627 depth_type const prev_depth = getDepth(prev_it);
4628 if (labeltype == prev_par.layout().labeltype) {
4629 if (prev_depth < min_depth)
4630 return prev_par.itemdepth + 1;
4631 if (prev_depth == min_depth)
4632 return prev_par.itemdepth;
4634 min_depth = min(min_depth, prev_depth);
4635 // small optimization: if we are at depth 0, we won't
4636 // find anything else
4637 if (prev_depth == 0)
4643 static bool needEnumCounterReset(ParIterator const & it)
4645 Paragraph const & par = *it;
4646 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4647 depth_type const cur_depth = par.getDepth();
4648 ParIterator prev_it = it;
4649 while (prev_it.pit()) {
4650 --prev_it.top().pit();
4651 Paragraph const & prev_par = *prev_it;
4652 if (prev_par.getDepth() <= cur_depth)
4653 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4655 // start of nested inset: reset
4660 // set the label of a paragraph. This includes the counters.
4661 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4663 BufferParams const & bp = owner_->masterBuffer()->params();
4664 DocumentClass const & textclass = bp.documentClass();
4665 Paragraph & par = it.paragraph();
4666 Layout const & layout = par.layout();
4667 Counters & counters = textclass.counters();
4669 if (par.params().startOfAppendix()) {
4670 // We want to reset the counter corresponding to toplevel sectioning
4671 Layout const & lay = textclass.getTOCLayout();
4672 docstring const cnt = lay.counter;
4674 counters.reset(cnt);
4675 counters.appendix(true);
4677 par.params().appendix(counters.appendix());
4679 // Compute the item depth of the paragraph
4680 par.itemdepth = getItemDepth(it);
4682 if (layout.margintype == MARGIN_MANUAL) {
4683 if (par.params().labelWidthString().empty())
4684 par.params().labelWidthString(par.expandLabel(layout, bp));
4685 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4686 // we do not need to do anything here, since the empty case is
4687 // handled during export.
4689 par.params().labelWidthString(docstring());
4692 switch(layout.labeltype) {
4693 case LABEL_ITEMIZE: {
4694 // At some point of time we should do something more
4695 // clever here, like:
4696 // par.params().labelString(
4697 // bp.user_defined_bullet(par.itemdepth).getText());
4698 // for now, use a simple hardcoded label
4699 docstring itemlabel;
4700 switch (par.itemdepth) {
4702 itemlabel = char_type(0x2022);
4705 itemlabel = char_type(0x2013);
4708 itemlabel = char_type(0x2217);
4711 itemlabel = char_type(0x2219); // or 0x00b7
4714 par.params().labelString(itemlabel);
4718 case LABEL_ENUMERATE: {
4719 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4721 switch (par.itemdepth) {
4730 enumcounter += "iv";
4733 // not a valid enumdepth...
4737 // Maybe we have to reset the enumeration counter.
4738 if (needEnumCounterReset(it))
4739 counters.reset(enumcounter);
4740 counters.step(enumcounter, utype);
4742 string const & lang = par.getParLanguage(bp)->code();
4743 par.params().labelString(counters.theCounter(enumcounter, lang));
4748 case LABEL_SENSITIVE: {
4749 string const & type = counters.current_float();
4750 docstring full_label;
4752 full_label = owner_->B_("Senseless!!! ");
4754 docstring name = owner_->B_(textclass.floats().getType(type).name());
4755 if (counters.hasCounter(from_utf8(type))) {
4756 string const & lang = par.getParLanguage(bp)->code();
4757 counters.step(from_utf8(type), utype);
4758 full_label = bformat(from_ascii("%1$s %2$s:"),
4760 counters.theCounter(from_utf8(type), lang));
4762 full_label = bformat(from_ascii("%1$s #:"), name);
4764 par.params().labelString(full_label);
4768 case LABEL_NO_LABEL:
4769 par.params().labelString(docstring());
4773 case LABEL_CENTERED:
4774 case LABEL_STATIC: {
4775 docstring const & lcounter = layout.counter;
4776 if (!lcounter.empty()) {
4777 if (layout.toclevel <= bp.secnumdepth
4778 && (layout.latextype != LATEX_ENVIRONMENT
4779 || it.text()->isFirstInSequence(it.pit()))) {
4780 if (counters.hasCounter(lcounter))
4781 counters.step(lcounter, utype);
4782 par.params().labelString(par.expandLabel(layout, bp));
4784 par.params().labelString(docstring());
4786 par.params().labelString(par.expandLabel(layout, bp));
4792 par.params().labelString(par.expandLabel(layout, bp));
4797 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4799 // LASSERT: Is it safe to continue here, or should we just return?
4800 LASSERT(parit.pit() == 0, /**/);
4802 // Set the position of the text in the buffer to be able
4803 // to resolve macros in it.
4804 parit.text()->setMacrocontextPosition(parit);
4806 depth_type maxdepth = 0;
4807 pit_type const lastpit = parit.lastpit();
4808 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4809 // reduce depth if necessary
4810 if (parit->params().depth() > maxdepth) {
4811 /** FIXME: this function is const, but
4812 * nevertheless it modifies the buffer. To be
4813 * cleaner, one should modify the buffer in
4814 * another function, which is actually
4815 * non-const. This would however be costly in
4816 * terms of code duplication.
4818 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4819 parit->params().depth(maxdepth);
4821 maxdepth = parit->getMaxDepthAfter();
4823 if (utype == OutputUpdate) {
4824 // track the active counters
4825 // we have to do this for the master buffer, since the local
4826 // buffer isn't tracking anything.
4827 masterBuffer()->params().documentClass().counters().
4828 setActiveLayout(parit->layout());
4831 // set the counter for this paragraph
4832 d->setLabel(parit, utype);
4835 InsetList::const_iterator iit = parit->insetList().begin();
4836 InsetList::const_iterator end = parit->insetList().end();
4837 for (; iit != end; ++iit) {
4838 parit.pos() = iit->pos;
4839 iit->inset->updateBuffer(parit, utype);
4845 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4846 WordLangTuple & word_lang, docstring_list & suggestions) const
4850 suggestions.clear();
4851 word_lang = WordLangTuple();
4852 bool const to_end = to.empty();
4853 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4854 // OK, we start from here.
4855 for (; from != end; from.forwardPos()) {
4856 // This skips all insets with spell check disabled.
4857 while (!from.allowSpellCheck()) {
4861 // If from is at the end of the document (which is possible
4862 // when "from" was changed above) LyX will crash later otherwise.
4863 if (from.atEnd() || (!to_end && from >= end))
4866 from.paragraph().spellCheck();
4867 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4868 if (SpellChecker::misspelled(res)) {
4872 // Do not increase progress when from == to, otherwise the word
4873 // count will be wrong.
4883 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4885 bool inword = false;
4890 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4891 if (!dit.inTexted()) {
4896 Paragraph const & par = dit.paragraph();
4897 pos_type const pos = dit.pos();
4899 // Copied and adapted from isWordSeparator() in Paragraph
4900 if (pos == dit.lastpos()) {
4903 Inset const * ins = par.getInset(pos);
4904 if (ins && skipNoOutput && !ins->producesOutput()) {
4907 // stop if end of range was skipped
4908 if (!to.atEnd() && dit >= to)
4911 } else if (!par.isDeleted(pos)) {
4912 if (par.isWordSeparator(pos))
4918 if (ins && ins->isLetter())
4920 else if (ins && ins->isSpace())
4923 char_type const c = par.getChar(pos);
4924 if (isPrintableNonspace(c))
4926 else if (isSpace(c))
4936 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4938 d->updateStatistics(from, to, skipNoOutput);
4942 int Buffer::wordCount() const
4944 return d->wordCount();
4948 int Buffer::charCount(bool with_blanks) const
4950 return d->charCount(with_blanks);
4954 Buffer::ReadStatus Buffer::reload()
4957 // c.f. bug http://www.lyx.org/trac/ticket/6587
4958 removeAutosaveFile();
4959 // e.g., read-only status could have changed due to version control
4960 d->filename.refresh();
4961 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4963 // clear parent. this will get reset if need be.
4965 ReadStatus const status = loadLyXFile();
4966 if (status == ReadSuccess) {
4971 message(bformat(_("Document %1$s reloaded."), disp_fn));
4974 message(bformat(_("Could not reload document %1$s."), disp_fn));
4984 bool Buffer::saveAs(FileName const & fn)
4986 FileName const old_name = fileName();
4987 FileName const old_auto = getAutosaveFileName();
4988 bool const old_unnamed = isUnnamed();
4989 bool success = true;
4990 d->old_position = filePath();
4997 // bring the autosave file with us, just in case.
4998 moveAutosaveFile(old_auto);
4999 // validate version control data and
5000 // correct buffer title
5001 lyxvc().file_found_hook(fileName());
5003 // the file has now been saved to the new location.
5004 // we need to check that the locations of child buffers
5006 checkChildBuffers();
5007 checkMasterBuffer();
5010 // reset the old filename and unnamed state
5011 setFileName(old_name);
5012 setUnnamed(old_unnamed);
5016 d->old_position.clear();
5021 void Buffer::checkChildBuffers()
5023 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5024 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5025 for (; it != en; ++it) {
5026 DocIterator dit = it->second;
5027 Buffer * cbuf = const_cast<Buffer *>(it->first);
5028 if (!cbuf || !theBufferList().isLoaded(cbuf))
5030 Inset * inset = dit.nextInset();
5031 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5032 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5033 docstring const & incfile = inset_inc->getParam("filename");
5034 string oldloc = cbuf->absFileName();
5035 string newloc = makeAbsPath(to_utf8(incfile),
5036 onlyPath(absFileName())).absFileName();
5037 if (oldloc == newloc)
5039 // the location of the child file is incorrect.
5041 inset_inc->setChildBuffer(0);
5043 // invalidate cache of children
5044 d->children_positions.clear();
5045 d->position_to_children.clear();
5049 // If a child has been saved under a different name/path, it might have been
5050 // orphaned. Therefore the master needs to be reset (bug 8161).
5051 void Buffer::checkMasterBuffer()
5053 Buffer const * const master = masterBuffer();
5057 // necessary to re-register the child (bug 5873)
5058 // FIXME: clean up updateMacros (here, only
5059 // child registering is needed).
5060 master->updateMacros();
5061 // (re)set master as master buffer, but only
5062 // if we are a real child
5063 if (master->isChild(this))
5070 string Buffer::includedFilePath(string const & name, string const & ext) const
5072 bool isabsolute = FileName::isAbsolute(name);
5073 // old_position already contains a trailing path separator
5074 string const absname = isabsolute ? name : d->old_position + name;
5076 if (d->old_position.empty()
5077 || equivalent(FileName(d->old_position), FileName(filePath()))
5078 || !FileName(addExtension(absname, ext)).exists())
5082 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5084 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5085 from_utf8(filePath())));