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"
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"
61 #include "TexStream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/PreviewLoader.h"
84 #include "frontends/alert.h"
85 #include "frontends/Delegates.h"
86 #include "frontends/WorkAreaManager.h"
88 #include "support/lassert.h"
89 #include "support/convert.h"
90 #include "support/debug.h"
91 #include "support/docstring_list.h"
92 #include "support/ExceptionMessage.h"
93 #include "support/FileName.h"
94 #include "support/FileNameList.h"
95 #include "support/filetools.h"
96 #include "support/ForkedCalls.h"
97 #include "support/gettext.h"
98 #include "support/gzstream.h"
99 #include "support/lstrings.h"
100 #include "support/lyxalgo.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/textutils.h"
106 #include "support/types.h"
108 #include "support/bind.h"
109 #include "support/shared_ptr.h"
120 using namespace lyx::support;
121 using namespace lyx::graphics;
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
153 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
157 delete preview_loader_;
165 /// search for macro in local (buffer) table or in children
166 MacroData const * getBufferMacro(docstring const & name,
167 DocIterator const & pos) const;
169 /// Update macro table starting with position of it \param it in some
171 void updateMacros(DocIterator & it, DocIterator & scope);
173 void setLabel(ParIterator & it, UpdateType utype) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this an unnamed file (New...)?
199 /// is this an internal bufffer?
200 bool internal_buffer;
205 /// name of the file the buffer is associated with.
208 /** Set to true only when the file is fully loaded.
209 * Used to prevent the premature generation of previews
210 * and by the citation inset.
212 bool file_fully_loaded;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
221 typedef pair<DocIterator, MacroData> ScopeMacro;
222 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
223 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
224 /// map from the macro name to the position map,
225 /// which maps the macro definition position to the scope and the MacroData.
226 NamePositionScopeMacroMap macros;
227 /// This seem to change the way Buffer::getMacro() works
228 mutable bool macro_lock;
230 /// positions of child buffers in the buffer
231 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
232 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Container for all sort of Buffer dependant errors.
240 map<string, ErrorList> errorLists;
242 /// timestamp and checksum used to test if the file has been externally
243 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245 unsigned long checksum_;
248 frontend::WorkAreaManager * wa_;
250 frontend::GuiBufferDelegate * gui_;
255 /// A cache for the bibfiles (including bibfiles of loaded child
256 /// documents), needed for appropriate update of natbib labels.
257 mutable support::FileNameList bibfiles_cache_;
259 // FIXME The caching mechanism could be improved. At present, we have a
260 // cache for each Buffer, that caches all the bibliography info for that
261 // Buffer. A more efficient solution would be to have a global cache per
262 // file, and then to construct the Buffer's bibinfo from that.
263 /// A cache for bibliography info
264 mutable BiblioInfo bibinfo_;
265 /// whether the bibinfo cache is valid
266 mutable bool bibinfo_cache_valid_;
267 /// whether the bibfile cache is valid
268 mutable bool bibfile_cache_valid_;
269 /// Cache of timestamps of .bib files
270 map<FileName, time_t> bibfile_status_;
271 /// Indicates whether the bibinfo has changed since the last time
272 /// we ran updateBuffer(), i.e., whether citation labels may need
274 mutable bool cite_labels_valid_;
276 mutable RefCache ref_cache_;
278 /// our Text that should be wrapped in an InsetText
282 PreviewLoader * preview_loader_;
284 /// This is here to force the test to be done whenever parent_buffer
286 Buffer const * parent() const
288 // ignore_parent temporarily "orphans" a buffer
289 // (e.g. if a child is compiled standalone)
292 // if parent_buffer is not loaded, then it has been unloaded,
293 // which means that parent_buffer is an invalid pointer. So we
294 // set it to null in that case.
295 // however, the BufferList doesn't know about cloned buffers, so
296 // they will always be regarded as unloaded. in that case, we hope
298 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
300 return parent_buffer;
304 void setParent(Buffer const * pb)
306 if (parent_buffer == pb)
309 if (!cloned_buffer_ && parent_buffer && pb)
310 LYXERR0("Warning: a buffer should not have two parents!");
312 if (!cloned_buffer_ && parent_buffer) {
313 parent_buffer->invalidateBibfileCache();
314 parent_buffer->invalidateBibinfoCache();
318 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
319 /// This one is useful for preview detached in a thread.
320 Buffer const * cloned_buffer_;
322 CloneList * clone_list_;
323 /// are we in the process of exporting this buffer?
324 mutable bool doing_export;
326 /// compute statistics
327 /// \p from initial position
328 /// \p to points to the end position
329 void updateStatistics(DocIterator & from, DocIterator & to,
330 bool skipNoOutput = true);
331 /// statistics accessor functions
332 int wordCount() const
336 int charCount(bool with_blanks) const
339 + (with_blanks ? blank_count_ : 0);
343 /// So we can force access via the accessors.
344 mutable Buffer const * parent_buffer;
353 /// Creates the per buffer temporary directory
354 static FileName createBufferTmpDir()
357 // We are in our own directory. Why bother to mangle name?
358 // In fact I wrote this code to circumvent a problematic behaviour
359 // (bug?) of EMX mkstemp().
360 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
361 convert<string>(count++));
363 if (!tmpfl.createDirectory(0777)) {
364 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
365 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
366 from_utf8(tmpfl.absFileName())));
372 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
373 Buffer const * cloned_buffer)
374 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
375 internal_buffer(false), read_only(readonly_), filename(file),
376 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
377 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
378 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
379 cite_labels_valid_(false), preview_loader_(0),
380 cloned_buffer_(cloned_buffer), clone_list_(0),
381 doing_export(false), parent_buffer(0)
383 if (!cloned_buffer_) {
384 temppath = createBufferTmpDir();
385 lyxvc.setBuffer(owner_);
387 wa_ = new frontend::WorkAreaManager;
390 temppath = cloned_buffer_->d->temppath;
391 file_fully_loaded = true;
392 params = cloned_buffer_->d->params;
393 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
394 bibinfo_ = cloned_buffer_->d->bibinfo_;
395 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
396 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
397 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
398 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
399 unnamed = cloned_buffer_->d->unnamed;
400 internal_buffer = cloned_buffer_->d->internal_buffer;
404 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
405 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
407 LYXERR(Debug::INFO, "Buffer::Buffer()");
409 d->inset = new InsetText(*cloned_buffer->d->inset);
410 d->inset->setBuffer(*this);
411 // FIXME: optimize this loop somewhat, maybe by creating a new
412 // general recursive Inset::setId().
413 DocIterator it = doc_iterator_begin(this);
414 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
415 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
416 it.paragraph().setId(cloned_it.paragraph().id());
418 d->inset = new InsetText(this);
419 d->inset->setAutoBreakRows(true);
420 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
426 LYXERR(Debug::INFO, "Buffer::~Buffer()");
427 // here the buffer should take care that it is
428 // saved properly, before it goes into the void.
430 // GuiView already destroyed
434 // No need to do additional cleanups for internal buffer.
440 // this is in case of recursive includes: we won't try to delete
441 // ourselves as a child.
442 d->clone_list_->erase(this);
443 // loop over children
444 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
445 Impl::BufferPositionMap::iterator end = d->children_positions.end();
446 for (; it != end; ++it) {
447 Buffer * child = const_cast<Buffer *>(it->first);
448 if (d->clone_list_->erase(child))
451 // if we're the master buffer, then we should get rid of the list
454 // if this is not empty, we have leaked something. worse, one of the
455 // children still has a reference to this list.
456 LASSERT(d->clone_list_->empty(), /* */);
457 list<CloneList *>::iterator it =
458 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
459 LASSERT(it != cloned_buffers.end(), /* */);
460 cloned_buffers.erase(it);
461 delete d->clone_list_;
463 // FIXME Do we really need to do this right before we delete d?
464 // clear references to children in macro tables
465 d->children_positions.clear();
466 d->position_to_children.clear();
468 // loop over children
469 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
470 Impl::BufferPositionMap::iterator end = d->children_positions.end();
471 for (; it != end; ++it) {
472 Buffer * child = const_cast<Buffer *>(it->first);
473 if (theBufferList().isLoaded(child))
474 theBufferList().releaseChild(this, child);
478 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
479 msg += emergencyWrite();
480 Alert::warning(_("Attempting to close changed document!"), msg);
483 // FIXME Do we really need to do this right before we delete d?
484 // clear references to children in macro tables
485 d->children_positions.clear();
486 d->position_to_children.clear();
488 if (!d->temppath.destroyDirectory()) {
489 Alert::warning(_("Could not remove temporary directory"),
490 bformat(_("Could not remove the temporary directory %1$s"),
491 from_utf8(d->temppath.absFileName())));
500 Buffer * Buffer::cloneFromMaster() const
503 cloned_buffers.push_back(new CloneList);
504 CloneList * clones = cloned_buffers.back();
506 masterBuffer()->cloneWithChildren(bufmap, clones);
508 // make sure we got cloned
509 BufferMap::const_iterator bit = bufmap.find(this);
510 LASSERT(bit != bufmap.end(), return 0);
511 Buffer * cloned_buffer = bit->second;
513 return cloned_buffer;
517 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
519 // have we already been cloned?
520 if (bufmap.find(this) != bufmap.end())
523 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
525 // The clone needs its own DocumentClass, since running updateBuffer() will
526 // modify it, and we would otherwise be sharing it with the original Buffer.
527 buffer_clone->params().makeDocumentClass();
529 cap::switchBetweenClasses(
530 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
531 static_cast<InsetText &>(buffer_clone->inset()), el);
533 bufmap[this] = buffer_clone;
534 clones->insert(buffer_clone);
535 buffer_clone->d->clone_list_ = clones;
536 buffer_clone->d->macro_lock = true;
537 buffer_clone->d->children_positions.clear();
539 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
540 // math macro caches need to be rethought and simplified.
541 // I am not sure wether we should handle Buffer cloning here or in BufferList.
542 // Right now BufferList knows nothing about buffer clones.
543 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
544 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
545 for (; it != end; ++it) {
546 DocIterator dit = it->first.clone(buffer_clone);
547 dit.setBuffer(buffer_clone);
548 Buffer * child = const_cast<Buffer *>(it->second.second);
550 child->cloneWithChildren(bufmap, clones);
551 BufferMap::iterator const bit = bufmap.find(child);
552 LASSERT(bit != bufmap.end(), continue);
553 Buffer * child_clone = bit->second;
555 Inset * inset = dit.nextInset();
556 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
557 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
558 inset_inc->setChildBuffer(child_clone);
559 child_clone->d->setParent(buffer_clone);
560 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
561 buffer_clone->setChild(dit, child_clone);
563 buffer_clone->d->macro_lock = false;
568 Buffer * Buffer::cloneBufferOnly() const {
569 cloned_buffers.push_back(new CloneList);
570 CloneList * clones = cloned_buffers.back();
571 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
573 // The clone needs its own DocumentClass, since running updateBuffer() will
574 // modify it, and we would otherwise be sharing it with the original Buffer.
575 buffer_clone->params().makeDocumentClass();
577 cap::switchBetweenClasses(
578 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
579 static_cast<InsetText &>(buffer_clone->inset()), el);
581 clones->insert(buffer_clone);
582 buffer_clone->d->clone_list_ = clones;
584 // we won't be cloning the children
585 buffer_clone->d->children_positions.clear();
590 bool Buffer::isClone() const
592 return d->cloned_buffer_;
596 void Buffer::changed(bool update_metrics) const
599 d->wa_->redrawAll(update_metrics);
603 frontend::WorkAreaManager & Buffer::workAreaManager() const
605 LASSERT(d->wa_, /**/);
610 Text & Buffer::text() const
612 return d->inset->text();
616 Inset & Buffer::inset() const
622 BufferParams & Buffer::params()
628 BufferParams const & Buffer::params() const
634 ParagraphList & Buffer::paragraphs()
636 return text().paragraphs();
640 ParagraphList const & Buffer::paragraphs() const
642 return text().paragraphs();
646 LyXVC & Buffer::lyxvc()
652 LyXVC const & Buffer::lyxvc() const
658 string const Buffer::temppath() const
660 return d->temppath.absFileName();
664 TexRow & Buffer::texrow()
670 TexRow const & Buffer::texrow() const
676 TocBackend & Buffer::tocBackend() const
678 return d->toc_backend;
682 Undo & Buffer::undo()
688 void Buffer::setChild(DocIterator const & dit, Buffer * child)
690 d->children_positions[child] = dit;
694 string Buffer::latexName(bool const no_path) const
696 FileName latex_name =
697 makeLatexName(d->exportFileName());
698 return no_path ? latex_name.onlyFileName()
699 : latex_name.absFileName();
703 FileName Buffer::Impl::exportFileName() const
705 docstring const branch_suffix =
706 params.branchlist().getFileNameSuffix();
707 if (branch_suffix.empty())
710 string const name = filename.onlyFileNameWithoutExt()
711 + to_utf8(branch_suffix);
712 FileName res(filename.onlyPath().absFileName() + "/" + name);
713 res.changeExtension(filename.extension());
719 string Buffer::logName(LogType * type) const
721 string const filename = latexName(false);
723 if (filename.empty()) {
729 string const path = temppath();
731 FileName const fname(addName(temppath(),
732 onlyFileName(changeExtension(filename,
735 // FIXME: how do we know this is the name of the build log?
736 FileName const bname(
737 addName(path, onlyFileName(
738 changeExtension(filename,
739 formats.extension(params().bufferFormat()) + ".out"))));
741 // Also consider the master buffer log file
742 FileName masterfname = fname;
744 if (masterBuffer() != this) {
745 string const mlogfile = masterBuffer()->logName(&mtype);
746 masterfname = FileName(mlogfile);
749 // If no Latex log or Build log is newer, show Build log
750 if (bname.exists() &&
751 ((!fname.exists() && !masterfname.exists())
752 || (fname.lastModified() < bname.lastModified()
753 && masterfname.lastModified() < bname.lastModified()))) {
754 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
757 return bname.absFileName();
758 // If we have a newer master file log or only a master log, show this
759 } else if (fname != masterfname
760 && (!fname.exists() && (masterfname.exists()
761 || fname.lastModified() < masterfname.lastModified()))) {
762 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
765 return masterfname.absFileName();
767 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
770 return fname.absFileName();
774 void Buffer::setReadonly(bool const flag)
776 if (d->read_only != flag) {
783 void Buffer::setFileName(FileName const & fname)
785 bool const changed = fname != d->filename;
788 lyxvc().file_found_hook(fname);
789 setReadonly(d->filename.isReadOnly());
795 int Buffer::readHeader(Lexer & lex)
797 int unknown_tokens = 0;
799 int begin_header_line = -1;
801 // Initialize parameters that may be/go lacking in header:
802 params().branchlist().clear();
803 params().preamble.erase();
804 params().options.erase();
805 params().master.erase();
806 params().float_placement.erase();
807 params().paperwidth.erase();
808 params().paperheight.erase();
809 params().leftmargin.erase();
810 params().rightmargin.erase();
811 params().topmargin.erase();
812 params().bottommargin.erase();
813 params().headheight.erase();
814 params().headsep.erase();
815 params().footskip.erase();
816 params().columnsep.erase();
817 params().fonts_cjk.erase();
818 params().listings_params.clear();
819 params().clearLayoutModules();
820 params().clearRemovedModules();
821 params().clearIncludedChildren();
822 params().pdfoptions().clear();
823 params().indiceslist().clear();
824 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
825 params().isbackgroundcolor = false;
826 params().fontcolor = RGBColor(0, 0, 0);
827 params().isfontcolor = false;
828 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
829 params().boxbgcolor = RGBColor(0xFF, 0, 0);
830 params().html_latex_start.clear();
831 params().html_latex_end.clear();
832 params().html_math_img_scale = 1.0;
833 params().output_sync_macro.erase();
834 params().local_layout.clear();
836 for (int i = 0; i < 4; ++i) {
837 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
838 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
841 ErrorList & errorList = d->errorLists["Parse"];
850 if (token == "\\end_header")
854 if (token == "\\begin_header") {
855 begin_header_line = line;
859 LYXERR(Debug::PARSER, "Handling document header token: `"
862 string unknown = params().readToken(lex, token, d->filename.onlyPath());
863 if (!unknown.empty()) {
864 if (unknown[0] != '\\' && token == "\\textclass") {
865 Alert::warning(_("Unknown document class"),
866 bformat(_("Using the default document class, because the "
867 "class %1$s is unknown."), from_utf8(unknown)));
870 docstring const s = bformat(_("Unknown token: "
874 errorList.push_back(ErrorItem(_("Document header error"),
879 if (begin_header_line) {
880 docstring const s = _("\\begin_header is missing");
881 errorList.push_back(ErrorItem(_("Document header error"),
885 params().makeDocumentClass();
887 return unknown_tokens;
892 // changed to be public and have one parameter
893 // Returns true if "\end_document" is not read (Asger)
894 bool Buffer::readDocument(Lexer & lex)
896 ErrorList & errorList = d->errorLists["Parse"];
899 // remove dummy empty par
900 paragraphs().clear();
902 if (!lex.checkFor("\\begin_document")) {
903 docstring const s = _("\\begin_document is missing");
904 errorList.push_back(ErrorItem(_("Document header error"),
910 if (params().outputChanges) {
911 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
912 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
913 LaTeXFeatures::isAvailable("xcolor");
915 if (!dvipost && !xcolorulem) {
916 Alert::warning(_("Changes not shown in LaTeX output"),
917 _("Changes will not be highlighted in LaTeX output, "
918 "because neither dvipost nor xcolor/ulem are installed.\n"
919 "Please install these packages or redefine "
920 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
921 } else if (!xcolorulem) {
922 Alert::warning(_("Changes not shown in LaTeX output"),
923 _("Changes will not be highlighted in LaTeX output "
924 "when using pdflatex, because xcolor and ulem are not installed.\n"
925 "Please install both packages or redefine "
926 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
930 if (!params().master.empty()) {
931 FileName const master_file = makeAbsPath(params().master,
932 onlyPath(absFileName()));
933 if (isLyXFileName(master_file.absFileName())) {
935 checkAndLoadLyXFile(master_file, true);
937 // necessary e.g. after a reload
938 // to re-register the child (bug 5873)
939 // FIXME: clean up updateMacros (here, only
940 // child registering is needed).
941 master->updateMacros();
942 // set master as master buffer, but only
943 // if we are a real child
944 if (master->isChild(this))
946 // if the master is not fully loaded
947 // it is probably just loading this
948 // child. No warning needed then.
949 else if (master->isFullyLoaded())
950 LYXERR0("The master '"
952 << "' assigned to this document ("
954 << ") does not include "
955 "this document. Ignoring the master assignment.");
960 // assure we have a default index
961 params().indiceslist().addDefault(B_("Index"));
964 bool const res = text().read(lex, errorList, d->inset);
966 // inform parent buffer about local macros
968 Buffer const * pbuf = parent();
969 UserMacroSet::const_iterator cit = usermacros.begin();
970 UserMacroSet::const_iterator end = usermacros.end();
971 for (; cit != end; ++cit)
972 pbuf->usermacros.insert(*cit);
976 updateMacroInstances(InternalUpdate);
981 bool Buffer::readString(string const & s)
983 params().compressed = false;
988 FileName const fn = FileName::tempName("Buffer_readString");
991 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
993 if (success && file_format != LYX_FORMAT) {
994 // We need to call lyx2lyx, so write the input to a file
995 ofstream os(fn.toFilesystemEncoding().c_str());
999 if (readFile(fn) != ReadSuccess)
1004 if (readDocument(lex))
1012 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1016 if (!lex.setFile(fname)) {
1017 Alert::error(_("File Not Found"),
1018 bformat(_("Unable to open file `%1$s'."),
1019 from_utf8(fn.absFileName())));
1020 return ReadFileNotFound;
1024 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1025 if (ret_plf != ReadSuccess)
1028 if (file_format != LYX_FORMAT) {
1030 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1031 if (ret_clf != ReadSuccess)
1033 return readFile(tmpFile);
1036 // FIXME: InsetInfo needs to know whether the file is under VCS
1037 // during the parse process, so this has to be done before.
1038 lyxvc().file_found_hook(d->filename);
1040 if (readDocument(lex)) {
1041 Alert::error(_("Document format failure"),
1042 bformat(_("%1$s ended unexpectedly, which means"
1043 " that it is probably corrupted."),
1044 from_utf8(fn.absFileName())));
1045 return ReadDocumentFailure;
1048 d->file_fully_loaded = true;
1049 d->read_only = !d->filename.isWritable();
1050 params().compressed = formats.isZippedFile(d->filename);
1056 bool Buffer::isFullyLoaded() const
1058 return d->file_fully_loaded;
1062 void Buffer::setFullyLoaded(bool value)
1064 d->file_fully_loaded = value;
1068 PreviewLoader * Buffer::loader() const
1070 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1072 if (!d->preview_loader_)
1073 d->preview_loader_ = new PreviewLoader(*this);
1074 return d->preview_loader_;
1078 void Buffer::removePreviews() const
1080 delete d->preview_loader_;
1081 d->preview_loader_ = 0;
1085 void Buffer::updatePreviews() const
1087 PreviewLoader * ploader = loader();
1091 InsetIterator it = inset_iterator_begin(*d->inset);
1092 InsetIterator const end = inset_iterator_end(*d->inset);
1093 for (; it != end; ++it)
1094 it->addPreview(it, *ploader);
1096 ploader->startLoading();
1100 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1101 FileName const & fn, int & file_format) const
1103 if(!lex.checkFor("\\lyxformat")) {
1104 Alert::error(_("Document format failure"),
1105 bformat(_("%1$s is not a readable LyX document."),
1106 from_utf8(fn.absFileName())));
1107 return ReadNoLyXFormat;
1113 // LyX formats 217 and earlier were written as 2.17. This corresponds
1114 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1115 // these cases. See also: www.lyx.org/trac/changeset/1313.
1116 size_t dot = tmp_format.find_first_of(".,");
1117 if (dot != string::npos)
1118 tmp_format.erase(dot, 1);
1120 file_format = convert<int>(tmp_format);
1125 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1126 FileName & tmpfile, int from_format)
1128 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1129 if(tmpfile.empty()) {
1130 Alert::error(_("Conversion failed"),
1131 bformat(_("%1$s is from a different"
1132 " version of LyX, but a temporary"
1133 " file for converting it could"
1134 " not be created."),
1135 from_utf8(fn.absFileName())));
1136 return LyX2LyXNoTempFile;
1139 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1140 if (lyx2lyx.empty()) {
1141 Alert::error(_("Conversion script not found"),
1142 bformat(_("%1$s is from a different"
1143 " version of LyX, but the"
1144 " conversion script lyx2lyx"
1145 " could not be found."),
1146 from_utf8(fn.absFileName())));
1147 return LyX2LyXNotFound;
1151 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1152 ostringstream command;
1153 command << os::python()
1154 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1155 << " -t " << convert<string>(LYX_FORMAT)
1156 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1157 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1158 string const command_str = command.str();
1160 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1162 cmd_ret const ret = runCommand(command_str);
1163 if (ret.first != 0) {
1164 if (from_format < LYX_FORMAT) {
1165 Alert::error(_("Conversion script failed"),
1166 bformat(_("%1$s is from an older version"
1167 " of LyX and the lyx2lyx script"
1168 " failed to convert it."),
1169 from_utf8(fn.absFileName())));
1170 return LyX2LyXOlderFormat;
1172 Alert::error(_("Conversion script failed"),
1173 bformat(_("%1$s is from a newer version"
1174 " of LyX and the lyx2lyx script"
1175 " failed to convert it."),
1176 from_utf8(fn.absFileName())));
1177 return LyX2LyXNewerFormat;
1184 // Should probably be moved to somewhere else: BufferView? GuiView?
1185 bool Buffer::save() const
1187 docstring const file = makeDisplayPath(absFileName(), 20);
1188 d->filename.refresh();
1190 // check the read-only status before moving the file as a backup
1191 if (d->filename.exists()) {
1192 bool const read_only = !d->filename.isWritable();
1194 Alert::warning(_("File is read-only"),
1195 bformat(_("The file %1$s cannot be written because it "
1196 "is marked as read-only."), file));
1201 // ask if the disk file has been externally modified (use checksum method)
1202 if (fileName().exists() && isExternallyModified(checksum_method)) {
1204 bformat(_("Document %1$s has been externally modified. "
1205 "Are you sure you want to overwrite this file?"), file);
1206 int const ret = Alert::prompt(_("Overwrite modified file?"),
1207 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1212 // We don't need autosaves in the immediate future. (Asger)
1213 resetAutosaveTimers();
1215 FileName backupName;
1216 bool madeBackup = false;
1218 // make a backup if the file already exists
1219 if (lyxrc.make_backup && fileName().exists()) {
1220 backupName = FileName(absFileName() + '~');
1221 if (!lyxrc.backupdir_path.empty()) {
1222 string const mangledName =
1223 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1224 backupName = FileName(addName(lyxrc.backupdir_path,
1228 // Except file is symlink do not copy because of #6587.
1229 // Hard links have bad luck.
1230 if (fileName().isSymLink())
1231 madeBackup = fileName().copyTo(backupName);
1233 madeBackup = fileName().moveTo(backupName);
1236 Alert::error(_("Backup failure"),
1237 bformat(_("Cannot create backup file %1$s.\n"
1238 "Please check whether the directory exists and is writable."),
1239 from_utf8(backupName.absFileName())));
1240 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1244 if (writeFile(d->filename)) {
1248 // Saving failed, so backup is not backup
1250 backupName.moveTo(d->filename);
1256 bool Buffer::writeFile(FileName const & fname) const
1258 if (d->read_only && fname == d->filename)
1261 bool retval = false;
1263 docstring const str = bformat(_("Saving document %1$s..."),
1264 makeDisplayPath(fname.absFileName()));
1267 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1269 if (params().compressed) {
1270 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1271 retval = ofs && write(ofs);
1273 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1274 retval = ofs && write(ofs);
1278 message(str + _(" could not write file!"));
1283 // removeAutosaveFile();
1286 message(str + _(" done."));
1292 docstring Buffer::emergencyWrite()
1294 // No need to save if the buffer has not changed.
1298 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1300 docstring user_message = bformat(
1301 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1303 // We try to save three places:
1304 // 1) Same place as document. Unless it is an unnamed doc.
1306 string s = absFileName();
1309 if (writeFile(FileName(s))) {
1311 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1312 return user_message;
1314 user_message += " " + _("Save failed! Trying again...\n");
1318 // 2) In HOME directory.
1319 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1321 lyxerr << ' ' << s << endl;
1322 if (writeFile(FileName(s))) {
1324 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1325 return user_message;
1328 user_message += " " + _("Save failed! Trying yet again...\n");
1330 // 3) In "/tmp" directory.
1331 // MakeAbsPath to prepend the current
1332 // drive letter on OS/2
1333 s = addName(package().temp_dir().absFileName(), absFileName());
1335 lyxerr << ' ' << s << endl;
1336 if (writeFile(FileName(s))) {
1338 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1339 return user_message;
1342 user_message += " " + _("Save failed! Bummer. Document is lost.");
1345 return user_message;
1349 bool Buffer::write(ostream & ofs) const
1352 // Use the standard "C" locale for file output.
1353 ofs.imbue(locale::classic());
1356 // The top of the file should not be written by params().
1358 // write out a comment in the top of the file
1359 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1360 << " created this file. For more info see http://www.lyx.org/\n"
1361 << "\\lyxformat " << LYX_FORMAT << "\n"
1362 << "\\begin_document\n";
1364 /// For each author, set 'used' to true if there is a change
1365 /// by this author in the document; otherwise set it to 'false'.
1366 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1367 AuthorList::Authors::const_iterator a_end = params().authors().end();
1368 for (; a_it != a_end; ++a_it)
1369 a_it->setUsed(false);
1371 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1372 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1373 for ( ; it != end; ++it)
1374 it->checkAuthors(params().authors());
1376 // now write out the buffer parameters.
1377 ofs << "\\begin_header\n";
1378 params().writeFile(ofs);
1379 ofs << "\\end_header\n";
1382 ofs << "\n\\begin_body\n";
1384 ofs << "\n\\end_body\n";
1386 // Write marker that shows file is complete
1387 ofs << "\\end_document" << endl;
1389 // Shouldn't really be needed....
1392 // how to check if close went ok?
1393 // Following is an attempt... (BE 20001011)
1395 // good() returns false if any error occured, including some
1396 // formatting error.
1397 // bad() returns true if something bad happened in the buffer,
1398 // which should include file system full errors.
1403 lyxerr << "File was not closed properly." << endl;
1410 bool Buffer::makeLaTeXFile(FileName const & fname,
1411 string const & original_path,
1412 OutputParams const & runparams_in,
1413 OutputWhat output) const
1415 OutputParams runparams = runparams_in;
1417 // This is necessary for LuaTeX/XeTeX with tex fonts.
1418 // See FIXME in BufferParams::encoding()
1419 if (runparams.isFullUnicode())
1420 runparams.encoding = encodings.fromLyXName("utf8-plain");
1422 string const encoding = runparams.encoding->iconvName();
1423 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1426 try { ofs.reset(encoding); }
1427 catch (iconv_codecvt_facet_exception const & e) {
1428 lyxerr << "Caught iconv exception: " << e.what() << endl;
1429 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1430 "verify that the support software for your encoding (%1$s) is "
1431 "properly installed"), from_ascii(encoding)));
1434 if (!openFileWrite(ofs, fname))
1437 //TexStream ts(ofs.rdbuf(), &texrow());
1438 ErrorList & errorList = d->errorLists["Export"];
1440 bool failed_export = false;
1441 otexstream os(ofs, d->texrow);
1443 // make sure we are ready to export
1444 // this needs to be done before we validate
1445 // FIXME Do we need to do this all the time? I.e., in children
1446 // of a master we are exporting?
1448 updateMacroInstances(OutputUpdate);
1451 os.texrow().reset();
1452 writeLaTeXSource(os, original_path, runparams, output);
1454 catch (EncodingException const & e) {
1455 odocstringstream ods;
1456 ods.put(e.failed_char);
1458 oss << "0x" << hex << e.failed_char << dec;
1459 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1460 " (code point %2$s)"),
1461 ods.str(), from_utf8(oss.str()));
1462 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1463 "representable in the chosen encoding.\n"
1464 "Changing the document encoding to utf8 could help."),
1465 e.par_id, e.pos, e.pos + 1));
1466 failed_export = true;
1468 catch (iconv_codecvt_facet_exception const & e) {
1469 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1470 _(e.what()), -1, 0, 0));
1471 failed_export = true;
1473 catch (exception const & e) {
1474 errorList.push_back(ErrorItem(_("conversion failed"),
1475 _(e.what()), -1, 0, 0));
1476 failed_export = true;
1479 lyxerr << "Caught some really weird exception..." << endl;
1485 failed_export = true;
1486 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1490 return !failed_export;
1494 void Buffer::writeLaTeXSource(otexstream & os,
1495 string const & original_path,
1496 OutputParams const & runparams_in,
1497 OutputWhat output) const
1499 // The child documents, if any, shall be already loaded at this point.
1501 OutputParams runparams = runparams_in;
1503 // If we are compiling a file standalone, even if this is the
1504 // child of some other buffer, let's cut the link here, so the
1505 // file is really independent and no concurring settings from
1506 // the master (e.g. branch state) interfere (see #8100).
1507 if (!runparams.is_child)
1508 d->ignore_parent = true;
1510 // Classify the unicode characters appearing in math insets
1511 Encodings::initUnicodeMath(*this);
1513 // validate the buffer.
1514 LYXERR(Debug::LATEX, " Validating buffer...");
1515 LaTeXFeatures features(*this, params(), runparams);
1517 runparams.use_polyglossia = features.usePolyglossia();
1518 LYXERR(Debug::LATEX, " Buffer validation done.");
1520 bool const output_preamble =
1521 output == FullSource || output == OnlyPreamble;
1522 bool const output_body =
1523 output == FullSource || output == OnlyBody;
1525 // The starting paragraph of the coming rows is the
1526 // first paragraph of the document. (Asger)
1527 if (output_preamble && runparams.nice) {
1528 os << "%% LyX " << lyx_version << " created this file. "
1529 "For more info, see http://www.lyx.org/.\n"
1530 "%% Do not edit unless you really know what "
1533 LYXERR(Debug::INFO, "lyx document header finished");
1535 // There are a few differences between nice LaTeX and usual files:
1536 // usual files have \batchmode and special input@path to allow
1537 // inclusion of figures specified by an explicitly relative path
1538 // (i.e., a path starting with './' or '../') with either \input or
1539 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1540 // input@path is set when the actual parameter original_path is set.
1541 // This is done for usual tex-file, but not for nice-latex-file.
1542 // (Matthias 250696)
1543 // Note that input@path is only needed for something the user does
1544 // in the preamble, included .tex files or ERT, files included by
1545 // LyX work without it.
1546 if (output_preamble) {
1547 if (!runparams.nice) {
1548 // code for usual, NOT nice-latex-file
1549 os << "\\batchmode\n"; // changed from \nonstopmode
1551 if (!original_path.empty()) {
1553 // We don't know the encoding of inputpath
1554 docstring const inputpath = from_utf8(original_path);
1555 docstring uncodable_glyphs;
1556 Encoding const * const enc = runparams.encoding;
1558 for (size_t n = 0; n < inputpath.size(); ++n) {
1559 if (!enc->encodable(inputpath[n])) {
1560 docstring const glyph(1, inputpath[n]);
1561 LYXERR0("Uncodable character '"
1563 << "' in input path!");
1564 uncodable_glyphs += glyph;
1569 // warn user if we found uncodable glyphs.
1570 if (!uncodable_glyphs.empty()) {
1571 frontend::Alert::warning(
1572 _("Uncodable character in file path"),
1574 _("The path of your document\n"
1576 "contains glyphs that are unknown "
1577 "in the current document encoding "
1578 "(namely %2$s). This may result in "
1579 "incomplete output, unless "
1580 "TEXINPUTS contains the document "
1581 "directory and you don't use "
1582 "explicitly relative paths (i.e., "
1583 "paths starting with './' or "
1584 "'../') in the preamble or in ERT."
1585 "\n\nIn case of problems, choose "
1586 "an appropriate document encoding\n"
1587 "(such as utf8) or change the "
1589 inputpath, uncodable_glyphs));
1592 support::latex_path(original_path);
1593 if (contains(docdir, '#')) {
1594 docdir = subst(docdir, "#", "\\#");
1595 os << "\\catcode`\\#=11"
1596 "\\def\\#{#}\\catcode`\\#=6\n";
1598 if (contains(docdir, '%')) {
1599 docdir = subst(docdir, "%", "\\%");
1600 os << "\\catcode`\\%=11"
1601 "\\def\\%{%}\\catcode`\\%=14\n";
1603 os << "\\makeatletter\n"
1604 << "\\def\\input@path{{"
1605 << docdir << "/}}\n"
1606 << "\\makeatother\n";
1610 // get parent macros (if this buffer has a parent) which will be
1611 // written at the document begin further down.
1612 MacroSet parentMacros;
1613 listParentMacros(parentMacros, features);
1615 // Write the preamble
1616 runparams.use_babel = params().writeLaTeX(os, features,
1617 d->filename.onlyPath());
1619 runparams.use_japanese = features.isRequired("japanese");
1622 // Restore the parenthood if needed
1623 if (!runparams.is_child)
1624 d->ignore_parent = false;
1629 os << "\\begin{document}\n";
1631 // output the parent macros
1632 MacroSet::iterator it = parentMacros.begin();
1633 MacroSet::iterator end = parentMacros.end();
1634 for (; it != end; ++it) {
1635 int num_lines = (*it)->write(os.os(), true);
1636 os.texrow().newlines(num_lines);
1639 } // output_preamble
1641 os.texrow().start(paragraphs().begin()->id(), 0);
1643 LYXERR(Debug::INFO, "preamble finished, now the body.");
1646 latexParagraphs(*this, text(), os, runparams);
1648 // Restore the parenthood if needed
1649 if (!runparams.is_child)
1650 d->ignore_parent = false;
1652 // add this just in case after all the paragraphs
1655 if (output_preamble) {
1656 os << "\\end{document}\n";
1657 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1659 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1661 runparams_in.encoding = runparams.encoding;
1663 // Just to be sure. (Asger)
1664 os.texrow().newline();
1666 //for (int i = 0; i<d->texrow.rows(); i++) {
1668 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1669 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1672 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1673 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1677 void Buffer::makeDocBookFile(FileName const & fname,
1678 OutputParams const & runparams,
1679 OutputWhat output) const
1681 LYXERR(Debug::LATEX, "makeDocBookFile...");
1684 if (!openFileWrite(ofs, fname))
1687 // make sure we are ready to export
1688 // this needs to be done before we validate
1690 updateMacroInstances(OutputUpdate);
1692 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1696 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1700 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1701 OutputParams const & runparams,
1702 OutputWhat output) const
1704 LaTeXFeatures features(*this, params(), runparams);
1709 DocumentClass const & tclass = params().documentClass();
1710 string const top_element = tclass.latexname();
1712 bool const output_preamble =
1713 output == FullSource || output == OnlyPreamble;
1714 bool const output_body =
1715 output == FullSource || output == OnlyBody;
1717 if (output_preamble) {
1718 if (runparams.flavor == OutputParams::XML)
1719 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1722 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1725 if (! tclass.class_header().empty())
1726 os << from_ascii(tclass.class_header());
1727 else if (runparams.flavor == OutputParams::XML)
1728 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1729 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1731 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1733 docstring preamble = from_utf8(params().preamble);
1734 if (runparams.flavor != OutputParams::XML ) {
1735 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1736 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1737 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1738 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1741 string const name = runparams.nice
1742 ? changeExtension(absFileName(), ".sgml") : fname;
1743 preamble += features.getIncludedFiles(name);
1744 preamble += features.getLyXSGMLEntities();
1746 if (!preamble.empty()) {
1747 os << "\n [ " << preamble << " ]";
1753 string top = top_element;
1755 if (runparams.flavor == OutputParams::XML)
1756 top += params().language->code();
1758 top += params().language->code().substr(0, 2);
1761 if (!params().options.empty()) {
1763 top += params().options;
1766 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1767 << " file was created by LyX " << lyx_version
1768 << "\n See http://www.lyx.org/ for more information -->\n";
1770 params().documentClass().counters().reset();
1772 sgml::openTag(os, top);
1774 docbookParagraphs(text(), *this, os, runparams);
1775 sgml::closeTag(os, top_element);
1780 void Buffer::makeLyXHTMLFile(FileName const & fname,
1781 OutputParams const & runparams) const
1783 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1786 if (!openFileWrite(ofs, fname))
1789 // make sure we are ready to export
1790 // this has to be done before we validate
1791 updateBuffer(UpdateMaster, OutputUpdate);
1792 updateMacroInstances(OutputUpdate);
1794 writeLyXHTMLSource(ofs, runparams, FullSource);
1798 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1802 void Buffer::writeLyXHTMLSource(odocstream & os,
1803 OutputParams const & runparams,
1804 OutputWhat output) const
1806 LaTeXFeatures features(*this, params(), runparams);
1808 d->bibinfo_.makeCitationLabels(*this);
1810 bool const output_preamble =
1811 output == FullSource || output == OnlyPreamble;
1812 bool const output_body =
1813 output == FullSource || output == OnlyBody || output == IncludedFile;
1815 if (output_preamble) {
1816 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1817 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/2001/REC-MathML2-20010221/dtd/xhtml-math11-f.dtd\">\n"
1818 // FIXME Language should be set properly.
1819 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1821 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1822 // FIXME Presumably need to set this right
1823 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1825 docstring const & doctitle = features.htmlTitle();
1827 << (doctitle.empty() ?
1828 from_ascii("LyX Document") :
1829 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1832 docstring styles = features.getTClassHTMLPreamble();
1833 if (!styles.empty())
1834 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1836 styles = from_utf8(features.getPreambleSnippets());
1837 if (!styles.empty())
1838 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1840 // we will collect CSS information in a stream, and then output it
1841 // either here, as part of the header, or else in a separate file.
1842 odocstringstream css;
1843 styles = from_utf8(features.getCSSSnippets());
1844 if (!styles.empty())
1845 css << "/* LyX Provided Styles */\n" << styles << '\n';
1847 styles = features.getTClassHTMLStyles();
1848 if (!styles.empty())
1849 css << "/* Layout-provided Styles */\n" << styles << '\n';
1851 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1852 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1853 if (needfg || needbg) {
1854 css << "\nbody {\n";
1857 << from_ascii(X11hexname(params().fontcolor))
1860 css << " background-color: "
1861 << from_ascii(X11hexname(params().backgroundcolor))
1866 docstring const dstyles = css.str();
1867 if (!dstyles.empty()) {
1868 bool written = false;
1869 if (params().html_css_as_file) {
1870 // open a file for CSS info
1872 string const fcssname = addName(temppath(), "docstyle.css");
1873 FileName const fcssfile = FileName(fcssname);
1874 if (openFileWrite(ocss, fcssfile)) {
1878 // write link to header
1879 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1881 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1884 // we are here if the CSS is supposed to be written to the header
1885 // or if we failed to write it to an external file.
1887 os << "<style type='text/css'>\n"
1896 bool const output_body_tag = (output != IncludedFile);
1897 if (output_body_tag)
1900 if (output != IncludedFile)
1901 // if we're an included file, the counters are in the master.
1902 params().documentClass().counters().reset();
1903 xhtmlParagraphs(text(), *this, xs, runparams);
1904 if (output_body_tag)
1908 if (output_preamble)
1913 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1914 // Other flags: -wall -v0 -x
1915 int Buffer::runChktex()
1919 // get LaTeX-Filename
1920 FileName const path(temppath());
1921 string const name = addName(path.absFileName(), latexName());
1922 string const org_path = filePath();
1924 PathChanger p(path); // path to LaTeX file
1925 message(_("Running chktex..."));
1927 // Generate the LaTeX file if neccessary
1928 OutputParams runparams(¶ms().encoding());
1929 runparams.flavor = OutputParams::LATEX;
1930 runparams.nice = false;
1931 runparams.linelen = lyxrc.plaintext_linelen;
1932 makeLaTeXFile(FileName(name), org_path, runparams);
1935 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1936 int const res = chktex.run(terr); // run chktex
1939 Alert::error(_("chktex failure"),
1940 _("Could not run chktex successfully."));
1941 } else if (res > 0) {
1942 ErrorList & errlist = d->errorLists["ChkTeX"];
1944 bufferErrors(terr, errlist);
1955 void Buffer::validate(LaTeXFeatures & features) const
1957 // Validate the buffer params, but not for included
1958 // files, since they also use the parent buffer's
1960 if (!features.runparams().is_child)
1961 params().validate(features);
1963 for_each(paragraphs().begin(), paragraphs().end(),
1964 bind(&Paragraph::validate, _1, ref(features)));
1966 if (lyxerr.debugging(Debug::LATEX)) {
1967 features.showStruct();
1972 void Buffer::getLabelList(vector<docstring> & list) const
1974 // If this is a child document, use the master's list instead.
1976 masterBuffer()->getLabelList(list);
1981 Toc & toc = d->toc_backend.toc("label");
1982 TocIterator toc_it = toc.begin();
1983 TocIterator end = toc.end();
1984 for (; toc_it != end; ++toc_it) {
1985 if (toc_it->depth() == 0)
1986 list.push_back(toc_it->str());
1991 void Buffer::updateBibfilesCache(UpdateScope scope) const
1993 // FIXME This is probably unnecssary, given where we call this.
1994 // If this is a child document, use the parent's cache instead.
1995 if (parent() && scope != UpdateChildOnly) {
1996 masterBuffer()->updateBibfilesCache();
2000 d->bibfiles_cache_.clear();
2001 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2002 if (it->lyxCode() == BIBTEX_CODE) {
2003 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2004 support::FileNameList const bibfiles = inset.getBibFiles();
2005 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2008 } else if (it->lyxCode() == INCLUDE_CODE) {
2009 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2010 Buffer const * const incbuf = inset.getChildBuffer();
2013 support::FileNameList const & bibfiles =
2014 incbuf->getBibfilesCache(UpdateChildOnly);
2015 if (!bibfiles.empty()) {
2016 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2022 d->bibfile_cache_valid_ = true;
2023 d->bibinfo_cache_valid_ = false;
2024 d->cite_labels_valid_ = false;
2028 void Buffer::invalidateBibinfoCache() const
2030 d->bibinfo_cache_valid_ = false;
2031 d->cite_labels_valid_ = false;
2032 // also invalidate the cache for the parent buffer
2033 Buffer const * const pbuf = d->parent();
2035 pbuf->invalidateBibinfoCache();
2039 void Buffer::invalidateBibfileCache() const
2041 d->bibfile_cache_valid_ = false;
2042 d->bibinfo_cache_valid_ = false;
2043 d->cite_labels_valid_ = false;
2044 // also invalidate the cache for the parent buffer
2045 Buffer const * const pbuf = d->parent();
2047 pbuf->invalidateBibfileCache();
2051 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2053 // FIXME This is probably unnecessary, given where we call this.
2054 // If this is a child document, use the master's cache instead.
2055 Buffer const * const pbuf = masterBuffer();
2056 if (pbuf != this && scope != UpdateChildOnly)
2057 return pbuf->getBibfilesCache();
2059 if (!d->bibfile_cache_valid_)
2060 this->updateBibfilesCache(scope);
2062 return d->bibfiles_cache_;
2066 BiblioInfo const & Buffer::masterBibInfo() const
2068 Buffer const * const tmp = masterBuffer();
2070 return tmp->masterBibInfo();
2075 void Buffer::checkIfBibInfoCacheIsValid() const
2077 // use the master's cache
2078 Buffer const * const tmp = masterBuffer();
2080 tmp->checkIfBibInfoCacheIsValid();
2084 // compare the cached timestamps with the actual ones.
2085 FileNameList const & bibfiles_cache = getBibfilesCache();
2086 FileNameList::const_iterator ei = bibfiles_cache.begin();
2087 FileNameList::const_iterator en = bibfiles_cache.end();
2088 for (; ei != en; ++ ei) {
2089 time_t lastw = ei->lastModified();
2090 time_t prevw = d->bibfile_status_[*ei];
2091 if (lastw != prevw) {
2092 d->bibinfo_cache_valid_ = false;
2093 d->cite_labels_valid_ = false;
2094 d->bibfile_status_[*ei] = lastw;
2100 void Buffer::reloadBibInfoCache() const
2102 // use the master's cache
2103 Buffer const * const tmp = masterBuffer();
2105 tmp->reloadBibInfoCache();
2109 checkIfBibInfoCacheIsValid();
2110 if (d->bibinfo_cache_valid_)
2113 d->bibinfo_.clear();
2115 d->bibinfo_cache_valid_ = true;
2119 void Buffer::collectBibKeys() const
2121 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2122 it->collectBibKeys(it);
2126 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2128 Buffer const * tmp = masterBuffer();
2129 BiblioInfo & masterbi = (tmp == this) ?
2130 d->bibinfo_ : tmp->d->bibinfo_;
2131 masterbi.mergeBiblioInfo(bi);
2135 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2137 Buffer const * tmp = masterBuffer();
2138 BiblioInfo & masterbi = (tmp == this) ?
2139 d->bibinfo_ : tmp->d->bibinfo_;
2144 void Buffer::makeCitationLabels() const
2146 Buffer const * const master = masterBuffer();
2147 return d->bibinfo_.makeCitationLabels(*master);
2151 bool Buffer::citeLabelsValid() const
2153 return masterBuffer()->d->cite_labels_valid_;
2157 void Buffer::removeBiblioTempFiles() const
2159 // We remove files that contain LaTeX commands specific to the
2160 // particular bibliographic style being used, in order to avoid
2161 // LaTeX errors when we switch style.
2162 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2163 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2164 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2165 aux_file.removeFile();
2166 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2167 bbl_file.removeFile();
2168 // Also for the parent buffer
2169 Buffer const * const pbuf = parent();
2171 pbuf->removeBiblioTempFiles();
2175 bool Buffer::isDepClean(string const & name) const
2177 DepClean::const_iterator const it = d->dep_clean.find(name);
2178 if (it == d->dep_clean.end())
2184 void Buffer::markDepClean(string const & name)
2186 d->dep_clean[name] = true;
2190 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2193 // FIXME? if there is an Buffer LFUN that can be dispatched even
2194 // if internal, put a switch '(cmd.action)' here.
2200 switch (cmd.action()) {
2202 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2203 flag.setOnOff(isReadonly());
2206 // FIXME: There is need for a command-line import.
2207 //case LFUN_BUFFER_IMPORT:
2209 case LFUN_BUFFER_AUTO_SAVE:
2212 case LFUN_BUFFER_EXPORT_CUSTOM:
2213 // FIXME: Nothing to check here?
2216 case LFUN_BUFFER_EXPORT: {
2217 docstring const arg = cmd.argument();
2218 if (arg == "custom") {
2222 string format = to_utf8(arg);
2223 size_t pos = format.find(' ');
2224 if (pos != string::npos)
2225 format = format.substr(0, pos);
2226 enable = params().isExportable(format);
2228 flag.message(bformat(
2229 _("Don't know how to export to format: %1$s"), arg));
2233 case LFUN_BUFFER_CHKTEX:
2234 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2237 case LFUN_BUILD_PROGRAM:
2238 enable = params().isExportable("program");
2241 case LFUN_BRANCH_ADD:
2242 case LFUN_BRANCHES_RENAME:
2243 case LFUN_BUFFER_PRINT:
2244 // if no Buffer is present, then of course we won't be called!
2247 case LFUN_BUFFER_LANGUAGE:
2248 enable = !isReadonly();
2254 flag.setEnabled(enable);
2259 void Buffer::dispatch(string const & command, DispatchResult & result)
2261 return dispatch(lyxaction.lookupFunc(command), result);
2265 // NOTE We can end up here even if we have no GUI, because we are called
2266 // by LyX::exec to handled command-line requests. So we may need to check
2267 // whether we have a GUI or not. The boolean use_gui holds this information.
2268 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2271 // FIXME? if there is an Buffer LFUN that can be dispatched even
2272 // if internal, put a switch '(cmd.action())' here.
2273 dr.dispatched(false);
2276 string const argument = to_utf8(func.argument());
2277 // We'll set this back to false if need be.
2278 bool dispatched = true;
2279 undo().beginUndoGroup();
2281 switch (func.action()) {
2282 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2283 if (lyxvc().inUse()) {
2284 string log = lyxvc().toggleReadOnly();
2289 setReadonly(!isReadonly());
2292 case LFUN_BUFFER_EXPORT: {
2293 ExportStatus const status = doExport(argument, false);
2294 dr.setError(status != ExportSuccess);
2295 if (status != ExportSuccess)
2296 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2301 case LFUN_BUILD_PROGRAM:
2302 doExport("program", true);
2305 case LFUN_BUFFER_CHKTEX:
2309 case LFUN_BUFFER_EXPORT_CUSTOM: {
2311 string command = split(argument, format_name, ' ');
2312 Format const * format = formats.getFormat(format_name);
2314 lyxerr << "Format \"" << format_name
2315 << "\" not recognized!"
2320 // The name of the file created by the conversion process
2323 // Output to filename
2324 if (format->name() == "lyx") {
2325 string const latexname = latexName(false);
2326 filename = changeExtension(latexname,
2327 format->extension());
2328 filename = addName(temppath(), filename);
2330 if (!writeFile(FileName(filename)))
2334 doExport(format_name, true, filename);
2337 // Substitute $$FName for filename
2338 if (!contains(command, "$$FName"))
2339 command = "( " + command + " ) < $$FName";
2340 command = subst(command, "$$FName", filename);
2342 // Execute the command in the background
2344 call.startscript(Systemcall::DontWait, command, filePath());
2348 // FIXME: There is need for a command-line import.
2350 case LFUN_BUFFER_IMPORT:
2355 case LFUN_BUFFER_AUTO_SAVE:
2357 resetAutosaveTimers();
2360 case LFUN_BRANCH_ADD: {
2361 docstring branch_name = func.argument();
2362 if (branch_name.empty()) {
2366 BranchList & branch_list = params().branchlist();
2367 vector<docstring> const branches =
2368 getVectorFromString(branch_name, branch_list.separator());
2370 for (vector<docstring>::const_iterator it = branches.begin();
2371 it != branches.end(); ++it) {
2373 Branch * branch = branch_list.find(branch_name);
2375 LYXERR0("Branch " << branch_name << " already exists.");
2379 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2381 branch_list.add(branch_name);
2382 branch = branch_list.find(branch_name);
2383 string const x11hexname = X11hexname(branch->color());
2384 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2385 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2387 dr.screenUpdate(Update::Force);
2395 case LFUN_BRANCHES_RENAME: {
2396 if (func.argument().empty())
2399 docstring const oldname = from_utf8(func.getArg(0));
2400 docstring const newname = from_utf8(func.getArg(1));
2401 InsetIterator it = inset_iterator_begin(inset());
2402 InsetIterator const end = inset_iterator_end(inset());
2403 bool success = false;
2404 for (; it != end; ++it) {
2405 if (it->lyxCode() == BRANCH_CODE) {
2406 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2407 if (ins.branch() == oldname) {
2408 undo().recordUndo(CursorData(it));
2409 ins.rename(newname);
2414 if (it->lyxCode() == INCLUDE_CODE) {
2415 // get buffer of external file
2416 InsetInclude const & ins =
2417 static_cast<InsetInclude const &>(*it);
2418 Buffer * child = ins.getChildBuffer();
2421 child->dispatch(func, dr);
2426 dr.screenUpdate(Update::Force);
2427 dr.forceBufferUpdate();
2432 case LFUN_BUFFER_PRINT: {
2433 // we'll assume there's a problem until we succeed
2435 string target = func.getArg(0);
2436 string target_name = func.getArg(1);
2437 string command = func.getArg(2);
2440 || target_name.empty()
2441 || command.empty()) {
2442 LYXERR0("Unable to parse " << func.argument());
2443 docstring const msg =
2444 bformat(_("Unable to parse \"%1$s\""), func.argument());
2448 if (target != "printer" && target != "file") {
2449 LYXERR0("Unrecognized target \"" << target << '"');
2450 docstring const msg =
2451 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2456 if (!doExport("dvi", true)) {
2457 showPrintError(absFileName());
2458 dr.setMessage(_("Error exporting to DVI."));
2462 // Push directory path.
2463 string const path = temppath();
2464 // Prevent the compiler from optimizing away p
2468 // there are three cases here:
2469 // 1. we print to a file
2470 // 2. we print directly to a printer
2471 // 3. we print using a spool command (print to file first)
2474 string const dviname = changeExtension(latexName(true), "dvi");
2476 if (target == "printer") {
2477 if (!lyxrc.print_spool_command.empty()) {
2478 // case 3: print using a spool
2479 string const psname = changeExtension(dviname,".ps");
2480 command += ' ' + lyxrc.print_to_file
2483 + quoteName(dviname);
2485 string command2 = lyxrc.print_spool_command + ' ';
2486 if (target_name != "default") {
2487 command2 += lyxrc.print_spool_printerprefix
2491 command2 += quoteName(psname);
2493 // If successful, then spool command
2494 res = one.startscript(Systemcall::Wait, command,
2498 // If there's no GUI, we have to wait on this command. Otherwise,
2499 // LyX deletes the temporary directory, and with it the spooled
2500 // file, before it can be printed!!
2501 Systemcall::Starttype stype = use_gui ?
2502 Systemcall::DontWait : Systemcall::Wait;
2503 res = one.startscript(stype, command2,
2507 // case 2: print directly to a printer
2508 if (target_name != "default")
2509 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2511 Systemcall::Starttype stype = use_gui ?
2512 Systemcall::DontWait : Systemcall::Wait;
2513 res = one.startscript(stype, command +
2514 quoteName(dviname), filePath());
2518 // case 1: print to a file
2519 FileName const filename(makeAbsPath(target_name, filePath()));
2520 FileName const dvifile(makeAbsPath(dviname, path));
2521 if (filename.exists()) {
2522 docstring text = bformat(
2523 _("The file %1$s already exists.\n\n"
2524 "Do you want to overwrite that file?"),
2525 makeDisplayPath(filename.absFileName()));
2526 if (Alert::prompt(_("Overwrite file?"),
2527 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2530 command += ' ' + lyxrc.print_to_file
2531 + quoteName(filename.toFilesystemEncoding())
2533 + quoteName(dvifile.toFilesystemEncoding());
2535 Systemcall::Starttype stype = use_gui ?
2536 Systemcall::DontWait : Systemcall::Wait;
2537 res = one.startscript(stype, command, filePath());
2543 dr.setMessage(_("Error running external commands."));
2544 showPrintError(absFileName());
2553 dr.dispatched(dispatched);
2554 undo().endUndoGroup();
2558 void Buffer::changeLanguage(Language const * from, Language const * to)
2560 LASSERT(from, /**/);
2563 for_each(par_iterator_begin(),
2565 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2569 bool Buffer::isMultiLingual() const
2571 ParConstIterator end = par_iterator_end();
2572 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2573 if (it->isMultiLingual(params()))
2580 std::set<Language const *> Buffer::getLanguages() const
2582 std::set<Language const *> languages;
2583 getLanguages(languages);
2588 void Buffer::getLanguages(std::set<Language const *> & languages) const
2590 ParConstIterator end = par_iterator_end();
2591 // add the buffer language, even if it's not actively used
2592 languages.insert(language());
2593 // iterate over the paragraphs
2594 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2595 it->getLanguages(languages);
2597 ListOfBuffers clist = getDescendents();
2598 ListOfBuffers::const_iterator cit = clist.begin();
2599 ListOfBuffers::const_iterator const cen = clist.end();
2600 for (; cit != cen; ++cit)
2601 (*cit)->getLanguages(languages);
2605 DocIterator Buffer::getParFromID(int const id) const
2607 Buffer * buf = const_cast<Buffer *>(this);
2609 // John says this is called with id == -1 from undo
2610 lyxerr << "getParFromID(), id: " << id << endl;
2611 return doc_iterator_end(buf);
2614 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2615 if (it.paragraph().id() == id)
2618 return doc_iterator_end(buf);
2622 bool Buffer::hasParWithID(int const id) const
2624 return !getParFromID(id).atEnd();
2628 ParIterator Buffer::par_iterator_begin()
2630 return ParIterator(doc_iterator_begin(this));
2634 ParIterator Buffer::par_iterator_end()
2636 return ParIterator(doc_iterator_end(this));
2640 ParConstIterator Buffer::par_iterator_begin() const
2642 return ParConstIterator(doc_iterator_begin(this));
2646 ParConstIterator Buffer::par_iterator_end() const
2648 return ParConstIterator(doc_iterator_end(this));
2652 Language const * Buffer::language() const
2654 return params().language;
2658 docstring const Buffer::B_(string const & l10n) const
2660 return params().B_(l10n);
2664 bool Buffer::isClean() const
2666 return d->lyx_clean;
2670 bool Buffer::isExternallyModified(CheckMethod method) const
2672 LASSERT(d->filename.exists(), /**/);
2673 // if method == timestamp, check timestamp before checksum
2674 return (method == checksum_method
2675 || d->timestamp_ != d->filename.lastModified())
2676 && d->checksum_ != d->filename.checksum();
2680 void Buffer::saveCheckSum() const
2682 FileName const & file = d->filename;
2685 if (file.exists()) {
2686 d->timestamp_ = file.lastModified();
2687 d->checksum_ = file.checksum();
2689 // in the case of save to a new file.
2696 void Buffer::markClean() const
2698 if (!d->lyx_clean) {
2699 d->lyx_clean = true;
2702 // if the .lyx file has been saved, we don't need an
2704 d->bak_clean = true;
2705 d->undo_.markDirty();
2709 void Buffer::setUnnamed(bool flag)
2715 bool Buffer::isUnnamed() const
2722 /// Don't check unnamed, here: isInternal() is used in
2723 /// newBuffer(), where the unnamed flag has not been set by anyone
2724 /// yet. Also, for an internal buffer, there should be no need for
2725 /// retrieving fileName() nor for checking if it is unnamed or not.
2726 bool Buffer::isInternal() const
2728 return d->internal_buffer;
2732 void Buffer::setInternal(bool flag)
2734 d->internal_buffer = flag;
2738 void Buffer::markDirty()
2741 d->lyx_clean = false;
2744 d->bak_clean = false;
2746 DepClean::iterator it = d->dep_clean.begin();
2747 DepClean::const_iterator const end = d->dep_clean.end();
2749 for (; it != end; ++it)
2754 FileName Buffer::fileName() const
2760 string Buffer::absFileName() const
2762 return d->filename.absFileName();
2766 string Buffer::filePath() const
2768 int last = d->filename.onlyPath().absFileName().length() - 1;
2770 return d->filename.onlyPath().absFileName()[last] == '/'
2771 ? d->filename.onlyPath().absFileName()
2772 : d->filename.onlyPath().absFileName() + "/";
2776 bool Buffer::isReadonly() const
2778 return d->read_only;
2782 void Buffer::setParent(Buffer const * buffer)
2784 // Avoids recursive include.
2785 d->setParent(buffer == this ? 0 : buffer);
2790 Buffer const * Buffer::parent() const
2796 ListOfBuffers Buffer::allRelatives() const
2798 ListOfBuffers lb = masterBuffer()->getDescendents();
2799 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2804 Buffer const * Buffer::masterBuffer() const
2806 // FIXME Should be make sure we are not in some kind
2807 // of recursive include? A -> B -> A will crash this.
2808 Buffer const * const pbuf = d->parent();
2812 return pbuf->masterBuffer();
2816 bool Buffer::isChild(Buffer * child) const
2818 return d->children_positions.find(child) != d->children_positions.end();
2822 DocIterator Buffer::firstChildPosition(Buffer const * child)
2824 Impl::BufferPositionMap::iterator it;
2825 it = d->children_positions.find(child);
2826 if (it == d->children_positions.end())
2827 return DocIterator(this);
2832 bool Buffer::hasChildren() const
2834 return !d->children_positions.empty();
2838 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2840 // loop over children
2841 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2842 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2843 for (; it != end; ++it) {
2844 Buffer * child = const_cast<Buffer *>(it->first);
2846 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2847 if (bit != clist.end())
2849 clist.push_back(child);
2851 // there might be grandchildren
2852 child->collectChildren(clist, true);
2857 ListOfBuffers Buffer::getChildren() const
2860 collectChildren(v, false);
2861 // Make sure we have not included ourselves.
2862 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2863 if (bit != v.end()) {
2864 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2871 ListOfBuffers Buffer::getDescendents() const
2874 collectChildren(v, true);
2875 // Make sure we have not included ourselves.
2876 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2877 if (bit != v.end()) {
2878 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2885 template<typename M>
2886 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2891 typename M::const_iterator it = m.lower_bound(x);
2892 if (it == m.begin())
2900 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2901 DocIterator const & pos) const
2903 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2905 // if paragraphs have no macro context set, pos will be empty
2909 // we haven't found anything yet
2910 DocIterator bestPos = owner_->par_iterator_begin();
2911 MacroData const * bestData = 0;
2913 // find macro definitions for name
2914 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2915 if (nameIt != macros.end()) {
2916 // find last definition in front of pos or at pos itself
2917 PositionScopeMacroMap::const_iterator it
2918 = greatest_below(nameIt->second, pos);
2919 if (it != nameIt->second.end()) {
2921 // scope ends behind pos?
2922 if (pos < it->second.first) {
2923 // Looks good, remember this. If there
2924 // is no external macro behind this,
2925 // we found the right one already.
2926 bestPos = it->first;
2927 bestData = &it->second.second;
2931 // try previous macro if there is one
2932 if (it == nameIt->second.begin())
2939 // find macros in included files
2940 PositionScopeBufferMap::const_iterator it
2941 = greatest_below(position_to_children, pos);
2942 if (it == position_to_children.end())
2943 // no children before
2947 // do we know something better (i.e. later) already?
2948 if (it->first < bestPos )
2951 // scope ends behind pos?
2952 if (pos < it->second.first
2953 && (cloned_buffer_ ||
2954 theBufferList().isLoaded(it->second.second))) {
2955 // look for macro in external file
2957 MacroData const * data
2958 = it->second.second->getMacro(name, false);
2961 bestPos = it->first;
2967 // try previous file if there is one
2968 if (it == position_to_children.begin())
2973 // return the best macro we have found
2978 MacroData const * Buffer::getMacro(docstring const & name,
2979 DocIterator const & pos, bool global) const
2984 // query buffer macros
2985 MacroData const * data = d->getBufferMacro(name, pos);
2989 // If there is a master buffer, query that
2990 Buffer const * const pbuf = d->parent();
2992 d->macro_lock = true;
2993 MacroData const * macro = pbuf->getMacro(
2994 name, *this, false);
2995 d->macro_lock = false;
3001 data = MacroTable::globalMacros().get(name);
3010 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3012 // set scope end behind the last paragraph
3013 DocIterator scope = par_iterator_begin();
3014 scope.pit() = scope.lastpit() + 1;
3016 return getMacro(name, scope, global);
3020 MacroData const * Buffer::getMacro(docstring const & name,
3021 Buffer const & child, bool global) const
3023 // look where the child buffer is included first
3024 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3025 if (it == d->children_positions.end())
3028 // check for macros at the inclusion position
3029 return getMacro(name, it->second, global);
3033 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3035 pit_type const lastpit = it.lastpit();
3037 // look for macros in each paragraph
3038 while (it.pit() <= lastpit) {
3039 Paragraph & par = it.paragraph();
3041 // iterate over the insets of the current paragraph
3042 InsetList const & insets = par.insetList();
3043 InsetList::const_iterator iit = insets.begin();
3044 InsetList::const_iterator end = insets.end();
3045 for (; iit != end; ++iit) {
3046 it.pos() = iit->pos;
3048 // is it a nested text inset?
3049 if (iit->inset->asInsetText()) {
3050 // Inset needs its own scope?
3051 InsetText const * itext = iit->inset->asInsetText();
3052 bool newScope = itext->isMacroScope();
3054 // scope which ends just behind the inset
3055 DocIterator insetScope = it;
3058 // collect macros in inset
3059 it.push_back(CursorSlice(*iit->inset));
3060 updateMacros(it, newScope ? insetScope : scope);
3065 if (iit->inset->asInsetTabular()) {
3066 CursorSlice slice(*iit->inset);
3067 size_t const numcells = slice.nargs();
3068 for (; slice.idx() < numcells; slice.forwardIdx()) {
3069 it.push_back(slice);
3070 updateMacros(it, scope);
3076 // is it an external file?
3077 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3078 // get buffer of external file
3079 InsetInclude const & inset =
3080 static_cast<InsetInclude const &>(*iit->inset);
3082 Buffer * child = inset.getChildBuffer();
3087 // register its position, but only when it is
3088 // included first in the buffer
3089 if (children_positions.find(child) ==
3090 children_positions.end())
3091 children_positions[child] = it;
3093 // register child with its scope
3094 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3098 InsetMath * im = iit->inset->asInsetMath();
3099 if (doing_export && im) {
3100 InsetMathHull * hull = im->asHullInset();
3102 hull->recordLocation(it);
3105 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3109 MathMacroTemplate & macroTemplate =
3110 *iit->inset->asInsetMath()->asMacroTemplate();
3111 MacroContext mc(owner_, it);
3112 macroTemplate.updateToContext(mc);
3115 bool valid = macroTemplate.validMacro();
3116 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3117 // then the BufferView's cursor will be invalid in
3118 // some cases which leads to crashes.
3123 // FIXME (Abdel), I don't understandt why we pass 'it' here
3124 // instead of 'macroTemplate' defined above... is this correct?
3125 macros[macroTemplate.name()][it] =
3126 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3136 void Buffer::updateMacros() const
3141 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3143 // start with empty table
3145 d->children_positions.clear();
3146 d->position_to_children.clear();
3148 // Iterate over buffer, starting with first paragraph
3149 // The scope must be bigger than any lookup DocIterator
3150 // later. For the global lookup, lastpit+1 is used, hence
3151 // we use lastpit+2 here.
3152 DocIterator it = par_iterator_begin();
3153 DocIterator outerScope = it;
3154 outerScope.pit() = outerScope.lastpit() + 2;
3155 d->updateMacros(it, outerScope);
3159 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3161 InsetIterator it = inset_iterator_begin(inset());
3162 InsetIterator const end = inset_iterator_end(inset());
3163 for (; it != end; ++it) {
3164 if (it->lyxCode() == BRANCH_CODE) {
3165 InsetBranch & br = static_cast<InsetBranch &>(*it);
3166 docstring const name = br.branch();
3167 if (!from_master && !params().branchlist().find(name))
3168 result.push_back(name);
3169 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3170 result.push_back(name);
3173 if (it->lyxCode() == INCLUDE_CODE) {
3174 // get buffer of external file
3175 InsetInclude const & ins =
3176 static_cast<InsetInclude const &>(*it);
3177 Buffer * child = ins.getChildBuffer();
3180 child->getUsedBranches(result, true);
3183 // remove duplicates
3188 void Buffer::updateMacroInstances(UpdateType utype) const
3190 LYXERR(Debug::MACROS, "updateMacroInstances for "
3191 << d->filename.onlyFileName());
3192 DocIterator it = doc_iterator_begin(this);
3194 DocIterator const end = doc_iterator_end(this);
3195 for (; it != end; it.forwardInset()) {
3196 // look for MathData cells in InsetMathNest insets
3197 InsetMath * minset = it.nextInset()->asInsetMath();
3201 // update macro in all cells of the InsetMathNest
3202 DocIterator::idx_type n = minset->nargs();
3203 MacroContext mc = MacroContext(this, it);
3204 for (DocIterator::idx_type i = 0; i < n; ++i) {
3205 MathData & data = minset->cell(i);
3206 data.updateMacros(0, mc, utype);
3212 void Buffer::listMacroNames(MacroNameSet & macros) const
3217 d->macro_lock = true;
3219 // loop over macro names
3220 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3221 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3222 for (; nameIt != nameEnd; ++nameIt)
3223 macros.insert(nameIt->first);
3225 // loop over children
3226 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3227 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3228 for (; it != end; ++it)
3229 it->first->listMacroNames(macros);
3232 Buffer const * const pbuf = d->parent();
3234 pbuf->listMacroNames(macros);
3236 d->macro_lock = false;
3240 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3242 Buffer const * const pbuf = d->parent();
3247 pbuf->listMacroNames(names);
3250 MacroNameSet::iterator it = names.begin();
3251 MacroNameSet::iterator end = names.end();
3252 for (; it != end; ++it) {
3254 MacroData const * data =
3255 pbuf->getMacro(*it, *this, false);
3257 macros.insert(data);
3259 // we cannot access the original MathMacroTemplate anymore
3260 // here to calls validate method. So we do its work here manually.
3261 // FIXME: somehow make the template accessible here.
3262 if (data->optionals() > 0)
3263 features.require("xargs");
3269 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3272 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3274 RefCache::iterator it = d->ref_cache_.find(label);
3275 if (it != d->ref_cache_.end())
3276 return it->second.second;
3278 static InsetLabel const * dummy_il = 0;
3279 static References const dummy_refs;
3280 it = d->ref_cache_.insert(
3281 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3282 return it->second.second;
3286 Buffer::References const & Buffer::references(docstring const & label) const
3288 return const_cast<Buffer *>(this)->getReferenceCache(label);
3292 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3294 References & refs = getReferenceCache(label);
3295 refs.push_back(make_pair(inset, it));
3299 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3301 masterBuffer()->d->ref_cache_[label].first = il;
3305 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3307 return masterBuffer()->d->ref_cache_[label].first;
3311 void Buffer::clearReferenceCache() const
3314 d->ref_cache_.clear();
3318 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3321 //FIXME: This does not work for child documents yet.
3322 LASSERT(code == CITE_CODE, /**/);
3324 reloadBibInfoCache();
3326 // Check if the label 'from' appears more than once
3327 BiblioInfo const & keys = masterBibInfo();
3328 BiblioInfo::const_iterator bit = keys.begin();
3329 BiblioInfo::const_iterator bend = keys.end();
3330 vector<docstring> labels;
3332 for (; bit != bend; ++bit)
3334 labels.push_back(bit->first);
3336 if (count(labels.begin(), labels.end(), from) > 1)
3339 string const paramName = "key";
3340 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3341 if (it->lyxCode() == code) {
3342 InsetCommand * inset = it->asInsetCommand();
3345 docstring const oldValue = inset->getParam(paramName);
3346 if (oldValue == from)
3347 inset->setParam(paramName, to);
3353 void Buffer::getSourceCode(odocstream & os, string const format,
3354 pit_type par_begin, pit_type par_end,
3355 OutputWhat output, bool master) const
3357 OutputParams runparams(¶ms().encoding());
3358 runparams.nice = true;
3359 runparams.flavor = params().getOutputFlavor(format);
3360 runparams.linelen = lyxrc.plaintext_linelen;
3361 // No side effect of file copying and image conversion
3362 runparams.dryrun = true;
3364 if (output == CurrentParagraph) {
3365 runparams.par_begin = par_begin;
3366 runparams.par_end = par_end;
3367 if (par_begin + 1 == par_end) {
3369 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3373 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3374 convert<docstring>(par_begin),
3375 convert<docstring>(par_end - 1))
3378 // output paragraphs
3379 if (runparams.flavor == OutputParams::LYX) {
3380 Paragraph const & par = text().paragraphs()[par_begin];
3382 depth_type dt = par.getDepth();
3383 par.write(ods, params(), dt);
3384 os << from_utf8(ods.str());
3385 } else if (runparams.flavor == OutputParams::HTML) {
3387 setMathFlavor(runparams);
3388 xhtmlParagraphs(text(), *this, xs, runparams);
3389 } else if (runparams.flavor == OutputParams::TEXT) {
3391 // FIXME Handles only one paragraph, unlike the others.
3392 // Probably should have some routine with a signature like them.
3393 writePlaintextParagraph(*this,
3394 text().paragraphs()[par_begin], os, runparams, dummy);
3395 } else if (params().isDocBook()) {
3396 docbookParagraphs(text(), *this, os, runparams);
3398 // If we are previewing a paragraph, even if this is the
3399 // child of some other buffer, let's cut the link here,
3400 // so that no concurring settings from the master
3401 // (e.g. branch state) interfere (see #8101).
3403 d->ignore_parent = true;
3404 // We need to validate the Buffer params' features here
3405 // in order to know if we should output polyglossia
3406 // macros (instead of babel macros)
3407 LaTeXFeatures features(*this, params(), runparams);
3408 params().validate(features);
3409 runparams.use_polyglossia = features.usePolyglossia();
3414 // latex or literate
3415 otexstream ots(os, texrow);
3418 latexParagraphs(*this, text(), ots, runparams);
3420 // Restore the parenthood
3422 d->ignore_parent = false;
3426 if (output == FullSource)
3427 os << _("Preview source code");
3428 else if (output == OnlyPreamble)
3429 os << _("Preview preamble");
3430 else if (output == OnlyBody)
3431 os << _("Preview body");
3433 if (runparams.flavor == OutputParams::LYX) {
3435 if (output == FullSource)
3437 else if (output == OnlyPreamble)
3438 params().writeFile(ods);
3439 else if (output == OnlyBody)
3441 os << from_utf8(ods.str());
3442 } else if (runparams.flavor == OutputParams::HTML) {
3443 writeLyXHTMLSource(os, runparams, output);
3444 } else if (runparams.flavor == OutputParams::TEXT) {
3445 if (output == OnlyPreamble) {
3446 os << "% "<< _("Plain text does not have a preamble.");
3448 writePlaintextFile(*this, os, runparams);
3449 } else if (params().isDocBook()) {
3450 writeDocBookSource(os, absFileName(), runparams, output);
3452 // latex or literate
3454 d->texrow.newline();
3455 d->texrow.newline();
3456 otexstream ots(os, d->texrow);
3458 runparams.is_child = true;
3459 writeLaTeXSource(ots, string(), runparams, output);
3465 ErrorList & Buffer::errorList(string const & type) const
3467 return d->errorLists[type];
3471 void Buffer::updateTocItem(std::string const & type,
3472 DocIterator const & dit) const
3475 d->gui_->updateTocItem(type, dit);
3479 void Buffer::structureChanged() const
3482 d->gui_->structureChanged();
3486 void Buffer::errors(string const & err, bool from_master) const
3489 d->gui_->errors(err, from_master);
3493 void Buffer::message(docstring const & msg) const
3496 d->gui_->message(msg);
3500 void Buffer::setBusy(bool on) const
3503 d->gui_->setBusy(on);
3507 void Buffer::updateTitles() const
3510 d->wa_->updateTitles();
3514 void Buffer::resetAutosaveTimers() const
3517 d->gui_->resetAutosaveTimers();
3521 bool Buffer::hasGuiDelegate() const
3527 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3536 class AutoSaveBuffer : public ForkedProcess {
3539 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3540 : buffer_(buffer), fname_(fname) {}
3542 virtual shared_ptr<ForkedProcess> clone() const
3544 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3549 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3550 from_utf8(fname_.absFileName())));
3551 return run(DontWait);
3555 virtual int generateChild();
3557 Buffer const & buffer_;
3562 int AutoSaveBuffer::generateChild()
3564 #if defined(__APPLE__)
3565 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3566 * We should use something else like threads.
3568 * Since I do not know how to determine at run time what is the OS X
3569 * version, I just disable forking altogether for now (JMarc)
3571 pid_t const pid = -1;
3573 // tmp_ret will be located (usually) in /tmp
3574 // will that be a problem?
3575 // Note that this calls ForkedCalls::fork(), so it's
3576 // ok cross-platform.
3577 pid_t const pid = fork();
3578 // If you want to debug the autosave
3579 // you should set pid to -1, and comment out the fork.
3580 if (pid != 0 && pid != -1)
3584 // pid = -1 signifies that lyx was unable
3585 // to fork. But we will do the save
3587 bool failed = false;
3588 FileName const tmp_ret = FileName::tempName("lyxauto");
3589 if (!tmp_ret.empty()) {
3590 buffer_.writeFile(tmp_ret);
3591 // assume successful write of tmp_ret
3592 if (!tmp_ret.moveTo(fname_))
3598 // failed to write/rename tmp_ret so try writing direct
3599 if (!buffer_.writeFile(fname_)) {
3600 // It is dangerous to do this in the child,
3601 // but safe in the parent, so...
3602 if (pid == -1) // emit message signal.
3603 buffer_.message(_("Autosave failed!"));
3607 if (pid == 0) // we are the child so...
3616 FileName Buffer::getEmergencyFileName() const
3618 return FileName(d->filename.absFileName() + ".emergency");
3622 FileName Buffer::getAutosaveFileName() const
3624 // if the document is unnamed try to save in the backup dir, else
3625 // in the default document path, and as a last try in the filePath,
3626 // which will most often be the temporary directory
3629 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3630 : lyxrc.backupdir_path;
3631 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3634 string const fname = "#" + d->filename.onlyFileName() + "#";
3636 return makeAbsPath(fname, fpath);
3640 void Buffer::removeAutosaveFile() const
3642 FileName const f = getAutosaveFileName();
3648 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3650 FileName const newauto = getAutosaveFileName();
3652 if (newauto != oldauto && oldauto.exists())
3653 if (!oldauto.moveTo(newauto))
3654 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3658 bool Buffer::autoSave() const
3660 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3661 if (buf->d->bak_clean || isReadonly())
3664 message(_("Autosaving current document..."));
3665 buf->d->bak_clean = true;
3667 FileName const fname = getAutosaveFileName();
3668 LASSERT(d->cloned_buffer_, return false);
3670 // If this buffer is cloned, we assume that
3671 // we are running in a separate thread already.
3672 FileName const tmp_ret = FileName::tempName("lyxauto");
3673 if (!tmp_ret.empty()) {
3675 // assume successful write of tmp_ret
3676 if (tmp_ret.moveTo(fname))
3679 // failed to write/rename tmp_ret so try writing direct
3680 return writeFile(fname);
3684 // helper class, to guarantee this gets reset properly
3685 class Buffer::MarkAsExporting {
3687 MarkAsExporting(Buffer const * buf) : buf_(buf)
3689 LASSERT(buf_, /* */);
3690 buf_->setExportStatus(true);
3694 buf_->setExportStatus(false);
3697 Buffer const * const buf_;
3702 void Buffer::setExportStatus(bool e) const
3704 d->doing_export = e;
3705 ListOfBuffers clist = getDescendents();
3706 ListOfBuffers::const_iterator cit = clist.begin();
3707 ListOfBuffers::const_iterator const cen = clist.end();
3708 for (; cit != cen; ++cit)
3709 (*cit)->d->doing_export = e;
3713 bool Buffer::isExporting() const
3715 return d->doing_export;
3719 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3723 return doExport(target, put_in_tempdir, result_file);
3726 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3727 string & result_file) const
3729 bool const update_unincluded =
3730 params().maintain_unincluded_children
3731 && !params().getIncludedChildren().empty();
3733 // (1) export with all included children (omit \includeonly)
3734 if (update_unincluded) {
3735 ExportStatus const status =
3736 doExport(target, put_in_tempdir, true, result_file);
3737 if (status != ExportSuccess)
3740 // (2) export with included children only
3741 return doExport(target, put_in_tempdir, false, result_file);
3745 void Buffer::setMathFlavor(OutputParams & op) const
3747 switch (params().html_math_output) {
3748 case BufferParams::MathML:
3749 op.math_flavor = OutputParams::MathAsMathML;
3751 case BufferParams::HTML:
3752 op.math_flavor = OutputParams::MathAsHTML;
3754 case BufferParams::Images:
3755 op.math_flavor = OutputParams::MathAsImages;
3757 case BufferParams::LaTeX:
3758 op.math_flavor = OutputParams::MathAsLaTeX;
3764 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3765 bool includeall, string & result_file) const
3767 LYXERR(Debug::FILES, "target=" << target);
3768 OutputParams runparams(¶ms().encoding());
3769 string format = target;
3770 string dest_filename;
3771 size_t pos = target.find(' ');
3772 if (pos != string::npos) {
3773 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3774 format = target.substr(0, pos);
3775 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3776 FileName(dest_filename).onlyPath().createPath();
3777 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3779 MarkAsExporting exporting(this);
3780 string backend_format;
3781 runparams.flavor = OutputParams::LATEX;
3782 runparams.linelen = lyxrc.plaintext_linelen;
3783 runparams.includeall = includeall;
3784 vector<string> backs = params().backends();
3785 Converters converters = theConverters();
3786 bool need_nice_file = false;
3787 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3788 // Get shortest path to format
3789 converters.buildGraph();
3790 Graph::EdgePath path;
3791 for (vector<string>::const_iterator it = backs.begin();
3792 it != backs.end(); ++it) {
3793 Graph::EdgePath p = converters.getPath(*it, format);
3794 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3795 backend_format = *it;
3800 if (!put_in_tempdir) {
3801 // Only show this alert if this is an export to a non-temporary
3802 // file (not for previewing).
3803 Alert::error(_("Couldn't export file"), bformat(
3804 _("No information for exporting the format %1$s."),
3805 formats.prettyName(format)));
3807 return ExportNoPathToFormat;
3809 runparams.flavor = converters.getFlavor(path, this);
3810 Graph::EdgePath::const_iterator it = path.begin();
3811 Graph::EdgePath::const_iterator en = path.end();
3812 for (; it != en; ++it)
3813 if (theConverters().get(*it).nice) {
3814 need_nice_file = true;
3819 backend_format = format;
3820 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3821 // FIXME: Don't hardcode format names here, but use a flag
3822 if (backend_format == "pdflatex")
3823 runparams.flavor = OutputParams::PDFLATEX;
3824 else if (backend_format == "luatex")
3825 runparams.flavor = OutputParams::LUATEX;
3826 else if (backend_format == "dviluatex")
3827 runparams.flavor = OutputParams::DVILUATEX;
3828 else if (backend_format == "xetex")
3829 runparams.flavor = OutputParams::XETEX;
3832 string filename = latexName(false);
3833 filename = addName(temppath(), filename);
3834 filename = changeExtension(filename,
3835 formats.extension(backend_format));
3836 LYXERR(Debug::FILES, "filename=" << filename);
3838 // Plain text backend
3839 if (backend_format == "text") {
3840 runparams.flavor = OutputParams::TEXT;
3841 writePlaintextFile(*this, FileName(filename), runparams);
3844 else if (backend_format == "xhtml") {
3845 runparams.flavor = OutputParams::HTML;
3846 setMathFlavor(runparams);
3847 makeLyXHTMLFile(FileName(filename), runparams);
3848 } else if (backend_format == "lyx")
3849 writeFile(FileName(filename));
3851 else if (params().isDocBook()) {
3852 runparams.nice = !put_in_tempdir;
3853 makeDocBookFile(FileName(filename), runparams);
3856 else if (backend_format == format || need_nice_file) {
3857 runparams.nice = true;
3858 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3859 if (d->cloned_buffer_)
3860 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3863 } else if (!lyxrc.tex_allows_spaces
3864 && contains(filePath(), ' ')) {
3865 Alert::error(_("File name error"),
3866 _("The directory path to the document cannot contain spaces."));
3867 return ExportTexPathHasSpaces;
3869 runparams.nice = false;
3870 bool const success = makeLaTeXFile(
3871 FileName(filename), filePath(), runparams);
3872 if (d->cloned_buffer_)
3873 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3878 string const error_type = (format == "program")
3879 ? "Build" : params().bufferFormat();
3880 ErrorList & error_list = d->errorLists[error_type];
3881 string const ext = formats.extension(format);
3882 FileName const tmp_result_file(changeExtension(filename, ext));
3883 bool const success = converters.convert(this, FileName(filename),
3884 tmp_result_file, FileName(absFileName()), backend_format, format,
3887 // Emit the signal to show the error list or copy it back to the
3888 // cloned Buffer so that it can be emitted afterwards.
3889 if (format != backend_format) {
3890 if (d->cloned_buffer_) {
3891 d->cloned_buffer_->d->errorLists[error_type] =
3892 d->errorLists[error_type];
3895 // also to the children, in case of master-buffer-view
3896 ListOfBuffers clist = getDescendents();
3897 ListOfBuffers::const_iterator cit = clist.begin();
3898 ListOfBuffers::const_iterator const cen = clist.end();
3899 for (; cit != cen; ++cit) {
3900 if (d->cloned_buffer_) {
3901 // Enable reverse search by copying back the
3902 // texrow object to the cloned buffer.
3903 // FIXME: this is not thread safe.
3904 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3905 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3906 (*cit)->d->errorLists[error_type];
3908 (*cit)->errors(error_type, true);
3912 if (d->cloned_buffer_) {
3913 // Enable reverse dvi or pdf to work by copying back the texrow
3914 // object to the cloned buffer.
3915 // FIXME: There is a possibility of concurrent access to texrow
3916 // here from the main GUI thread that should be securized.
3917 d->cloned_buffer_->d->texrow = d->texrow;
3918 string const error_type = params().bufferFormat();
3919 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3923 return ExportConverterError;
3925 if (put_in_tempdir) {
3926 result_file = tmp_result_file.absFileName();
3927 return ExportSuccess;
3930 if (dest_filename.empty())
3931 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3933 result_file = dest_filename;
3934 // We need to copy referenced files (e. g. included graphics
3935 // if format == "dvi") to the result dir.
3936 vector<ExportedFile> const files =
3937 runparams.exportdata->externalFiles(format);
3938 string const dest = runparams.export_folder.empty() ?
3939 onlyPath(result_file) : runparams.export_folder;
3940 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3941 : force_overwrite == ALL_FILES;
3942 CopyStatus status = use_force ? FORCE : SUCCESS;
3944 vector<ExportedFile>::const_iterator it = files.begin();
3945 vector<ExportedFile>::const_iterator const en = files.end();
3946 for (; it != en && status != CANCEL; ++it) {
3947 string const fmt = formats.getFormatFromFile(it->sourceName);
3948 string fixedName = it->exportName;
3949 if (!runparams.export_folder.empty()) {
3950 // Relative pathnames starting with ../ will be sanitized
3951 // if exporting to a different folder
3952 while (fixedName.substr(0, 3) == "../")
3953 fixedName = fixedName.substr(3, fixedName.length() - 3);
3955 FileName fixedFileName = makeAbsPath(fixedName, dest);
3956 fixedFileName.onlyPath().createPath();
3957 status = copyFile(fmt, it->sourceName,
3959 it->exportName, status == FORCE,
3960 runparams.export_folder.empty());
3963 if (status == CANCEL) {
3964 message(_("Document export cancelled."));
3965 return ExportCancel;
3968 if (tmp_result_file.exists()) {
3969 // Finally copy the main file
3970 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3971 : force_overwrite != NO_FILES;
3972 if (status == SUCCESS && use_force)
3974 status = copyFile(format, tmp_result_file,
3975 FileName(result_file), result_file,
3977 if (status == CANCEL) {
3978 message(_("Document export cancelled."));
3979 return ExportCancel;
3981 message(bformat(_("Document exported as %1$s "
3983 formats.prettyName(format),
3984 makeDisplayPath(result_file)));
3987 // This must be a dummy converter like fax (bug 1888)
3988 message(bformat(_("Document exported as %1$s"),
3989 formats.prettyName(format)));
3992 return ExportSuccess;
3996 Buffer::ExportStatus Buffer::preview(string const & format) const
3998 bool const update_unincluded =
3999 params().maintain_unincluded_children
4000 && !params().getIncludedChildren().empty();
4001 return preview(format, update_unincluded);
4004 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4006 MarkAsExporting exporting(this);
4008 // (1) export with all included children (omit \includeonly)
4010 ExportStatus const status = doExport(format, true, true, result_file);
4011 if (status != ExportSuccess)
4014 // (2) export with included children only
4015 ExportStatus const status = doExport(format, true, false, result_file);
4016 if (status != ExportSuccess)
4018 if (!formats.view(*this, FileName(result_file), format))
4019 return PreviewError;
4020 return PreviewSuccess;
4024 Buffer::ReadStatus Buffer::extractFromVC()
4026 bool const found = LyXVC::file_not_found_hook(d->filename);
4028 return ReadFileNotFound;
4029 if (!d->filename.isReadableFile())
4035 Buffer::ReadStatus Buffer::loadEmergency()
4037 FileName const emergencyFile = getEmergencyFileName();
4038 if (!emergencyFile.exists()
4039 || emergencyFile.lastModified() <= d->filename.lastModified())
4040 return ReadFileNotFound;
4042 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4043 docstring const text = bformat(_("An emergency save of the document "
4044 "%1$s exists.\n\nRecover emergency save?"), file);
4046 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4047 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4053 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4054 bool const success = (ret_llf == ReadSuccess);
4057 Alert::warning(_("File is read-only"),
4058 bformat(_("An emergency file is successfully loaded, "
4059 "but the original file %1$s is marked read-only. "
4060 "Please make sure to save the document as a different "
4061 "file."), from_utf8(d->filename.absFileName())));
4064 lyxvc().file_found_hook(d->filename);
4065 str = _("Document was successfully recovered.");
4067 str = _("Document was NOT successfully recovered.");
4068 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4069 makeDisplayPath(emergencyFile.absFileName()));
4071 int const del_emerg =
4072 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4073 _("&Remove"), _("&Keep"));
4074 if (del_emerg == 0) {
4075 emergencyFile.removeFile();
4077 Alert::warning(_("Emergency file deleted"),
4078 _("Do not forget to save your file now!"), true);
4080 return success ? ReadSuccess : ReadEmergencyFailure;
4083 int const del_emerg =
4084 Alert::prompt(_("Delete emergency file?"),
4085 _("Remove emergency file now?"), 1, 1,
4086 _("&Remove"), _("&Keep"));
4088 emergencyFile.removeFile();
4089 return ReadOriginal;
4099 Buffer::ReadStatus Buffer::loadAutosave()
4101 // Now check if autosave file is newer.
4102 FileName const autosaveFile = getAutosaveFileName();
4103 if (!autosaveFile.exists()
4104 || autosaveFile.lastModified() <= d->filename.lastModified())
4105 return ReadFileNotFound;
4107 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4108 docstring const text = bformat(_("The backup of the document %1$s "
4109 "is newer.\n\nLoad the backup instead?"), file);
4110 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4111 _("&Load backup"), _("Load &original"), _("&Cancel"));
4116 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4117 // the file is not saved if we load the autosave file.
4118 if (ret_llf == ReadSuccess) {
4120 Alert::warning(_("File is read-only"),
4121 bformat(_("A backup file is successfully loaded, "
4122 "but the original file %1$s is marked read-only. "
4123 "Please make sure to save the document as a "
4125 from_utf8(d->filename.absFileName())));
4128 lyxvc().file_found_hook(d->filename);
4131 return ReadAutosaveFailure;
4134 // Here we delete the autosave
4135 autosaveFile.removeFile();
4136 return ReadOriginal;
4144 Buffer::ReadStatus Buffer::loadLyXFile()
4146 if (!d->filename.isReadableFile()) {
4147 ReadStatus const ret_rvc = extractFromVC();
4148 if (ret_rvc != ReadSuccess)
4152 ReadStatus const ret_re = loadEmergency();
4153 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4156 ReadStatus const ret_ra = loadAutosave();
4157 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4160 return loadThisLyXFile(d->filename);
4164 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4166 return readFile(fn);
4170 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4172 TeXErrors::Errors::const_iterator it = terr.begin();
4173 TeXErrors::Errors::const_iterator end = terr.end();
4174 ListOfBuffers clist = getDescendents();
4175 ListOfBuffers::const_iterator cen = clist.end();
4177 for (; it != end; ++it) {
4180 int errorRow = it->error_in_line;
4181 Buffer const * buf = 0;
4183 if (it->child_name.empty())
4184 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4186 // The error occurred in a child
4187 ListOfBuffers::const_iterator cit = clist.begin();
4188 for (; cit != cen; ++cit) {
4189 string const child_name =
4190 DocFileName(changeExtension(
4191 (*cit)->absFileName(), "tex")).
4193 if (it->child_name != child_name)
4195 (*cit)->d->texrow.getIdFromRow(errorRow,
4196 id_start, pos_start);
4197 if (id_start != -1) {
4198 buf = d->cloned_buffer_
4199 ? (*cit)->d->cloned_buffer_->d->owner_
4200 : (*cit)->d->owner_;
4211 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4212 } while (found && id_start == id_end && pos_start == pos_end);
4214 if (id_start != id_end) {
4215 // Next registered position is outside the inset where
4216 // the error occurred, so signal end-of-paragraph
4220 errorList.push_back(ErrorItem(it->error_desc,
4221 it->error_text, id_start, pos_start, pos_end, buf));
4226 void Buffer::setBuffersForInsets() const
4228 inset().setBuffer(const_cast<Buffer &>(*this));
4232 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4234 // Use the master text class also for child documents
4235 Buffer const * const master = masterBuffer();
4236 DocumentClass const & textclass = master->params().documentClass();
4238 // do this only if we are the top-level Buffer
4240 reloadBibInfoCache();
4242 // keep the buffers to be children in this set. If the call from the
4243 // master comes back we can see which of them were actually seen (i.e.
4244 // via an InsetInclude). The remaining ones in the set need still be updated.
4245 static std::set<Buffer const *> bufToUpdate;
4246 if (scope == UpdateMaster) {
4247 // If this is a child document start with the master
4248 if (master != this) {
4249 bufToUpdate.insert(this);
4250 master->updateBuffer(UpdateMaster, utype);
4251 // Do this here in case the master has no gui associated with it. Then,
4252 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4253 if (!master->d->gui_)
4256 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4257 if (bufToUpdate.find(this) == bufToUpdate.end())
4261 // start over the counters in the master
4262 textclass.counters().reset();
4265 // update will be done below for this buffer
4266 bufToUpdate.erase(this);
4268 // update all caches
4269 clearReferenceCache();
4272 Buffer & cbuf = const_cast<Buffer &>(*this);
4274 LASSERT(!text().paragraphs().empty(), /**/);
4277 ParIterator parit = cbuf.par_iterator_begin();
4278 updateBuffer(parit, utype);
4281 // TocBackend update will be done later.
4284 d->bibinfo_cache_valid_ = true;
4285 d->cite_labels_valid_ = true;
4286 cbuf.tocBackend().update(utype == OutputUpdate);
4287 if (scope == UpdateMaster)
4288 cbuf.structureChanged();
4292 static depth_type getDepth(DocIterator const & it)
4294 depth_type depth = 0;
4295 for (size_t i = 0 ; i < it.depth() ; ++i)
4296 if (!it[i].inset().inMathed())
4297 depth += it[i].paragraph().getDepth() + 1;
4298 // remove 1 since the outer inset does not count
4302 static depth_type getItemDepth(ParIterator const & it)
4304 Paragraph const & par = *it;
4305 LabelType const labeltype = par.layout().labeltype;
4307 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4310 // this will hold the lowest depth encountered up to now.
4311 depth_type min_depth = getDepth(it);
4312 ParIterator prev_it = it;
4315 --prev_it.top().pit();
4317 // start of nested inset: go to outer par
4319 if (prev_it.empty()) {
4320 // start of document: nothing to do
4325 // We search for the first paragraph with same label
4326 // that is not more deeply nested.
4327 Paragraph & prev_par = *prev_it;
4328 depth_type const prev_depth = getDepth(prev_it);
4329 if (labeltype == prev_par.layout().labeltype) {
4330 if (prev_depth < min_depth)
4331 return prev_par.itemdepth + 1;
4332 if (prev_depth == min_depth)
4333 return prev_par.itemdepth;
4335 min_depth = min(min_depth, prev_depth);
4336 // small optimization: if we are at depth 0, we won't
4337 // find anything else
4338 if (prev_depth == 0)
4344 static bool needEnumCounterReset(ParIterator const & it)
4346 Paragraph const & par = *it;
4347 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4348 depth_type const cur_depth = par.getDepth();
4349 ParIterator prev_it = it;
4350 while (prev_it.pit()) {
4351 --prev_it.top().pit();
4352 Paragraph const & prev_par = *prev_it;
4353 if (prev_par.getDepth() <= cur_depth)
4354 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4356 // start of nested inset: reset
4361 // set the label of a paragraph. This includes the counters.
4362 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4364 BufferParams const & bp = owner_->masterBuffer()->params();
4365 DocumentClass const & textclass = bp.documentClass();
4366 Paragraph & par = it.paragraph();
4367 Layout const & layout = par.layout();
4368 Counters & counters = textclass.counters();
4370 if (par.params().startOfAppendix()) {
4371 // We want to reset the counter corresponding to toplevel sectioning
4372 Layout const & lay = textclass.getTOCLayout();
4373 docstring const cnt = lay.counter;
4375 counters.reset(cnt);
4376 counters.appendix(true);
4378 par.params().appendix(counters.appendix());
4380 // Compute the item depth of the paragraph
4381 par.itemdepth = getItemDepth(it);
4383 if (layout.margintype == MARGIN_MANUAL) {
4384 if (par.params().labelWidthString().empty())
4385 par.params().labelWidthString(par.expandLabel(layout, bp));
4386 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4387 // we do not need to do anything here, since the empty case is
4388 // handled during export.
4390 par.params().labelWidthString(docstring());
4393 switch(layout.labeltype) {
4394 case LABEL_ITEMIZE: {
4395 // At some point of time we should do something more
4396 // clever here, like:
4397 // par.params().labelString(
4398 // bp.user_defined_bullet(par.itemdepth).getText());
4399 // for now, use a simple hardcoded label
4400 docstring itemlabel;
4401 switch (par.itemdepth) {
4403 itemlabel = char_type(0x2022);
4406 itemlabel = char_type(0x2013);
4409 itemlabel = char_type(0x2217);
4412 itemlabel = char_type(0x2219); // or 0x00b7
4415 par.params().labelString(itemlabel);
4419 case LABEL_ENUMERATE: {
4420 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4422 switch (par.itemdepth) {
4431 enumcounter += "iv";
4434 // not a valid enumdepth...
4438 // Maybe we have to reset the enumeration counter.
4439 if (needEnumCounterReset(it))
4440 counters.reset(enumcounter);
4441 counters.step(enumcounter, utype);
4443 string const & lang = par.getParLanguage(bp)->code();
4444 par.params().labelString(counters.theCounter(enumcounter, lang));
4449 case LABEL_SENSITIVE: {
4450 string const & type = counters.current_float();
4451 docstring full_label;
4453 full_label = owner_->B_("Senseless!!! ");
4455 docstring name = owner_->B_(textclass.floats().getType(type).name());
4456 if (counters.hasCounter(from_utf8(type))) {
4457 string const & lang = par.getParLanguage(bp)->code();
4458 counters.step(from_utf8(type), utype);
4459 full_label = bformat(from_ascii("%1$s %2$s:"),
4461 counters.theCounter(from_utf8(type), lang));
4463 full_label = bformat(from_ascii("%1$s #:"), name);
4465 par.params().labelString(full_label);
4469 case LABEL_NO_LABEL:
4470 par.params().labelString(docstring());
4474 case LABEL_CENTERED:
4475 case LABEL_STATIC: {
4476 docstring const & lcounter = layout.counter;
4477 if (!lcounter.empty()) {
4478 if (layout.toclevel <= bp.secnumdepth
4479 && (layout.latextype != LATEX_ENVIRONMENT
4480 || it.text()->isFirstInSequence(it.pit()))) {
4481 if (counters.hasCounter(lcounter))
4482 counters.step(lcounter, utype);
4483 par.params().labelString(par.expandLabel(layout, bp));
4485 par.params().labelString(docstring());
4487 par.params().labelString(par.expandLabel(layout, bp));
4493 par.params().labelString(par.expandLabel(layout, bp));
4498 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4500 LASSERT(parit.pit() == 0, /**/);
4502 // Set the position of the text in the buffer to be able
4503 // to resolve macros in it.
4504 parit.text()->setMacrocontextPosition(parit);
4506 depth_type maxdepth = 0;
4507 pit_type const lastpit = parit.lastpit();
4508 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4509 // reduce depth if necessary
4510 if (parit->params().depth() > maxdepth) {
4511 /** FIXME: this function is const, but
4512 * nevertheless it modifies the buffer. To be
4513 * cleaner, one should modify the buffer in
4514 * another function, which is actually
4515 * non-const. This would however be costly in
4516 * terms of code duplication.
4518 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4519 parit->params().depth(maxdepth);
4521 maxdepth = parit->getMaxDepthAfter();
4523 if (utype == OutputUpdate) {
4524 // track the active counters
4525 // we have to do this for the master buffer, since the local
4526 // buffer isn't tracking anything.
4527 masterBuffer()->params().documentClass().counters().
4528 setActiveLayout(parit->layout());
4531 // set the counter for this paragraph
4532 d->setLabel(parit, utype);
4535 InsetList::const_iterator iit = parit->insetList().begin();
4536 InsetList::const_iterator end = parit->insetList().end();
4537 for (; iit != end; ++iit) {
4538 parit.pos() = iit->pos;
4539 iit->inset->updateBuffer(parit, utype);
4545 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4546 WordLangTuple & word_lang, docstring_list & suggestions) const
4550 suggestions.clear();
4551 word_lang = WordLangTuple();
4552 bool const to_end = to.empty();
4553 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4554 // OK, we start from here.
4555 for (; from != end; from.forwardPos()) {
4556 // We are only interested in text so remove the math CursorSlice.
4557 while (from.inMathed()) {
4561 // If from is at the end of the document (which is possible
4562 // when leaving the mathed) LyX will crash later otherwise.
4563 if (from.atEnd() || (!to_end && from >= end))
4566 from.paragraph().spellCheck();
4567 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4568 if (SpellChecker::misspelled(res)) {
4573 // Do not increase progress when from == to, otherwise the word
4574 // count will be wrong.
4584 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4586 bool inword = false;
4591 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4592 if (!dit.inTexted()) {
4597 Paragraph const & par = dit.paragraph();
4598 pos_type const pos = dit.pos();
4600 // Copied and adapted from isWordSeparator() in Paragraph
4601 if (pos == dit.lastpos()) {
4604 Inset const * ins = par.getInset(pos);
4605 if (ins && skipNoOutput && !ins->producesOutput()) {
4608 // stop if end of range was skipped
4609 if (!to.atEnd() && dit >= to)
4612 } else if (!par.isDeleted(pos)) {
4613 if (par.isWordSeparator(pos))
4619 if (ins && ins->isLetter())
4621 else if (ins && ins->isSpace())
4624 char_type const c = par.getChar(pos);
4625 if (isPrintableNonspace(c))
4627 else if (isSpace(c))
4637 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4639 d->updateStatistics(from, to, skipNoOutput);
4643 int Buffer::wordCount() const
4645 return d->wordCount();
4649 int Buffer::charCount(bool with_blanks) const
4651 return d->charCount(with_blanks);
4655 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4658 // c.f. bug http://www.lyx.org/trac/ticket/6587
4659 removeAutosaveFile();
4660 // e.g., read-only status could have changed due to version control
4661 d->filename.refresh();
4662 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4664 // clear parent. this will get reset if need be.
4666 ReadStatus const status = loadLyXFile();
4667 if (status == ReadSuccess) {
4672 message(bformat(_("Document %1$s reloaded."), disp_fn));
4676 message(bformat(_("Could not reload document %1$s."), disp_fn));
4686 bool Buffer::saveAs(FileName const & fn)
4688 FileName const old_name = fileName();
4689 FileName const old_auto = getAutosaveFileName();
4690 bool const old_unnamed = isUnnamed();
4697 // bring the autosave file with us, just in case.
4698 moveAutosaveFile(old_auto);
4699 // validate version control data and
4700 // correct buffer title
4701 lyxvc().file_found_hook(fileName());
4703 // the file has now been saved to the new location.
4704 // we need to check that the locations of child buffers
4706 checkChildBuffers();
4707 checkMasterBuffer();
4711 // reset the old filename and unnamed state
4712 setFileName(old_name);
4713 setUnnamed(old_unnamed);
4719 // FIXME We could do better here, but it is complicated. What would be
4720 // nice is to offer either (a) to save the child buffer to an appropriate
4721 // location, so that it would "move with the master", or else (b) to update
4722 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4723 // complicated, because the code for this lives in GuiView.
4724 void Buffer::checkChildBuffers()
4726 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4727 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4728 for (; it != en; ++it) {
4729 DocIterator dit = it->second;
4730 Buffer * cbuf = const_cast<Buffer *>(it->first);
4731 if (!cbuf || !theBufferList().isLoaded(cbuf))
4733 Inset * inset = dit.nextInset();
4734 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4735 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4736 docstring const & incfile = inset_inc->getParam("filename");
4737 string oldloc = cbuf->absFileName();
4738 string newloc = makeAbsPath(to_utf8(incfile),
4739 onlyPath(absFileName())).absFileName();
4740 if (oldloc == newloc)
4742 // the location of the child file is incorrect.
4743 Alert::warning(_("Included File Invalid"),
4744 bformat(_("Saving this document to a new location has made the file:\n"
4746 "inaccessible. You will need to update the included filename."),
4747 from_utf8(oldloc)));
4749 inset_inc->setChildBuffer(0);
4751 // invalidate cache of children
4752 d->children_positions.clear();
4753 d->position_to_children.clear();
4757 // If a child has been saved under a different name/path, it might have been
4758 // orphaned. Therefore the master needs to be reset (bug 8161).
4759 void Buffer::checkMasterBuffer()
4761 Buffer const * const master = masterBuffer();
4765 // necessary to re-register the child (bug 5873)
4766 // FIXME: clean up updateMacros (here, only
4767 // child registering is needed).
4768 master->updateMacros();
4769 // (re)set master as master buffer, but only
4770 // if we are a real child
4771 if (master->isChild(this))