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;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
224 ScopeMacro(DocIterator const & s, MacroData const & m)
225 : scope(s), macro(m) {}
229 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231 /// map from the macro name to the position map,
232 /// which maps the macro definition position to the scope and the MacroData.
233 NamePositionScopeMacroMap macros;
234 /// This seem to change the way Buffer::getMacro() works
235 mutable bool macro_lock;
237 /// positions of child buffers in the buffer
238 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer(DocIterator const & s,Buffer const * b)
242 : scope(s), buffer(b) {}
244 Buffer const * buffer;
246 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247 /// position of children buffers in this buffer
248 BufferPositionMap children_positions;
249 /// map from children inclusion positions to their scope and their buffer
250 PositionScopeBufferMap position_to_children;
252 /// Container for all sort of Buffer dependant errors.
253 map<string, ErrorList> errorLists;
255 /// timestamp and checksum used to test if the file has been externally
256 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
258 unsigned long checksum_;
261 frontend::WorkAreaManager * wa_;
263 frontend::GuiBufferDelegate * gui_;
268 /// A cache for the bibfiles (including bibfiles of loaded child
269 /// documents), needed for appropriate update of natbib labels.
270 mutable support::FileNameList bibfiles_cache_;
272 // FIXME The caching mechanism could be improved. At present, we have a
273 // cache for each Buffer, that caches all the bibliography info for that
274 // Buffer. A more efficient solution would be to have a global cache per
275 // file, and then to construct the Buffer's bibinfo from that.
276 /// A cache for bibliography info
277 mutable BiblioInfo bibinfo_;
278 /// whether the bibinfo cache is valid
279 mutable bool bibinfo_cache_valid_;
280 /// whether the bibfile cache is valid
281 mutable bool bibfile_cache_valid_;
282 /// Cache of timestamps of .bib files
283 map<FileName, time_t> bibfile_status_;
284 /// Indicates whether the bibinfo has changed since the last time
285 /// we ran updateBuffer(), i.e., whether citation labels may need
287 mutable bool cite_labels_valid_;
289 mutable RefCache ref_cache_;
291 /// our Text that should be wrapped in an InsetText
295 PreviewLoader * preview_loader_;
297 /// This is here to force the test to be done whenever parent_buffer
299 Buffer const * parent() const
301 // ignore_parent temporarily "orphans" a buffer
302 // (e.g. if a child is compiled standalone)
305 // if parent_buffer is not loaded, then it has been unloaded,
306 // which means that parent_buffer is an invalid pointer. So we
307 // set it to null in that case.
308 // however, the BufferList doesn't know about cloned buffers, so
309 // they will always be regarded as unloaded. in that case, we hope
311 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
313 return parent_buffer;
317 void setParent(Buffer const * pb)
319 if (parent_buffer == pb)
322 if (!cloned_buffer_ && parent_buffer && pb)
323 LYXERR0("Warning: a buffer should not have two parents!");
325 if (!cloned_buffer_ && parent_buffer) {
326 parent_buffer->invalidateBibfileCache();
327 parent_buffer->invalidateBibinfoCache();
331 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
332 /// This one is useful for preview detached in a thread.
333 Buffer const * cloned_buffer_;
335 CloneList * clone_list_;
336 /// are we in the process of exporting this buffer?
337 mutable bool doing_export;
339 /// compute statistics
340 /// \p from initial position
341 /// \p to points to the end position
342 void updateStatistics(DocIterator & from, DocIterator & to,
343 bool skipNoOutput = true);
344 /// statistics accessor functions
345 int wordCount() const
349 int charCount(bool with_blanks) const
352 + (with_blanks ? blank_count_ : 0);
356 /// So we can force access via the accessors.
357 mutable Buffer const * parent_buffer;
366 /// Creates the per buffer temporary directory
367 static FileName createBufferTmpDir()
369 // FIXME This would be the ideal application for a TempDir class (like
370 // TempFile but for directories)
375 Mutex::Locker locker(&mutex);
376 counter = convert<string>(count++);
378 // We are in our own directory. Why bother to mangle name?
379 // In fact I wrote this code to circumvent a problematic behaviour
380 // (bug?) of EMX mkstemp().
381 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
384 if (!tmpfl.createDirectory(0777)) {
385 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
386 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
387 from_utf8(tmpfl.absFileName())));
393 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
394 Buffer const * cloned_buffer)
395 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
396 internal_buffer(false), read_only(readonly_), filename(file),
397 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
398 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
399 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
400 cite_labels_valid_(false), inset(0), preview_loader_(0),
401 cloned_buffer_(cloned_buffer), clone_list_(0),
402 doing_export(false), parent_buffer(0),
403 word_count_(0), char_count_(0), blank_count_(0)
405 if (!cloned_buffer_) {
406 temppath = createBufferTmpDir();
407 lyxvc.setBuffer(owner_);
409 wa_ = new frontend::WorkAreaManager;
412 temppath = cloned_buffer_->d->temppath;
413 file_fully_loaded = true;
414 params = cloned_buffer_->d->params;
415 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
416 bibinfo_ = cloned_buffer_->d->bibinfo_;
417 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
418 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
419 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
420 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
421 unnamed = cloned_buffer_->d->unnamed;
422 internal_buffer = cloned_buffer_->d->internal_buffer;
426 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
427 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
429 LYXERR(Debug::INFO, "Buffer::Buffer()");
431 d->inset = new InsetText(*cloned_buffer->d->inset);
432 d->inset->setBuffer(*this);
433 // FIXME: optimize this loop somewhat, maybe by creating a new
434 // general recursive Inset::setId().
435 DocIterator it = doc_iterator_begin(this);
436 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
437 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
438 it.paragraph().setId(cloned_it.paragraph().id());
440 d->inset = new InsetText(this);
441 d->inset->setAutoBreakRows(true);
442 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
448 LYXERR(Debug::INFO, "Buffer::~Buffer()");
449 // here the buffer should take care that it is
450 // saved properly, before it goes into the void.
452 // GuiView already destroyed
456 // No need to do additional cleanups for internal buffer.
462 // this is in case of recursive includes: we won't try to delete
463 // ourselves as a child.
464 d->clone_list_->erase(this);
465 // loop over children
466 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
467 Impl::BufferPositionMap::iterator end = d->children_positions.end();
468 for (; it != end; ++it) {
469 Buffer * child = const_cast<Buffer *>(it->first);
470 if (d->clone_list_->erase(child))
473 // if we're the master buffer, then we should get rid of the list
476 // If this is not empty, we have leaked something. Worse, one of the
477 // children still has a reference to this list. But we will try to
478 // continue, rather than shut down.
479 LATTEST(d->clone_list_->empty());
480 list<CloneList *>::iterator it =
481 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
482 if (it == cloned_buffers.end()) {
483 // We will leak in this case, but it is safe to continue.
486 cloned_buffers.erase(it);
487 delete d->clone_list_;
489 // FIXME Do we really need to do this right before we delete d?
490 // clear references to children in macro tables
491 d->children_positions.clear();
492 d->position_to_children.clear();
494 // loop over children
495 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
496 Impl::BufferPositionMap::iterator end = d->children_positions.end();
497 for (; it != end; ++it) {
498 Buffer * child = const_cast<Buffer *>(it->first);
499 if (theBufferList().isLoaded(child))
500 theBufferList().releaseChild(this, child);
504 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
505 msg += emergencyWrite();
506 Alert::warning(_("Attempting to close changed document!"), msg);
509 // FIXME Do we really need to do this right before we delete d?
510 // clear references to children in macro tables
511 d->children_positions.clear();
512 d->position_to_children.clear();
514 if (!d->temppath.destroyDirectory()) {
515 Alert::warning(_("Could not remove temporary directory"),
516 bformat(_("Could not remove the temporary directory %1$s"),
517 from_utf8(d->temppath.absFileName())));
526 Buffer * Buffer::cloneFromMaster() const
529 cloned_buffers.push_back(new CloneList);
530 CloneList * clones = cloned_buffers.back();
532 masterBuffer()->cloneWithChildren(bufmap, clones);
534 // make sure we got cloned
535 BufferMap::const_iterator bit = bufmap.find(this);
536 LASSERT(bit != bufmap.end(), return 0);
537 Buffer * cloned_buffer = bit->second;
539 return cloned_buffer;
543 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
545 // have we already been cloned?
546 if (bufmap.find(this) != bufmap.end())
549 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
551 // The clone needs its own DocumentClass, since running updateBuffer() will
552 // modify it, and we would otherwise be sharing it with the original Buffer.
553 buffer_clone->params().makeDocumentClass(true);
555 cap::switchBetweenClasses(
556 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
557 static_cast<InsetText &>(buffer_clone->inset()), el);
559 bufmap[this] = buffer_clone;
560 clones->insert(buffer_clone);
561 buffer_clone->d->clone_list_ = clones;
562 buffer_clone->d->macro_lock = true;
563 buffer_clone->d->children_positions.clear();
565 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
566 // math macro caches need to be rethought and simplified.
567 // I am not sure wether we should handle Buffer cloning here or in BufferList.
568 // Right now BufferList knows nothing about buffer clones.
569 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
570 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
571 for (; it != end; ++it) {
572 DocIterator dit = it->first.clone(buffer_clone);
573 dit.setBuffer(buffer_clone);
574 Buffer * child = const_cast<Buffer *>(it->second.buffer);
576 child->cloneWithChildren(bufmap, clones);
577 BufferMap::iterator const bit = bufmap.find(child);
578 LASSERT(bit != bufmap.end(), continue);
579 Buffer * child_clone = bit->second;
581 Inset * inset = dit.nextInset();
582 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
583 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
584 inset_inc->setChildBuffer(child_clone);
585 child_clone->d->setParent(buffer_clone);
586 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
587 buffer_clone->setChild(dit, child_clone);
589 buffer_clone->d->macro_lock = false;
594 Buffer * Buffer::cloneBufferOnly() const {
595 cloned_buffers.push_back(new CloneList);
596 CloneList * clones = cloned_buffers.back();
597 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
599 // The clone needs its own DocumentClass, since running updateBuffer() will
600 // modify it, and we would otherwise be sharing it with the original Buffer.
601 buffer_clone->params().makeDocumentClass(true);
603 cap::switchBetweenClasses(
604 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
605 static_cast<InsetText &>(buffer_clone->inset()), el);
607 clones->insert(buffer_clone);
608 buffer_clone->d->clone_list_ = clones;
610 // we won't be cloning the children
611 buffer_clone->d->children_positions.clear();
616 bool Buffer::isClone() const
618 return d->cloned_buffer_;
622 void Buffer::changed(bool update_metrics) const
625 d->wa_->redrawAll(update_metrics);
629 frontend::WorkAreaManager & Buffer::workAreaManager() const
636 Text & Buffer::text() const
638 return d->inset->text();
642 Inset & Buffer::inset() const
648 BufferParams & Buffer::params()
654 BufferParams const & Buffer::params() const
660 BufferParams const & Buffer::masterParams() const
662 if (masterBuffer() == this)
665 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
666 // Copy child authors to the params. We need those pointers.
667 AuthorList const & child_authors = params().authors();
668 AuthorList::Authors::const_iterator it = child_authors.begin();
669 for (; it != child_authors.end(); ++it)
670 mparams.authors().record(*it);
675 double Buffer::fontScalingFactor() const
677 return isExporting() ? 75.0 * params().html_math_img_scale
678 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
682 ParagraphList & Buffer::paragraphs()
684 return text().paragraphs();
688 ParagraphList const & Buffer::paragraphs() const
690 return text().paragraphs();
694 LyXVC & Buffer::lyxvc()
700 LyXVC const & Buffer::lyxvc() const
706 string const Buffer::temppath() const
708 return d->temppath.absFileName();
712 TexRow & Buffer::texrow()
718 TexRow const & Buffer::texrow() const
724 TocBackend & Buffer::tocBackend() const
726 return d->toc_backend;
730 Undo & Buffer::undo()
736 void Buffer::setChild(DocIterator const & dit, Buffer * child)
738 d->children_positions[child] = dit;
742 string Buffer::latexName(bool const no_path) const
744 FileName latex_name =
745 makeLatexName(d->exportFileName());
746 return no_path ? latex_name.onlyFileName()
747 : latex_name.absFileName();
751 FileName Buffer::Impl::exportFileName() const
753 docstring const branch_suffix =
754 params.branchlist().getFileNameSuffix();
755 if (branch_suffix.empty())
758 string const name = filename.onlyFileNameWithoutExt()
759 + to_utf8(branch_suffix);
760 FileName res(filename.onlyPath().absFileName() + "/" + name);
761 res.changeExtension(filename.extension());
767 string Buffer::logName(LogType * type) const
769 string const filename = latexName(false);
771 if (filename.empty()) {
777 string const path = temppath();
779 FileName const fname(addName(temppath(),
780 onlyFileName(changeExtension(filename,
783 // FIXME: how do we know this is the name of the build log?
784 FileName const bname(
785 addName(path, onlyFileName(
786 changeExtension(filename,
787 formats.extension(params().bufferFormat()) + ".out"))));
789 // Also consider the master buffer log file
790 FileName masterfname = fname;
791 LogType mtype = latexlog;
792 if (masterBuffer() != this) {
793 string const mlogfile = masterBuffer()->logName(&mtype);
794 masterfname = FileName(mlogfile);
797 // If no Latex log or Build log is newer, show Build log
798 if (bname.exists() &&
799 ((!fname.exists() && !masterfname.exists())
800 || (fname.lastModified() < bname.lastModified()
801 && masterfname.lastModified() < bname.lastModified()))) {
802 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
805 return bname.absFileName();
806 // If we have a newer master file log or only a master log, show this
807 } else if (fname != masterfname
808 && (!fname.exists() && (masterfname.exists()
809 || fname.lastModified() < masterfname.lastModified()))) {
810 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
813 return masterfname.absFileName();
815 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
818 return fname.absFileName();
822 void Buffer::setReadonly(bool const flag)
824 if (d->read_only != flag) {
831 void Buffer::setFileName(FileName const & fname)
833 bool const changed = fname != d->filename;
836 lyxvc().file_found_hook(fname);
837 setReadonly(d->filename.isReadOnly());
843 int Buffer::readHeader(Lexer & lex)
845 int unknown_tokens = 0;
847 int begin_header_line = -1;
849 // Initialize parameters that may be/go lacking in header:
850 params().branchlist().clear();
851 params().preamble.erase();
852 params().options.erase();
853 params().master.erase();
854 params().float_placement.erase();
855 params().paperwidth.erase();
856 params().paperheight.erase();
857 params().leftmargin.erase();
858 params().rightmargin.erase();
859 params().topmargin.erase();
860 params().bottommargin.erase();
861 params().headheight.erase();
862 params().headsep.erase();
863 params().footskip.erase();
864 params().columnsep.erase();
865 params().fonts_cjk.erase();
866 params().listings_params.clear();
867 params().clearLayoutModules();
868 params().clearRemovedModules();
869 params().clearIncludedChildren();
870 params().pdfoptions().clear();
871 params().indiceslist().clear();
872 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
873 params().isbackgroundcolor = false;
874 params().fontcolor = RGBColor(0, 0, 0);
875 params().isfontcolor = false;
876 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
877 params().boxbgcolor = RGBColor(0xFF, 0, 0);
878 params().html_latex_start.clear();
879 params().html_latex_end.clear();
880 params().html_math_img_scale = 1.0;
881 params().output_sync_macro.erase();
882 params().setLocalLayout(string(), false);
883 params().setLocalLayout(string(), true);
885 for (int i = 0; i < 4; ++i) {
886 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
887 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
890 ErrorList & errorList = d->errorLists["Parse"];
899 if (token == "\\end_header")
903 if (token == "\\begin_header") {
904 begin_header_line = line;
908 LYXERR(Debug::PARSER, "Handling document header token: `"
911 string unknown = params().readToken(lex, token, d->filename.onlyPath());
912 if (!unknown.empty()) {
913 if (unknown[0] != '\\' && token == "\\textclass") {
914 Alert::warning(_("Unknown document class"),
915 bformat(_("Using the default document class, because the "
916 "class %1$s is unknown."), from_utf8(unknown)));
919 docstring const s = bformat(_("Unknown token: "
923 errorList.push_back(ErrorItem(_("Document header error"),
928 if (begin_header_line) {
929 docstring const s = _("\\begin_header is missing");
930 errorList.push_back(ErrorItem(_("Document header error"),
934 params().makeDocumentClass();
936 return unknown_tokens;
941 // changed to be public and have one parameter
942 // Returns true if "\end_document" is not read (Asger)
943 bool Buffer::readDocument(Lexer & lex)
945 ErrorList & errorList = d->errorLists["Parse"];
948 // remove dummy empty par
949 paragraphs().clear();
951 if (!lex.checkFor("\\begin_document")) {
952 docstring const s = _("\\begin_document is missing");
953 errorList.push_back(ErrorItem(_("Document header error"),
959 if (params().output_changes) {
960 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
961 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
962 LaTeXFeatures::isAvailable("xcolor");
964 if (!dvipost && !xcolorulem) {
965 Alert::warning(_("Changes not shown in LaTeX output"),
966 _("Changes will not be highlighted in LaTeX output, "
967 "because neither dvipost nor xcolor/ulem are installed.\n"
968 "Please install these packages or redefine "
969 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
970 } else if (!xcolorulem) {
971 Alert::warning(_("Changes not shown in LaTeX output"),
972 _("Changes will not be highlighted in LaTeX output "
973 "when using pdflatex, because xcolor and ulem are not installed.\n"
974 "Please install both packages or redefine "
975 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
979 if (!parent() && !params().master.empty()) {
980 FileName const master_file = makeAbsPath(params().master,
981 onlyPath(absFileName()));
982 if (isLyXFileName(master_file.absFileName())) {
984 checkAndLoadLyXFile(master_file, true);
986 // necessary e.g. after a reload
987 // to re-register the child (bug 5873)
988 // FIXME: clean up updateMacros (here, only
989 // child registering is needed).
990 master->updateMacros();
991 // set master as master buffer, but only
992 // if we are a real child
993 if (master->isChild(this))
995 // if the master is not fully loaded
996 // it is probably just loading this
997 // child. No warning needed then.
998 else if (master->isFullyLoaded())
999 LYXERR0("The master '"
1001 << "' assigned to this document ("
1003 << ") does not include "
1004 "this document. Ignoring the master assignment.");
1009 // assure we have a default index
1010 params().indiceslist().addDefault(B_("Index"));
1013 bool const res = text().read(lex, errorList, d->inset);
1015 // inform parent buffer about local macros
1017 Buffer const * pbuf = parent();
1018 UserMacroSet::const_iterator cit = usermacros.begin();
1019 UserMacroSet::const_iterator end = usermacros.end();
1020 for (; cit != end; ++cit)
1021 pbuf->usermacros.insert(*cit);
1025 updateMacroInstances(InternalUpdate);
1030 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1032 Format const * fmt = formats.getFormat(format);
1035 // It is important to use the correct extension here, since some
1036 // converters create a wrong output file otherwise (e.g. html2latex)
1037 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1038 FileName const name(tempfile.name());
1039 ofdocstream os(name.toFilesystemEncoding().c_str());
1040 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1041 bool const success = !(os << contents).fail();
1044 bool converted = false;
1046 params().compressed = false;
1048 // remove dummy empty par
1049 paragraphs().clear();
1051 converted = importFile(format, name, errorList);
1060 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1062 if (!theConverters().isReachable(format, "lyx"))
1065 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1066 FileName const lyx(tempfile.name());
1067 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1068 return readFile(lyx) == ReadSuccess;
1074 bool Buffer::readString(string const & s)
1076 params().compressed = false;
1079 istringstream is(s);
1081 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1082 FileName const fn = tempfile.name();
1085 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1087 if (success && file_format != LYX_FORMAT) {
1088 // We need to call lyx2lyx, so write the input to a file
1089 ofstream os(fn.toFilesystemEncoding().c_str());
1092 // lyxvc in readFile
1093 if (readFile(fn) != ReadSuccess)
1097 if (readDocument(lex))
1103 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1107 if (!lex.setFile(fname)) {
1108 Alert::error(_("File Not Found"),
1109 bformat(_("Unable to open file `%1$s'."),
1110 from_utf8(fn.absFileName())));
1111 return ReadFileNotFound;
1115 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1116 if (ret_plf != ReadSuccess)
1119 if (file_format != LYX_FORMAT) {
1121 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1122 if (ret_clf != ReadSuccess)
1124 return readFile(tmpFile);
1127 // FIXME: InsetInfo needs to know whether the file is under VCS
1128 // during the parse process, so this has to be done before.
1129 lyxvc().file_found_hook(d->filename);
1131 if (readDocument(lex)) {
1132 Alert::error(_("Document format failure"),
1133 bformat(_("%1$s ended unexpectedly, which means"
1134 " that it is probably corrupted."),
1135 from_utf8(fn.absFileName())));
1136 return ReadDocumentFailure;
1139 d->file_fully_loaded = true;
1140 d->read_only = !d->filename.isWritable();
1141 params().compressed = formats.isZippedFile(d->filename);
1147 bool Buffer::isFullyLoaded() const
1149 return d->file_fully_loaded;
1153 void Buffer::setFullyLoaded(bool value)
1155 d->file_fully_loaded = value;
1159 PreviewLoader * Buffer::loader() const
1161 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1163 if (!d->preview_loader_)
1164 d->preview_loader_ = new PreviewLoader(*this);
1165 return d->preview_loader_;
1169 void Buffer::removePreviews() const
1171 delete d->preview_loader_;
1172 d->preview_loader_ = 0;
1176 void Buffer::updatePreviews() const
1178 PreviewLoader * ploader = loader();
1182 InsetIterator it = inset_iterator_begin(*d->inset);
1183 InsetIterator const end = inset_iterator_end(*d->inset);
1184 for (; it != end; ++it)
1185 it->addPreview(it, *ploader);
1187 ploader->startLoading();
1191 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1192 FileName const & fn, int & file_format) const
1194 if(!lex.checkFor("\\lyxformat")) {
1195 Alert::error(_("Document format failure"),
1196 bformat(_("%1$s is not a readable LyX document."),
1197 from_utf8(fn.absFileName())));
1198 return ReadNoLyXFormat;
1204 // LyX formats 217 and earlier were written as 2.17. This corresponds
1205 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1206 // these cases. See also: www.lyx.org/trac/changeset/1313.
1207 size_t dot = tmp_format.find_first_of(".,");
1208 if (dot != string::npos)
1209 tmp_format.erase(dot, 1);
1211 file_format = convert<int>(tmp_format);
1216 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1217 FileName & tmpfile, int from_format)
1219 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1220 tempfile.setAutoRemove(false);
1221 tmpfile = tempfile.name();
1222 if(tmpfile.empty()) {
1223 Alert::error(_("Conversion failed"),
1224 bformat(_("%1$s is from a different"
1225 " version of LyX, but a temporary"
1226 " file for converting it could"
1227 " not be created."),
1228 from_utf8(fn.absFileName())));
1229 return LyX2LyXNoTempFile;
1232 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1233 if (lyx2lyx.empty()) {
1234 Alert::error(_("Conversion script not found"),
1235 bformat(_("%1$s is from a different"
1236 " version of LyX, but the"
1237 " conversion script lyx2lyx"
1238 " could not be found."),
1239 from_utf8(fn.absFileName())));
1240 return LyX2LyXNotFound;
1244 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1245 ostringstream command;
1246 command << os::python()
1247 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1248 << " -t " << convert<string>(LYX_FORMAT)
1249 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1250 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1251 string const command_str = command.str();
1253 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1255 cmd_ret const ret = runCommand(command_str);
1256 if (ret.first != 0) {
1257 if (from_format < LYX_FORMAT) {
1258 Alert::error(_("Conversion script failed"),
1259 bformat(_("%1$s is from an older version"
1260 " of LyX and the lyx2lyx script"
1261 " failed to convert it."),
1262 from_utf8(fn.absFileName())));
1263 return LyX2LyXOlderFormat;
1265 Alert::error(_("Conversion script failed"),
1266 bformat(_("%1$s is from a newer version"
1267 " of LyX and the lyx2lyx script"
1268 " failed to convert it."),
1269 from_utf8(fn.absFileName())));
1270 return LyX2LyXNewerFormat;
1277 // Should probably be moved to somewhere else: BufferView? GuiView?
1278 bool Buffer::save() const
1280 docstring const file = makeDisplayPath(absFileName(), 20);
1281 d->filename.refresh();
1283 // check the read-only status before moving the file as a backup
1284 if (d->filename.exists()) {
1285 bool const read_only = !d->filename.isWritable();
1287 Alert::warning(_("File is read-only"),
1288 bformat(_("The file %1$s cannot be written because it "
1289 "is marked as read-only."), file));
1294 // ask if the disk file has been externally modified (use checksum method)
1295 if (fileName().exists() && isExternallyModified(checksum_method)) {
1297 bformat(_("Document %1$s has been externally modified. "
1298 "Are you sure you want to overwrite this file?"), file);
1299 int const ret = Alert::prompt(_("Overwrite modified file?"),
1300 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1305 // We don't need autosaves in the immediate future. (Asger)
1306 resetAutosaveTimers();
1308 // if the file does not yet exist, none of the backup activity
1309 // that follows is necessary
1310 if (!fileName().exists())
1311 return writeFile(fileName());
1313 // we first write the file to a new name, then move it to its
1314 // proper location once that has been done successfully. that
1315 // way we preserve the original file if something goes wrong.
1316 string const justname = fileName().onlyFileNameWithoutExt();
1317 boost::scoped_ptr<TempFile>
1318 tempfile(new TempFile(fileName().onlyPath(),
1319 justname + "-XXXXXX.lyx"));
1320 bool const symlink = fileName().isSymLink();
1322 tempfile->setAutoRemove(false);
1324 FileName savefile(tempfile->name());
1325 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1326 if (!writeFile(savefile))
1329 // we will set this to false if we fail
1330 bool made_backup = true;
1332 FileName backupName(absFileName() + '~');
1333 if (lyxrc.make_backup) {
1334 if (!lyxrc.backupdir_path.empty()) {
1335 string const mangledName =
1336 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1337 backupName = FileName(addName(lyxrc.backupdir_path,
1341 LYXERR(Debug::FILES, "Backing up original file to " <<
1342 backupName.absFileName());
1343 // Except file is symlink do not copy because of #6587.
1344 // Hard links have bad luck.
1345 made_backup = symlink ?
1346 fileName().copyTo(backupName):
1347 fileName().moveTo(backupName);
1350 Alert::error(_("Backup failure"),
1351 bformat(_("Cannot create backup file %1$s.\n"
1352 "Please check whether the directory exists and is writable."),
1353 from_utf8(backupName.absFileName())));
1354 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1358 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1359 // Only do this if tempfile is not in autoremove mode
1362 // If we have no symlink, we can simply rename the temp file.
1363 // Otherwise, we need to copy it so the symlink stays intact.
1364 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1365 savefile.moveTo(fileName()))
1367 // saveCheckSum() was already called by writeFile(), but the
1368 // time stamp is invalidated by copying/moving
1373 // else we saved the file, but failed to move it to the right location.
1375 if (lyxrc.make_backup && made_backup && !symlink) {
1376 // the original file was moved to filename.lyx~, so it will look
1377 // to the user as if it was deleted. (see bug #9234.) we could try
1378 // to restore it, but that would basically mean trying to do again
1379 // what we just failed to do. better to leave things as they are.
1380 Alert::error(_("Write failure"),
1381 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1382 "But LyX could not move it to:\n %2$s.\n"
1383 "Your original file has been backed up to:\n %3$s"),
1384 from_utf8(savefile.absFileName()),
1385 from_utf8(fileName().absFileName()),
1386 from_utf8(backupName.absFileName())));
1388 // either we did not try to make a backup, or else we tried and failed,
1389 // or else the original file was a symlink, in which case it was copied,
1390 // not moved. so the original file is intact.
1391 Alert::error(_("Write failure"),
1392 bformat(_("Cannot move saved file to:\n %1$s.\n"
1393 "But the file has successfully been saved as:\n %2$s."),
1394 from_utf8(fileName().absFileName()),
1395 from_utf8(savefile.absFileName())));
1401 bool Buffer::writeFile(FileName const & fname) const
1403 if (d->read_only && fname == d->filename)
1406 bool retval = false;
1408 docstring const str = bformat(_("Saving document %1$s..."),
1409 makeDisplayPath(fname.absFileName()));
1412 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1414 if (params().compressed) {
1415 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1416 retval = ofs && write(ofs);
1418 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1419 retval = ofs && write(ofs);
1423 message(str + _(" could not write file!"));
1428 // removeAutosaveFile();
1431 message(str + _(" done."));
1437 docstring Buffer::emergencyWrite()
1439 // No need to save if the buffer has not changed.
1443 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1445 docstring user_message = bformat(
1446 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1448 // We try to save three places:
1449 // 1) Same place as document. Unless it is an unnamed doc.
1451 string s = absFileName();
1454 if (writeFile(FileName(s))) {
1456 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1457 return user_message;
1459 user_message += " " + _("Save failed! Trying again...\n");
1463 // 2) In HOME directory.
1464 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1466 lyxerr << ' ' << s << endl;
1467 if (writeFile(FileName(s))) {
1469 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1470 return user_message;
1473 user_message += " " + _("Save failed! Trying yet again...\n");
1475 // 3) In "/tmp" directory.
1476 // MakeAbsPath to prepend the current
1477 // drive letter on OS/2
1478 s = addName(package().temp_dir().absFileName(), absFileName());
1480 lyxerr << ' ' << s << endl;
1481 if (writeFile(FileName(s))) {
1483 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1484 return user_message;
1487 user_message += " " + _("Save failed! Bummer. Document is lost.");
1490 return user_message;
1494 bool Buffer::write(ostream & ofs) const
1497 // Use the standard "C" locale for file output.
1498 ofs.imbue(locale::classic());
1501 // The top of the file should not be written by params().
1503 // write out a comment in the top of the file
1504 // Important: Keep the version formatting in sync with lyx2lyx and
1505 // tex2lyx (bug 7951)
1506 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1507 << " created this file. For more info see http://www.lyx.org/\n"
1508 << "\\lyxformat " << LYX_FORMAT << "\n"
1509 << "\\begin_document\n";
1511 /// For each author, set 'used' to true if there is a change
1512 /// by this author in the document; otherwise set it to 'false'.
1513 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1514 AuthorList::Authors::const_iterator a_end = params().authors().end();
1515 for (; a_it != a_end; ++a_it)
1516 a_it->setUsed(false);
1518 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1519 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1520 for ( ; it != end; ++it)
1521 it->checkAuthors(params().authors());
1523 // now write out the buffer parameters.
1524 ofs << "\\begin_header\n";
1525 params().writeFile(ofs);
1526 ofs << "\\end_header\n";
1529 ofs << "\n\\begin_body\n";
1531 ofs << "\n\\end_body\n";
1533 // Write marker that shows file is complete
1534 ofs << "\\end_document" << endl;
1536 // Shouldn't really be needed....
1539 // how to check if close went ok?
1540 // Following is an attempt... (BE 20001011)
1542 // good() returns false if any error occurred, including some
1543 // formatting error.
1544 // bad() returns true if something bad happened in the buffer,
1545 // which should include file system full errors.
1550 lyxerr << "File was not closed properly." << endl;
1557 bool Buffer::makeLaTeXFile(FileName const & fname,
1558 string const & original_path,
1559 OutputParams const & runparams_in,
1560 OutputWhat output) const
1562 OutputParams runparams = runparams_in;
1564 // This is necessary for LuaTeX/XeTeX with tex fonts.
1565 // See FIXME in BufferParams::encoding()
1566 if (runparams.isFullUnicode())
1567 runparams.encoding = encodings.fromLyXName("utf8-plain");
1569 string const encoding = runparams.encoding->iconvName();
1570 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1573 try { ofs.reset(encoding); }
1574 catch (iconv_codecvt_facet_exception const & e) {
1575 lyxerr << "Caught iconv exception: " << e.what() << endl;
1576 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1577 "verify that the support software for your encoding (%1$s) is "
1578 "properly installed"), from_ascii(encoding)));
1581 if (!openFileWrite(ofs, fname))
1584 ErrorList & errorList = d->errorLists["Export"];
1586 bool failed_export = false;
1587 otexstream os(ofs, d->texrow);
1589 // make sure we are ready to export
1590 // this needs to be done before we validate
1591 // FIXME Do we need to do this all the time? I.e., in children
1592 // of a master we are exporting?
1594 updateMacroInstances(OutputUpdate);
1597 os.texrow().reset();
1598 writeLaTeXSource(os, original_path, runparams, output);
1600 catch (EncodingException const & e) {
1601 docstring const failed(1, e.failed_char);
1603 oss << "0x" << hex << e.failed_char << dec;
1604 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1605 " (code point %2$s)"),
1606 failed, from_utf8(oss.str()));
1607 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1608 "representable in the chosen encoding.\n"
1609 "Changing the document encoding to utf8 could help."),
1610 e.par_id, e.pos, e.pos + 1));
1611 failed_export = true;
1613 catch (iconv_codecvt_facet_exception const & e) {
1614 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1615 _(e.what()), -1, 0, 0));
1616 failed_export = true;
1618 catch (exception const & e) {
1619 errorList.push_back(ErrorItem(_("conversion failed"),
1620 _(e.what()), -1, 0, 0));
1621 failed_export = true;
1624 lyxerr << "Caught some really weird exception..." << endl;
1630 failed_export = true;
1631 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1634 if (runparams_in.silent)
1638 return !failed_export;
1642 void Buffer::writeLaTeXSource(otexstream & os,
1643 string const & original_path,
1644 OutputParams const & runparams_in,
1645 OutputWhat output) const
1647 // The child documents, if any, shall be already loaded at this point.
1649 OutputParams runparams = runparams_in;
1651 // This is necessary for LuaTeX/XeTeX with tex fonts.
1652 // See FIXME in BufferParams::encoding()
1653 if (runparams.isFullUnicode())
1654 runparams.encoding = encodings.fromLyXName("utf8-plain");
1656 // If we are compiling a file standalone, even if this is the
1657 // child of some other buffer, let's cut the link here, so the
1658 // file is really independent and no concurring settings from
1659 // the master (e.g. branch state) interfere (see #8100).
1660 if (!runparams.is_child)
1661 d->ignore_parent = true;
1663 // Classify the unicode characters appearing in math insets
1664 BufferEncodings::initUnicodeMath(*this);
1666 // validate the buffer.
1667 LYXERR(Debug::LATEX, " Validating buffer...");
1668 LaTeXFeatures features(*this, params(), runparams);
1670 // This is only set once per document (in master)
1671 if (!runparams.is_child)
1672 runparams.use_polyglossia = features.usePolyglossia();
1673 LYXERR(Debug::LATEX, " Buffer validation done.");
1675 bool const output_preamble =
1676 output == FullSource || output == OnlyPreamble;
1677 bool const output_body =
1678 output == FullSource || output == OnlyBody;
1680 // The starting paragraph of the coming rows is the
1681 // first paragraph of the document. (Asger)
1682 if (output_preamble && runparams.nice) {
1683 os << "%% LyX " << lyx_version << " created this file. "
1684 "For more info, see http://www.lyx.org/.\n"
1685 "%% Do not edit unless you really know what "
1688 LYXERR(Debug::INFO, "lyx document header finished");
1690 // There are a few differences between nice LaTeX and usual files:
1691 // usual files have \batchmode and special input@path to allow
1692 // inclusion of figures specified by an explicitly relative path
1693 // (i.e., a path starting with './' or '../') with either \input or
1694 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1695 // input@path is set when the actual parameter original_path is set.
1696 // This is done for usual tex-file, but not for nice-latex-file.
1697 // (Matthias 250696)
1698 // Note that input@path is only needed for something the user does
1699 // in the preamble, included .tex files or ERT, files included by
1700 // LyX work without it.
1701 if (output_preamble) {
1702 if (!runparams.nice) {
1703 // code for usual, NOT nice-latex-file
1704 os << "\\batchmode\n"; // changed from \nonstopmode
1706 if (!original_path.empty()) {
1708 // We don't know the encoding of inputpath
1709 docstring const inputpath = from_utf8(original_path);
1710 docstring uncodable_glyphs;
1711 Encoding const * const enc = runparams.encoding;
1713 for (size_t n = 0; n < inputpath.size(); ++n) {
1714 if (!enc->encodable(inputpath[n])) {
1715 docstring const glyph(1, inputpath[n]);
1716 LYXERR0("Uncodable character '"
1718 << "' in input path!");
1719 uncodable_glyphs += glyph;
1724 // warn user if we found uncodable glyphs.
1725 if (!uncodable_glyphs.empty()) {
1726 frontend::Alert::warning(
1727 _("Uncodable character in file path"),
1729 _("The path of your document\n"
1731 "contains glyphs that are unknown "
1732 "in the current document encoding "
1733 "(namely %2$s). This may result in "
1734 "incomplete output, unless "
1735 "TEXINPUTS contains the document "
1736 "directory and you don't use "
1737 "explicitly relative paths (i.e., "
1738 "paths starting with './' or "
1739 "'../') in the preamble or in ERT."
1740 "\n\nIn case of problems, choose "
1741 "an appropriate document encoding\n"
1742 "(such as utf8) or change the "
1744 inputpath, uncodable_glyphs));
1747 support::latex_path(original_path);
1748 if (contains(docdir, '#')) {
1749 docdir = subst(docdir, "#", "\\#");
1750 os << "\\catcode`\\#=11"
1751 "\\def\\#{#}\\catcode`\\#=6\n";
1753 if (contains(docdir, '%')) {
1754 docdir = subst(docdir, "%", "\\%");
1755 os << "\\catcode`\\%=11"
1756 "\\def\\%{%}\\catcode`\\%=14\n";
1758 os << "\\makeatletter\n"
1759 << "\\def\\input@path{{"
1760 << docdir << "/}}\n"
1761 << "\\makeatother\n";
1765 // get parent macros (if this buffer has a parent) which will be
1766 // written at the document begin further down.
1767 MacroSet parentMacros;
1768 listParentMacros(parentMacros, features);
1770 // Write the preamble
1771 runparams.use_babel = params().writeLaTeX(os, features,
1772 d->filename.onlyPath());
1774 // Japanese might be required only in some children of a document,
1775 // but once required, we must keep use_japanese true.
1776 runparams.use_japanese |= features.isRequired("japanese");
1779 // Restore the parenthood if needed
1780 if (!runparams.is_child)
1781 d->ignore_parent = false;
1786 os << "\\begin{document}\n";
1788 // output the parent macros
1789 MacroSet::iterator it = parentMacros.begin();
1790 MacroSet::iterator end = parentMacros.end();
1791 for (; it != end; ++it) {
1792 int num_lines = (*it)->write(os.os(), true);
1793 os.texrow().newlines(num_lines);
1796 } // output_preamble
1798 os.texrow().start(paragraphs().begin()->id(), 0);
1800 LYXERR(Debug::INFO, "preamble finished, now the body.");
1803 latexParagraphs(*this, text(), os, runparams);
1805 // Restore the parenthood if needed
1806 if (!runparams.is_child)
1807 d->ignore_parent = false;
1809 // add this just in case after all the paragraphs
1812 if (output_preamble) {
1813 os << "\\end{document}\n";
1814 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1816 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1818 runparams_in.encoding = runparams.encoding;
1820 // Just to be sure. (Asger)
1821 os.texrow().newline();
1823 //for (int i = 0; i<d->texrow.rows(); i++) {
1825 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1826 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1829 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1830 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1834 void Buffer::makeDocBookFile(FileName const & fname,
1835 OutputParams const & runparams,
1836 OutputWhat output) const
1838 LYXERR(Debug::LATEX, "makeDocBookFile...");
1841 if (!openFileWrite(ofs, fname))
1844 // make sure we are ready to export
1845 // this needs to be done before we validate
1847 updateMacroInstances(OutputUpdate);
1849 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1853 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1857 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1858 OutputParams const & runparams,
1859 OutputWhat output) const
1861 LaTeXFeatures features(*this, params(), runparams);
1866 DocumentClass const & tclass = params().documentClass();
1867 string const & top_element = tclass.latexname();
1869 bool const output_preamble =
1870 output == FullSource || output == OnlyPreamble;
1871 bool const output_body =
1872 output == FullSource || output == OnlyBody;
1874 if (output_preamble) {
1875 if (runparams.flavor == OutputParams::XML)
1876 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1879 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1882 if (! tclass.class_header().empty())
1883 os << from_ascii(tclass.class_header());
1884 else if (runparams.flavor == OutputParams::XML)
1885 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1886 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1888 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1890 docstring preamble = from_utf8(params().preamble);
1891 if (runparams.flavor != OutputParams::XML ) {
1892 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1893 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1894 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1895 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1898 string const name = runparams.nice
1899 ? changeExtension(absFileName(), ".sgml") : fname;
1900 preamble += features.getIncludedFiles(name);
1901 preamble += features.getLyXSGMLEntities();
1903 if (!preamble.empty()) {
1904 os << "\n [ " << preamble << " ]";
1910 string top = top_element;
1912 if (runparams.flavor == OutputParams::XML)
1913 top += params().language->code();
1915 top += params().language->code().substr(0, 2);
1918 if (!params().options.empty()) {
1920 top += params().options;
1923 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1924 << " file was created by LyX " << lyx_version
1925 << "\n See http://www.lyx.org/ for more information -->\n";
1927 params().documentClass().counters().reset();
1929 sgml::openTag(os, top);
1931 docbookParagraphs(text(), *this, os, runparams);
1932 sgml::closeTag(os, top_element);
1937 void Buffer::makeLyXHTMLFile(FileName const & fname,
1938 OutputParams const & runparams) const
1940 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1943 if (!openFileWrite(ofs, fname))
1946 // make sure we are ready to export
1947 // this has to be done before we validate
1948 updateBuffer(UpdateMaster, OutputUpdate);
1949 updateMacroInstances(OutputUpdate);
1951 writeLyXHTMLSource(ofs, runparams, FullSource);
1955 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1959 void Buffer::writeLyXHTMLSource(odocstream & os,
1960 OutputParams const & runparams,
1961 OutputWhat output) const
1963 LaTeXFeatures features(*this, params(), runparams);
1965 d->bibinfo_.makeCitationLabels(*this);
1967 bool const output_preamble =
1968 output == FullSource || output == OnlyPreamble;
1969 bool const output_body =
1970 output == FullSource || output == OnlyBody || output == IncludedFile;
1972 if (output_preamble) {
1973 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1974 << "<!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"
1975 // FIXME Language should be set properly.
1976 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1978 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1979 // FIXME Presumably need to set this right
1980 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1982 docstring const & doctitle = features.htmlTitle();
1984 << (doctitle.empty() ?
1985 from_ascii("LyX Document") :
1986 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1989 docstring styles = features.getTClassHTMLPreamble();
1990 if (!styles.empty())
1991 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1993 styles = from_utf8(features.getPreambleSnippets());
1994 if (!styles.empty())
1995 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1997 // we will collect CSS information in a stream, and then output it
1998 // either here, as part of the header, or else in a separate file.
1999 odocstringstream css;
2000 styles = from_utf8(features.getCSSSnippets());
2001 if (!styles.empty())
2002 css << "/* LyX Provided Styles */\n" << styles << '\n';
2004 styles = features.getTClassHTMLStyles();
2005 if (!styles.empty())
2006 css << "/* Layout-provided Styles */\n" << styles << '\n';
2008 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2009 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2010 if (needfg || needbg) {
2011 css << "\nbody {\n";
2014 << from_ascii(X11hexname(params().fontcolor))
2017 css << " background-color: "
2018 << from_ascii(X11hexname(params().backgroundcolor))
2023 docstring const dstyles = css.str();
2024 if (!dstyles.empty()) {
2025 bool written = false;
2026 if (params().html_css_as_file) {
2027 // open a file for CSS info
2029 string const fcssname = addName(temppath(), "docstyle.css");
2030 FileName const fcssfile = FileName(fcssname);
2031 if (openFileWrite(ocss, fcssfile)) {
2035 // write link to header
2036 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2038 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2041 // we are here if the CSS is supposed to be written to the header
2042 // or if we failed to write it to an external file.
2044 os << "<style type='text/css'>\n"
2053 bool const output_body_tag = (output != IncludedFile);
2054 if (output_body_tag)
2057 if (output != IncludedFile)
2058 // if we're an included file, the counters are in the master.
2059 params().documentClass().counters().reset();
2060 xhtmlParagraphs(text(), *this, xs, runparams);
2061 if (output_body_tag)
2065 if (output_preamble)
2070 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2071 // Other flags: -wall -v0 -x
2072 int Buffer::runChktex()
2076 // get LaTeX-Filename
2077 FileName const path(temppath());
2078 string const name = addName(path.absFileName(), latexName());
2079 string const org_path = filePath();
2081 PathChanger p(path); // path to LaTeX file
2082 message(_("Running chktex..."));
2084 // Generate the LaTeX file if neccessary
2085 OutputParams runparams(¶ms().encoding());
2086 runparams.flavor = OutputParams::LATEX;
2087 runparams.nice = false;
2088 runparams.linelen = lyxrc.plaintext_linelen;
2089 makeLaTeXFile(FileName(name), org_path, runparams);
2092 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2093 int const res = chktex.run(terr); // run chktex
2096 Alert::error(_("chktex failure"),
2097 _("Could not run chktex successfully."));
2099 ErrorList & errlist = d->errorLists["ChkTeX"];
2101 bufferErrors(terr, errlist);
2106 if (runparams.silent)
2107 d->errorLists["ChkTeX"].clear();
2115 void Buffer::validate(LaTeXFeatures & features) const
2117 // Validate the buffer params, but not for included
2118 // files, since they also use the parent buffer's
2120 if (!features.runparams().is_child)
2121 params().validate(features);
2123 for_each(paragraphs().begin(), paragraphs().end(),
2124 bind(&Paragraph::validate, _1, ref(features)));
2126 if (lyxerr.debugging(Debug::LATEX)) {
2127 features.showStruct();
2132 void Buffer::getLabelList(vector<docstring> & list) const
2134 // If this is a child document, use the master's list instead.
2136 masterBuffer()->getLabelList(list);
2141 Toc & toc = d->toc_backend.toc("label");
2142 TocIterator toc_it = toc.begin();
2143 TocIterator end = toc.end();
2144 for (; toc_it != end; ++toc_it) {
2145 if (toc_it->depth() == 0)
2146 list.push_back(toc_it->str());
2151 void Buffer::updateBibfilesCache(UpdateScope scope) const
2153 // FIXME This is probably unnecssary, given where we call this.
2154 // If this is a child document, use the parent's cache instead.
2155 if (parent() && scope != UpdateChildOnly) {
2156 masterBuffer()->updateBibfilesCache();
2160 d->bibfiles_cache_.clear();
2161 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2162 if (it->lyxCode() == BIBTEX_CODE) {
2163 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2164 support::FileNameList const bibfiles = inset.getBibFiles();
2165 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2168 } else if (it->lyxCode() == INCLUDE_CODE) {
2169 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2170 Buffer const * const incbuf = inset.getChildBuffer();
2173 support::FileNameList const & bibfiles =
2174 incbuf->getBibfilesCache(UpdateChildOnly);
2175 if (!bibfiles.empty()) {
2176 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2182 d->bibfile_cache_valid_ = true;
2183 d->bibinfo_cache_valid_ = false;
2184 d->cite_labels_valid_ = false;
2188 void Buffer::invalidateBibinfoCache() const
2190 d->bibinfo_cache_valid_ = false;
2191 d->cite_labels_valid_ = false;
2192 // also invalidate the cache for the parent buffer
2193 Buffer const * const pbuf = d->parent();
2195 pbuf->invalidateBibinfoCache();
2199 void Buffer::invalidateBibfileCache() const
2201 d->bibfile_cache_valid_ = false;
2202 d->bibinfo_cache_valid_ = false;
2203 d->cite_labels_valid_ = false;
2204 // also invalidate the cache for the parent buffer
2205 Buffer const * const pbuf = d->parent();
2207 pbuf->invalidateBibfileCache();
2211 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2213 // FIXME This is probably unnecessary, given where we call this.
2214 // If this is a child document, use the master's cache instead.
2215 Buffer const * const pbuf = masterBuffer();
2216 if (pbuf != this && scope != UpdateChildOnly)
2217 return pbuf->getBibfilesCache();
2219 if (!d->bibfile_cache_valid_)
2220 this->updateBibfilesCache(scope);
2222 return d->bibfiles_cache_;
2226 BiblioInfo const & Buffer::masterBibInfo() const
2228 Buffer const * const tmp = masterBuffer();
2230 return tmp->masterBibInfo();
2235 void Buffer::checkIfBibInfoCacheIsValid() const
2237 // use the master's cache
2238 Buffer const * const tmp = masterBuffer();
2240 tmp->checkIfBibInfoCacheIsValid();
2244 // compare the cached timestamps with the actual ones.
2245 FileNameList const & bibfiles_cache = getBibfilesCache();
2246 FileNameList::const_iterator ei = bibfiles_cache.begin();
2247 FileNameList::const_iterator en = bibfiles_cache.end();
2248 for (; ei != en; ++ ei) {
2249 time_t lastw = ei->lastModified();
2250 time_t prevw = d->bibfile_status_[*ei];
2251 if (lastw != prevw) {
2252 d->bibinfo_cache_valid_ = false;
2253 d->cite_labels_valid_ = false;
2254 d->bibfile_status_[*ei] = lastw;
2260 void Buffer::reloadBibInfoCache() const
2262 // use the master's cache
2263 Buffer const * const tmp = masterBuffer();
2265 tmp->reloadBibInfoCache();
2269 checkIfBibInfoCacheIsValid();
2270 if (d->bibinfo_cache_valid_)
2273 d->bibinfo_.clear();
2275 d->bibinfo_cache_valid_ = true;
2279 void Buffer::collectBibKeys() const
2281 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2282 it->collectBibKeys(it);
2286 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2288 Buffer const * tmp = masterBuffer();
2289 BiblioInfo & masterbi = (tmp == this) ?
2290 d->bibinfo_ : tmp->d->bibinfo_;
2291 masterbi.mergeBiblioInfo(bi);
2295 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2297 Buffer const * tmp = masterBuffer();
2298 BiblioInfo & masterbi = (tmp == this) ?
2299 d->bibinfo_ : tmp->d->bibinfo_;
2304 void Buffer::makeCitationLabels() const
2306 Buffer const * const master = masterBuffer();
2307 return d->bibinfo_.makeCitationLabels(*master);
2311 bool Buffer::citeLabelsValid() const
2313 return masterBuffer()->d->cite_labels_valid_;
2317 void Buffer::removeBiblioTempFiles() const
2319 // We remove files that contain LaTeX commands specific to the
2320 // particular bibliographic style being used, in order to avoid
2321 // LaTeX errors when we switch style.
2322 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2323 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2324 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2325 aux_file.removeFile();
2326 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2327 bbl_file.removeFile();
2328 // Also for the parent buffer
2329 Buffer const * const pbuf = parent();
2331 pbuf->removeBiblioTempFiles();
2335 bool Buffer::isDepClean(string const & name) const
2337 DepClean::const_iterator const it = d->dep_clean.find(name);
2338 if (it == d->dep_clean.end())
2344 void Buffer::markDepClean(string const & name)
2346 d->dep_clean[name] = true;
2350 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2353 // FIXME? if there is an Buffer LFUN that can be dispatched even
2354 // if internal, put a switch '(cmd.action)' here.
2360 switch (cmd.action()) {
2362 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2363 flag.setOnOff(isReadonly());
2366 // FIXME: There is need for a command-line import.
2367 //case LFUN_BUFFER_IMPORT:
2369 case LFUN_BUFFER_AUTO_SAVE:
2372 case LFUN_BUFFER_EXPORT_CUSTOM:
2373 // FIXME: Nothing to check here?
2376 case LFUN_BUFFER_EXPORT: {
2377 docstring const arg = cmd.argument();
2378 if (arg == "custom") {
2382 string format = to_utf8(arg);
2383 size_t pos = format.find(' ');
2384 if (pos != string::npos)
2385 format = format.substr(0, pos);
2386 enable = params().isExportable(format);
2388 flag.message(bformat(
2389 _("Don't know how to export to format: %1$s"), arg));
2393 case LFUN_BUFFER_CHKTEX:
2394 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2397 case LFUN_BUILD_PROGRAM:
2398 enable = params().isExportable("program");
2401 case LFUN_BRANCH_ACTIVATE:
2402 case LFUN_BRANCH_DEACTIVATE:
2403 case LFUN_BRANCH_MASTER_ACTIVATE:
2404 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2405 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2406 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2407 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2408 : params().branchlist();
2409 docstring const branchName = cmd.argument();
2410 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2414 case LFUN_BRANCH_ADD:
2415 case LFUN_BRANCHES_RENAME:
2416 case LFUN_BUFFER_PRINT:
2417 // if no Buffer is present, then of course we won't be called!
2420 case LFUN_BUFFER_LANGUAGE:
2421 enable = !isReadonly();
2427 flag.setEnabled(enable);
2432 void Buffer::dispatch(string const & command, DispatchResult & result)
2434 return dispatch(lyxaction.lookupFunc(command), result);
2438 // NOTE We can end up here even if we have no GUI, because we are called
2439 // by LyX::exec to handled command-line requests. So we may need to check
2440 // whether we have a GUI or not. The boolean use_gui holds this information.
2441 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2444 // FIXME? if there is an Buffer LFUN that can be dispatched even
2445 // if internal, put a switch '(cmd.action())' here.
2446 dr.dispatched(false);
2449 string const argument = to_utf8(func.argument());
2450 // We'll set this back to false if need be.
2451 bool dispatched = true;
2452 undo().beginUndoGroup();
2454 switch (func.action()) {
2455 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2456 if (lyxvc().inUse()) {
2457 string log = lyxvc().toggleReadOnly();
2462 setReadonly(!isReadonly());
2465 case LFUN_BUFFER_EXPORT: {
2466 ExportStatus const status = doExport(argument, false);
2467 dr.setError(status != ExportSuccess);
2468 if (status != ExportSuccess)
2469 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2474 case LFUN_BUILD_PROGRAM: {
2475 ExportStatus const status = doExport("program", true);
2476 dr.setError(status != ExportSuccess);
2477 if (status != ExportSuccess)
2478 dr.setMessage(_("Error generating literate programming code."));
2482 case LFUN_BUFFER_CHKTEX:
2486 case LFUN_BUFFER_EXPORT_CUSTOM: {
2488 string command = split(argument, format_name, ' ');
2489 Format const * format = formats.getFormat(format_name);
2491 lyxerr << "Format \"" << format_name
2492 << "\" not recognized!"
2497 // The name of the file created by the conversion process
2500 // Output to filename
2501 if (format->name() == "lyx") {
2502 string const latexname = latexName(false);
2503 filename = changeExtension(latexname,
2504 format->extension());
2505 filename = addName(temppath(), filename);
2507 if (!writeFile(FileName(filename)))
2511 doExport(format_name, true, filename);
2514 // Substitute $$FName for filename
2515 if (!contains(command, "$$FName"))
2516 command = "( " + command + " ) < $$FName";
2517 command = subst(command, "$$FName", filename);
2519 // Execute the command in the background
2521 call.startscript(Systemcall::DontWait, command, filePath());
2525 // FIXME: There is need for a command-line import.
2527 case LFUN_BUFFER_IMPORT:
2532 case LFUN_BUFFER_AUTO_SAVE:
2534 resetAutosaveTimers();
2537 case LFUN_BRANCH_ACTIVATE:
2538 case LFUN_BRANCH_DEACTIVATE:
2539 case LFUN_BRANCH_MASTER_ACTIVATE:
2540 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2541 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2542 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2543 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2546 docstring const branch_name = func.argument();
2547 // the case without a branch name is handled elsewhere
2548 if (branch_name.empty()) {
2552 Branch * branch = buf->params().branchlist().find(branch_name);
2554 LYXERR0("Branch " << branch_name << " does not exist.");
2556 docstring const msg =
2557 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2561 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2562 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2563 if (branch->isSelected() != activate) {
2564 buf->undo().recordUndoBufferParams(CursorData());
2565 branch->setSelected(activate);
2567 dr.screenUpdate(Update::Force);
2568 dr.forceBufferUpdate();
2573 case LFUN_BRANCH_ADD: {
2574 docstring branch_name = func.argument();
2575 if (branch_name.empty()) {
2579 BranchList & branch_list = params().branchlist();
2580 vector<docstring> const branches =
2581 getVectorFromString(branch_name, branch_list.separator());
2583 for (vector<docstring>::const_iterator it = branches.begin();
2584 it != branches.end(); ++it) {
2586 Branch * branch = branch_list.find(branch_name);
2588 LYXERR0("Branch " << branch_name << " already exists.");
2592 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2594 undo().recordUndoBufferParams(CursorData());
2595 branch_list.add(branch_name);
2596 branch = branch_list.find(branch_name);
2597 string const x11hexname = X11hexname(branch->color());
2598 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2599 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2601 dr.screenUpdate(Update::Force);
2609 case LFUN_BRANCHES_RENAME: {
2610 if (func.argument().empty())
2613 docstring const oldname = from_utf8(func.getArg(0));
2614 docstring const newname = from_utf8(func.getArg(1));
2615 InsetIterator it = inset_iterator_begin(inset());
2616 InsetIterator const end = inset_iterator_end(inset());
2617 bool success = false;
2618 for (; it != end; ++it) {
2619 if (it->lyxCode() == BRANCH_CODE) {
2620 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2621 if (ins.branch() == oldname) {
2622 undo().recordUndo(CursorData(it));
2623 ins.rename(newname);
2628 if (it->lyxCode() == INCLUDE_CODE) {
2629 // get buffer of external file
2630 InsetInclude const & ins =
2631 static_cast<InsetInclude const &>(*it);
2632 Buffer * child = ins.getChildBuffer();
2635 child->dispatch(func, dr);
2640 dr.screenUpdate(Update::Force);
2641 dr.forceBufferUpdate();
2646 case LFUN_BUFFER_PRINT: {
2647 // we'll assume there's a problem until we succeed
2649 string target = func.getArg(0);
2650 string target_name = func.getArg(1);
2651 string command = func.getArg(2);
2654 || target_name.empty()
2655 || command.empty()) {
2656 LYXERR0("Unable to parse " << func.argument());
2657 docstring const msg =
2658 bformat(_("Unable to parse \"%1$s\""), func.argument());
2662 if (target != "printer" && target != "file") {
2663 LYXERR0("Unrecognized target \"" << target << '"');
2664 docstring const msg =
2665 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2670 if (doExport("dvi", true) != ExportSuccess) {
2671 showPrintError(absFileName());
2672 dr.setMessage(_("Error exporting to DVI."));
2676 // Push directory path.
2677 string const path = temppath();
2678 // Prevent the compiler from optimizing away p
2682 // there are three cases here:
2683 // 1. we print to a file
2684 // 2. we print directly to a printer
2685 // 3. we print using a spool command (print to file first)
2688 string const dviname = changeExtension(latexName(true), "dvi");
2690 if (target == "printer") {
2691 if (!lyxrc.print_spool_command.empty()) {
2692 // case 3: print using a spool
2693 string const psname = changeExtension(dviname,".ps");
2694 command += ' ' + lyxrc.print_to_file
2697 + quoteName(dviname);
2699 string command2 = lyxrc.print_spool_command + ' ';
2700 if (target_name != "default") {
2701 command2 += lyxrc.print_spool_printerprefix
2705 command2 += quoteName(psname);
2707 // If successful, then spool command
2708 res = one.startscript(Systemcall::Wait, command,
2712 // If there's no GUI, we have to wait on this command. Otherwise,
2713 // LyX deletes the temporary directory, and with it the spooled
2714 // file, before it can be printed!!
2715 Systemcall::Starttype stype = use_gui ?
2716 Systemcall::DontWait : Systemcall::Wait;
2717 res = one.startscript(stype, command2,
2721 // case 2: print directly to a printer
2722 if (target_name != "default")
2723 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2725 Systemcall::Starttype stype = use_gui ?
2726 Systemcall::DontWait : Systemcall::Wait;
2727 res = one.startscript(stype, command +
2728 quoteName(dviname), filePath());
2732 // case 1: print to a file
2733 FileName const filename(makeAbsPath(target_name, filePath()));
2734 FileName const dvifile(makeAbsPath(dviname, path));
2735 if (filename.exists()) {
2736 docstring text = bformat(
2737 _("The file %1$s already exists.\n\n"
2738 "Do you want to overwrite that file?"),
2739 makeDisplayPath(filename.absFileName()));
2740 if (Alert::prompt(_("Overwrite file?"),
2741 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2744 command += ' ' + lyxrc.print_to_file
2745 + quoteName(filename.toFilesystemEncoding())
2747 + quoteName(dvifile.toFilesystemEncoding());
2749 Systemcall::Starttype stype = use_gui ?
2750 Systemcall::DontWait : Systemcall::Wait;
2751 res = one.startscript(stype, command, filePath());
2757 dr.setMessage(_("Error running external commands."));
2758 showPrintError(absFileName());
2767 dr.dispatched(dispatched);
2768 undo().endUndoGroup();
2772 void Buffer::changeLanguage(Language const * from, Language const * to)
2774 LASSERT(from, return);
2775 LASSERT(to, return);
2777 for_each(par_iterator_begin(),
2779 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2783 bool Buffer::isMultiLingual() const
2785 ParConstIterator end = par_iterator_end();
2786 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2787 if (it->isMultiLingual(params()))
2794 std::set<Language const *> Buffer::getLanguages() const
2796 std::set<Language const *> languages;
2797 getLanguages(languages);
2802 void Buffer::getLanguages(std::set<Language const *> & languages) const
2804 ParConstIterator end = par_iterator_end();
2805 // add the buffer language, even if it's not actively used
2806 languages.insert(language());
2807 // iterate over the paragraphs
2808 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2809 it->getLanguages(languages);
2811 ListOfBuffers clist = getDescendents();
2812 ListOfBuffers::const_iterator cit = clist.begin();
2813 ListOfBuffers::const_iterator const cen = clist.end();
2814 for (; cit != cen; ++cit)
2815 (*cit)->getLanguages(languages);
2819 DocIterator Buffer::getParFromID(int const id) const
2821 Buffer * buf = const_cast<Buffer *>(this);
2823 // John says this is called with id == -1 from undo
2824 lyxerr << "getParFromID(), id: " << id << endl;
2825 return doc_iterator_end(buf);
2828 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2829 if (it.paragraph().id() == id)
2832 return doc_iterator_end(buf);
2836 bool Buffer::hasParWithID(int const id) const
2838 return !getParFromID(id).atEnd();
2842 ParIterator Buffer::par_iterator_begin()
2844 return ParIterator(doc_iterator_begin(this));
2848 ParIterator Buffer::par_iterator_end()
2850 return ParIterator(doc_iterator_end(this));
2854 ParConstIterator Buffer::par_iterator_begin() const
2856 return ParConstIterator(doc_iterator_begin(this));
2860 ParConstIterator Buffer::par_iterator_end() const
2862 return ParConstIterator(doc_iterator_end(this));
2866 Language const * Buffer::language() const
2868 return params().language;
2872 docstring const Buffer::B_(string const & l10n) const
2874 return params().B_(l10n);
2878 bool Buffer::isClean() const
2880 return d->lyx_clean;
2884 bool Buffer::isExternallyModified(CheckMethod method) const
2886 LASSERT(d->filename.exists(), return false);
2887 // if method == timestamp, check timestamp before checksum
2888 return (method == checksum_method
2889 || d->timestamp_ != d->filename.lastModified())
2890 && d->checksum_ != d->filename.checksum();
2894 void Buffer::saveCheckSum() const
2896 FileName const & file = d->filename;
2899 if (file.exists()) {
2900 d->timestamp_ = file.lastModified();
2901 d->checksum_ = file.checksum();
2903 // in the case of save to a new file.
2910 void Buffer::markClean() const
2912 if (!d->lyx_clean) {
2913 d->lyx_clean = true;
2916 // if the .lyx file has been saved, we don't need an
2918 d->bak_clean = true;
2919 d->undo_.markDirty();
2923 void Buffer::setUnnamed(bool flag)
2929 bool Buffer::isUnnamed() const
2936 /// Don't check unnamed, here: isInternal() is used in
2937 /// newBuffer(), where the unnamed flag has not been set by anyone
2938 /// yet. Also, for an internal buffer, there should be no need for
2939 /// retrieving fileName() nor for checking if it is unnamed or not.
2940 bool Buffer::isInternal() const
2942 return d->internal_buffer;
2946 void Buffer::setInternal(bool flag)
2948 d->internal_buffer = flag;
2952 void Buffer::markDirty()
2955 d->lyx_clean = false;
2958 d->bak_clean = false;
2960 DepClean::iterator it = d->dep_clean.begin();
2961 DepClean::const_iterator const end = d->dep_clean.end();
2963 for (; it != end; ++it)
2968 FileName Buffer::fileName() const
2974 string Buffer::absFileName() const
2976 return d->filename.absFileName();
2980 string Buffer::filePath() const
2982 string const abs = d->filename.onlyPath().absFileName();
2985 int last = abs.length() - 1;
2987 return abs[last] == '/' ? abs : abs + '/';
2991 bool Buffer::isReadonly() const
2993 return d->read_only;
2997 void Buffer::setParent(Buffer const * buffer)
2999 // Avoids recursive include.
3000 d->setParent(buffer == this ? 0 : buffer);
3005 Buffer const * Buffer::parent() const
3011 ListOfBuffers Buffer::allRelatives() const
3013 ListOfBuffers lb = masterBuffer()->getDescendents();
3014 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3019 Buffer const * Buffer::masterBuffer() const
3021 // FIXME Should be make sure we are not in some kind
3022 // of recursive include? A -> B -> A will crash this.
3023 Buffer const * const pbuf = d->parent();
3027 return pbuf->masterBuffer();
3031 bool Buffer::isChild(Buffer * child) const
3033 return d->children_positions.find(child) != d->children_positions.end();
3037 DocIterator Buffer::firstChildPosition(Buffer const * child)
3039 Impl::BufferPositionMap::iterator it;
3040 it = d->children_positions.find(child);
3041 if (it == d->children_positions.end())
3042 return DocIterator(this);
3047 bool Buffer::hasChildren() const
3049 return !d->children_positions.empty();
3053 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3055 // loop over children
3056 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3057 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3058 for (; it != end; ++it) {
3059 Buffer * child = const_cast<Buffer *>(it->first);
3061 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3062 if (bit != clist.end())
3064 clist.push_back(child);
3066 // there might be grandchildren
3067 child->collectChildren(clist, true);
3072 ListOfBuffers Buffer::getChildren() const
3075 collectChildren(v, false);
3076 // Make sure we have not included ourselves.
3077 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3078 if (bit != v.end()) {
3079 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3086 ListOfBuffers Buffer::getDescendents() const
3089 collectChildren(v, true);
3090 // Make sure we have not included ourselves.
3091 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3092 if (bit != v.end()) {
3093 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3100 template<typename M>
3101 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3106 typename M::const_iterator it = m.lower_bound(x);
3107 if (it == m.begin())
3115 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3116 DocIterator const & pos) const
3118 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3120 // if paragraphs have no macro context set, pos will be empty
3124 // we haven't found anything yet
3125 DocIterator bestPos = owner_->par_iterator_begin();
3126 MacroData const * bestData = 0;
3128 // find macro definitions for name
3129 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3130 if (nameIt != macros.end()) {
3131 // find last definition in front of pos or at pos itself
3132 PositionScopeMacroMap::const_iterator it
3133 = greatest_below(nameIt->second, pos);
3134 if (it != nameIt->second.end()) {
3136 // scope ends behind pos?
3137 if (pos < it->second.scope) {
3138 // Looks good, remember this. If there
3139 // is no external macro behind this,
3140 // we found the right one already.
3141 bestPos = it->first;
3142 bestData = &it->second.macro;
3146 // try previous macro if there is one
3147 if (it == nameIt->second.begin())
3154 // find macros in included files
3155 PositionScopeBufferMap::const_iterator it
3156 = greatest_below(position_to_children, pos);
3157 if (it == position_to_children.end())
3158 // no children before
3162 // do we know something better (i.e. later) already?
3163 if (it->first < bestPos )
3166 // scope ends behind pos?
3167 if (pos < it->second.scope
3168 && (cloned_buffer_ ||
3169 theBufferList().isLoaded(it->second.buffer))) {
3170 // look for macro in external file
3172 MacroData const * data
3173 = it->second.buffer->getMacro(name, false);
3176 bestPos = it->first;
3182 // try previous file if there is one
3183 if (it == position_to_children.begin())
3188 // return the best macro we have found
3193 MacroData const * Buffer::getMacro(docstring const & name,
3194 DocIterator const & pos, bool global) const
3199 // query buffer macros
3200 MacroData const * data = d->getBufferMacro(name, pos);
3204 // If there is a master buffer, query that
3205 Buffer const * const pbuf = d->parent();
3207 d->macro_lock = true;
3208 MacroData const * macro = pbuf->getMacro(
3209 name, *this, false);
3210 d->macro_lock = false;
3216 data = MacroTable::globalMacros().get(name);
3225 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3227 // set scope end behind the last paragraph
3228 DocIterator scope = par_iterator_begin();
3229 scope.pit() = scope.lastpit() + 1;
3231 return getMacro(name, scope, global);
3235 MacroData const * Buffer::getMacro(docstring const & name,
3236 Buffer const & child, bool global) const
3238 // look where the child buffer is included first
3239 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3240 if (it == d->children_positions.end())
3243 // check for macros at the inclusion position
3244 return getMacro(name, it->second, global);
3248 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3250 pit_type const lastpit = it.lastpit();
3252 // look for macros in each paragraph
3253 while (it.pit() <= lastpit) {
3254 Paragraph & par = it.paragraph();
3256 // iterate over the insets of the current paragraph
3257 InsetList const & insets = par.insetList();
3258 InsetList::const_iterator iit = insets.begin();
3259 InsetList::const_iterator end = insets.end();
3260 for (; iit != end; ++iit) {
3261 it.pos() = iit->pos;
3263 // is it a nested text inset?
3264 if (iit->inset->asInsetText()) {
3265 // Inset needs its own scope?
3266 InsetText const * itext = iit->inset->asInsetText();
3267 bool newScope = itext->isMacroScope();
3269 // scope which ends just behind the inset
3270 DocIterator insetScope = it;
3273 // collect macros in inset
3274 it.push_back(CursorSlice(*iit->inset));
3275 updateMacros(it, newScope ? insetScope : scope);
3280 if (iit->inset->asInsetTabular()) {
3281 CursorSlice slice(*iit->inset);
3282 size_t const numcells = slice.nargs();
3283 for (; slice.idx() < numcells; slice.forwardIdx()) {
3284 it.push_back(slice);
3285 updateMacros(it, scope);
3291 // is it an external file?
3292 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3293 // get buffer of external file
3294 InsetInclude const & inset =
3295 static_cast<InsetInclude const &>(*iit->inset);
3297 Buffer * child = inset.getChildBuffer();
3302 // register its position, but only when it is
3303 // included first in the buffer
3304 if (children_positions.find(child) ==
3305 children_positions.end())
3306 children_positions[child] = it;
3308 // register child with its scope
3309 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3313 InsetMath * im = iit->inset->asInsetMath();
3314 if (doing_export && im) {
3315 InsetMathHull * hull = im->asHullInset();
3317 hull->recordLocation(it);
3320 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3324 MathMacroTemplate & macroTemplate =
3325 *iit->inset->asInsetMath()->asMacroTemplate();
3326 MacroContext mc(owner_, it);
3327 macroTemplate.updateToContext(mc);
3330 bool valid = macroTemplate.validMacro();
3331 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3332 // then the BufferView's cursor will be invalid in
3333 // some cases which leads to crashes.
3338 // FIXME (Abdel), I don't understand why we pass 'it' here
3339 // instead of 'macroTemplate' defined above... is this correct?
3340 macros[macroTemplate.name()][it] =
3341 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3351 void Buffer::updateMacros() const
3356 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3358 // start with empty table
3360 d->children_positions.clear();
3361 d->position_to_children.clear();
3363 // Iterate over buffer, starting with first paragraph
3364 // The scope must be bigger than any lookup DocIterator
3365 // later. For the global lookup, lastpit+1 is used, hence
3366 // we use lastpit+2 here.
3367 DocIterator it = par_iterator_begin();
3368 DocIterator outerScope = it;
3369 outerScope.pit() = outerScope.lastpit() + 2;
3370 d->updateMacros(it, outerScope);
3374 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3376 InsetIterator it = inset_iterator_begin(inset());
3377 InsetIterator const end = inset_iterator_end(inset());
3378 for (; it != end; ++it) {
3379 if (it->lyxCode() == BRANCH_CODE) {
3380 InsetBranch & br = static_cast<InsetBranch &>(*it);
3381 docstring const name = br.branch();
3382 if (!from_master && !params().branchlist().find(name))
3383 result.push_back(name);
3384 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3385 result.push_back(name);
3388 if (it->lyxCode() == INCLUDE_CODE) {
3389 // get buffer of external file
3390 InsetInclude const & ins =
3391 static_cast<InsetInclude const &>(*it);
3392 Buffer * child = ins.getChildBuffer();
3395 child->getUsedBranches(result, true);
3398 // remove duplicates
3403 void Buffer::updateMacroInstances(UpdateType utype) const
3405 LYXERR(Debug::MACROS, "updateMacroInstances for "
3406 << d->filename.onlyFileName());
3407 DocIterator it = doc_iterator_begin(this);
3409 DocIterator const end = doc_iterator_end(this);
3410 for (; it != end; it.forwardInset()) {
3411 // look for MathData cells in InsetMathNest insets
3412 InsetMath * minset = it.nextInset()->asInsetMath();
3416 // update macro in all cells of the InsetMathNest
3417 DocIterator::idx_type n = minset->nargs();
3418 MacroContext mc = MacroContext(this, it);
3419 for (DocIterator::idx_type i = 0; i < n; ++i) {
3420 MathData & data = minset->cell(i);
3421 data.updateMacros(0, mc, utype);
3427 void Buffer::listMacroNames(MacroNameSet & macros) const
3432 d->macro_lock = true;
3434 // loop over macro names
3435 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3436 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3437 for (; nameIt != nameEnd; ++nameIt)
3438 macros.insert(nameIt->first);
3440 // loop over children
3441 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3442 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3443 for (; it != end; ++it)
3444 it->first->listMacroNames(macros);
3447 Buffer const * const pbuf = d->parent();
3449 pbuf->listMacroNames(macros);
3451 d->macro_lock = false;
3455 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3457 Buffer const * const pbuf = d->parent();
3462 pbuf->listMacroNames(names);
3465 MacroNameSet::iterator it = names.begin();
3466 MacroNameSet::iterator end = names.end();
3467 for (; it != end; ++it) {
3469 MacroData const * data =
3470 pbuf->getMacro(*it, *this, false);
3472 macros.insert(data);
3474 // we cannot access the original MathMacroTemplate anymore
3475 // here to calls validate method. So we do its work here manually.
3476 // FIXME: somehow make the template accessible here.
3477 if (data->optionals() > 0)
3478 features.require("xargs");
3484 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3487 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3489 RefCache::iterator it = d->ref_cache_.find(label);
3490 if (it != d->ref_cache_.end())
3491 return it->second.second;
3493 static InsetLabel const * dummy_il = 0;
3494 static References const dummy_refs;
3495 it = d->ref_cache_.insert(
3496 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3497 return it->second.second;
3501 Buffer::References const & Buffer::references(docstring const & label) const
3503 return const_cast<Buffer *>(this)->getReferenceCache(label);
3507 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3509 References & refs = getReferenceCache(label);
3510 refs.push_back(make_pair(inset, it));
3514 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3516 masterBuffer()->d->ref_cache_[label].first = il;
3520 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3522 return masterBuffer()->d->ref_cache_[label].first;
3526 void Buffer::clearReferenceCache() const
3529 d->ref_cache_.clear();
3533 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3535 //FIXME: This does not work for child documents yet.
3536 reloadBibInfoCache();
3538 // Check if the label 'from' appears more than once
3539 BiblioInfo const & keys = masterBibInfo();
3540 BiblioInfo::const_iterator bit = keys.begin();
3541 BiblioInfo::const_iterator bend = keys.end();
3542 vector<docstring> labels;
3544 for (; bit != bend; ++bit)
3546 labels.push_back(bit->first);
3548 if (count(labels.begin(), labels.end(), from) > 1)
3551 string const paramName = "key";
3552 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3553 if (it->lyxCode() != CITE_CODE)
3555 InsetCommand * inset = it->asInsetCommand();
3556 docstring const oldValue = inset->getParam(paramName);
3557 if (oldValue == from)
3558 inset->setParam(paramName, to);
3563 void Buffer::getSourceCode(odocstream & os, string const & format,
3564 pit_type par_begin, pit_type par_end,
3565 OutputWhat output, bool master) const
3567 OutputParams runparams(¶ms().encoding());
3568 runparams.nice = true;
3569 runparams.flavor = params().getOutputFlavor(format);
3570 runparams.linelen = lyxrc.plaintext_linelen;
3571 // No side effect of file copying and image conversion
3572 runparams.dryrun = true;
3574 if (output == CurrentParagraph) {
3575 runparams.par_begin = par_begin;
3576 runparams.par_end = par_end;
3577 if (par_begin + 1 == par_end) {
3579 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3583 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3584 convert<docstring>(par_begin),
3585 convert<docstring>(par_end - 1))
3588 // output paragraphs
3589 if (runparams.flavor == OutputParams::LYX) {
3590 Paragraph const & par = text().paragraphs()[par_begin];
3592 depth_type dt = par.getDepth();
3593 par.write(ods, params(), dt);
3594 os << from_utf8(ods.str());
3595 } else if (runparams.flavor == OutputParams::HTML) {
3597 setMathFlavor(runparams);
3598 xhtmlParagraphs(text(), *this, xs, runparams);
3599 } else if (runparams.flavor == OutputParams::TEXT) {
3601 // FIXME Handles only one paragraph, unlike the others.
3602 // Probably should have some routine with a signature like them.
3603 writePlaintextParagraph(*this,
3604 text().paragraphs()[par_begin], os, runparams, dummy);
3605 } else if (params().isDocBook()) {
3606 docbookParagraphs(text(), *this, os, runparams);
3608 // If we are previewing a paragraph, even if this is the
3609 // child of some other buffer, let's cut the link here,
3610 // so that no concurring settings from the master
3611 // (e.g. branch state) interfere (see #8101).
3613 d->ignore_parent = true;
3614 // We need to validate the Buffer params' features here
3615 // in order to know if we should output polyglossia
3616 // macros (instead of babel macros)
3617 LaTeXFeatures features(*this, params(), runparams);
3618 params().validate(features);
3619 runparams.use_polyglossia = features.usePolyglossia();
3624 // latex or literate
3625 otexstream ots(os, texrow);
3628 latexParagraphs(*this, text(), ots, runparams);
3630 // Restore the parenthood
3632 d->ignore_parent = false;
3636 if (output == FullSource)
3637 os << _("Preview source code");
3638 else if (output == OnlyPreamble)
3639 os << _("Preview preamble");
3640 else if (output == OnlyBody)
3641 os << _("Preview body");
3643 if (runparams.flavor == OutputParams::LYX) {
3645 if (output == FullSource)
3647 else if (output == OnlyPreamble)
3648 params().writeFile(ods);
3649 else if (output == OnlyBody)
3651 os << from_utf8(ods.str());
3652 } else if (runparams.flavor == OutputParams::HTML) {
3653 writeLyXHTMLSource(os, runparams, output);
3654 } else if (runparams.flavor == OutputParams::TEXT) {
3655 if (output == OnlyPreamble) {
3656 os << "% "<< _("Plain text does not have a preamble.");
3658 writePlaintextFile(*this, os, runparams);
3659 } else if (params().isDocBook()) {
3660 writeDocBookSource(os, absFileName(), runparams, output);
3662 // latex or literate
3664 d->texrow.newline();
3665 d->texrow.newline();
3666 otexstream ots(os, d->texrow);
3668 runparams.is_child = true;
3669 writeLaTeXSource(ots, string(), runparams, output);
3675 ErrorList & Buffer::errorList(string const & type) const
3677 return d->errorLists[type];
3681 void Buffer::updateTocItem(std::string const & type,
3682 DocIterator const & dit) const
3685 d->gui_->updateTocItem(type, dit);
3689 void Buffer::structureChanged() const
3692 d->gui_->structureChanged();
3696 void Buffer::errors(string const & err, bool from_master) const
3699 d->gui_->errors(err, from_master);
3703 void Buffer::message(docstring const & msg) const
3706 d->gui_->message(msg);
3710 void Buffer::setBusy(bool on) const
3713 d->gui_->setBusy(on);
3717 void Buffer::updateTitles() const
3720 d->wa_->updateTitles();
3724 void Buffer::resetAutosaveTimers() const
3727 d->gui_->resetAutosaveTimers();
3731 bool Buffer::hasGuiDelegate() const
3737 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3746 class AutoSaveBuffer : public ForkedProcess {
3749 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3750 : buffer_(buffer), fname_(fname) {}
3752 virtual shared_ptr<ForkedProcess> clone() const
3754 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3759 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3760 from_utf8(fname_.absFileName())));
3761 return run(DontWait);
3765 virtual int generateChild();
3767 Buffer const & buffer_;
3772 int AutoSaveBuffer::generateChild()
3774 #if defined(__APPLE__)
3775 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3776 * We should use something else like threads.
3778 * Since I do not know how to determine at run time what is the OS X
3779 * version, I just disable forking altogether for now (JMarc)
3781 pid_t const pid = -1;
3783 // tmp_ret will be located (usually) in /tmp
3784 // will that be a problem?
3785 // Note that this calls ForkedCalls::fork(), so it's
3786 // ok cross-platform.
3787 pid_t const pid = fork();
3788 // If you want to debug the autosave
3789 // you should set pid to -1, and comment out the fork.
3790 if (pid != 0 && pid != -1)
3794 // pid = -1 signifies that lyx was unable
3795 // to fork. But we will do the save
3797 bool failed = false;
3798 TempFile tempfile("lyxautoXXXXXX.lyx");
3799 tempfile.setAutoRemove(false);
3800 FileName const tmp_ret = tempfile.name();
3801 if (!tmp_ret.empty()) {
3802 if (!buffer_.writeFile(tmp_ret))
3804 else if (!tmp_ret.moveTo(fname_))
3810 // failed to write/rename tmp_ret so try writing direct
3811 if (!buffer_.writeFile(fname_)) {
3812 // It is dangerous to do this in the child,
3813 // but safe in the parent, so...
3814 if (pid == -1) // emit message signal.
3815 buffer_.message(_("Autosave failed!"));
3819 if (pid == 0) // we are the child so...
3828 FileName Buffer::getEmergencyFileName() const
3830 return FileName(d->filename.absFileName() + ".emergency");
3834 FileName Buffer::getAutosaveFileName() const
3836 // if the document is unnamed try to save in the backup dir, else
3837 // in the default document path, and as a last try in the filePath,
3838 // which will most often be the temporary directory
3841 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3842 : lyxrc.backupdir_path;
3843 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3846 string const fname = "#" + d->filename.onlyFileName() + "#";
3848 return makeAbsPath(fname, fpath);
3852 void Buffer::removeAutosaveFile() const
3854 FileName const f = getAutosaveFileName();
3860 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3862 FileName const newauto = getAutosaveFileName();
3864 if (newauto != oldauto && oldauto.exists())
3865 if (!oldauto.moveTo(newauto))
3866 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3870 bool Buffer::autoSave() const
3872 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3873 if (buf->d->bak_clean || isReadonly())
3876 message(_("Autosaving current document..."));
3877 buf->d->bak_clean = true;
3879 FileName const fname = getAutosaveFileName();
3880 LASSERT(d->cloned_buffer_, return false);
3882 // If this buffer is cloned, we assume that
3883 // we are running in a separate thread already.
3884 TempFile tempfile("lyxautoXXXXXX.lyx");
3885 tempfile.setAutoRemove(false);
3886 FileName const tmp_ret = tempfile.name();
3887 if (!tmp_ret.empty()) {
3889 // assume successful write of tmp_ret
3890 if (tmp_ret.moveTo(fname))
3893 // failed to write/rename tmp_ret so try writing direct
3894 return writeFile(fname);
3898 void Buffer::setExportStatus(bool e) const
3900 d->doing_export = e;
3901 ListOfBuffers clist = getDescendents();
3902 ListOfBuffers::const_iterator cit = clist.begin();
3903 ListOfBuffers::const_iterator const cen = clist.end();
3904 for (; cit != cen; ++cit)
3905 (*cit)->d->doing_export = e;
3909 bool Buffer::isExporting() const
3911 return d->doing_export;
3915 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3919 return doExport(target, put_in_tempdir, result_file);
3922 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3923 string & result_file) const
3925 bool const update_unincluded =
3926 params().maintain_unincluded_children
3927 && !params().getIncludedChildren().empty();
3929 // (1) export with all included children (omit \includeonly)
3930 if (update_unincluded) {
3931 ExportStatus const status =
3932 doExport(target, put_in_tempdir, true, result_file);
3933 if (status != ExportSuccess)
3936 // (2) export with included children only
3937 return doExport(target, put_in_tempdir, false, result_file);
3941 void Buffer::setMathFlavor(OutputParams & op) const
3943 switch (params().html_math_output) {
3944 case BufferParams::MathML:
3945 op.math_flavor = OutputParams::MathAsMathML;
3947 case BufferParams::HTML:
3948 op.math_flavor = OutputParams::MathAsHTML;
3950 case BufferParams::Images:
3951 op.math_flavor = OutputParams::MathAsImages;
3953 case BufferParams::LaTeX:
3954 op.math_flavor = OutputParams::MathAsLaTeX;
3960 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3961 bool includeall, string & result_file) const
3963 LYXERR(Debug::FILES, "target=" << target);
3964 OutputParams runparams(¶ms().encoding());
3965 string format = target;
3966 string dest_filename;
3967 size_t pos = target.find(' ');
3968 if (pos != string::npos) {
3969 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3970 format = target.substr(0, pos);
3971 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3972 FileName(dest_filename).onlyPath().createPath();
3973 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3975 MarkAsExporting exporting(this);
3976 string backend_format;
3977 runparams.flavor = OutputParams::LATEX;
3978 runparams.linelen = lyxrc.plaintext_linelen;
3979 runparams.includeall = includeall;
3980 vector<string> backs = params().backends();
3981 Converters converters = theConverters();
3982 bool need_nice_file = false;
3983 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3984 // Get shortest path to format
3985 converters.buildGraph();
3986 Graph::EdgePath path;
3987 for (vector<string>::const_iterator it = backs.begin();
3988 it != backs.end(); ++it) {
3989 Graph::EdgePath p = converters.getPath(*it, format);
3990 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3991 backend_format = *it;
3996 if (!put_in_tempdir) {
3997 // Only show this alert if this is an export to a non-temporary
3998 // file (not for previewing).
3999 Alert::error(_("Couldn't export file"), bformat(
4000 _("No information for exporting the format %1$s."),
4001 formats.prettyName(format)));
4003 return ExportNoPathToFormat;
4005 runparams.flavor = converters.getFlavor(path, this);
4006 Graph::EdgePath::const_iterator it = path.begin();
4007 Graph::EdgePath::const_iterator en = path.end();
4008 for (; it != en; ++it)
4009 if (theConverters().get(*it).nice()) {
4010 need_nice_file = true;
4015 backend_format = format;
4016 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4017 // FIXME: Don't hardcode format names here, but use a flag
4018 if (backend_format == "pdflatex")
4019 runparams.flavor = OutputParams::PDFLATEX;
4020 else if (backend_format == "luatex")
4021 runparams.flavor = OutputParams::LUATEX;
4022 else if (backend_format == "dviluatex")
4023 runparams.flavor = OutputParams::DVILUATEX;
4024 else if (backend_format == "xetex")
4025 runparams.flavor = OutputParams::XETEX;
4028 string filename = latexName(false);
4029 filename = addName(temppath(), filename);
4030 filename = changeExtension(filename,
4031 formats.extension(backend_format));
4032 LYXERR(Debug::FILES, "filename=" << filename);
4034 // Plain text backend
4035 if (backend_format == "text") {
4036 runparams.flavor = OutputParams::TEXT;
4037 writePlaintextFile(*this, FileName(filename), runparams);
4040 else if (backend_format == "xhtml") {
4041 runparams.flavor = OutputParams::HTML;
4042 setMathFlavor(runparams);
4043 makeLyXHTMLFile(FileName(filename), runparams);
4044 } else if (backend_format == "lyx")
4045 writeFile(FileName(filename));
4047 else if (params().isDocBook()) {
4048 runparams.nice = !put_in_tempdir;
4049 makeDocBookFile(FileName(filename), runparams);
4052 else if (backend_format == format || need_nice_file) {
4053 runparams.nice = true;
4054 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4055 if (d->cloned_buffer_)
4056 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4059 } else if (!lyxrc.tex_allows_spaces
4060 && contains(filePath(), ' ')) {
4061 Alert::error(_("File name error"),
4062 _("The directory path to the document cannot contain spaces."));
4063 return ExportTexPathHasSpaces;
4065 runparams.nice = false;
4066 bool const success = makeLaTeXFile(
4067 FileName(filename), filePath(), runparams);
4068 if (d->cloned_buffer_)
4069 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4074 string const error_type = (format == "program")
4075 ? "Build" : params().bufferFormat();
4076 ErrorList & error_list = d->errorLists[error_type];
4077 string const ext = formats.extension(format);
4078 FileName const tmp_result_file(changeExtension(filename, ext));
4079 bool const success = converters.convert(this, FileName(filename),
4080 tmp_result_file, FileName(absFileName()), backend_format, format,
4083 // Emit the signal to show the error list or copy it back to the
4084 // cloned Buffer so that it can be emitted afterwards.
4085 if (format != backend_format) {
4086 if (runparams.silent)
4088 else if (d->cloned_buffer_)
4089 d->cloned_buffer_->d->errorLists[error_type] =
4090 d->errorLists[error_type];
4093 // also to the children, in case of master-buffer-view
4094 ListOfBuffers clist = getDescendents();
4095 ListOfBuffers::const_iterator cit = clist.begin();
4096 ListOfBuffers::const_iterator const cen = clist.end();
4097 for (; cit != cen; ++cit) {
4098 if (runparams.silent)
4099 (*cit)->d->errorLists[error_type].clear();
4100 else if (d->cloned_buffer_) {
4101 // Enable reverse search by copying back the
4102 // texrow object to the cloned buffer.
4103 // FIXME: this is not thread safe.
4104 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4105 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4106 (*cit)->d->errorLists[error_type];
4108 (*cit)->errors(error_type, true);
4112 if (d->cloned_buffer_) {
4113 // Enable reverse dvi or pdf to work by copying back the texrow
4114 // object to the cloned buffer.
4115 // FIXME: There is a possibility of concurrent access to texrow
4116 // here from the main GUI thread that should be securized.
4117 d->cloned_buffer_->d->texrow = d->texrow;
4118 string const error_type = params().bufferFormat();
4119 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4123 return ExportConverterError;
4125 if (put_in_tempdir) {
4126 result_file = tmp_result_file.absFileName();
4127 return ExportSuccess;
4130 if (dest_filename.empty())
4131 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4133 result_file = dest_filename;
4134 // We need to copy referenced files (e. g. included graphics
4135 // if format == "dvi") to the result dir.
4136 vector<ExportedFile> const files =
4137 runparams.exportdata->externalFiles(format);
4138 string const dest = runparams.export_folder.empty() ?
4139 onlyPath(result_file) : runparams.export_folder;
4140 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4141 : force_overwrite == ALL_FILES;
4142 CopyStatus status = use_force ? FORCE : SUCCESS;
4144 vector<ExportedFile>::const_iterator it = files.begin();
4145 vector<ExportedFile>::const_iterator const en = files.end();
4146 for (; it != en && status != CANCEL; ++it) {
4147 string const fmt = formats.getFormatFromFile(it->sourceName);
4148 string fixedName = it->exportName;
4149 if (!runparams.export_folder.empty()) {
4150 // Relative pathnames starting with ../ will be sanitized
4151 // if exporting to a different folder
4152 while (fixedName.substr(0, 3) == "../")
4153 fixedName = fixedName.substr(3, fixedName.length() - 3);
4155 FileName fixedFileName = makeAbsPath(fixedName, dest);
4156 fixedFileName.onlyPath().createPath();
4157 status = copyFile(fmt, it->sourceName,
4159 it->exportName, status == FORCE,
4160 runparams.export_folder.empty());
4163 if (status == CANCEL) {
4164 message(_("Document export cancelled."));
4165 return ExportCancel;
4168 if (tmp_result_file.exists()) {
4169 // Finally copy the main file
4170 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4171 : force_overwrite != NO_FILES;
4172 if (status == SUCCESS && use_force)
4174 status = copyFile(format, tmp_result_file,
4175 FileName(result_file), result_file,
4177 if (status == CANCEL) {
4178 message(_("Document export cancelled."));
4179 return ExportCancel;
4181 message(bformat(_("Document exported as %1$s "
4183 formats.prettyName(format),
4184 makeDisplayPath(result_file)));
4187 // This must be a dummy converter like fax (bug 1888)
4188 message(bformat(_("Document exported as %1$s"),
4189 formats.prettyName(format)));
4192 return ExportSuccess;
4196 Buffer::ExportStatus Buffer::preview(string const & format) const
4198 bool const update_unincluded =
4199 params().maintain_unincluded_children
4200 && !params().getIncludedChildren().empty();
4201 return preview(format, update_unincluded);
4205 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4207 MarkAsExporting exporting(this);
4209 // (1) export with all included children (omit \includeonly)
4211 ExportStatus const status = doExport(format, true, true, result_file);
4212 if (status != ExportSuccess)
4215 // (2) export with included children only
4216 ExportStatus const status = doExport(format, true, false, result_file);
4217 if (status != ExportSuccess)
4219 if (!formats.view(*this, FileName(result_file), format))
4220 return PreviewError;
4221 return PreviewSuccess;
4225 Buffer::ReadStatus Buffer::extractFromVC()
4227 bool const found = LyXVC::file_not_found_hook(d->filename);
4229 return ReadFileNotFound;
4230 if (!d->filename.isReadableFile())
4236 Buffer::ReadStatus Buffer::loadEmergency()
4238 FileName const emergencyFile = getEmergencyFileName();
4239 if (!emergencyFile.exists()
4240 || emergencyFile.lastModified() <= d->filename.lastModified())
4241 return ReadFileNotFound;
4243 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4244 docstring const text = bformat(_("An emergency save of the document "
4245 "%1$s exists.\n\nRecover emergency save?"), file);
4247 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4248 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4254 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4255 bool const success = (ret_llf == ReadSuccess);
4258 Alert::warning(_("File is read-only"),
4259 bformat(_("An emergency file is successfully loaded, "
4260 "but the original file %1$s is marked read-only. "
4261 "Please make sure to save the document as a different "
4262 "file."), from_utf8(d->filename.absFileName())));
4265 lyxvc().file_found_hook(d->filename);
4266 str = _("Document was successfully recovered.");
4268 str = _("Document was NOT successfully recovered.");
4269 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4270 makeDisplayPath(emergencyFile.absFileName()));
4272 int const del_emerg =
4273 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4274 _("&Remove"), _("&Keep"));
4275 if (del_emerg == 0) {
4276 emergencyFile.removeFile();
4278 Alert::warning(_("Emergency file deleted"),
4279 _("Do not forget to save your file now!"), true);
4281 return success ? ReadSuccess : ReadEmergencyFailure;
4284 int const del_emerg =
4285 Alert::prompt(_("Delete emergency file?"),
4286 _("Remove emergency file now?"), 1, 1,
4287 _("&Remove"), _("&Keep"));
4289 emergencyFile.removeFile();
4290 return ReadOriginal;
4300 Buffer::ReadStatus Buffer::loadAutosave()
4302 // Now check if autosave file is newer.
4303 FileName const autosaveFile = getAutosaveFileName();
4304 if (!autosaveFile.exists()
4305 || autosaveFile.lastModified() <= d->filename.lastModified())
4306 return ReadFileNotFound;
4308 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4309 docstring const text = bformat(_("The backup of the document %1$s "
4310 "is newer.\n\nLoad the backup instead?"), file);
4311 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4312 _("&Load backup"), _("Load &original"), _("&Cancel"));
4317 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4318 // the file is not saved if we load the autosave file.
4319 if (ret_llf == ReadSuccess) {
4321 Alert::warning(_("File is read-only"),
4322 bformat(_("A backup file is successfully loaded, "
4323 "but the original file %1$s is marked read-only. "
4324 "Please make sure to save the document as a "
4326 from_utf8(d->filename.absFileName())));
4329 lyxvc().file_found_hook(d->filename);
4332 return ReadAutosaveFailure;
4335 // Here we delete the autosave
4336 autosaveFile.removeFile();
4337 return ReadOriginal;
4345 Buffer::ReadStatus Buffer::loadLyXFile()
4347 if (!d->filename.isReadableFile()) {
4348 ReadStatus const ret_rvc = extractFromVC();
4349 if (ret_rvc != ReadSuccess)
4353 ReadStatus const ret_re = loadEmergency();
4354 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4357 ReadStatus const ret_ra = loadAutosave();
4358 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4361 return loadThisLyXFile(d->filename);
4365 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4367 return readFile(fn);
4371 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4373 TeXErrors::Errors::const_iterator it = terr.begin();
4374 TeXErrors::Errors::const_iterator end = terr.end();
4375 ListOfBuffers clist = getDescendents();
4376 ListOfBuffers::const_iterator cen = clist.end();
4378 for (; it != end; ++it) {
4381 int errorRow = it->error_in_line;
4382 Buffer const * buf = 0;
4384 if (it->child_name.empty())
4385 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4387 // The error occurred in a child
4388 ListOfBuffers::const_iterator cit = clist.begin();
4389 for (; cit != cen; ++cit) {
4390 string const child_name =
4391 DocFileName(changeExtension(
4392 (*cit)->absFileName(), "tex")).
4394 if (it->child_name != child_name)
4396 (*cit)->d->texrow.getIdFromRow(errorRow,
4397 id_start, pos_start);
4398 if (id_start != -1) {
4399 buf = d->cloned_buffer_
4400 ? (*cit)->d->cloned_buffer_->d->owner_
4401 : (*cit)->d->owner_;
4412 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4413 } while (found && id_start == id_end && pos_start == pos_end);
4415 if (id_start != id_end) {
4416 // Next registered position is outside the inset where
4417 // the error occurred, so signal end-of-paragraph
4421 errorList.push_back(ErrorItem(it->error_desc,
4422 it->error_text, id_start, pos_start, pos_end, buf));
4427 void Buffer::setBuffersForInsets() const
4429 inset().setBuffer(const_cast<Buffer &>(*this));
4433 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4435 LBUFERR(!text().paragraphs().empty());
4437 // Use the master text class also for child documents
4438 Buffer const * const master = masterBuffer();
4439 DocumentClass const & textclass = master->params().documentClass();
4441 // do this only if we are the top-level Buffer
4442 if (master == this) {
4443 textclass.counters().reset(from_ascii("bibitem"));
4444 reloadBibInfoCache();
4447 // keep the buffers to be children in this set. If the call from the
4448 // master comes back we can see which of them were actually seen (i.e.
4449 // via an InsetInclude). The remaining ones in the set need still be updated.
4450 static std::set<Buffer const *> bufToUpdate;
4451 if (scope == UpdateMaster) {
4452 // If this is a child document start with the master
4453 if (master != this) {
4454 bufToUpdate.insert(this);
4455 master->updateBuffer(UpdateMaster, utype);
4456 // If the master buffer has no gui associated with it, then the TocModel is
4457 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4458 // (bug 5699). The same happens if the master buffer is open in a different
4459 // window. This test catches both possibilities.
4460 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4461 // There remains a problem here: If there is another child open in yet a third
4462 // window, that TOC is not updated. So some more general solution is needed at
4464 if (master->d->gui_ != d->gui_)
4467 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4468 if (bufToUpdate.find(this) == bufToUpdate.end())
4472 // start over the counters in the master
4473 textclass.counters().reset();
4476 // update will be done below for this buffer
4477 bufToUpdate.erase(this);
4479 // update all caches
4480 clearReferenceCache();
4483 Buffer & cbuf = const_cast<Buffer &>(*this);
4486 ParIterator parit = cbuf.par_iterator_begin();
4487 updateBuffer(parit, utype);
4490 // TocBackend update will be done later.
4493 d->bibinfo_cache_valid_ = true;
4494 d->cite_labels_valid_ = true;
4495 cbuf.tocBackend().update(utype == OutputUpdate);
4496 if (scope == UpdateMaster)
4497 cbuf.structureChanged();
4501 static depth_type getDepth(DocIterator const & it)
4503 depth_type depth = 0;
4504 for (size_t i = 0 ; i < it.depth() ; ++i)
4505 if (!it[i].inset().inMathed())
4506 depth += it[i].paragraph().getDepth() + 1;
4507 // remove 1 since the outer inset does not count
4511 static depth_type getItemDepth(ParIterator const & it)
4513 Paragraph const & par = *it;
4514 LabelType const labeltype = par.layout().labeltype;
4516 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4519 // this will hold the lowest depth encountered up to now.
4520 depth_type min_depth = getDepth(it);
4521 ParIterator prev_it = it;
4524 --prev_it.top().pit();
4526 // start of nested inset: go to outer par
4528 if (prev_it.empty()) {
4529 // start of document: nothing to do
4534 // We search for the first paragraph with same label
4535 // that is not more deeply nested.
4536 Paragraph & prev_par = *prev_it;
4537 depth_type const prev_depth = getDepth(prev_it);
4538 if (labeltype == prev_par.layout().labeltype) {
4539 if (prev_depth < min_depth)
4540 return prev_par.itemdepth + 1;
4541 if (prev_depth == min_depth)
4542 return prev_par.itemdepth;
4544 min_depth = min(min_depth, prev_depth);
4545 // small optimization: if we are at depth 0, we won't
4546 // find anything else
4547 if (prev_depth == 0)
4553 static bool needEnumCounterReset(ParIterator const & it)
4555 Paragraph const & par = *it;
4556 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4557 depth_type const cur_depth = par.getDepth();
4558 ParIterator prev_it = it;
4559 while (prev_it.pit()) {
4560 --prev_it.top().pit();
4561 Paragraph const & prev_par = *prev_it;
4562 if (prev_par.getDepth() <= cur_depth)
4563 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4565 // start of nested inset: reset
4570 // set the label of a paragraph. This includes the counters.
4571 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4573 BufferParams const & bp = owner_->masterBuffer()->params();
4574 DocumentClass const & textclass = bp.documentClass();
4575 Paragraph & par = it.paragraph();
4576 Layout const & layout = par.layout();
4577 Counters & counters = textclass.counters();
4579 if (par.params().startOfAppendix()) {
4580 // We want to reset the counter corresponding to toplevel sectioning
4581 Layout const & lay = textclass.getTOCLayout();
4582 docstring const cnt = lay.counter;
4584 counters.reset(cnt);
4585 counters.appendix(true);
4587 par.params().appendix(counters.appendix());
4589 // Compute the item depth of the paragraph
4590 par.itemdepth = getItemDepth(it);
4592 if (layout.margintype == MARGIN_MANUAL) {
4593 if (par.params().labelWidthString().empty())
4594 par.params().labelWidthString(par.expandLabel(layout, bp));
4595 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4596 // we do not need to do anything here, since the empty case is
4597 // handled during export.
4599 par.params().labelWidthString(docstring());
4602 switch(layout.labeltype) {
4603 case LABEL_ITEMIZE: {
4604 // At some point of time we should do something more
4605 // clever here, like:
4606 // par.params().labelString(
4607 // bp.user_defined_bullet(par.itemdepth).getText());
4608 // for now, use a simple hardcoded label
4609 docstring itemlabel;
4610 switch (par.itemdepth) {
4612 itemlabel = char_type(0x2022);
4615 itemlabel = char_type(0x2013);
4618 itemlabel = char_type(0x2217);
4621 itemlabel = char_type(0x2219); // or 0x00b7
4624 par.params().labelString(itemlabel);
4628 case LABEL_ENUMERATE: {
4629 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4631 switch (par.itemdepth) {
4640 enumcounter += "iv";
4643 // not a valid enumdepth...
4647 // Maybe we have to reset the enumeration counter.
4648 if (needEnumCounterReset(it))
4649 counters.reset(enumcounter);
4650 counters.step(enumcounter, utype);
4652 string const & lang = par.getParLanguage(bp)->code();
4653 par.params().labelString(counters.theCounter(enumcounter, lang));
4658 case LABEL_SENSITIVE: {
4659 string const & type = counters.current_float();
4660 docstring full_label;
4662 full_label = owner_->B_("Senseless!!! ");
4664 docstring name = owner_->B_(textclass.floats().getType(type).name());
4665 if (counters.hasCounter(from_utf8(type))) {
4666 string const & lang = par.getParLanguage(bp)->code();
4667 counters.step(from_utf8(type), utype);
4668 full_label = bformat(from_ascii("%1$s %2$s:"),
4670 counters.theCounter(from_utf8(type), lang));
4672 full_label = bformat(from_ascii("%1$s #:"), name);
4674 par.params().labelString(full_label);
4678 case LABEL_NO_LABEL:
4679 par.params().labelString(docstring());
4683 case LABEL_CENTERED:
4684 case LABEL_STATIC: {
4685 docstring const & lcounter = layout.counter;
4686 if (!lcounter.empty()) {
4687 if (layout.toclevel <= bp.secnumdepth
4688 && (layout.latextype != LATEX_ENVIRONMENT
4689 || it.text()->isFirstInSequence(it.pit()))) {
4690 if (counters.hasCounter(lcounter))
4691 counters.step(lcounter, utype);
4692 par.params().labelString(par.expandLabel(layout, bp));
4694 par.params().labelString(docstring());
4696 par.params().labelString(par.expandLabel(layout, bp));
4702 par.params().labelString(par.expandLabel(layout, bp));
4707 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4709 // LASSERT: Is it safe to continue here, or should we just return?
4710 LASSERT(parit.pit() == 0, /**/);
4712 // Set the position of the text in the buffer to be able
4713 // to resolve macros in it.
4714 parit.text()->setMacrocontextPosition(parit);
4716 depth_type maxdepth = 0;
4717 pit_type const lastpit = parit.lastpit();
4718 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4719 // reduce depth if necessary
4720 if (parit->params().depth() > maxdepth) {
4721 /** FIXME: this function is const, but
4722 * nevertheless it modifies the buffer. To be
4723 * cleaner, one should modify the buffer in
4724 * another function, which is actually
4725 * non-const. This would however be costly in
4726 * terms of code duplication.
4728 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4729 parit->params().depth(maxdepth);
4731 maxdepth = parit->getMaxDepthAfter();
4733 if (utype == OutputUpdate) {
4734 // track the active counters
4735 // we have to do this for the master buffer, since the local
4736 // buffer isn't tracking anything.
4737 masterBuffer()->params().documentClass().counters().
4738 setActiveLayout(parit->layout());
4741 // set the counter for this paragraph
4742 d->setLabel(parit, utype);
4745 InsetList::const_iterator iit = parit->insetList().begin();
4746 InsetList::const_iterator end = parit->insetList().end();
4747 for (; iit != end; ++iit) {
4748 parit.pos() = iit->pos;
4749 iit->inset->updateBuffer(parit, utype);
4755 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4756 WordLangTuple & word_lang, docstring_list & suggestions) const
4760 suggestions.clear();
4761 word_lang = WordLangTuple();
4762 bool const to_end = to.empty();
4763 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4764 // OK, we start from here.
4765 for (; from != end; from.forwardPos()) {
4766 // We are only interested in text so remove the math CursorSlice.
4767 while (from.inMathed()) {
4771 // If from is at the end of the document (which is possible
4772 // when leaving the mathed) LyX will crash later otherwise.
4773 if (from.atEnd() || (!to_end && from >= end))
4776 from.paragraph().spellCheck();
4777 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4778 if (SpellChecker::misspelled(res)) {
4783 // Do not increase progress when from == to, otherwise the word
4784 // count will be wrong.
4794 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4796 bool inword = false;
4801 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4802 if (!dit.inTexted()) {
4807 Paragraph const & par = dit.paragraph();
4808 pos_type const pos = dit.pos();
4810 // Copied and adapted from isWordSeparator() in Paragraph
4811 if (pos == dit.lastpos()) {
4814 Inset const * ins = par.getInset(pos);
4815 if (ins && skipNoOutput && !ins->producesOutput()) {
4818 // stop if end of range was skipped
4819 if (!to.atEnd() && dit >= to)
4822 } else if (!par.isDeleted(pos)) {
4823 if (par.isWordSeparator(pos))
4829 if (ins && ins->isLetter())
4831 else if (ins && ins->isSpace())
4834 char_type const c = par.getChar(pos);
4835 if (isPrintableNonspace(c))
4837 else if (isSpace(c))
4847 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4849 d->updateStatistics(from, to, skipNoOutput);
4853 int Buffer::wordCount() const
4855 return d->wordCount();
4859 int Buffer::charCount(bool with_blanks) const
4861 return d->charCount(with_blanks);
4865 Buffer::ReadStatus Buffer::reload()
4868 // c.f. bug http://www.lyx.org/trac/ticket/6587
4869 removeAutosaveFile();
4870 // e.g., read-only status could have changed due to version control
4871 d->filename.refresh();
4872 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4874 // clear parent. this will get reset if need be.
4876 ReadStatus const status = loadLyXFile();
4877 if (status == ReadSuccess) {
4882 message(bformat(_("Document %1$s reloaded."), disp_fn));
4885 message(bformat(_("Could not reload document %1$s."), disp_fn));
4895 bool Buffer::saveAs(FileName const & fn)
4897 FileName const old_name = fileName();
4898 FileName const old_auto = getAutosaveFileName();
4899 bool const old_unnamed = isUnnamed();
4906 // bring the autosave file with us, just in case.
4907 moveAutosaveFile(old_auto);
4908 // validate version control data and
4909 // correct buffer title
4910 lyxvc().file_found_hook(fileName());
4912 // the file has now been saved to the new location.
4913 // we need to check that the locations of child buffers
4915 checkChildBuffers();
4916 checkMasterBuffer();
4920 // reset the old filename and unnamed state
4921 setFileName(old_name);
4922 setUnnamed(old_unnamed);
4928 // FIXME We could do better here, but it is complicated. What would be
4929 // nice is to offer either (a) to save the child buffer to an appropriate
4930 // location, so that it would "move with the master", or else (b) to update
4931 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4932 // complicated, because the code for this lives in GuiView.
4933 void Buffer::checkChildBuffers()
4935 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4936 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4937 for (; it != en; ++it) {
4938 DocIterator dit = it->second;
4939 Buffer * cbuf = const_cast<Buffer *>(it->first);
4940 if (!cbuf || !theBufferList().isLoaded(cbuf))
4942 Inset * inset = dit.nextInset();
4943 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4944 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4945 docstring const & incfile = inset_inc->getParam("filename");
4946 string oldloc = cbuf->absFileName();
4947 string newloc = makeAbsPath(to_utf8(incfile),
4948 onlyPath(absFileName())).absFileName();
4949 if (oldloc == newloc)
4951 // the location of the child file is incorrect.
4952 Alert::warning(_("Included File Invalid"),
4953 bformat(_("Saving this document to a new location has made the file:\n"
4955 "inaccessible. You will need to update the included filename."),
4956 from_utf8(oldloc)));
4958 inset_inc->setChildBuffer(0);
4960 // invalidate cache of children
4961 d->children_positions.clear();
4962 d->position_to_children.clear();
4966 // If a child has been saved under a different name/path, it might have been
4967 // orphaned. Therefore the master needs to be reset (bug 8161).
4968 void Buffer::checkMasterBuffer()
4970 Buffer const * const master = masterBuffer();
4974 // necessary to re-register the child (bug 5873)
4975 // FIXME: clean up updateMacros (here, only
4976 // child registering is needed).
4977 master->updateMacros();
4978 // (re)set master as master buffer, but only
4979 // if we are a real child
4980 if (master->isChild(this))