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;
222 typedef pair<DocIterator, MacroData> ScopeMacro;
223 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225 /// map from the macro name to the position map,
226 /// which maps the macro definition position to the scope and the MacroData.
227 NamePositionScopeMacroMap macros;
228 /// This seem to change the way Buffer::getMacro() works
229 mutable bool macro_lock;
231 /// positions of child buffers in the buffer
232 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235 /// position of children buffers in this buffer
236 BufferPositionMap children_positions;
237 /// map from children inclusion positions to their scope and their buffer
238 PositionScopeBufferMap position_to_children;
240 /// Container for all sort of Buffer dependant errors.
241 map<string, ErrorList> errorLists;
243 /// timestamp and checksum used to test if the file has been externally
244 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
246 unsigned long checksum_;
249 frontend::WorkAreaManager * wa_;
251 frontend::GuiBufferDelegate * gui_;
256 /// A cache for the bibfiles (including bibfiles of loaded child
257 /// documents), needed for appropriate update of natbib labels.
258 mutable support::FileNameList bibfiles_cache_;
260 // FIXME The caching mechanism could be improved. At present, we have a
261 // cache for each Buffer, that caches all the bibliography info for that
262 // Buffer. A more efficient solution would be to have a global cache per
263 // file, and then to construct the Buffer's bibinfo from that.
264 /// A cache for bibliography info
265 mutable BiblioInfo bibinfo_;
266 /// whether the bibinfo cache is valid
267 mutable bool bibinfo_cache_valid_;
268 /// whether the bibfile cache is valid
269 mutable bool bibfile_cache_valid_;
270 /// Cache of timestamps of .bib files
271 map<FileName, time_t> bibfile_status_;
272 /// Indicates whether the bibinfo has changed since the last time
273 /// we ran updateBuffer(), i.e., whether citation labels may need
275 mutable bool cite_labels_valid_;
277 mutable RefCache ref_cache_;
279 /// our Text that should be wrapped in an InsetText
283 PreviewLoader * preview_loader_;
285 /// This is here to force the test to be done whenever parent_buffer
287 Buffer const * parent() const
289 // ignore_parent temporarily "orphans" a buffer
290 // (e.g. if a child is compiled standalone)
293 // if parent_buffer is not loaded, then it has been unloaded,
294 // which means that parent_buffer is an invalid pointer. So we
295 // set it to null in that case.
296 // however, the BufferList doesn't know about cloned buffers, so
297 // they will always be regarded as unloaded. in that case, we hope
299 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
301 return parent_buffer;
305 void setParent(Buffer const * pb)
307 if (parent_buffer == pb)
310 if (!cloned_buffer_ && parent_buffer && pb)
311 LYXERR0("Warning: a buffer should not have two parents!");
313 if (!cloned_buffer_ && parent_buffer) {
314 parent_buffer->invalidateBibfileCache();
315 parent_buffer->invalidateBibinfoCache();
319 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320 /// This one is useful for preview detached in a thread.
321 Buffer const * cloned_buffer_;
323 CloneList * clone_list_;
324 /// are we in the process of exporting this buffer?
325 mutable bool doing_export;
327 /// compute statistics
328 /// \p from initial position
329 /// \p to points to the end position
330 void updateStatistics(DocIterator & from, DocIterator & to,
331 bool skipNoOutput = true);
332 /// statistics accessor functions
333 int wordCount() const
337 int charCount(bool with_blanks) const
340 + (with_blanks ? blank_count_ : 0);
344 /// So we can force access via the accessors.
345 mutable Buffer const * parent_buffer;
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
357 // FIXME This would be the ideal application for a TempDir class (like
358 // TempFile but for directories)
363 Mutex::Locker locker(&mutex);
364 counter = convert<string>(count++);
366 // We are in our own directory. Why bother to mangle name?
367 // In fact I wrote this code to circumvent a problematic behaviour
368 // (bug?) of EMX mkstemp().
369 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
372 if (!tmpfl.createDirectory(0777)) {
373 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
374 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
375 from_utf8(tmpfl.absFileName())));
381 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
382 Buffer const * cloned_buffer)
383 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
384 internal_buffer(false), read_only(readonly_), filename(file),
385 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
386 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
387 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
388 cite_labels_valid_(false), preview_loader_(0),
389 cloned_buffer_(cloned_buffer), clone_list_(0),
390 doing_export(false), parent_buffer(0)
392 if (!cloned_buffer_) {
393 temppath = createBufferTmpDir();
394 lyxvc.setBuffer(owner_);
396 wa_ = new frontend::WorkAreaManager;
399 temppath = cloned_buffer_->d->temppath;
400 file_fully_loaded = true;
401 params = cloned_buffer_->d->params;
402 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
403 bibinfo_ = cloned_buffer_->d->bibinfo_;
404 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
405 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
406 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
407 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
408 unnamed = cloned_buffer_->d->unnamed;
409 internal_buffer = cloned_buffer_->d->internal_buffer;
413 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
414 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
416 LYXERR(Debug::INFO, "Buffer::Buffer()");
418 d->inset = new InsetText(*cloned_buffer->d->inset);
419 d->inset->setBuffer(*this);
420 // FIXME: optimize this loop somewhat, maybe by creating a new
421 // general recursive Inset::setId().
422 DocIterator it = doc_iterator_begin(this);
423 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
424 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
425 it.paragraph().setId(cloned_it.paragraph().id());
427 d->inset = new InsetText(this);
428 d->inset->setAutoBreakRows(true);
429 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
435 LYXERR(Debug::INFO, "Buffer::~Buffer()");
436 // here the buffer should take care that it is
437 // saved properly, before it goes into the void.
439 // GuiView already destroyed
443 // No need to do additional cleanups for internal buffer.
449 // this is in case of recursive includes: we won't try to delete
450 // ourselves as a child.
451 d->clone_list_->erase(this);
452 // loop over children
453 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
454 Impl::BufferPositionMap::iterator end = d->children_positions.end();
455 for (; it != end; ++it) {
456 Buffer * child = const_cast<Buffer *>(it->first);
457 if (d->clone_list_->erase(child))
460 // if we're the master buffer, then we should get rid of the list
463 // If this is not empty, we have leaked something. Worse, one of the
464 // children still has a reference to this list. But we will try to
465 // continue, rather than shut down.
466 LATTEST(d->clone_list_->empty());
467 list<CloneList *>::iterator it =
468 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
469 if (it == cloned_buffers.end()) {
470 // We will leak in this case, but it is safe to continue.
473 cloned_buffers.erase(it);
474 delete d->clone_list_;
476 // FIXME Do we really need to do this right before we delete d?
477 // clear references to children in macro tables
478 d->children_positions.clear();
479 d->position_to_children.clear();
481 // loop over children
482 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
483 Impl::BufferPositionMap::iterator end = d->children_positions.end();
484 for (; it != end; ++it) {
485 Buffer * child = const_cast<Buffer *>(it->first);
486 if (theBufferList().isLoaded(child))
487 theBufferList().releaseChild(this, child);
491 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
492 msg += emergencyWrite();
493 Alert::warning(_("Attempting to close changed document!"), msg);
496 // FIXME Do we really need to do this right before we delete d?
497 // clear references to children in macro tables
498 d->children_positions.clear();
499 d->position_to_children.clear();
501 if (!d->temppath.destroyDirectory()) {
502 Alert::warning(_("Could not remove temporary directory"),
503 bformat(_("Could not remove the temporary directory %1$s"),
504 from_utf8(d->temppath.absFileName())));
513 Buffer * Buffer::cloneFromMaster() const
516 cloned_buffers.push_back(new CloneList);
517 CloneList * clones = cloned_buffers.back();
519 masterBuffer()->cloneWithChildren(bufmap, clones);
521 // make sure we got cloned
522 BufferMap::const_iterator bit = bufmap.find(this);
523 LASSERT(bit != bufmap.end(), return 0);
524 Buffer * cloned_buffer = bit->second;
526 return cloned_buffer;
530 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
532 // have we already been cloned?
533 if (bufmap.find(this) != bufmap.end())
536 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
538 // The clone needs its own DocumentClass, since running updateBuffer() will
539 // modify it, and we would otherwise be sharing it with the original Buffer.
540 buffer_clone->params().makeDocumentClass(true);
542 cap::switchBetweenClasses(
543 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
544 static_cast<InsetText &>(buffer_clone->inset()), el);
546 bufmap[this] = buffer_clone;
547 clones->insert(buffer_clone);
548 buffer_clone->d->clone_list_ = clones;
549 buffer_clone->d->macro_lock = true;
550 buffer_clone->d->children_positions.clear();
552 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
553 // math macro caches need to be rethought and simplified.
554 // I am not sure wether we should handle Buffer cloning here or in BufferList.
555 // Right now BufferList knows nothing about buffer clones.
556 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
557 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
558 for (; it != end; ++it) {
559 DocIterator dit = it->first.clone(buffer_clone);
560 dit.setBuffer(buffer_clone);
561 Buffer * child = const_cast<Buffer *>(it->second.second);
563 child->cloneWithChildren(bufmap, clones);
564 BufferMap::iterator const bit = bufmap.find(child);
565 LASSERT(bit != bufmap.end(), continue);
566 Buffer * child_clone = bit->second;
568 Inset * inset = dit.nextInset();
569 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
570 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
571 inset_inc->setChildBuffer(child_clone);
572 child_clone->d->setParent(buffer_clone);
573 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
574 buffer_clone->setChild(dit, child_clone);
576 buffer_clone->d->macro_lock = false;
581 Buffer * Buffer::cloneBufferOnly() const {
582 cloned_buffers.push_back(new CloneList);
583 CloneList * clones = cloned_buffers.back();
584 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
586 // The clone needs its own DocumentClass, since running updateBuffer() will
587 // modify it, and we would otherwise be sharing it with the original Buffer.
588 buffer_clone->params().makeDocumentClass(true);
590 cap::switchBetweenClasses(
591 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
592 static_cast<InsetText &>(buffer_clone->inset()), el);
594 clones->insert(buffer_clone);
595 buffer_clone->d->clone_list_ = clones;
597 // we won't be cloning the children
598 buffer_clone->d->children_positions.clear();
603 bool Buffer::isClone() const
605 return d->cloned_buffer_;
609 void Buffer::changed(bool update_metrics) const
612 d->wa_->redrawAll(update_metrics);
616 frontend::WorkAreaManager & Buffer::workAreaManager() const
623 Text & Buffer::text() const
625 return d->inset->text();
629 Inset & Buffer::inset() const
635 BufferParams & Buffer::params()
641 BufferParams const & Buffer::params() const
647 BufferParams const & Buffer::masterParams() const
649 if (masterBuffer() == this)
652 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
653 // Copy child authors to the params. We need those pointers.
654 AuthorList const & child_authors = params().authors();
655 AuthorList::Authors::const_iterator it = child_authors.begin();
656 for (; it != child_authors.end(); ++it)
657 mparams.authors().record(*it);
662 double Buffer::fontScalingFactor() const
664 return isExporting() ? 75.0 * params().html_math_img_scale
665 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
669 ParagraphList & Buffer::paragraphs()
671 return text().paragraphs();
675 ParagraphList const & Buffer::paragraphs() const
677 return text().paragraphs();
681 LyXVC & Buffer::lyxvc()
687 LyXVC const & Buffer::lyxvc() const
693 string const Buffer::temppath() const
695 return d->temppath.absFileName();
699 TexRow & Buffer::texrow()
705 TexRow const & Buffer::texrow() const
711 TocBackend & Buffer::tocBackend() const
713 return d->toc_backend;
717 Undo & Buffer::undo()
723 void Buffer::setChild(DocIterator const & dit, Buffer * child)
725 d->children_positions[child] = dit;
729 string Buffer::latexName(bool const no_path) const
731 FileName latex_name =
732 makeLatexName(d->exportFileName());
733 return no_path ? latex_name.onlyFileName()
734 : latex_name.absFileName();
738 FileName Buffer::Impl::exportFileName() const
740 docstring const branch_suffix =
741 params.branchlist().getFileNameSuffix();
742 if (branch_suffix.empty())
745 string const name = filename.onlyFileNameWithoutExt()
746 + to_utf8(branch_suffix);
747 FileName res(filename.onlyPath().absFileName() + "/" + name);
748 res.changeExtension(filename.extension());
754 string Buffer::logName(LogType * type) const
756 string const filename = latexName(false);
758 if (filename.empty()) {
764 string const path = temppath();
766 FileName const fname(addName(temppath(),
767 onlyFileName(changeExtension(filename,
770 // FIXME: how do we know this is the name of the build log?
771 FileName const bname(
772 addName(path, onlyFileName(
773 changeExtension(filename,
774 formats.extension(params().bufferFormat()) + ".out"))));
776 // Also consider the master buffer log file
777 FileName masterfname = fname;
779 if (masterBuffer() != this) {
780 string const mlogfile = masterBuffer()->logName(&mtype);
781 masterfname = FileName(mlogfile);
784 // If no Latex log or Build log is newer, show Build log
785 if (bname.exists() &&
786 ((!fname.exists() && !masterfname.exists())
787 || (fname.lastModified() < bname.lastModified()
788 && masterfname.lastModified() < bname.lastModified()))) {
789 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
792 return bname.absFileName();
793 // If we have a newer master file log or only a master log, show this
794 } else if (fname != masterfname
795 && (!fname.exists() && (masterfname.exists()
796 || fname.lastModified() < masterfname.lastModified()))) {
797 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
800 return masterfname.absFileName();
802 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
805 return fname.absFileName();
809 void Buffer::setReadonly(bool const flag)
811 if (d->read_only != flag) {
818 void Buffer::setFileName(FileName const & fname)
820 bool const changed = fname != d->filename;
823 lyxvc().file_found_hook(fname);
824 setReadonly(d->filename.isReadOnly());
830 int Buffer::readHeader(Lexer & lex)
832 int unknown_tokens = 0;
834 int begin_header_line = -1;
836 // Initialize parameters that may be/go lacking in header:
837 params().branchlist().clear();
838 params().preamble.erase();
839 params().options.erase();
840 params().master.erase();
841 params().float_placement.erase();
842 params().paperwidth.erase();
843 params().paperheight.erase();
844 params().leftmargin.erase();
845 params().rightmargin.erase();
846 params().topmargin.erase();
847 params().bottommargin.erase();
848 params().headheight.erase();
849 params().headsep.erase();
850 params().footskip.erase();
851 params().columnsep.erase();
852 params().fonts_cjk.erase();
853 params().listings_params.clear();
854 params().clearLayoutModules();
855 params().clearRemovedModules();
856 params().clearIncludedChildren();
857 params().pdfoptions().clear();
858 params().indiceslist().clear();
859 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
860 params().isbackgroundcolor = false;
861 params().fontcolor = RGBColor(0, 0, 0);
862 params().isfontcolor = false;
863 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
864 params().boxbgcolor = RGBColor(0xFF, 0, 0);
865 params().html_latex_start.clear();
866 params().html_latex_end.clear();
867 params().html_math_img_scale = 1.0;
868 params().output_sync_macro.erase();
869 params().setLocalLayout(string(), false);
870 params().setLocalLayout(string(), true);
872 for (int i = 0; i < 4; ++i) {
873 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
874 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
877 ErrorList & errorList = d->errorLists["Parse"];
886 if (token == "\\end_header")
890 if (token == "\\begin_header") {
891 begin_header_line = line;
895 LYXERR(Debug::PARSER, "Handling document header token: `"
898 string unknown = params().readToken(lex, token, d->filename.onlyPath());
899 if (!unknown.empty()) {
900 if (unknown[0] != '\\' && token == "\\textclass") {
901 Alert::warning(_("Unknown document class"),
902 bformat(_("Using the default document class, because the "
903 "class %1$s is unknown."), from_utf8(unknown)));
906 docstring const s = bformat(_("Unknown token: "
910 errorList.push_back(ErrorItem(_("Document header error"),
915 if (begin_header_line) {
916 docstring const s = _("\\begin_header is missing");
917 errorList.push_back(ErrorItem(_("Document header error"),
921 params().makeDocumentClass();
923 return unknown_tokens;
928 // changed to be public and have one parameter
929 // Returns true if "\end_document" is not read (Asger)
930 bool Buffer::readDocument(Lexer & lex)
932 ErrorList & errorList = d->errorLists["Parse"];
935 // remove dummy empty par
936 paragraphs().clear();
938 if (!lex.checkFor("\\begin_document")) {
939 docstring const s = _("\\begin_document is missing");
940 errorList.push_back(ErrorItem(_("Document header error"),
946 if (params().output_changes) {
947 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
948 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
949 LaTeXFeatures::isAvailable("xcolor");
951 if (!dvipost && !xcolorulem) {
952 Alert::warning(_("Changes not shown in LaTeX output"),
953 _("Changes will not be highlighted in LaTeX output, "
954 "because neither dvipost nor xcolor/ulem are installed.\n"
955 "Please install these packages or redefine "
956 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
957 } else if (!xcolorulem) {
958 Alert::warning(_("Changes not shown in LaTeX output"),
959 _("Changes will not be highlighted in LaTeX output "
960 "when using pdflatex, because xcolor and ulem are not installed.\n"
961 "Please install both packages or redefine "
962 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
966 if (!parent() && !params().master.empty()) {
967 FileName const master_file = makeAbsPath(params().master,
968 onlyPath(absFileName()));
969 if (isLyXFileName(master_file.absFileName())) {
971 checkAndLoadLyXFile(master_file, true);
973 // necessary e.g. after a reload
974 // to re-register the child (bug 5873)
975 // FIXME: clean up updateMacros (here, only
976 // child registering is needed).
977 master->updateMacros();
978 // set master as master buffer, but only
979 // if we are a real child
980 if (master->isChild(this))
982 // if the master is not fully loaded
983 // it is probably just loading this
984 // child. No warning needed then.
985 else if (master->isFullyLoaded())
986 LYXERR0("The master '"
988 << "' assigned to this document ("
990 << ") does not include "
991 "this document. Ignoring the master assignment.");
996 // assure we have a default index
997 params().indiceslist().addDefault(B_("Index"));
1000 bool const res = text().read(lex, errorList, d->inset);
1002 // inform parent buffer about local macros
1004 Buffer const * pbuf = parent();
1005 UserMacroSet::const_iterator cit = usermacros.begin();
1006 UserMacroSet::const_iterator end = usermacros.end();
1007 for (; cit != end; ++cit)
1008 pbuf->usermacros.insert(*cit);
1012 updateMacroInstances(InternalUpdate);
1017 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1019 Format const * fmt = formats.getFormat(format);
1022 // It is important to use the correct extension here, since some
1023 // converters create a wrong output file otherwise (e.g. html2latex)
1024 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1025 FileName const name(tempfile.name());
1026 ofdocstream os(name.toFilesystemEncoding().c_str());
1027 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1028 bool const success = !(os << contents).fail();
1031 bool converted = false;
1033 params().compressed = false;
1035 // remove dummy empty par
1036 paragraphs().clear();
1038 converted = importFile(format, name, errorList);
1047 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1049 if (!theConverters().isReachable(format, "lyx"))
1052 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1053 FileName const lyx(tempfile.name());
1054 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1055 return readFile(lyx) == ReadSuccess;
1061 bool Buffer::readString(string const & s)
1063 params().compressed = false;
1066 istringstream is(s);
1068 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1069 FileName const fn = tempfile.name();
1072 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1074 if (success && file_format != LYX_FORMAT) {
1075 // We need to call lyx2lyx, so write the input to a file
1076 ofstream os(fn.toFilesystemEncoding().c_str());
1079 // lyxvc in readFile
1080 if (readFile(fn) != ReadSuccess)
1084 if (readDocument(lex))
1090 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1094 if (!lex.setFile(fname)) {
1095 Alert::error(_("File Not Found"),
1096 bformat(_("Unable to open file `%1$s'."),
1097 from_utf8(fn.absFileName())));
1098 return ReadFileNotFound;
1102 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1103 if (ret_plf != ReadSuccess)
1106 if (file_format != LYX_FORMAT) {
1108 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1109 if (ret_clf != ReadSuccess)
1111 return readFile(tmpFile);
1114 // FIXME: InsetInfo needs to know whether the file is under VCS
1115 // during the parse process, so this has to be done before.
1116 lyxvc().file_found_hook(d->filename);
1118 if (readDocument(lex)) {
1119 Alert::error(_("Document format failure"),
1120 bformat(_("%1$s ended unexpectedly, which means"
1121 " that it is probably corrupted."),
1122 from_utf8(fn.absFileName())));
1123 return ReadDocumentFailure;
1126 d->file_fully_loaded = true;
1127 d->read_only = !d->filename.isWritable();
1128 params().compressed = formats.isZippedFile(d->filename);
1134 bool Buffer::isFullyLoaded() const
1136 return d->file_fully_loaded;
1140 void Buffer::setFullyLoaded(bool value)
1142 d->file_fully_loaded = value;
1146 PreviewLoader * Buffer::loader() const
1148 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1150 if (!d->preview_loader_)
1151 d->preview_loader_ = new PreviewLoader(*this);
1152 return d->preview_loader_;
1156 void Buffer::removePreviews() const
1158 delete d->preview_loader_;
1159 d->preview_loader_ = 0;
1163 void Buffer::updatePreviews() const
1165 PreviewLoader * ploader = loader();
1169 InsetIterator it = inset_iterator_begin(*d->inset);
1170 InsetIterator const end = inset_iterator_end(*d->inset);
1171 for (; it != end; ++it)
1172 it->addPreview(it, *ploader);
1174 ploader->startLoading();
1178 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1179 FileName const & fn, int & file_format) const
1181 if(!lex.checkFor("\\lyxformat")) {
1182 Alert::error(_("Document format failure"),
1183 bformat(_("%1$s is not a readable LyX document."),
1184 from_utf8(fn.absFileName())));
1185 return ReadNoLyXFormat;
1191 // LyX formats 217 and earlier were written as 2.17. This corresponds
1192 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1193 // these cases. See also: www.lyx.org/trac/changeset/1313.
1194 size_t dot = tmp_format.find_first_of(".,");
1195 if (dot != string::npos)
1196 tmp_format.erase(dot, 1);
1198 file_format = convert<int>(tmp_format);
1203 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1204 FileName & tmpfile, int from_format)
1206 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1207 tempfile.setAutoRemove(false);
1208 tmpfile = tempfile.name();
1209 if(tmpfile.empty()) {
1210 Alert::error(_("Conversion failed"),
1211 bformat(_("%1$s is from a different"
1212 " version of LyX, but a temporary"
1213 " file for converting it could"
1214 " not be created."),
1215 from_utf8(fn.absFileName())));
1216 return LyX2LyXNoTempFile;
1219 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1220 if (lyx2lyx.empty()) {
1221 Alert::error(_("Conversion script not found"),
1222 bformat(_("%1$s is from a different"
1223 " version of LyX, but the"
1224 " conversion script lyx2lyx"
1225 " could not be found."),
1226 from_utf8(fn.absFileName())));
1227 return LyX2LyXNotFound;
1231 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1232 ostringstream command;
1233 command << os::python()
1234 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1235 << " -t " << convert<string>(LYX_FORMAT)
1236 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1237 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1238 string const command_str = command.str();
1240 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1242 cmd_ret const ret = runCommand(command_str);
1243 if (ret.first != 0) {
1244 if (from_format < LYX_FORMAT) {
1245 Alert::error(_("Conversion script failed"),
1246 bformat(_("%1$s is from an older version"
1247 " of LyX and the lyx2lyx script"
1248 " failed to convert it."),
1249 from_utf8(fn.absFileName())));
1250 return LyX2LyXOlderFormat;
1252 Alert::error(_("Conversion script failed"),
1253 bformat(_("%1$s is from a newer version"
1254 " of LyX and the lyx2lyx script"
1255 " failed to convert it."),
1256 from_utf8(fn.absFileName())));
1257 return LyX2LyXNewerFormat;
1264 // Should probably be moved to somewhere else: BufferView? GuiView?
1265 bool Buffer::save() const
1267 docstring const file = makeDisplayPath(absFileName(), 20);
1268 d->filename.refresh();
1270 // check the read-only status before moving the file as a backup
1271 if (d->filename.exists()) {
1272 bool const read_only = !d->filename.isWritable();
1274 Alert::warning(_("File is read-only"),
1275 bformat(_("The file %1$s cannot be written because it "
1276 "is marked as read-only."), file));
1281 // ask if the disk file has been externally modified (use checksum method)
1282 if (fileName().exists() && isExternallyModified(checksum_method)) {
1284 bformat(_("Document %1$s has been externally modified. "
1285 "Are you sure you want to overwrite this file?"), file);
1286 int const ret = Alert::prompt(_("Overwrite modified file?"),
1287 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1292 // We don't need autosaves in the immediate future. (Asger)
1293 resetAutosaveTimers();
1295 // if the file does not yet exist, none of the backup activity
1296 // that follows is necessary
1297 if (!fileName().exists())
1298 return writeFile(fileName());
1300 // we first write the file to a new name, then move it to its
1301 // proper location once that has been done successfully. that
1302 // way we preserve the original file if something goes wrong.
1303 string const justname = fileName().onlyFileNameWithoutExt();
1304 boost::scoped_ptr<TempFile>
1305 tempfile(new TempFile(fileName().onlyPath(),
1306 justname + "-XXXXXX.lyx"));
1307 bool const symlink = fileName().isSymLink();
1309 tempfile->setAutoRemove(false);
1311 FileName savefile(tempfile->name());
1312 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1313 if (!writeFile(savefile))
1316 // we will set this to false if we fail
1317 bool made_backup = true;
1319 FileName backupName(absFileName() + '~');
1320 if (lyxrc.make_backup) {
1321 if (!lyxrc.backupdir_path.empty()) {
1322 string const mangledName =
1323 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1324 backupName = FileName(addName(lyxrc.backupdir_path,
1328 LYXERR(Debug::FILES, "Backing up original file to " <<
1329 backupName.absFileName());
1330 // Except file is symlink do not copy because of #6587.
1331 // Hard links have bad luck.
1332 made_backup = symlink ?
1333 fileName().copyTo(backupName):
1334 fileName().moveTo(backupName);
1337 Alert::error(_("Backup failure"),
1338 bformat(_("Cannot create backup file %1$s.\n"
1339 "Please check whether the directory exists and is writable."),
1340 from_utf8(backupName.absFileName())));
1341 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1345 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1346 // Only do this if tempfile is not in autoremove mode
1349 // If we have no symlink, we can simply rename the temp file.
1350 // Otherwise, we need to copy it so the symlink stays intact.
1351 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1352 savefile.moveTo(fileName()))
1354 // saveCheckSum() was already called by writeFile(), but the
1355 // time stamp is invalidated by copying/moving
1360 // else we saved the file, but failed to move it to the right location.
1362 if (lyxrc.make_backup && made_backup && !symlink) {
1363 // the original file was moved to filename.lyx~, so it will look
1364 // to the user as if it was deleted. (see bug #9234.) we could try
1365 // to restore it, but that would basically mean trying to do again
1366 // what we just failed to do. better to leave things as they are.
1367 Alert::error(_("Write failure"),
1368 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1369 "But LyX could not move it to:\n %2$s.\n"
1370 "Your original file has been backed up to:\n %3$s"),
1371 from_utf8(savefile.absFileName()),
1372 from_utf8(fileName().absFileName()),
1373 from_utf8(backupName.absFileName())));
1375 // either we did not try to make a backup, or else we tried and failed,
1376 // or else the original file was a symlink, in which case it was copied,
1377 // not moved. so the original file is intact.
1378 Alert::error(_("Write failure"),
1379 bformat(_("Cannot move saved file to:\n %1$s.\n"
1380 "But the file has successfully been saved as:\n %2$s."),
1381 from_utf8(fileName().absFileName()),
1382 from_utf8(savefile.absFileName())));
1388 bool Buffer::writeFile(FileName const & fname) const
1390 if (d->read_only && fname == d->filename)
1393 bool retval = false;
1395 docstring const str = bformat(_("Saving document %1$s..."),
1396 makeDisplayPath(fname.absFileName()));
1399 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1401 if (params().compressed) {
1402 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1403 retval = ofs && write(ofs);
1405 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1406 retval = ofs && write(ofs);
1410 message(str + _(" could not write file!"));
1415 // removeAutosaveFile();
1418 message(str + _(" done."));
1424 docstring Buffer::emergencyWrite()
1426 // No need to save if the buffer has not changed.
1430 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1432 docstring user_message = bformat(
1433 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1435 // We try to save three places:
1436 // 1) Same place as document. Unless it is an unnamed doc.
1438 string s = absFileName();
1441 if (writeFile(FileName(s))) {
1443 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1444 return user_message;
1446 user_message += " " + _("Save failed! Trying again...\n");
1450 // 2) In HOME directory.
1451 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1453 lyxerr << ' ' << s << endl;
1454 if (writeFile(FileName(s))) {
1456 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1457 return user_message;
1460 user_message += " " + _("Save failed! Trying yet again...\n");
1462 // 3) In "/tmp" directory.
1463 // MakeAbsPath to prepend the current
1464 // drive letter on OS/2
1465 s = addName(package().temp_dir().absFileName(), absFileName());
1467 lyxerr << ' ' << s << endl;
1468 if (writeFile(FileName(s))) {
1470 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1471 return user_message;
1474 user_message += " " + _("Save failed! Bummer. Document is lost.");
1477 return user_message;
1481 bool Buffer::write(ostream & ofs) const
1484 // Use the standard "C" locale for file output.
1485 ofs.imbue(locale::classic());
1488 // The top of the file should not be written by params().
1490 // write out a comment in the top of the file
1491 // Important: Keep the version formatting in sync with lyx2lyx and
1492 // tex2lyx (bug 7951)
1493 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1494 << " created this file. For more info see http://www.lyx.org/\n"
1495 << "\\lyxformat " << LYX_FORMAT << "\n"
1496 << "\\begin_document\n";
1498 /// For each author, set 'used' to true if there is a change
1499 /// by this author in the document; otherwise set it to 'false'.
1500 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1501 AuthorList::Authors::const_iterator a_end = params().authors().end();
1502 for (; a_it != a_end; ++a_it)
1503 a_it->setUsed(false);
1505 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1506 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1507 for ( ; it != end; ++it)
1508 it->checkAuthors(params().authors());
1510 // now write out the buffer parameters.
1511 ofs << "\\begin_header\n";
1512 params().writeFile(ofs);
1513 ofs << "\\end_header\n";
1516 ofs << "\n\\begin_body\n";
1518 ofs << "\n\\end_body\n";
1520 // Write marker that shows file is complete
1521 ofs << "\\end_document" << endl;
1523 // Shouldn't really be needed....
1526 // how to check if close went ok?
1527 // Following is an attempt... (BE 20001011)
1529 // good() returns false if any error occured, including some
1530 // formatting error.
1531 // bad() returns true if something bad happened in the buffer,
1532 // which should include file system full errors.
1537 lyxerr << "File was not closed properly." << endl;
1544 bool Buffer::makeLaTeXFile(FileName const & fname,
1545 string const & original_path,
1546 OutputParams const & runparams_in,
1547 OutputWhat output) const
1549 OutputParams runparams = runparams_in;
1551 // This is necessary for LuaTeX/XeTeX with tex fonts.
1552 // See FIXME in BufferParams::encoding()
1553 if (runparams.isFullUnicode())
1554 runparams.encoding = encodings.fromLyXName("utf8-plain");
1556 string const encoding = runparams.encoding->iconvName();
1557 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1560 try { ofs.reset(encoding); }
1561 catch (iconv_codecvt_facet_exception const & e) {
1562 lyxerr << "Caught iconv exception: " << e.what() << endl;
1563 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1564 "verify that the support software for your encoding (%1$s) is "
1565 "properly installed"), from_ascii(encoding)));
1568 if (!openFileWrite(ofs, fname))
1571 ErrorList & errorList = d->errorLists["Export"];
1573 bool failed_export = false;
1574 otexstream os(ofs, d->texrow);
1576 // make sure we are ready to export
1577 // this needs to be done before we validate
1578 // FIXME Do we need to do this all the time? I.e., in children
1579 // of a master we are exporting?
1581 updateMacroInstances(OutputUpdate);
1584 os.texrow().reset();
1585 writeLaTeXSource(os, original_path, runparams, output);
1587 catch (EncodingException const & e) {
1588 docstring const failed(1, e.failed_char);
1590 oss << "0x" << hex << e.failed_char << dec;
1591 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1592 " (code point %2$s)"),
1593 failed, from_utf8(oss.str()));
1594 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1595 "representable in the chosen encoding.\n"
1596 "Changing the document encoding to utf8 could help."),
1597 e.par_id, e.pos, e.pos + 1));
1598 failed_export = true;
1600 catch (iconv_codecvt_facet_exception const & e) {
1601 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1602 _(e.what()), -1, 0, 0));
1603 failed_export = true;
1605 catch (exception const & e) {
1606 errorList.push_back(ErrorItem(_("conversion failed"),
1607 _(e.what()), -1, 0, 0));
1608 failed_export = true;
1611 lyxerr << "Caught some really weird exception..." << endl;
1617 failed_export = true;
1618 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1621 if (runparams_in.silent)
1625 return !failed_export;
1629 void Buffer::writeLaTeXSource(otexstream & os,
1630 string const & original_path,
1631 OutputParams const & runparams_in,
1632 OutputWhat output) const
1634 // The child documents, if any, shall be already loaded at this point.
1636 OutputParams runparams = runparams_in;
1638 // If we are compiling a file standalone, even if this is the
1639 // child of some other buffer, let's cut the link here, so the
1640 // file is really independent and no concurring settings from
1641 // the master (e.g. branch state) interfere (see #8100).
1642 if (!runparams.is_child)
1643 d->ignore_parent = true;
1645 // Classify the unicode characters appearing in math insets
1646 BufferEncodings::initUnicodeMath(*this);
1648 // validate the buffer.
1649 LYXERR(Debug::LATEX, " Validating buffer...");
1650 LaTeXFeatures features(*this, params(), runparams);
1652 // This is only set once per document (in master)
1653 if (!runparams.is_child)
1654 runparams.use_polyglossia = features.usePolyglossia();
1655 LYXERR(Debug::LATEX, " Buffer validation done.");
1657 bool const output_preamble =
1658 output == FullSource || output == OnlyPreamble;
1659 bool const output_body =
1660 output == FullSource || output == OnlyBody;
1662 // The starting paragraph of the coming rows is the
1663 // first paragraph of the document. (Asger)
1664 if (output_preamble && runparams.nice) {
1665 os << "%% LyX " << lyx_version << " created this file. "
1666 "For more info, see http://www.lyx.org/.\n"
1667 "%% Do not edit unless you really know what "
1670 LYXERR(Debug::INFO, "lyx document header finished");
1672 // There are a few differences between nice LaTeX and usual files:
1673 // usual files have \batchmode and special input@path to allow
1674 // inclusion of figures specified by an explicitly relative path
1675 // (i.e., a path starting with './' or '../') with either \input or
1676 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1677 // input@path is set when the actual parameter original_path is set.
1678 // This is done for usual tex-file, but not for nice-latex-file.
1679 // (Matthias 250696)
1680 // Note that input@path is only needed for something the user does
1681 // in the preamble, included .tex files or ERT, files included by
1682 // LyX work without it.
1683 if (output_preamble) {
1684 if (!runparams.nice) {
1685 // code for usual, NOT nice-latex-file
1686 os << "\\batchmode\n"; // changed from \nonstopmode
1688 if (!original_path.empty()) {
1690 // We don't know the encoding of inputpath
1691 docstring const inputpath = from_utf8(original_path);
1692 docstring uncodable_glyphs;
1693 Encoding const * const enc = runparams.encoding;
1695 for (size_t n = 0; n < inputpath.size(); ++n) {
1696 if (!enc->encodable(inputpath[n])) {
1697 docstring const glyph(1, inputpath[n]);
1698 LYXERR0("Uncodable character '"
1700 << "' in input path!");
1701 uncodable_glyphs += glyph;
1706 // warn user if we found uncodable glyphs.
1707 if (!uncodable_glyphs.empty()) {
1708 frontend::Alert::warning(
1709 _("Uncodable character in file path"),
1711 _("The path of your document\n"
1713 "contains glyphs that are unknown "
1714 "in the current document encoding "
1715 "(namely %2$s). This may result in "
1716 "incomplete output, unless "
1717 "TEXINPUTS contains the document "
1718 "directory and you don't use "
1719 "explicitly relative paths (i.e., "
1720 "paths starting with './' or "
1721 "'../') in the preamble or in ERT."
1722 "\n\nIn case of problems, choose "
1723 "an appropriate document encoding\n"
1724 "(such as utf8) or change the "
1726 inputpath, uncodable_glyphs));
1729 support::latex_path(original_path);
1730 if (contains(docdir, '#')) {
1731 docdir = subst(docdir, "#", "\\#");
1732 os << "\\catcode`\\#=11"
1733 "\\def\\#{#}\\catcode`\\#=6\n";
1735 if (contains(docdir, '%')) {
1736 docdir = subst(docdir, "%", "\\%");
1737 os << "\\catcode`\\%=11"
1738 "\\def\\%{%}\\catcode`\\%=14\n";
1740 os << "\\makeatletter\n"
1741 << "\\def\\input@path{{"
1742 << docdir << "/}}\n"
1743 << "\\makeatother\n";
1747 // get parent macros (if this buffer has a parent) which will be
1748 // written at the document begin further down.
1749 MacroSet parentMacros;
1750 listParentMacros(parentMacros, features);
1752 // Write the preamble
1753 runparams.use_babel = params().writeLaTeX(os, features,
1754 d->filename.onlyPath());
1756 // Japanese might be required only in some children of a document,
1757 // but once required, we must keep use_japanese true.
1758 runparams.use_japanese |= features.isRequired("japanese");
1761 // Restore the parenthood if needed
1762 if (!runparams.is_child)
1763 d->ignore_parent = false;
1768 os << "\\begin{document}\n";
1770 // output the parent macros
1771 MacroSet::iterator it = parentMacros.begin();
1772 MacroSet::iterator end = parentMacros.end();
1773 for (; it != end; ++it) {
1774 int num_lines = (*it)->write(os.os(), true);
1775 os.texrow().newlines(num_lines);
1778 } // output_preamble
1780 os.texrow().start(paragraphs().begin()->id(), 0);
1782 LYXERR(Debug::INFO, "preamble finished, now the body.");
1785 latexParagraphs(*this, text(), os, runparams);
1787 // Restore the parenthood if needed
1788 if (!runparams.is_child)
1789 d->ignore_parent = false;
1791 // add this just in case after all the paragraphs
1794 if (output_preamble) {
1795 os << "\\end{document}\n";
1796 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1798 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1800 runparams_in.encoding = runparams.encoding;
1802 // Just to be sure. (Asger)
1803 os.texrow().newline();
1805 //for (int i = 0; i<d->texrow.rows(); i++) {
1807 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1808 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1811 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1812 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1816 void Buffer::makeDocBookFile(FileName const & fname,
1817 OutputParams const & runparams,
1818 OutputWhat output) const
1820 LYXERR(Debug::LATEX, "makeDocBookFile...");
1823 if (!openFileWrite(ofs, fname))
1826 // make sure we are ready to export
1827 // this needs to be done before we validate
1829 updateMacroInstances(OutputUpdate);
1831 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1835 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1839 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1840 OutputParams const & runparams,
1841 OutputWhat output) const
1843 LaTeXFeatures features(*this, params(), runparams);
1848 DocumentClass const & tclass = params().documentClass();
1849 string const top_element = tclass.latexname();
1851 bool const output_preamble =
1852 output == FullSource || output == OnlyPreamble;
1853 bool const output_body =
1854 output == FullSource || output == OnlyBody;
1856 if (output_preamble) {
1857 if (runparams.flavor == OutputParams::XML)
1858 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1861 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1864 if (! tclass.class_header().empty())
1865 os << from_ascii(tclass.class_header());
1866 else if (runparams.flavor == OutputParams::XML)
1867 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1868 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1870 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1872 docstring preamble = from_utf8(params().preamble);
1873 if (runparams.flavor != OutputParams::XML ) {
1874 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1875 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1876 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1877 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1880 string const name = runparams.nice
1881 ? changeExtension(absFileName(), ".sgml") : fname;
1882 preamble += features.getIncludedFiles(name);
1883 preamble += features.getLyXSGMLEntities();
1885 if (!preamble.empty()) {
1886 os << "\n [ " << preamble << " ]";
1892 string top = top_element;
1894 if (runparams.flavor == OutputParams::XML)
1895 top += params().language->code();
1897 top += params().language->code().substr(0, 2);
1900 if (!params().options.empty()) {
1902 top += params().options;
1905 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1906 << " file was created by LyX " << lyx_version
1907 << "\n See http://www.lyx.org/ for more information -->\n";
1909 params().documentClass().counters().reset();
1911 sgml::openTag(os, top);
1913 docbookParagraphs(text(), *this, os, runparams);
1914 sgml::closeTag(os, top_element);
1919 void Buffer::makeLyXHTMLFile(FileName const & fname,
1920 OutputParams const & runparams) const
1922 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1925 if (!openFileWrite(ofs, fname))
1928 // make sure we are ready to export
1929 // this has to be done before we validate
1930 updateBuffer(UpdateMaster, OutputUpdate);
1931 updateMacroInstances(OutputUpdate);
1933 writeLyXHTMLSource(ofs, runparams, FullSource);
1937 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1941 void Buffer::writeLyXHTMLSource(odocstream & os,
1942 OutputParams const & runparams,
1943 OutputWhat output) const
1945 LaTeXFeatures features(*this, params(), runparams);
1947 d->bibinfo_.makeCitationLabels(*this);
1949 bool const output_preamble =
1950 output == FullSource || output == OnlyPreamble;
1951 bool const output_body =
1952 output == FullSource || output == OnlyBody || output == IncludedFile;
1954 if (output_preamble) {
1955 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1956 << "<!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"
1957 // FIXME Language should be set properly.
1958 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1960 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1961 // FIXME Presumably need to set this right
1962 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1964 docstring const & doctitle = features.htmlTitle();
1966 << (doctitle.empty() ?
1967 from_ascii("LyX Document") :
1968 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1971 docstring styles = features.getTClassHTMLPreamble();
1972 if (!styles.empty())
1973 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1975 styles = from_utf8(features.getPreambleSnippets());
1976 if (!styles.empty())
1977 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1979 // we will collect CSS information in a stream, and then output it
1980 // either here, as part of the header, or else in a separate file.
1981 odocstringstream css;
1982 styles = from_utf8(features.getCSSSnippets());
1983 if (!styles.empty())
1984 css << "/* LyX Provided Styles */\n" << styles << '\n';
1986 styles = features.getTClassHTMLStyles();
1987 if (!styles.empty())
1988 css << "/* Layout-provided Styles */\n" << styles << '\n';
1990 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1991 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1992 if (needfg || needbg) {
1993 css << "\nbody {\n";
1996 << from_ascii(X11hexname(params().fontcolor))
1999 css << " background-color: "
2000 << from_ascii(X11hexname(params().backgroundcolor))
2005 docstring const dstyles = css.str();
2006 if (!dstyles.empty()) {
2007 bool written = false;
2008 if (params().html_css_as_file) {
2009 // open a file for CSS info
2011 string const fcssname = addName(temppath(), "docstyle.css");
2012 FileName const fcssfile = FileName(fcssname);
2013 if (openFileWrite(ocss, fcssfile)) {
2017 // write link to header
2018 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2020 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2023 // we are here if the CSS is supposed to be written to the header
2024 // or if we failed to write it to an external file.
2026 os << "<style type='text/css'>\n"
2035 bool const output_body_tag = (output != IncludedFile);
2036 if (output_body_tag)
2039 if (output != IncludedFile)
2040 // if we're an included file, the counters are in the master.
2041 params().documentClass().counters().reset();
2042 xhtmlParagraphs(text(), *this, xs, runparams);
2043 if (output_body_tag)
2047 if (output_preamble)
2052 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2053 // Other flags: -wall -v0 -x
2054 int Buffer::runChktex()
2058 // get LaTeX-Filename
2059 FileName const path(temppath());
2060 string const name = addName(path.absFileName(), latexName());
2061 string const org_path = filePath();
2063 PathChanger p(path); // path to LaTeX file
2064 message(_("Running chktex..."));
2066 // Generate the LaTeX file if neccessary
2067 OutputParams runparams(¶ms().encoding());
2068 runparams.flavor = OutputParams::LATEX;
2069 runparams.nice = false;
2070 runparams.linelen = lyxrc.plaintext_linelen;
2071 makeLaTeXFile(FileName(name), org_path, runparams);
2074 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2075 int const res = chktex.run(terr); // run chktex
2078 Alert::error(_("chktex failure"),
2079 _("Could not run chktex successfully."));
2081 ErrorList & errlist = d->errorLists["ChkTeX"];
2083 bufferErrors(terr, errlist);
2088 if (runparams.silent)
2089 d->errorLists["ChkTeX"].clear();
2097 void Buffer::validate(LaTeXFeatures & features) const
2099 // Validate the buffer params, but not for included
2100 // files, since they also use the parent buffer's
2102 if (!features.runparams().is_child)
2103 params().validate(features);
2105 for_each(paragraphs().begin(), paragraphs().end(),
2106 bind(&Paragraph::validate, _1, ref(features)));
2108 if (lyxerr.debugging(Debug::LATEX)) {
2109 features.showStruct();
2114 void Buffer::getLabelList(vector<docstring> & list) const
2116 // If this is a child document, use the master's list instead.
2118 masterBuffer()->getLabelList(list);
2123 Toc & toc = d->toc_backend.toc("label");
2124 TocIterator toc_it = toc.begin();
2125 TocIterator end = toc.end();
2126 for (; toc_it != end; ++toc_it) {
2127 if (toc_it->depth() == 0)
2128 list.push_back(toc_it->str());
2133 void Buffer::updateBibfilesCache(UpdateScope scope) const
2135 // FIXME This is probably unnecssary, given where we call this.
2136 // If this is a child document, use the parent's cache instead.
2137 if (parent() && scope != UpdateChildOnly) {
2138 masterBuffer()->updateBibfilesCache();
2142 d->bibfiles_cache_.clear();
2143 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2144 if (it->lyxCode() == BIBTEX_CODE) {
2145 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2146 support::FileNameList const bibfiles = inset.getBibFiles();
2147 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2150 } else if (it->lyxCode() == INCLUDE_CODE) {
2151 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2152 Buffer const * const incbuf = inset.getChildBuffer();
2155 support::FileNameList const & bibfiles =
2156 incbuf->getBibfilesCache(UpdateChildOnly);
2157 if (!bibfiles.empty()) {
2158 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2164 d->bibfile_cache_valid_ = true;
2165 d->bibinfo_cache_valid_ = false;
2166 d->cite_labels_valid_ = false;
2170 void Buffer::invalidateBibinfoCache() const
2172 d->bibinfo_cache_valid_ = false;
2173 d->cite_labels_valid_ = false;
2174 // also invalidate the cache for the parent buffer
2175 Buffer const * const pbuf = d->parent();
2177 pbuf->invalidateBibinfoCache();
2181 void Buffer::invalidateBibfileCache() const
2183 d->bibfile_cache_valid_ = false;
2184 d->bibinfo_cache_valid_ = false;
2185 d->cite_labels_valid_ = false;
2186 // also invalidate the cache for the parent buffer
2187 Buffer const * const pbuf = d->parent();
2189 pbuf->invalidateBibfileCache();
2193 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2195 // FIXME This is probably unnecessary, given where we call this.
2196 // If this is a child document, use the master's cache instead.
2197 Buffer const * const pbuf = masterBuffer();
2198 if (pbuf != this && scope != UpdateChildOnly)
2199 return pbuf->getBibfilesCache();
2201 if (!d->bibfile_cache_valid_)
2202 this->updateBibfilesCache(scope);
2204 return d->bibfiles_cache_;
2208 BiblioInfo const & Buffer::masterBibInfo() const
2210 Buffer const * const tmp = masterBuffer();
2212 return tmp->masterBibInfo();
2217 void Buffer::checkIfBibInfoCacheIsValid() const
2219 // use the master's cache
2220 Buffer const * const tmp = masterBuffer();
2222 tmp->checkIfBibInfoCacheIsValid();
2226 // compare the cached timestamps with the actual ones.
2227 FileNameList const & bibfiles_cache = getBibfilesCache();
2228 FileNameList::const_iterator ei = bibfiles_cache.begin();
2229 FileNameList::const_iterator en = bibfiles_cache.end();
2230 for (; ei != en; ++ ei) {
2231 time_t lastw = ei->lastModified();
2232 time_t prevw = d->bibfile_status_[*ei];
2233 if (lastw != prevw) {
2234 d->bibinfo_cache_valid_ = false;
2235 d->cite_labels_valid_ = false;
2236 d->bibfile_status_[*ei] = lastw;
2242 void Buffer::reloadBibInfoCache() const
2244 // use the master's cache
2245 Buffer const * const tmp = masterBuffer();
2247 tmp->reloadBibInfoCache();
2251 checkIfBibInfoCacheIsValid();
2252 if (d->bibinfo_cache_valid_)
2255 d->bibinfo_.clear();
2257 d->bibinfo_cache_valid_ = true;
2261 void Buffer::collectBibKeys() const
2263 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2264 it->collectBibKeys(it);
2268 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2270 Buffer const * tmp = masterBuffer();
2271 BiblioInfo & masterbi = (tmp == this) ?
2272 d->bibinfo_ : tmp->d->bibinfo_;
2273 masterbi.mergeBiblioInfo(bi);
2277 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2279 Buffer const * tmp = masterBuffer();
2280 BiblioInfo & masterbi = (tmp == this) ?
2281 d->bibinfo_ : tmp->d->bibinfo_;
2286 void Buffer::makeCitationLabels() const
2288 Buffer const * const master = masterBuffer();
2289 return d->bibinfo_.makeCitationLabels(*master);
2293 bool Buffer::citeLabelsValid() const
2295 return masterBuffer()->d->cite_labels_valid_;
2299 void Buffer::removeBiblioTempFiles() const
2301 // We remove files that contain LaTeX commands specific to the
2302 // particular bibliographic style being used, in order to avoid
2303 // LaTeX errors when we switch style.
2304 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2305 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2306 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2307 aux_file.removeFile();
2308 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2309 bbl_file.removeFile();
2310 // Also for the parent buffer
2311 Buffer const * const pbuf = parent();
2313 pbuf->removeBiblioTempFiles();
2317 bool Buffer::isDepClean(string const & name) const
2319 DepClean::const_iterator const it = d->dep_clean.find(name);
2320 if (it == d->dep_clean.end())
2326 void Buffer::markDepClean(string const & name)
2328 d->dep_clean[name] = true;
2332 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2335 // FIXME? if there is an Buffer LFUN that can be dispatched even
2336 // if internal, put a switch '(cmd.action)' here.
2342 switch (cmd.action()) {
2344 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2345 flag.setOnOff(isReadonly());
2348 // FIXME: There is need for a command-line import.
2349 //case LFUN_BUFFER_IMPORT:
2351 case LFUN_BUFFER_AUTO_SAVE:
2354 case LFUN_BUFFER_EXPORT_CUSTOM:
2355 // FIXME: Nothing to check here?
2358 case LFUN_BUFFER_EXPORT: {
2359 docstring const arg = cmd.argument();
2360 if (arg == "custom") {
2364 string format = to_utf8(arg);
2365 size_t pos = format.find(' ');
2366 if (pos != string::npos)
2367 format = format.substr(0, pos);
2368 enable = params().isExportable(format);
2370 flag.message(bformat(
2371 _("Don't know how to export to format: %1$s"), arg));
2375 case LFUN_BUFFER_CHKTEX:
2376 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2379 case LFUN_BUILD_PROGRAM:
2380 enable = params().isExportable("program");
2383 case LFUN_BRANCH_ACTIVATE:
2384 case LFUN_BRANCH_DEACTIVATE:
2385 case LFUN_BRANCH_MASTER_ACTIVATE:
2386 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2387 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2388 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2389 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2390 : params().branchlist();
2391 docstring const branchName = cmd.argument();
2392 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2396 case LFUN_BRANCH_ADD:
2397 case LFUN_BRANCHES_RENAME:
2398 case LFUN_BUFFER_PRINT:
2399 // if no Buffer is present, then of course we won't be called!
2402 case LFUN_BUFFER_LANGUAGE:
2403 enable = !isReadonly();
2409 flag.setEnabled(enable);
2414 void Buffer::dispatch(string const & command, DispatchResult & result)
2416 return dispatch(lyxaction.lookupFunc(command), result);
2420 // NOTE We can end up here even if we have no GUI, because we are called
2421 // by LyX::exec to handled command-line requests. So we may need to check
2422 // whether we have a GUI or not. The boolean use_gui holds this information.
2423 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2426 // FIXME? if there is an Buffer LFUN that can be dispatched even
2427 // if internal, put a switch '(cmd.action())' here.
2428 dr.dispatched(false);
2431 string const argument = to_utf8(func.argument());
2432 // We'll set this back to false if need be.
2433 bool dispatched = true;
2434 undo().beginUndoGroup();
2436 switch (func.action()) {
2437 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2438 if (lyxvc().inUse()) {
2439 string log = lyxvc().toggleReadOnly();
2444 setReadonly(!isReadonly());
2447 case LFUN_BUFFER_EXPORT: {
2448 ExportStatus const status = doExport(argument, false);
2449 dr.setError(status != ExportSuccess);
2450 if (status != ExportSuccess)
2451 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2456 case LFUN_BUILD_PROGRAM: {
2457 ExportStatus const status = doExport("program", true);
2458 dr.setError(status != ExportSuccess);
2459 if (status != ExportSuccess)
2460 dr.setMessage(_("Error generating literate programming code."));
2464 case LFUN_BUFFER_CHKTEX:
2468 case LFUN_BUFFER_EXPORT_CUSTOM: {
2470 string command = split(argument, format_name, ' ');
2471 Format const * format = formats.getFormat(format_name);
2473 lyxerr << "Format \"" << format_name
2474 << "\" not recognized!"
2479 // The name of the file created by the conversion process
2482 // Output to filename
2483 if (format->name() == "lyx") {
2484 string const latexname = latexName(false);
2485 filename = changeExtension(latexname,
2486 format->extension());
2487 filename = addName(temppath(), filename);
2489 if (!writeFile(FileName(filename)))
2493 doExport(format_name, true, filename);
2496 // Substitute $$FName for filename
2497 if (!contains(command, "$$FName"))
2498 command = "( " + command + " ) < $$FName";
2499 command = subst(command, "$$FName", filename);
2501 // Execute the command in the background
2503 call.startscript(Systemcall::DontWait, command, filePath());
2507 // FIXME: There is need for a command-line import.
2509 case LFUN_BUFFER_IMPORT:
2514 case LFUN_BUFFER_AUTO_SAVE:
2516 resetAutosaveTimers();
2519 case LFUN_BRANCH_ACTIVATE:
2520 case LFUN_BRANCH_DEACTIVATE:
2521 case LFUN_BRANCH_MASTER_ACTIVATE:
2522 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2523 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2524 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2525 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2528 docstring const branch_name = func.argument();
2529 // the case without a branch name is handled elsewhere
2530 if (branch_name.empty()) {
2534 Branch * branch = buf->params().branchlist().find(branch_name);
2536 LYXERR0("Branch " << branch_name << " does not exist.");
2538 docstring const msg =
2539 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2543 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2544 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2545 if (branch->isSelected() != activate) {
2546 buf->undo().recordUndoFullDocument(CursorData());
2547 branch->setSelected(activate);
2549 dr.screenUpdate(Update::Force);
2550 dr.forceBufferUpdate();
2555 case LFUN_BRANCH_ADD: {
2556 docstring branch_name = func.argument();
2557 if (branch_name.empty()) {
2561 BranchList & branch_list = params().branchlist();
2562 vector<docstring> const branches =
2563 getVectorFromString(branch_name, branch_list.separator());
2565 for (vector<docstring>::const_iterator it = branches.begin();
2566 it != branches.end(); ++it) {
2568 Branch * branch = branch_list.find(branch_name);
2570 LYXERR0("Branch " << branch_name << " already exists.");
2574 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2576 undo().recordUndoFullDocument(CursorData());
2577 branch_list.add(branch_name);
2578 branch = branch_list.find(branch_name);
2579 string const x11hexname = X11hexname(branch->color());
2580 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2581 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2583 dr.screenUpdate(Update::Force);
2591 case LFUN_BRANCHES_RENAME: {
2592 if (func.argument().empty())
2595 docstring const oldname = from_utf8(func.getArg(0));
2596 docstring const newname = from_utf8(func.getArg(1));
2597 InsetIterator it = inset_iterator_begin(inset());
2598 InsetIterator const end = inset_iterator_end(inset());
2599 bool success = false;
2600 for (; it != end; ++it) {
2601 if (it->lyxCode() == BRANCH_CODE) {
2602 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2603 if (ins.branch() == oldname) {
2604 undo().recordUndo(CursorData(it));
2605 ins.rename(newname);
2610 if (it->lyxCode() == INCLUDE_CODE) {
2611 // get buffer of external file
2612 InsetInclude const & ins =
2613 static_cast<InsetInclude const &>(*it);
2614 Buffer * child = ins.getChildBuffer();
2617 child->dispatch(func, dr);
2622 dr.screenUpdate(Update::Force);
2623 dr.forceBufferUpdate();
2628 case LFUN_BUFFER_PRINT: {
2629 // we'll assume there's a problem until we succeed
2631 string target = func.getArg(0);
2632 string target_name = func.getArg(1);
2633 string command = func.getArg(2);
2636 || target_name.empty()
2637 || command.empty()) {
2638 LYXERR0("Unable to parse " << func.argument());
2639 docstring const msg =
2640 bformat(_("Unable to parse \"%1$s\""), func.argument());
2644 if (target != "printer" && target != "file") {
2645 LYXERR0("Unrecognized target \"" << target << '"');
2646 docstring const msg =
2647 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2652 if (doExport("dvi", true) != ExportSuccess) {
2653 showPrintError(absFileName());
2654 dr.setMessage(_("Error exporting to DVI."));
2658 // Push directory path.
2659 string const path = temppath();
2660 // Prevent the compiler from optimizing away p
2664 // there are three cases here:
2665 // 1. we print to a file
2666 // 2. we print directly to a printer
2667 // 3. we print using a spool command (print to file first)
2670 string const dviname = changeExtension(latexName(true), "dvi");
2672 if (target == "printer") {
2673 if (!lyxrc.print_spool_command.empty()) {
2674 // case 3: print using a spool
2675 string const psname = changeExtension(dviname,".ps");
2676 command += ' ' + lyxrc.print_to_file
2679 + quoteName(dviname);
2681 string command2 = lyxrc.print_spool_command + ' ';
2682 if (target_name != "default") {
2683 command2 += lyxrc.print_spool_printerprefix
2687 command2 += quoteName(psname);
2689 // If successful, then spool command
2690 res = one.startscript(Systemcall::Wait, command,
2694 // If there's no GUI, we have to wait on this command. Otherwise,
2695 // LyX deletes the temporary directory, and with it the spooled
2696 // file, before it can be printed!!
2697 Systemcall::Starttype stype = use_gui ?
2698 Systemcall::DontWait : Systemcall::Wait;
2699 res = one.startscript(stype, command2,
2703 // case 2: print directly to a printer
2704 if (target_name != "default")
2705 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2707 Systemcall::Starttype stype = use_gui ?
2708 Systemcall::DontWait : Systemcall::Wait;
2709 res = one.startscript(stype, command +
2710 quoteName(dviname), filePath());
2714 // case 1: print to a file
2715 FileName const filename(makeAbsPath(target_name, filePath()));
2716 FileName const dvifile(makeAbsPath(dviname, path));
2717 if (filename.exists()) {
2718 docstring text = bformat(
2719 _("The file %1$s already exists.\n\n"
2720 "Do you want to overwrite that file?"),
2721 makeDisplayPath(filename.absFileName()));
2722 if (Alert::prompt(_("Overwrite file?"),
2723 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2726 command += ' ' + lyxrc.print_to_file
2727 + quoteName(filename.toFilesystemEncoding())
2729 + quoteName(dvifile.toFilesystemEncoding());
2731 Systemcall::Starttype stype = use_gui ?
2732 Systemcall::DontWait : Systemcall::Wait;
2733 res = one.startscript(stype, command, filePath());
2739 dr.setMessage(_("Error running external commands."));
2740 showPrintError(absFileName());
2749 dr.dispatched(dispatched);
2750 undo().endUndoGroup();
2754 void Buffer::changeLanguage(Language const * from, Language const * to)
2756 LASSERT(from, return);
2757 LASSERT(to, return);
2759 for_each(par_iterator_begin(),
2761 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2765 bool Buffer::isMultiLingual() const
2767 ParConstIterator end = par_iterator_end();
2768 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2769 if (it->isMultiLingual(params()))
2776 std::set<Language const *> Buffer::getLanguages() const
2778 std::set<Language const *> languages;
2779 getLanguages(languages);
2784 void Buffer::getLanguages(std::set<Language const *> & languages) const
2786 ParConstIterator end = par_iterator_end();
2787 // add the buffer language, even if it's not actively used
2788 languages.insert(language());
2789 // iterate over the paragraphs
2790 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2791 it->getLanguages(languages);
2793 ListOfBuffers clist = getDescendents();
2794 ListOfBuffers::const_iterator cit = clist.begin();
2795 ListOfBuffers::const_iterator const cen = clist.end();
2796 for (; cit != cen; ++cit)
2797 (*cit)->getLanguages(languages);
2801 DocIterator Buffer::getParFromID(int const id) const
2803 Buffer * buf = const_cast<Buffer *>(this);
2805 // John says this is called with id == -1 from undo
2806 lyxerr << "getParFromID(), id: " << id << endl;
2807 return doc_iterator_end(buf);
2810 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2811 if (it.paragraph().id() == id)
2814 return doc_iterator_end(buf);
2818 bool Buffer::hasParWithID(int const id) const
2820 return !getParFromID(id).atEnd();
2824 ParIterator Buffer::par_iterator_begin()
2826 return ParIterator(doc_iterator_begin(this));
2830 ParIterator Buffer::par_iterator_end()
2832 return ParIterator(doc_iterator_end(this));
2836 ParConstIterator Buffer::par_iterator_begin() const
2838 return ParConstIterator(doc_iterator_begin(this));
2842 ParConstIterator Buffer::par_iterator_end() const
2844 return ParConstIterator(doc_iterator_end(this));
2848 Language const * Buffer::language() const
2850 return params().language;
2854 docstring const Buffer::B_(string const & l10n) const
2856 return params().B_(l10n);
2860 bool Buffer::isClean() const
2862 return d->lyx_clean;
2866 bool Buffer::isExternallyModified(CheckMethod method) const
2868 LASSERT(d->filename.exists(), return false);
2869 // if method == timestamp, check timestamp before checksum
2870 return (method == checksum_method
2871 || d->timestamp_ != d->filename.lastModified())
2872 && d->checksum_ != d->filename.checksum();
2876 void Buffer::saveCheckSum() const
2878 FileName const & file = d->filename;
2881 if (file.exists()) {
2882 d->timestamp_ = file.lastModified();
2883 d->checksum_ = file.checksum();
2885 // in the case of save to a new file.
2892 void Buffer::markClean() const
2894 if (!d->lyx_clean) {
2895 d->lyx_clean = true;
2898 // if the .lyx file has been saved, we don't need an
2900 d->bak_clean = true;
2901 d->undo_.markDirty();
2905 void Buffer::setUnnamed(bool flag)
2911 bool Buffer::isUnnamed() const
2918 /// Don't check unnamed, here: isInternal() is used in
2919 /// newBuffer(), where the unnamed flag has not been set by anyone
2920 /// yet. Also, for an internal buffer, there should be no need for
2921 /// retrieving fileName() nor for checking if it is unnamed or not.
2922 bool Buffer::isInternal() const
2924 return d->internal_buffer;
2928 void Buffer::setInternal(bool flag)
2930 d->internal_buffer = flag;
2934 void Buffer::markDirty()
2937 d->lyx_clean = false;
2940 d->bak_clean = false;
2942 DepClean::iterator it = d->dep_clean.begin();
2943 DepClean::const_iterator const end = d->dep_clean.end();
2945 for (; it != end; ++it)
2950 FileName Buffer::fileName() const
2956 string Buffer::absFileName() const
2958 return d->filename.absFileName();
2962 string Buffer::filePath() const
2964 string const abs = d->filename.onlyPath().absFileName();
2967 int last = abs.length() - 1;
2969 return abs[last] == '/' ? abs : abs + '/';
2973 bool Buffer::isReadonly() const
2975 return d->read_only;
2979 void Buffer::setParent(Buffer const * buffer)
2981 // Avoids recursive include.
2982 d->setParent(buffer == this ? 0 : buffer);
2987 Buffer const * Buffer::parent() const
2993 ListOfBuffers Buffer::allRelatives() const
2995 ListOfBuffers lb = masterBuffer()->getDescendents();
2996 lb.push_front(const_cast<Buffer *>(masterBuffer()));
3001 Buffer const * Buffer::masterBuffer() const
3003 // FIXME Should be make sure we are not in some kind
3004 // of recursive include? A -> B -> A will crash this.
3005 Buffer const * const pbuf = d->parent();
3009 return pbuf->masterBuffer();
3013 bool Buffer::isChild(Buffer * child) const
3015 return d->children_positions.find(child) != d->children_positions.end();
3019 DocIterator Buffer::firstChildPosition(Buffer const * child)
3021 Impl::BufferPositionMap::iterator it;
3022 it = d->children_positions.find(child);
3023 if (it == d->children_positions.end())
3024 return DocIterator(this);
3029 bool Buffer::hasChildren() const
3031 return !d->children_positions.empty();
3035 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3037 // loop over children
3038 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3039 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3040 for (; it != end; ++it) {
3041 Buffer * child = const_cast<Buffer *>(it->first);
3043 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3044 if (bit != clist.end())
3046 clist.push_back(child);
3048 // there might be grandchildren
3049 child->collectChildren(clist, true);
3054 ListOfBuffers Buffer::getChildren() const
3057 collectChildren(v, false);
3058 // Make sure we have not included ourselves.
3059 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3060 if (bit != v.end()) {
3061 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3068 ListOfBuffers Buffer::getDescendents() const
3071 collectChildren(v, true);
3072 // Make sure we have not included ourselves.
3073 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3074 if (bit != v.end()) {
3075 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3082 template<typename M>
3083 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3088 typename M::const_iterator it = m.lower_bound(x);
3089 if (it == m.begin())
3097 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3098 DocIterator const & pos) const
3100 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3102 // if paragraphs have no macro context set, pos will be empty
3106 // we haven't found anything yet
3107 DocIterator bestPos = owner_->par_iterator_begin();
3108 MacroData const * bestData = 0;
3110 // find macro definitions for name
3111 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3112 if (nameIt != macros.end()) {
3113 // find last definition in front of pos or at pos itself
3114 PositionScopeMacroMap::const_iterator it
3115 = greatest_below(nameIt->second, pos);
3116 if (it != nameIt->second.end()) {
3118 // scope ends behind pos?
3119 if (pos < it->second.first) {
3120 // Looks good, remember this. If there
3121 // is no external macro behind this,
3122 // we found the right one already.
3123 bestPos = it->first;
3124 bestData = &it->second.second;
3128 // try previous macro if there is one
3129 if (it == nameIt->second.begin())
3136 // find macros in included files
3137 PositionScopeBufferMap::const_iterator it
3138 = greatest_below(position_to_children, pos);
3139 if (it == position_to_children.end())
3140 // no children before
3144 // do we know something better (i.e. later) already?
3145 if (it->first < bestPos )
3148 // scope ends behind pos?
3149 if (pos < it->second.first
3150 && (cloned_buffer_ ||
3151 theBufferList().isLoaded(it->second.second))) {
3152 // look for macro in external file
3154 MacroData const * data
3155 = it->second.second->getMacro(name, false);
3158 bestPos = it->first;
3164 // try previous file if there is one
3165 if (it == position_to_children.begin())
3170 // return the best macro we have found
3175 MacroData const * Buffer::getMacro(docstring const & name,
3176 DocIterator const & pos, bool global) const
3181 // query buffer macros
3182 MacroData const * data = d->getBufferMacro(name, pos);
3186 // If there is a master buffer, query that
3187 Buffer const * const pbuf = d->parent();
3189 d->macro_lock = true;
3190 MacroData const * macro = pbuf->getMacro(
3191 name, *this, false);
3192 d->macro_lock = false;
3198 data = MacroTable::globalMacros().get(name);
3207 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3209 // set scope end behind the last paragraph
3210 DocIterator scope = par_iterator_begin();
3211 scope.pit() = scope.lastpit() + 1;
3213 return getMacro(name, scope, global);
3217 MacroData const * Buffer::getMacro(docstring const & name,
3218 Buffer const & child, bool global) const
3220 // look where the child buffer is included first
3221 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3222 if (it == d->children_positions.end())
3225 // check for macros at the inclusion position
3226 return getMacro(name, it->second, global);
3230 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3232 pit_type const lastpit = it.lastpit();
3234 // look for macros in each paragraph
3235 while (it.pit() <= lastpit) {
3236 Paragraph & par = it.paragraph();
3238 // iterate over the insets of the current paragraph
3239 InsetList const & insets = par.insetList();
3240 InsetList::const_iterator iit = insets.begin();
3241 InsetList::const_iterator end = insets.end();
3242 for (; iit != end; ++iit) {
3243 it.pos() = iit->pos;
3245 // is it a nested text inset?
3246 if (iit->inset->asInsetText()) {
3247 // Inset needs its own scope?
3248 InsetText const * itext = iit->inset->asInsetText();
3249 bool newScope = itext->isMacroScope();
3251 // scope which ends just behind the inset
3252 DocIterator insetScope = it;
3255 // collect macros in inset
3256 it.push_back(CursorSlice(*iit->inset));
3257 updateMacros(it, newScope ? insetScope : scope);
3262 if (iit->inset->asInsetTabular()) {
3263 CursorSlice slice(*iit->inset);
3264 size_t const numcells = slice.nargs();
3265 for (; slice.idx() < numcells; slice.forwardIdx()) {
3266 it.push_back(slice);
3267 updateMacros(it, scope);
3273 // is it an external file?
3274 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3275 // get buffer of external file
3276 InsetInclude const & inset =
3277 static_cast<InsetInclude const &>(*iit->inset);
3279 Buffer * child = inset.getChildBuffer();
3284 // register its position, but only when it is
3285 // included first in the buffer
3286 if (children_positions.find(child) ==
3287 children_positions.end())
3288 children_positions[child] = it;
3290 // register child with its scope
3291 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3295 InsetMath * im = iit->inset->asInsetMath();
3296 if (doing_export && im) {
3297 InsetMathHull * hull = im->asHullInset();
3299 hull->recordLocation(it);
3302 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3306 MathMacroTemplate & macroTemplate =
3307 *iit->inset->asInsetMath()->asMacroTemplate();
3308 MacroContext mc(owner_, it);
3309 macroTemplate.updateToContext(mc);
3312 bool valid = macroTemplate.validMacro();
3313 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3314 // then the BufferView's cursor will be invalid in
3315 // some cases which leads to crashes.
3320 // FIXME (Abdel), I don't understandt why we pass 'it' here
3321 // instead of 'macroTemplate' defined above... is this correct?
3322 macros[macroTemplate.name()][it] =
3323 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3333 void Buffer::updateMacros() const
3338 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3340 // start with empty table
3342 d->children_positions.clear();
3343 d->position_to_children.clear();
3345 // Iterate over buffer, starting with first paragraph
3346 // The scope must be bigger than any lookup DocIterator
3347 // later. For the global lookup, lastpit+1 is used, hence
3348 // we use lastpit+2 here.
3349 DocIterator it = par_iterator_begin();
3350 DocIterator outerScope = it;
3351 outerScope.pit() = outerScope.lastpit() + 2;
3352 d->updateMacros(it, outerScope);
3356 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3358 InsetIterator it = inset_iterator_begin(inset());
3359 InsetIterator const end = inset_iterator_end(inset());
3360 for (; it != end; ++it) {
3361 if (it->lyxCode() == BRANCH_CODE) {
3362 InsetBranch & br = static_cast<InsetBranch &>(*it);
3363 docstring const name = br.branch();
3364 if (!from_master && !params().branchlist().find(name))
3365 result.push_back(name);
3366 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3367 result.push_back(name);
3370 if (it->lyxCode() == INCLUDE_CODE) {
3371 // get buffer of external file
3372 InsetInclude const & ins =
3373 static_cast<InsetInclude const &>(*it);
3374 Buffer * child = ins.getChildBuffer();
3377 child->getUsedBranches(result, true);
3380 // remove duplicates
3385 void Buffer::updateMacroInstances(UpdateType utype) const
3387 LYXERR(Debug::MACROS, "updateMacroInstances for "
3388 << d->filename.onlyFileName());
3389 DocIterator it = doc_iterator_begin(this);
3391 DocIterator const end = doc_iterator_end(this);
3392 for (; it != end; it.forwardInset()) {
3393 // look for MathData cells in InsetMathNest insets
3394 InsetMath * minset = it.nextInset()->asInsetMath();
3398 // update macro in all cells of the InsetMathNest
3399 DocIterator::idx_type n = minset->nargs();
3400 MacroContext mc = MacroContext(this, it);
3401 for (DocIterator::idx_type i = 0; i < n; ++i) {
3402 MathData & data = minset->cell(i);
3403 data.updateMacros(0, mc, utype);
3409 void Buffer::listMacroNames(MacroNameSet & macros) const
3414 d->macro_lock = true;
3416 // loop over macro names
3417 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3418 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3419 for (; nameIt != nameEnd; ++nameIt)
3420 macros.insert(nameIt->first);
3422 // loop over children
3423 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3424 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3425 for (; it != end; ++it)
3426 it->first->listMacroNames(macros);
3429 Buffer const * const pbuf = d->parent();
3431 pbuf->listMacroNames(macros);
3433 d->macro_lock = false;
3437 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3439 Buffer const * const pbuf = d->parent();
3444 pbuf->listMacroNames(names);
3447 MacroNameSet::iterator it = names.begin();
3448 MacroNameSet::iterator end = names.end();
3449 for (; it != end; ++it) {
3451 MacroData const * data =
3452 pbuf->getMacro(*it, *this, false);
3454 macros.insert(data);
3456 // we cannot access the original MathMacroTemplate anymore
3457 // here to calls validate method. So we do its work here manually.
3458 // FIXME: somehow make the template accessible here.
3459 if (data->optionals() > 0)
3460 features.require("xargs");
3466 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3469 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3471 RefCache::iterator it = d->ref_cache_.find(label);
3472 if (it != d->ref_cache_.end())
3473 return it->second.second;
3475 static InsetLabel const * dummy_il = 0;
3476 static References const dummy_refs;
3477 it = d->ref_cache_.insert(
3478 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3479 return it->second.second;
3483 Buffer::References const & Buffer::references(docstring const & label) const
3485 return const_cast<Buffer *>(this)->getReferenceCache(label);
3489 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3491 References & refs = getReferenceCache(label);
3492 refs.push_back(make_pair(inset, it));
3496 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3498 masterBuffer()->d->ref_cache_[label].first = il;
3502 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3504 return masterBuffer()->d->ref_cache_[label].first;
3508 void Buffer::clearReferenceCache() const
3511 d->ref_cache_.clear();
3515 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3517 //FIXME: This does not work for child documents yet.
3518 reloadBibInfoCache();
3520 // Check if the label 'from' appears more than once
3521 BiblioInfo const & keys = masterBibInfo();
3522 BiblioInfo::const_iterator bit = keys.begin();
3523 BiblioInfo::const_iterator bend = keys.end();
3524 vector<docstring> labels;
3526 for (; bit != bend; ++bit)
3528 labels.push_back(bit->first);
3530 if (count(labels.begin(), labels.end(), from) > 1)
3533 string const paramName = "key";
3534 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3535 if (it->lyxCode() != CITE_CODE)
3537 InsetCommand * inset = it->asInsetCommand();
3538 docstring const oldValue = inset->getParam(paramName);
3539 if (oldValue == from)
3540 inset->setParam(paramName, to);
3545 void Buffer::getSourceCode(odocstream & os, string const & format,
3546 pit_type par_begin, pit_type par_end,
3547 OutputWhat output, bool master) const
3549 OutputParams runparams(¶ms().encoding());
3550 runparams.nice = true;
3551 runparams.flavor = params().getOutputFlavor(format);
3552 runparams.linelen = lyxrc.plaintext_linelen;
3553 // No side effect of file copying and image conversion
3554 runparams.dryrun = true;
3556 if (output == CurrentParagraph) {
3557 runparams.par_begin = par_begin;
3558 runparams.par_end = par_end;
3559 if (par_begin + 1 == par_end) {
3561 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3565 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3566 convert<docstring>(par_begin),
3567 convert<docstring>(par_end - 1))
3570 // output paragraphs
3571 if (runparams.flavor == OutputParams::LYX) {
3572 Paragraph const & par = text().paragraphs()[par_begin];
3574 depth_type dt = par.getDepth();
3575 par.write(ods, params(), dt);
3576 os << from_utf8(ods.str());
3577 } else if (runparams.flavor == OutputParams::HTML) {
3579 setMathFlavor(runparams);
3580 xhtmlParagraphs(text(), *this, xs, runparams);
3581 } else if (runparams.flavor == OutputParams::TEXT) {
3583 // FIXME Handles only one paragraph, unlike the others.
3584 // Probably should have some routine with a signature like them.
3585 writePlaintextParagraph(*this,
3586 text().paragraphs()[par_begin], os, runparams, dummy);
3587 } else if (params().isDocBook()) {
3588 docbookParagraphs(text(), *this, os, runparams);
3590 // If we are previewing a paragraph, even if this is the
3591 // child of some other buffer, let's cut the link here,
3592 // so that no concurring settings from the master
3593 // (e.g. branch state) interfere (see #8101).
3595 d->ignore_parent = true;
3596 // We need to validate the Buffer params' features here
3597 // in order to know if we should output polyglossia
3598 // macros (instead of babel macros)
3599 LaTeXFeatures features(*this, params(), runparams);
3600 params().validate(features);
3601 runparams.use_polyglossia = features.usePolyglossia();
3606 // latex or literate
3607 otexstream ots(os, texrow);
3610 latexParagraphs(*this, text(), ots, runparams);
3612 // Restore the parenthood
3614 d->ignore_parent = false;
3618 if (output == FullSource)
3619 os << _("Preview source code");
3620 else if (output == OnlyPreamble)
3621 os << _("Preview preamble");
3622 else if (output == OnlyBody)
3623 os << _("Preview body");
3625 if (runparams.flavor == OutputParams::LYX) {
3627 if (output == FullSource)
3629 else if (output == OnlyPreamble)
3630 params().writeFile(ods);
3631 else if (output == OnlyBody)
3633 os << from_utf8(ods.str());
3634 } else if (runparams.flavor == OutputParams::HTML) {
3635 writeLyXHTMLSource(os, runparams, output);
3636 } else if (runparams.flavor == OutputParams::TEXT) {
3637 if (output == OnlyPreamble) {
3638 os << "% "<< _("Plain text does not have a preamble.");
3640 writePlaintextFile(*this, os, runparams);
3641 } else if (params().isDocBook()) {
3642 writeDocBookSource(os, absFileName(), runparams, output);
3644 // latex or literate
3646 d->texrow.newline();
3647 d->texrow.newline();
3648 otexstream ots(os, d->texrow);
3650 runparams.is_child = true;
3651 writeLaTeXSource(ots, string(), runparams, output);
3657 ErrorList & Buffer::errorList(string const & type) const
3659 return d->errorLists[type];
3663 void Buffer::updateTocItem(std::string const & type,
3664 DocIterator const & dit) const
3667 d->gui_->updateTocItem(type, dit);
3671 void Buffer::structureChanged() const
3674 d->gui_->structureChanged();
3678 void Buffer::errors(string const & err, bool from_master) const
3681 d->gui_->errors(err, from_master);
3685 void Buffer::message(docstring const & msg) const
3688 d->gui_->message(msg);
3692 void Buffer::setBusy(bool on) const
3695 d->gui_->setBusy(on);
3699 void Buffer::updateTitles() const
3702 d->wa_->updateTitles();
3706 void Buffer::resetAutosaveTimers() const
3709 d->gui_->resetAutosaveTimers();
3713 bool Buffer::hasGuiDelegate() const
3719 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3728 class AutoSaveBuffer : public ForkedProcess {
3731 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3732 : buffer_(buffer), fname_(fname) {}
3734 virtual shared_ptr<ForkedProcess> clone() const
3736 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3741 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3742 from_utf8(fname_.absFileName())));
3743 return run(DontWait);
3747 virtual int generateChild();
3749 Buffer const & buffer_;
3754 int AutoSaveBuffer::generateChild()
3756 #if defined(__APPLE__)
3757 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3758 * We should use something else like threads.
3760 * Since I do not know how to determine at run time what is the OS X
3761 * version, I just disable forking altogether for now (JMarc)
3763 pid_t const pid = -1;
3765 // tmp_ret will be located (usually) in /tmp
3766 // will that be a problem?
3767 // Note that this calls ForkedCalls::fork(), so it's
3768 // ok cross-platform.
3769 pid_t const pid = fork();
3770 // If you want to debug the autosave
3771 // you should set pid to -1, and comment out the fork.
3772 if (pid != 0 && pid != -1)
3776 // pid = -1 signifies that lyx was unable
3777 // to fork. But we will do the save
3779 bool failed = false;
3780 TempFile tempfile("lyxautoXXXXXX.lyx");
3781 tempfile.setAutoRemove(false);
3782 FileName const tmp_ret = tempfile.name();
3783 if (!tmp_ret.empty()) {
3784 if (!buffer_.writeFile(tmp_ret))
3786 else if (!tmp_ret.moveTo(fname_))
3792 // failed to write/rename tmp_ret so try writing direct
3793 if (!buffer_.writeFile(fname_)) {
3794 // It is dangerous to do this in the child,
3795 // but safe in the parent, so...
3796 if (pid == -1) // emit message signal.
3797 buffer_.message(_("Autosave failed!"));
3801 if (pid == 0) // we are the child so...
3810 FileName Buffer::getEmergencyFileName() const
3812 return FileName(d->filename.absFileName() + ".emergency");
3816 FileName Buffer::getAutosaveFileName() const
3818 // if the document is unnamed try to save in the backup dir, else
3819 // in the default document path, and as a last try in the filePath,
3820 // which will most often be the temporary directory
3823 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3824 : lyxrc.backupdir_path;
3825 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3828 string const fname = "#" + d->filename.onlyFileName() + "#";
3830 return makeAbsPath(fname, fpath);
3834 void Buffer::removeAutosaveFile() const
3836 FileName const f = getAutosaveFileName();
3842 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3844 FileName const newauto = getAutosaveFileName();
3846 if (newauto != oldauto && oldauto.exists())
3847 if (!oldauto.moveTo(newauto))
3848 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3852 bool Buffer::autoSave() const
3854 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3855 if (buf->d->bak_clean || isReadonly())
3858 message(_("Autosaving current document..."));
3859 buf->d->bak_clean = true;
3861 FileName const fname = getAutosaveFileName();
3862 LASSERT(d->cloned_buffer_, return false);
3864 // If this buffer is cloned, we assume that
3865 // we are running in a separate thread already.
3866 TempFile tempfile("lyxautoXXXXXX.lyx");
3867 tempfile.setAutoRemove(false);
3868 FileName const tmp_ret = tempfile.name();
3869 if (!tmp_ret.empty()) {
3871 // assume successful write of tmp_ret
3872 if (tmp_ret.moveTo(fname))
3875 // failed to write/rename tmp_ret so try writing direct
3876 return writeFile(fname);
3880 void Buffer::setExportStatus(bool e) const
3882 d->doing_export = e;
3883 ListOfBuffers clist = getDescendents();
3884 ListOfBuffers::const_iterator cit = clist.begin();
3885 ListOfBuffers::const_iterator const cen = clist.end();
3886 for (; cit != cen; ++cit)
3887 (*cit)->d->doing_export = e;
3891 bool Buffer::isExporting() const
3893 return d->doing_export;
3897 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3901 return doExport(target, put_in_tempdir, result_file);
3904 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3905 string & result_file) const
3907 bool const update_unincluded =
3908 params().maintain_unincluded_children
3909 && !params().getIncludedChildren().empty();
3911 // (1) export with all included children (omit \includeonly)
3912 if (update_unincluded) {
3913 ExportStatus const status =
3914 doExport(target, put_in_tempdir, true, result_file);
3915 if (status != ExportSuccess)
3918 // (2) export with included children only
3919 return doExport(target, put_in_tempdir, false, result_file);
3923 void Buffer::setMathFlavor(OutputParams & op) const
3925 switch (params().html_math_output) {
3926 case BufferParams::MathML:
3927 op.math_flavor = OutputParams::MathAsMathML;
3929 case BufferParams::HTML:
3930 op.math_flavor = OutputParams::MathAsHTML;
3932 case BufferParams::Images:
3933 op.math_flavor = OutputParams::MathAsImages;
3935 case BufferParams::LaTeX:
3936 op.math_flavor = OutputParams::MathAsLaTeX;
3942 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3943 bool includeall, string & result_file) const
3945 LYXERR(Debug::FILES, "target=" << target);
3946 OutputParams runparams(¶ms().encoding());
3947 string format = target;
3948 string dest_filename;
3949 size_t pos = target.find(' ');
3950 if (pos != string::npos) {
3951 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3952 format = target.substr(0, pos);
3953 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3954 FileName(dest_filename).onlyPath().createPath();
3955 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3957 MarkAsExporting exporting(this);
3958 string backend_format;
3959 runparams.flavor = OutputParams::LATEX;
3960 runparams.linelen = lyxrc.plaintext_linelen;
3961 runparams.includeall = includeall;
3962 vector<string> backs = params().backends();
3963 Converters converters = theConverters();
3964 bool need_nice_file = false;
3965 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3966 // Get shortest path to format
3967 converters.buildGraph();
3968 Graph::EdgePath path;
3969 for (vector<string>::const_iterator it = backs.begin();
3970 it != backs.end(); ++it) {
3971 Graph::EdgePath p = converters.getPath(*it, format);
3972 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3973 backend_format = *it;
3978 if (!put_in_tempdir) {
3979 // Only show this alert if this is an export to a non-temporary
3980 // file (not for previewing).
3981 Alert::error(_("Couldn't export file"), bformat(
3982 _("No information for exporting the format %1$s."),
3983 formats.prettyName(format)));
3985 return ExportNoPathToFormat;
3987 runparams.flavor = converters.getFlavor(path, this);
3988 Graph::EdgePath::const_iterator it = path.begin();
3989 Graph::EdgePath::const_iterator en = path.end();
3990 for (; it != en; ++it)
3991 if (theConverters().get(*it).nice()) {
3992 need_nice_file = true;
3997 backend_format = format;
3998 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3999 // FIXME: Don't hardcode format names here, but use a flag
4000 if (backend_format == "pdflatex")
4001 runparams.flavor = OutputParams::PDFLATEX;
4002 else if (backend_format == "luatex")
4003 runparams.flavor = OutputParams::LUATEX;
4004 else if (backend_format == "dviluatex")
4005 runparams.flavor = OutputParams::DVILUATEX;
4006 else if (backend_format == "xetex")
4007 runparams.flavor = OutputParams::XETEX;
4010 string filename = latexName(false);
4011 filename = addName(temppath(), filename);
4012 filename = changeExtension(filename,
4013 formats.extension(backend_format));
4014 LYXERR(Debug::FILES, "filename=" << filename);
4016 // Plain text backend
4017 if (backend_format == "text") {
4018 runparams.flavor = OutputParams::TEXT;
4019 writePlaintextFile(*this, FileName(filename), runparams);
4022 else if (backend_format == "xhtml") {
4023 runparams.flavor = OutputParams::HTML;
4024 setMathFlavor(runparams);
4025 makeLyXHTMLFile(FileName(filename), runparams);
4026 } else if (backend_format == "lyx")
4027 writeFile(FileName(filename));
4029 else if (params().isDocBook()) {
4030 runparams.nice = !put_in_tempdir;
4031 makeDocBookFile(FileName(filename), runparams);
4034 else if (backend_format == format || need_nice_file) {
4035 runparams.nice = true;
4036 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4037 if (d->cloned_buffer_)
4038 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4041 } else if (!lyxrc.tex_allows_spaces
4042 && contains(filePath(), ' ')) {
4043 Alert::error(_("File name error"),
4044 _("The directory path to the document cannot contain spaces."));
4045 return ExportTexPathHasSpaces;
4047 runparams.nice = false;
4048 bool const success = makeLaTeXFile(
4049 FileName(filename), filePath(), runparams);
4050 if (d->cloned_buffer_)
4051 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4056 string const error_type = (format == "program")
4057 ? "Build" : params().bufferFormat();
4058 ErrorList & error_list = d->errorLists[error_type];
4059 string const ext = formats.extension(format);
4060 FileName const tmp_result_file(changeExtension(filename, ext));
4061 bool const success = converters.convert(this, FileName(filename),
4062 tmp_result_file, FileName(absFileName()), backend_format, format,
4065 // Emit the signal to show the error list or copy it back to the
4066 // cloned Buffer so that it can be emitted afterwards.
4067 if (format != backend_format) {
4068 if (runparams.silent)
4070 else if (d->cloned_buffer_)
4071 d->cloned_buffer_->d->errorLists[error_type] =
4072 d->errorLists[error_type];
4075 // also to the children, in case of master-buffer-view
4076 ListOfBuffers clist = getDescendents();
4077 ListOfBuffers::const_iterator cit = clist.begin();
4078 ListOfBuffers::const_iterator const cen = clist.end();
4079 for (; cit != cen; ++cit) {
4080 if (runparams.silent)
4081 (*cit)->d->errorLists[error_type].clear();
4082 else if (d->cloned_buffer_) {
4083 // Enable reverse search by copying back the
4084 // texrow object to the cloned buffer.
4085 // FIXME: this is not thread safe.
4086 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4087 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4088 (*cit)->d->errorLists[error_type];
4090 (*cit)->errors(error_type, true);
4094 if (d->cloned_buffer_) {
4095 // Enable reverse dvi or pdf to work by copying back the texrow
4096 // object to the cloned buffer.
4097 // FIXME: There is a possibility of concurrent access to texrow
4098 // here from the main GUI thread that should be securized.
4099 d->cloned_buffer_->d->texrow = d->texrow;
4100 string const error_type = params().bufferFormat();
4101 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4105 return ExportConverterError;
4107 if (put_in_tempdir) {
4108 result_file = tmp_result_file.absFileName();
4109 return ExportSuccess;
4112 if (dest_filename.empty())
4113 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4115 result_file = dest_filename;
4116 // We need to copy referenced files (e. g. included graphics
4117 // if format == "dvi") to the result dir.
4118 vector<ExportedFile> const files =
4119 runparams.exportdata->externalFiles(format);
4120 string const dest = runparams.export_folder.empty() ?
4121 onlyPath(result_file) : runparams.export_folder;
4122 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4123 : force_overwrite == ALL_FILES;
4124 CopyStatus status = use_force ? FORCE : SUCCESS;
4126 vector<ExportedFile>::const_iterator it = files.begin();
4127 vector<ExportedFile>::const_iterator const en = files.end();
4128 for (; it != en && status != CANCEL; ++it) {
4129 string const fmt = formats.getFormatFromFile(it->sourceName);
4130 string fixedName = it->exportName;
4131 if (!runparams.export_folder.empty()) {
4132 // Relative pathnames starting with ../ will be sanitized
4133 // if exporting to a different folder
4134 while (fixedName.substr(0, 3) == "../")
4135 fixedName = fixedName.substr(3, fixedName.length() - 3);
4137 FileName fixedFileName = makeAbsPath(fixedName, dest);
4138 fixedFileName.onlyPath().createPath();
4139 status = copyFile(fmt, it->sourceName,
4141 it->exportName, status == FORCE,
4142 runparams.export_folder.empty());
4145 if (status == CANCEL) {
4146 message(_("Document export cancelled."));
4147 return ExportCancel;
4150 if (tmp_result_file.exists()) {
4151 // Finally copy the main file
4152 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4153 : force_overwrite != NO_FILES;
4154 if (status == SUCCESS && use_force)
4156 status = copyFile(format, tmp_result_file,
4157 FileName(result_file), result_file,
4159 if (status == CANCEL) {
4160 message(_("Document export cancelled."));
4161 return ExportCancel;
4163 message(bformat(_("Document exported as %1$s "
4165 formats.prettyName(format),
4166 makeDisplayPath(result_file)));
4169 // This must be a dummy converter like fax (bug 1888)
4170 message(bformat(_("Document exported as %1$s"),
4171 formats.prettyName(format)));
4174 return ExportSuccess;
4178 Buffer::ExportStatus Buffer::preview(string const & format) const
4180 bool const update_unincluded =
4181 params().maintain_unincluded_children
4182 && !params().getIncludedChildren().empty();
4183 return preview(format, update_unincluded);
4187 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4189 MarkAsExporting exporting(this);
4191 // (1) export with all included children (omit \includeonly)
4193 ExportStatus const status = doExport(format, true, true, result_file);
4194 if (status != ExportSuccess)
4197 // (2) export with included children only
4198 ExportStatus const status = doExport(format, true, false, result_file);
4199 if (status != ExportSuccess)
4201 if (!formats.view(*this, FileName(result_file), format))
4202 return PreviewError;
4203 return PreviewSuccess;
4207 Buffer::ReadStatus Buffer::extractFromVC()
4209 bool const found = LyXVC::file_not_found_hook(d->filename);
4211 return ReadFileNotFound;
4212 if (!d->filename.isReadableFile())
4218 Buffer::ReadStatus Buffer::loadEmergency()
4220 FileName const emergencyFile = getEmergencyFileName();
4221 if (!emergencyFile.exists()
4222 || emergencyFile.lastModified() <= d->filename.lastModified())
4223 return ReadFileNotFound;
4225 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4226 docstring const text = bformat(_("An emergency save of the document "
4227 "%1$s exists.\n\nRecover emergency save?"), file);
4229 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4230 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4236 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4237 bool const success = (ret_llf == ReadSuccess);
4240 Alert::warning(_("File is read-only"),
4241 bformat(_("An emergency file is successfully loaded, "
4242 "but the original file %1$s is marked read-only. "
4243 "Please make sure to save the document as a different "
4244 "file."), from_utf8(d->filename.absFileName())));
4247 lyxvc().file_found_hook(d->filename);
4248 str = _("Document was successfully recovered.");
4250 str = _("Document was NOT successfully recovered.");
4251 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4252 makeDisplayPath(emergencyFile.absFileName()));
4254 int const del_emerg =
4255 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4256 _("&Remove"), _("&Keep"));
4257 if (del_emerg == 0) {
4258 emergencyFile.removeFile();
4260 Alert::warning(_("Emergency file deleted"),
4261 _("Do not forget to save your file now!"), true);
4263 return success ? ReadSuccess : ReadEmergencyFailure;
4266 int const del_emerg =
4267 Alert::prompt(_("Delete emergency file?"),
4268 _("Remove emergency file now?"), 1, 1,
4269 _("&Remove"), _("&Keep"));
4271 emergencyFile.removeFile();
4272 return ReadOriginal;
4282 Buffer::ReadStatus Buffer::loadAutosave()
4284 // Now check if autosave file is newer.
4285 FileName const autosaveFile = getAutosaveFileName();
4286 if (!autosaveFile.exists()
4287 || autosaveFile.lastModified() <= d->filename.lastModified())
4288 return ReadFileNotFound;
4290 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4291 docstring const text = bformat(_("The backup of the document %1$s "
4292 "is newer.\n\nLoad the backup instead?"), file);
4293 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4294 _("&Load backup"), _("Load &original"), _("&Cancel"));
4299 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4300 // the file is not saved if we load the autosave file.
4301 if (ret_llf == ReadSuccess) {
4303 Alert::warning(_("File is read-only"),
4304 bformat(_("A backup file is successfully loaded, "
4305 "but the original file %1$s is marked read-only. "
4306 "Please make sure to save the document as a "
4308 from_utf8(d->filename.absFileName())));
4311 lyxvc().file_found_hook(d->filename);
4314 return ReadAutosaveFailure;
4317 // Here we delete the autosave
4318 autosaveFile.removeFile();
4319 return ReadOriginal;
4327 Buffer::ReadStatus Buffer::loadLyXFile()
4329 if (!d->filename.isReadableFile()) {
4330 ReadStatus const ret_rvc = extractFromVC();
4331 if (ret_rvc != ReadSuccess)
4335 ReadStatus const ret_re = loadEmergency();
4336 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4339 ReadStatus const ret_ra = loadAutosave();
4340 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4343 return loadThisLyXFile(d->filename);
4347 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4349 return readFile(fn);
4353 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4355 TeXErrors::Errors::const_iterator it = terr.begin();
4356 TeXErrors::Errors::const_iterator end = terr.end();
4357 ListOfBuffers clist = getDescendents();
4358 ListOfBuffers::const_iterator cen = clist.end();
4360 for (; it != end; ++it) {
4363 int errorRow = it->error_in_line;
4364 Buffer const * buf = 0;
4366 if (it->child_name.empty())
4367 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4369 // The error occurred in a child
4370 ListOfBuffers::const_iterator cit = clist.begin();
4371 for (; cit != cen; ++cit) {
4372 string const child_name =
4373 DocFileName(changeExtension(
4374 (*cit)->absFileName(), "tex")).
4376 if (it->child_name != child_name)
4378 (*cit)->d->texrow.getIdFromRow(errorRow,
4379 id_start, pos_start);
4380 if (id_start != -1) {
4381 buf = d->cloned_buffer_
4382 ? (*cit)->d->cloned_buffer_->d->owner_
4383 : (*cit)->d->owner_;
4394 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4395 } while (found && id_start == id_end && pos_start == pos_end);
4397 if (id_start != id_end) {
4398 // Next registered position is outside the inset where
4399 // the error occurred, so signal end-of-paragraph
4403 errorList.push_back(ErrorItem(it->error_desc,
4404 it->error_text, id_start, pos_start, pos_end, buf));
4409 void Buffer::setBuffersForInsets() const
4411 inset().setBuffer(const_cast<Buffer &>(*this));
4415 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4417 LBUFERR(!text().paragraphs().empty());
4419 // Use the master text class also for child documents
4420 Buffer const * const master = masterBuffer();
4421 DocumentClass const & textclass = master->params().documentClass();
4423 // do this only if we are the top-level Buffer
4424 if (master == this) {
4425 textclass.counters().reset(from_ascii("bibitem"));
4426 reloadBibInfoCache();
4429 // keep the buffers to be children in this set. If the call from the
4430 // master comes back we can see which of them were actually seen (i.e.
4431 // via an InsetInclude). The remaining ones in the set need still be updated.
4432 static std::set<Buffer const *> bufToUpdate;
4433 if (scope == UpdateMaster) {
4434 // If this is a child document start with the master
4435 if (master != this) {
4436 bufToUpdate.insert(this);
4437 master->updateBuffer(UpdateMaster, utype);
4438 // If the master buffer has no gui associated with it, then the TocModel is
4439 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4440 // (bug 5699). The same happens if the master buffer is open in a different
4441 // window. This test catches both possibilities.
4442 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4443 // There remains a problem here: If there is another child open in yet a third
4444 // window, that TOC is not updated. So some more general solution is needed at
4446 if (master->d->gui_ != d->gui_)
4449 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4450 if (bufToUpdate.find(this) == bufToUpdate.end())
4454 // start over the counters in the master
4455 textclass.counters().reset();
4458 // update will be done below for this buffer
4459 bufToUpdate.erase(this);
4461 // update all caches
4462 clearReferenceCache();
4465 Buffer & cbuf = const_cast<Buffer &>(*this);
4468 ParIterator parit = cbuf.par_iterator_begin();
4469 updateBuffer(parit, utype);
4472 // TocBackend update will be done later.
4475 d->bibinfo_cache_valid_ = true;
4476 d->cite_labels_valid_ = true;
4477 cbuf.tocBackend().update(utype == OutputUpdate);
4478 if (scope == UpdateMaster)
4479 cbuf.structureChanged();
4483 static depth_type getDepth(DocIterator const & it)
4485 depth_type depth = 0;
4486 for (size_t i = 0 ; i < it.depth() ; ++i)
4487 if (!it[i].inset().inMathed())
4488 depth += it[i].paragraph().getDepth() + 1;
4489 // remove 1 since the outer inset does not count
4493 static depth_type getItemDepth(ParIterator const & it)
4495 Paragraph const & par = *it;
4496 LabelType const labeltype = par.layout().labeltype;
4498 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4501 // this will hold the lowest depth encountered up to now.
4502 depth_type min_depth = getDepth(it);
4503 ParIterator prev_it = it;
4506 --prev_it.top().pit();
4508 // start of nested inset: go to outer par
4510 if (prev_it.empty()) {
4511 // start of document: nothing to do
4516 // We search for the first paragraph with same label
4517 // that is not more deeply nested.
4518 Paragraph & prev_par = *prev_it;
4519 depth_type const prev_depth = getDepth(prev_it);
4520 if (labeltype == prev_par.layout().labeltype) {
4521 if (prev_depth < min_depth)
4522 return prev_par.itemdepth + 1;
4523 if (prev_depth == min_depth)
4524 return prev_par.itemdepth;
4526 min_depth = min(min_depth, prev_depth);
4527 // small optimization: if we are at depth 0, we won't
4528 // find anything else
4529 if (prev_depth == 0)
4535 static bool needEnumCounterReset(ParIterator const & it)
4537 Paragraph const & par = *it;
4538 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4539 depth_type const cur_depth = par.getDepth();
4540 ParIterator prev_it = it;
4541 while (prev_it.pit()) {
4542 --prev_it.top().pit();
4543 Paragraph const & prev_par = *prev_it;
4544 if (prev_par.getDepth() <= cur_depth)
4545 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4547 // start of nested inset: reset
4552 // set the label of a paragraph. This includes the counters.
4553 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4555 BufferParams const & bp = owner_->masterBuffer()->params();
4556 DocumentClass const & textclass = bp.documentClass();
4557 Paragraph & par = it.paragraph();
4558 Layout const & layout = par.layout();
4559 Counters & counters = textclass.counters();
4561 if (par.params().startOfAppendix()) {
4562 // We want to reset the counter corresponding to toplevel sectioning
4563 Layout const & lay = textclass.getTOCLayout();
4564 docstring const cnt = lay.counter;
4566 counters.reset(cnt);
4567 counters.appendix(true);
4569 par.params().appendix(counters.appendix());
4571 // Compute the item depth of the paragraph
4572 par.itemdepth = getItemDepth(it);
4574 if (layout.margintype == MARGIN_MANUAL) {
4575 if (par.params().labelWidthString().empty())
4576 par.params().labelWidthString(par.expandLabel(layout, bp));
4577 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4578 // we do not need to do anything here, since the empty case is
4579 // handled during export.
4581 par.params().labelWidthString(docstring());
4584 switch(layout.labeltype) {
4585 case LABEL_ITEMIZE: {
4586 // At some point of time we should do something more
4587 // clever here, like:
4588 // par.params().labelString(
4589 // bp.user_defined_bullet(par.itemdepth).getText());
4590 // for now, use a simple hardcoded label
4591 docstring itemlabel;
4592 switch (par.itemdepth) {
4594 itemlabel = char_type(0x2022);
4597 itemlabel = char_type(0x2013);
4600 itemlabel = char_type(0x2217);
4603 itemlabel = char_type(0x2219); // or 0x00b7
4606 par.params().labelString(itemlabel);
4610 case LABEL_ENUMERATE: {
4611 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4613 switch (par.itemdepth) {
4622 enumcounter += "iv";
4625 // not a valid enumdepth...
4629 // Maybe we have to reset the enumeration counter.
4630 if (needEnumCounterReset(it))
4631 counters.reset(enumcounter);
4632 counters.step(enumcounter, utype);
4634 string const & lang = par.getParLanguage(bp)->code();
4635 par.params().labelString(counters.theCounter(enumcounter, lang));
4640 case LABEL_SENSITIVE: {
4641 string const & type = counters.current_float();
4642 docstring full_label;
4644 full_label = owner_->B_("Senseless!!! ");
4646 docstring name = owner_->B_(textclass.floats().getType(type).name());
4647 if (counters.hasCounter(from_utf8(type))) {
4648 string const & lang = par.getParLanguage(bp)->code();
4649 counters.step(from_utf8(type), utype);
4650 full_label = bformat(from_ascii("%1$s %2$s:"),
4652 counters.theCounter(from_utf8(type), lang));
4654 full_label = bformat(from_ascii("%1$s #:"), name);
4656 par.params().labelString(full_label);
4660 case LABEL_NO_LABEL:
4661 par.params().labelString(docstring());
4665 case LABEL_CENTERED:
4666 case LABEL_STATIC: {
4667 docstring const & lcounter = layout.counter;
4668 if (!lcounter.empty()) {
4669 if (layout.toclevel <= bp.secnumdepth
4670 && (layout.latextype != LATEX_ENVIRONMENT
4671 || it.text()->isFirstInSequence(it.pit()))) {
4672 if (counters.hasCounter(lcounter))
4673 counters.step(lcounter, utype);
4674 par.params().labelString(par.expandLabel(layout, bp));
4676 par.params().labelString(docstring());
4678 par.params().labelString(par.expandLabel(layout, bp));
4684 par.params().labelString(par.expandLabel(layout, bp));
4689 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4691 // LASSERT: Is it safe to continue here, or should we just return?
4692 LASSERT(parit.pit() == 0, /**/);
4694 // Set the position of the text in the buffer to be able
4695 // to resolve macros in it.
4696 parit.text()->setMacrocontextPosition(parit);
4698 depth_type maxdepth = 0;
4699 pit_type const lastpit = parit.lastpit();
4700 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4701 // reduce depth if necessary
4702 if (parit->params().depth() > maxdepth) {
4703 /** FIXME: this function is const, but
4704 * nevertheless it modifies the buffer. To be
4705 * cleaner, one should modify the buffer in
4706 * another function, which is actually
4707 * non-const. This would however be costly in
4708 * terms of code duplication.
4710 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4711 parit->params().depth(maxdepth);
4713 maxdepth = parit->getMaxDepthAfter();
4715 if (utype == OutputUpdate) {
4716 // track the active counters
4717 // we have to do this for the master buffer, since the local
4718 // buffer isn't tracking anything.
4719 masterBuffer()->params().documentClass().counters().
4720 setActiveLayout(parit->layout());
4723 // set the counter for this paragraph
4724 d->setLabel(parit, utype);
4727 InsetList::const_iterator iit = parit->insetList().begin();
4728 InsetList::const_iterator end = parit->insetList().end();
4729 for (; iit != end; ++iit) {
4730 parit.pos() = iit->pos;
4731 iit->inset->updateBuffer(parit, utype);
4737 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4738 WordLangTuple & word_lang, docstring_list & suggestions) const
4742 suggestions.clear();
4743 word_lang = WordLangTuple();
4744 bool const to_end = to.empty();
4745 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4746 // OK, we start from here.
4747 for (; from != end; from.forwardPos()) {
4748 // We are only interested in text so remove the math CursorSlice.
4749 while (from.inMathed()) {
4753 // If from is at the end of the document (which is possible
4754 // when leaving the mathed) LyX will crash later otherwise.
4755 if (from.atEnd() || (!to_end && from >= end))
4758 from.paragraph().spellCheck();
4759 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4760 if (SpellChecker::misspelled(res)) {
4765 // Do not increase progress when from == to, otherwise the word
4766 // count will be wrong.
4776 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4778 bool inword = false;
4783 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4784 if (!dit.inTexted()) {
4789 Paragraph const & par = dit.paragraph();
4790 pos_type const pos = dit.pos();
4792 // Copied and adapted from isWordSeparator() in Paragraph
4793 if (pos == dit.lastpos()) {
4796 Inset const * ins = par.getInset(pos);
4797 if (ins && skipNoOutput && !ins->producesOutput()) {
4800 // stop if end of range was skipped
4801 if (!to.atEnd() && dit >= to)
4804 } else if (!par.isDeleted(pos)) {
4805 if (par.isWordSeparator(pos))
4811 if (ins && ins->isLetter())
4813 else if (ins && ins->isSpace())
4816 char_type const c = par.getChar(pos);
4817 if (isPrintableNonspace(c))
4819 else if (isSpace(c))
4829 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4831 d->updateStatistics(from, to, skipNoOutput);
4835 int Buffer::wordCount() const
4837 return d->wordCount();
4841 int Buffer::charCount(bool with_blanks) const
4843 return d->charCount(with_blanks);
4847 Buffer::ReadStatus Buffer::reload()
4850 // c.f. bug http://www.lyx.org/trac/ticket/6587
4851 removeAutosaveFile();
4852 // e.g., read-only status could have changed due to version control
4853 d->filename.refresh();
4854 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4856 // clear parent. this will get reset if need be.
4858 ReadStatus const status = loadLyXFile();
4859 if (status == ReadSuccess) {
4864 message(bformat(_("Document %1$s reloaded."), disp_fn));
4867 message(bformat(_("Could not reload document %1$s."), disp_fn));
4877 bool Buffer::saveAs(FileName const & fn)
4879 FileName const old_name = fileName();
4880 FileName const old_auto = getAutosaveFileName();
4881 bool const old_unnamed = isUnnamed();
4888 // bring the autosave file with us, just in case.
4889 moveAutosaveFile(old_auto);
4890 // validate version control data and
4891 // correct buffer title
4892 lyxvc().file_found_hook(fileName());
4894 // the file has now been saved to the new location.
4895 // we need to check that the locations of child buffers
4897 checkChildBuffers();
4898 checkMasterBuffer();
4902 // reset the old filename and unnamed state
4903 setFileName(old_name);
4904 setUnnamed(old_unnamed);
4910 // FIXME We could do better here, but it is complicated. What would be
4911 // nice is to offer either (a) to save the child buffer to an appropriate
4912 // location, so that it would "move with the master", or else (b) to update
4913 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4914 // complicated, because the code for this lives in GuiView.
4915 void Buffer::checkChildBuffers()
4917 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4918 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4919 for (; it != en; ++it) {
4920 DocIterator dit = it->second;
4921 Buffer * cbuf = const_cast<Buffer *>(it->first);
4922 if (!cbuf || !theBufferList().isLoaded(cbuf))
4924 Inset * inset = dit.nextInset();
4925 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4926 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4927 docstring const & incfile = inset_inc->getParam("filename");
4928 string oldloc = cbuf->absFileName();
4929 string newloc = makeAbsPath(to_utf8(incfile),
4930 onlyPath(absFileName())).absFileName();
4931 if (oldloc == newloc)
4933 // the location of the child file is incorrect.
4934 Alert::warning(_("Included File Invalid"),
4935 bformat(_("Saving this document to a new location has made the file:\n"
4937 "inaccessible. You will need to update the included filename."),
4938 from_utf8(oldloc)));
4940 inset_inc->setChildBuffer(0);
4942 // invalidate cache of children
4943 d->children_positions.clear();
4944 d->position_to_children.clear();
4948 // If a child has been saved under a different name/path, it might have been
4949 // orphaned. Therefore the master needs to be reset (bug 8161).
4950 void Buffer::checkMasterBuffer()
4952 Buffer const * const master = masterBuffer();
4956 // necessary to re-register the child (bug 5873)
4957 // FIXME: clean up updateMacros (here, only
4958 // child registering is needed).
4959 master->updateMacros();
4960 // (re)set master as master buffer, but only
4961 // if we are a real child
4962 if (master->isChild(this))