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"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibtex.h"
70 #include "insets/InsetBranch.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetTabular.h"
73 #include "insets/InsetText.h"
75 #include "mathed/InsetMathHull.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "graphics/PreviewLoader.h"
82 #include "frontends/alert.h"
83 #include "frontends/Delegates.h"
84 #include "frontends/WorkAreaManager.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include "support/bind.h"
107 #include "support/shared_ptr.h"
119 using namespace lyx::support;
120 using namespace lyx::graphics;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 int const LYX_FORMAT = LYX_FORMAT_LYX;
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
145 // A storehouse for the cloned buffers.
146 list<CloneList *> cloned_buffers;
152 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
156 delete preview_loader_;
164 /// search for macro in local (buffer) table or in children
165 MacroData const * getBufferMacro(docstring const & name,
166 DocIterator const & pos) const;
168 /// Update macro table starting with position of it \param it in some
170 void updateMacros(DocIterator & it, DocIterator & scope);
172 void setLabel(ParIterator & it, UpdateType utype) const;
174 /** If we have branches that use the file suffix
175 feature, return the file name with suffix appended.
177 support::FileName exportFileName() const;
184 mutable TexRow texrow;
186 /// need to regenerate .tex?
190 mutable bool lyx_clean;
192 /// is autosave needed?
193 mutable bool bak_clean;
195 /// is this an unnamed file (New...)?
198 /// is this an internal bufffer?
199 bool internal_buffer;
204 /// name of the file the buffer is associated with.
207 /** Set to true only when the file is fully loaded.
208 * Used to prevent the premature generation of previews
209 * and by the citation inset.
211 bool file_fully_loaded;
214 mutable TocBackend toc_backend;
217 typedef pair<DocIterator, MacroData> ScopeMacro;
218 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
219 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
220 /// map from the macro name to the position map,
221 /// which maps the macro definition position to the scope and the MacroData.
222 NamePositionScopeMacroMap macros;
223 /// This seem to change the way Buffer::getMacro() works
224 mutable bool macro_lock;
226 /// positions of child buffers in the buffer
227 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
228 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
229 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
230 /// position of children buffers in this buffer
231 BufferPositionMap children_positions;
232 /// map from children inclusion positions to their scope and their buffer
233 PositionScopeBufferMap position_to_children;
235 /// Container for all sort of Buffer dependant errors.
236 map<string, ErrorList> errorLists;
238 /// timestamp and checksum used to test if the file has been externally
239 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
241 unsigned long checksum_;
244 frontend::WorkAreaManager * wa_;
246 frontend::GuiBufferDelegate * gui_;
251 /// A cache for the bibfiles (including bibfiles of loaded child
252 /// documents), needed for appropriate update of natbib labels.
253 mutable support::FileNameList bibfiles_cache_;
255 // FIXME The caching mechanism could be improved. At present, we have a
256 // cache for each Buffer, that caches all the bibliography info for that
257 // Buffer. A more efficient solution would be to have a global cache per
258 // file, and then to construct the Buffer's bibinfo from that.
259 /// A cache for bibliography info
260 mutable BiblioInfo bibinfo_;
261 /// whether the bibinfo cache is valid
262 mutable bool bibinfo_cache_valid_;
263 /// whether the bibfile cache is valid
264 mutable bool bibfile_cache_valid_;
265 /// Cache of timestamps of .bib files
266 map<FileName, time_t> bibfile_status_;
267 /// Indicates whether the bibinfo has changed since the last time
268 /// we ran updateBuffer(), i.e., whether citation labels may need
270 mutable bool cite_labels_valid_;
272 mutable RefCache ref_cache_;
274 /// our Text that should be wrapped in an InsetText
278 PreviewLoader * preview_loader_;
280 /// This is here to force the test to be done whenever parent_buffer
282 Buffer const * parent() const {
283 // if parent_buffer is not loaded, then it has been unloaded,
284 // which means that parent_buffer is an invalid pointer. So we
285 // set it to null in that case.
286 // however, the BufferList doesn't know about cloned buffers, so
287 // they will always be regarded as unloaded. in that case, we hope
289 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
291 return parent_buffer;
295 void setParent(Buffer const * pb) {
296 if (parent_buffer == pb)
299 if (!cloned_buffer_ && parent_buffer && pb)
300 LYXERR0("Warning: a buffer should not have two parents!");
302 if (!cloned_buffer_ && parent_buffer) {
303 parent_buffer->invalidateBibfileCache();
304 parent_buffer->invalidateBibinfoCache();
308 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
309 /// This one is useful for preview detached in a thread.
310 Buffer const * cloned_buffer_;
312 CloneList * clone_list_;
313 /// are we in the process of exporting this buffer?
314 mutable bool doing_export;
316 /// compute statistics
317 /// \p from initial position
318 /// \p to points to the end position
319 void updateStatistics(DocIterator & from, DocIterator & to,
320 bool skipNoOutput = true);
321 /// statistics accessor functions
322 int wordCount() const { return word_count_; }
323 int charCount(bool with_blanks) const {
325 + (with_blanks ? blank_count_ : 0);
329 /// So we can force access via the accessors.
330 mutable Buffer const * parent_buffer;
339 /// Creates the per buffer temporary directory
340 static FileName createBufferTmpDir()
343 // We are in our own directory. Why bother to mangle name?
344 // In fact I wrote this code to circumvent a problematic behaviour
345 // (bug?) of EMX mkstemp().
346 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
347 convert<string>(count++));
349 if (!tmpfl.createDirectory(0777)) {
350 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
351 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
352 from_utf8(tmpfl.absFileName())));
358 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
359 Buffer const * cloned_buffer)
360 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
361 internal_buffer(false), read_only(readonly_), filename(file),
362 file_fully_loaded(false), toc_backend(owner), macro_lock(false),
363 timestamp_(0), checksum_(0), wa_(0), gui_(0), undo_(*owner),
364 bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
365 cite_labels_valid_(false), preview_loader_(0),
366 cloned_buffer_(cloned_buffer), clone_list_(0),
367 doing_export(false), parent_buffer(0)
369 if (!cloned_buffer_) {
370 temppath = createBufferTmpDir();
371 lyxvc.setBuffer(owner_);
373 wa_ = new frontend::WorkAreaManager;
376 temppath = cloned_buffer_->d->temppath;
377 file_fully_loaded = true;
378 params = cloned_buffer_->d->params;
379 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
380 bibinfo_ = cloned_buffer_->d->bibinfo_;
381 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
382 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
383 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
384 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
385 unnamed = cloned_buffer_->d->unnamed;
386 internal_buffer = cloned_buffer_->d->internal_buffer;
390 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
391 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
393 LYXERR(Debug::INFO, "Buffer::Buffer()");
395 d->inset = new InsetText(*cloned_buffer->d->inset);
396 d->inset->setBuffer(*this);
397 // FIXME: optimize this loop somewhat, maybe by creating a new
398 // general recursive Inset::setId().
399 DocIterator it = doc_iterator_begin(this);
400 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
401 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
402 it.paragraph().setId(cloned_it.paragraph().id());
404 d->inset = new InsetText(this);
405 d->inset->setAutoBreakRows(true);
406 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
412 LYXERR(Debug::INFO, "Buffer::~Buffer()");
413 // here the buffer should take care that it is
414 // saved properly, before it goes into the void.
416 // GuiView already destroyed
420 // No need to do additional cleanups for internal buffer.
426 // this is in case of recursive includes: we won't try to delete
427 // ourselves as a child.
428 d->clone_list_->erase(this);
429 // loop over children
430 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
431 Impl::BufferPositionMap::iterator end = d->children_positions.end();
432 for (; it != end; ++it) {
433 Buffer * child = const_cast<Buffer *>(it->first);
434 if (d->clone_list_->erase(child))
437 // if we're the master buffer, then we should get rid of the list
440 // if this is not empty, we have leaked something. worse, one of the
441 // children still has a reference to this list.
442 LASSERT(d->clone_list_->empty(), /* */);
443 list<CloneList *>::iterator it =
444 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
445 LASSERT(it != cloned_buffers.end(), /* */);
446 cloned_buffers.erase(it);
447 delete d->clone_list_;
449 // FIXME Do we really need to do this right before we delete d?
450 // clear references to children in macro tables
451 d->children_positions.clear();
452 d->position_to_children.clear();
454 // loop over children
455 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
456 Impl::BufferPositionMap::iterator end = d->children_positions.end();
457 for (; it != end; ++it) {
458 Buffer * child = const_cast<Buffer *>(it->first);
459 if (theBufferList().isLoaded(child))
460 theBufferList().releaseChild(this, child);
464 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
465 msg += emergencyWrite();
466 Alert::warning(_("Attempting to close changed document!"), msg);
469 // FIXME Do we really need to do this right before we delete d?
470 // clear references to children in macro tables
471 d->children_positions.clear();
472 d->position_to_children.clear();
474 if (!d->temppath.destroyDirectory()) {
475 Alert::warning(_("Could not remove temporary directory"),
476 bformat(_("Could not remove the temporary directory %1$s"),
477 from_utf8(d->temppath.absFileName())));
486 Buffer * Buffer::cloneFromMaster() const
489 cloned_buffers.push_back(new CloneList());
490 CloneList * clones = cloned_buffers.back();
492 masterBuffer()->cloneWithChildren(bufmap, clones);
494 // make sure we got cloned
495 BufferMap::const_iterator bit = bufmap.find(this);
496 LASSERT(bit != bufmap.end(), return 0);
497 Buffer * cloned_buffer = bit->second;
499 return cloned_buffer;
503 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
505 // have we already been cloned?
506 if (bufmap.find(this) != bufmap.end())
509 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
510 bufmap[this] = buffer_clone;
511 clones->insert(buffer_clone);
512 buffer_clone->d->clone_list_ = clones;
513 buffer_clone->d->macro_lock = true;
514 buffer_clone->d->children_positions.clear();
515 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
516 // math macro caches need to be rethought and simplified.
517 // I am not sure wether we should handle Buffer cloning here or in BufferList.
518 // Right now BufferList knows nothing about buffer clones.
519 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
520 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
521 for (; it != end; ++it) {
522 DocIterator dit = it->first.clone(buffer_clone);
523 dit.setBuffer(buffer_clone);
524 Buffer * child = const_cast<Buffer *>(it->second.second);
526 child->cloneWithChildren(bufmap, clones);
527 BufferMap::iterator const bit = bufmap.find(child);
528 LASSERT(bit != bufmap.end(), continue);
529 Buffer * child_clone = bit->second;
531 Inset * inset = dit.nextInset();
532 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
533 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
534 inset_inc->setChildBuffer(child_clone);
535 child_clone->d->setParent(buffer_clone);
536 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
537 buffer_clone->setChild(dit, child_clone);
539 buffer_clone->d->macro_lock = false;
544 Buffer * Buffer::cloneBufferOnly() const {
545 cloned_buffers.push_back(new CloneList());
546 CloneList * clones = cloned_buffers.back();
547 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
548 clones->insert(buffer_clone);
549 buffer_clone->d->clone_list_ = clones;
550 // we won't be cloning the children
551 buffer_clone->d->children_positions.clear();
556 bool Buffer::isClone() const
558 return d->cloned_buffer_;
562 void Buffer::changed(bool update_metrics) const
565 d->wa_->redrawAll(update_metrics);
569 frontend::WorkAreaManager & Buffer::workAreaManager() const
571 LASSERT(d->wa_, /**/);
576 Text & Buffer::text() const
578 return d->inset->text();
582 Inset & Buffer::inset() const
588 BufferParams & Buffer::params()
594 BufferParams const & Buffer::params() const
600 ParagraphList & Buffer::paragraphs()
602 return text().paragraphs();
606 ParagraphList const & Buffer::paragraphs() const
608 return text().paragraphs();
612 LyXVC & Buffer::lyxvc()
618 LyXVC const & Buffer::lyxvc() const
624 string const Buffer::temppath() const
626 return d->temppath.absFileName();
630 TexRow & Buffer::texrow()
636 TexRow const & Buffer::texrow() const
642 TocBackend & Buffer::tocBackend() const
644 return d->toc_backend;
648 Undo & Buffer::undo()
654 void Buffer::setChild(DocIterator const & dit, Buffer * child)
656 d->children_positions[child] = dit;
660 string Buffer::latexName(bool const no_path) const
662 FileName latex_name =
663 makeLatexName(d->exportFileName());
664 return no_path ? latex_name.onlyFileName()
665 : latex_name.absFileName();
669 FileName Buffer::Impl::exportFileName() const
671 docstring const branch_suffix =
672 params.branchlist().getFileNameSuffix();
673 if (branch_suffix.empty())
676 string const name = filename.onlyFileNameWithoutExt()
677 + to_utf8(branch_suffix);
678 FileName res(filename.onlyPath().absFileName() + "/" + name);
679 res.changeExtension(filename.extension());
685 string Buffer::logName(LogType * type) const
687 string const filename = latexName(false);
689 if (filename.empty()) {
695 string const path = temppath();
697 FileName const fname(addName(temppath(),
698 onlyFileName(changeExtension(filename,
701 // FIXME: how do we know this is the name of the build log?
702 FileName const bname(
703 addName(path, onlyFileName(
704 changeExtension(filename,
705 formats.extension(params().bufferFormat()) + ".out"))));
707 // Also consider the master buffer log file
708 FileName masterfname = fname;
710 if (masterBuffer() != this) {
711 string const mlogfile = masterBuffer()->logName(&mtype);
712 masterfname = FileName(mlogfile);
715 // If no Latex log or Build log is newer, show Build log
716 if (bname.exists() &&
717 ((!fname.exists() && !masterfname.exists())
718 || (fname.lastModified() < bname.lastModified()
719 && masterfname.lastModified() < bname.lastModified()))) {
720 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
723 return bname.absFileName();
724 // If we have a newer master file log or only a master log, show this
725 } else if (fname != masterfname
726 && (!fname.exists() && (masterfname.exists()
727 || fname.lastModified() < masterfname.lastModified()))) {
728 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
731 return masterfname.absFileName();
733 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
736 return fname.absFileName();
740 void Buffer::setReadonly(bool const flag)
742 if (d->read_only != flag) {
749 void Buffer::setFileName(FileName const & fname)
752 setReadonly(d->filename.isReadOnly());
758 int Buffer::readHeader(Lexer & lex)
760 int unknown_tokens = 0;
762 int begin_header_line = -1;
764 // Initialize parameters that may be/go lacking in header:
765 params().branchlist().clear();
766 params().preamble.erase();
767 params().options.erase();
768 params().master.erase();
769 params().float_placement.erase();
770 params().paperwidth.erase();
771 params().paperheight.erase();
772 params().leftmargin.erase();
773 params().rightmargin.erase();
774 params().topmargin.erase();
775 params().bottommargin.erase();
776 params().headheight.erase();
777 params().headsep.erase();
778 params().footskip.erase();
779 params().columnsep.erase();
780 params().fonts_cjk.erase();
781 params().listings_params.clear();
782 params().clearLayoutModules();
783 params().clearRemovedModules();
784 params().clearIncludedChildren();
785 params().pdfoptions().clear();
786 params().indiceslist().clear();
787 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
788 params().isbackgroundcolor = false;
789 params().fontcolor = RGBColor(0, 0, 0);
790 params().isfontcolor = false;
791 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
792 params().boxbgcolor = RGBColor(0xFF, 0, 0);
793 params().html_latex_start.clear();
794 params().html_latex_end.clear();
795 params().html_math_img_scale = 1.0;
796 params().output_sync_macro.erase();
797 params().local_layout.clear();
799 for (int i = 0; i < 4; ++i) {
800 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
801 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
804 ErrorList & errorList = d->errorLists["Parse"];
813 if (token == "\\end_header")
817 if (token == "\\begin_header") {
818 begin_header_line = line;
822 LYXERR(Debug::PARSER, "Handling document header token: `"
825 string unknown = params().readToken(lex, token, d->filename.onlyPath());
826 if (!unknown.empty()) {
827 if (unknown[0] != '\\' && token == "\\textclass") {
828 Alert::warning(_("Unknown document class"),
829 bformat(_("Using the default document class, because the "
830 "class %1$s is unknown."), from_utf8(unknown)));
833 docstring const s = bformat(_("Unknown token: "
837 errorList.push_back(ErrorItem(_("Document header error"),
842 if (begin_header_line) {
843 docstring const s = _("\\begin_header is missing");
844 errorList.push_back(ErrorItem(_("Document header error"),
848 params().makeDocumentClass();
850 return unknown_tokens;
855 // changed to be public and have one parameter
856 // Returns true if "\end_document" is not read (Asger)
857 bool Buffer::readDocument(Lexer & lex)
859 ErrorList & errorList = d->errorLists["Parse"];
862 // remove dummy empty par
863 paragraphs().clear();
865 if (!lex.checkFor("\\begin_document")) {
866 docstring const s = _("\\begin_document is missing");
867 errorList.push_back(ErrorItem(_("Document header error"),
873 if (params().outputChanges) {
874 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
875 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
876 LaTeXFeatures::isAvailable("xcolor");
878 if (!dvipost && !xcolorulem) {
879 Alert::warning(_("Changes not shown in LaTeX output"),
880 _("Changes will not be highlighted in LaTeX output, "
881 "because neither dvipost nor xcolor/ulem are installed.\n"
882 "Please install these packages or redefine "
883 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
884 } else if (!xcolorulem) {
885 Alert::warning(_("Changes not shown in LaTeX output"),
886 _("Changes will not be highlighted in LaTeX output "
887 "when using pdflatex, because xcolor and ulem are not installed.\n"
888 "Please install both packages or redefine "
889 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
893 if (!params().master.empty()) {
894 FileName const master_file = makeAbsPath(params().master,
895 onlyPath(absFileName()));
896 if (isLyXFileName(master_file.absFileName())) {
898 checkAndLoadLyXFile(master_file, true);
900 // necessary e.g. after a reload
901 // to re-register the child (bug 5873)
902 // FIXME: clean up updateMacros (here, only
903 // child registering is needed).
904 master->updateMacros();
905 // set master as master buffer, but only
906 // if we are a real child
907 if (master->isChild(this))
909 // if the master is not fully loaded
910 // it is probably just loading this
911 // child. No warning needed then.
912 else if (master->isFullyLoaded())
913 LYXERR0("The master '"
915 << "' assigned to this document ("
917 << ") does not include "
918 "this document. Ignoring the master assignment.");
923 // assure we have a default index
924 params().indiceslist().addDefault(B_("Index"));
927 bool const res = text().read(lex, errorList, d->inset);
929 // inform parent buffer about local macros
931 Buffer const * pbuf = parent();
932 UserMacroSet::const_iterator cit = usermacros.begin();
933 UserMacroSet::const_iterator end = usermacros.end();
934 for (; cit != end; ++cit)
935 pbuf->usermacros.insert(*cit);
939 updateMacroInstances(InternalUpdate);
944 bool Buffer::readString(string const & s)
946 params().compressed = false;
951 FileName const fn = FileName::tempName("Buffer_readString");
954 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
955 if (ret_plf != ReadSuccess)
958 if (file_format != LYX_FORMAT) {
959 // We need to call lyx2lyx, so write the input to a file
960 ofstream os(fn.toFilesystemEncoding().c_str());
964 return readFile(fn) == ReadSuccess;
967 if (readDocument(lex))
973 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
977 if (!lex.setFile(fname)) {
978 Alert::error(_("File Not Found"),
979 bformat(_("Unable to open file `%1$s'."),
980 from_utf8(fn.absFileName())));
981 return ReadFileNotFound;
985 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
986 if (ret_plf != ReadSuccess)
989 if (file_format != LYX_FORMAT) {
991 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
992 if (ret_clf != ReadSuccess)
994 return readFile(tmpFile);
997 // FIXME: InsetInfo needs to know whether the file is under VCS
998 // during the parse process, so this has to be done before.
999 lyxvc().file_found_hook(d->filename);
1001 if (readDocument(lex)) {
1002 Alert::error(_("Document format failure"),
1003 bformat(_("%1$s ended unexpectedly, which means"
1004 " that it is probably corrupted."),
1005 from_utf8(fn.absFileName())));
1006 return ReadDocumentFailure;
1009 d->file_fully_loaded = true;
1010 d->read_only = !d->filename.isWritable();
1011 params().compressed = formats.isZippedFile(d->filename);
1017 bool Buffer::isFullyLoaded() const
1019 return d->file_fully_loaded;
1023 void Buffer::setFullyLoaded(bool value)
1025 d->file_fully_loaded = value;
1029 PreviewLoader * Buffer::loader() const
1031 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1033 if (!d->preview_loader_)
1034 d->preview_loader_ = new PreviewLoader(*this);
1035 return d->preview_loader_;
1039 void Buffer::removePreviews() const
1041 delete d->preview_loader_;
1042 d->preview_loader_ = 0;
1046 void Buffer::updatePreviews() const
1048 PreviewLoader * ploader = loader();
1052 InsetIterator it = inset_iterator_begin(*d->inset);
1053 InsetIterator const end = inset_iterator_end(*d->inset);
1054 for (; it != end; ++it)
1055 it->addPreview(it, *ploader);
1057 ploader->startLoading();
1061 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1062 FileName const & fn, int & file_format) const
1064 if(!lex.checkFor("\\lyxformat")) {
1065 Alert::error(_("Document format failure"),
1066 bformat(_("%1$s is not a readable LyX document."),
1067 from_utf8(fn.absFileName())));
1068 return ReadNoLyXFormat;
1074 // LyX formats 217 and earlier were written as 2.17. This corresponds
1075 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1076 // these cases. See also: www.lyx.org/trac/changeset/1313.
1077 size_t dot = tmp_format.find_first_of(".,");
1078 if (dot != string::npos)
1079 tmp_format.erase(dot, 1);
1081 file_format = convert<int>(tmp_format);
1086 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1087 FileName & tmpfile, int from_format)
1089 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1090 if(tmpfile.empty()) {
1091 Alert::error(_("Conversion failed"),
1092 bformat(_("%1$s is from a different"
1093 " version of LyX, but a temporary"
1094 " file for converting it could"
1095 " not be created."),
1096 from_utf8(fn.absFileName())));
1097 return LyX2LyXNoTempFile;
1100 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1101 if (lyx2lyx.empty()) {
1102 Alert::error(_("Conversion script not found"),
1103 bformat(_("%1$s is from a different"
1104 " version of LyX, but the"
1105 " conversion script lyx2lyx"
1106 " could not be found."),
1107 from_utf8(fn.absFileName())));
1108 return LyX2LyXNotFound;
1112 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1113 ostringstream command;
1114 command << os::python()
1115 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1116 << " -t " << convert<string>(LYX_FORMAT)
1117 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1118 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1119 string const command_str = command.str();
1121 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1123 cmd_ret const ret = runCommand(command_str);
1124 if (ret.first != 0) {
1125 if (from_format < LYX_FORMAT) {
1126 Alert::error(_("Conversion script failed"),
1127 bformat(_("%1$s is from an older version"
1128 " of LyX and the lyx2lyx script"
1129 " failed to convert it."),
1130 from_utf8(fn.absFileName())));
1131 return LyX2LyXOlderFormat;
1133 Alert::error(_("Conversion script failed"),
1134 bformat(_("%1$s is from a newer version"
1135 " of LyX and the lyx2lyx script"
1136 " failed to convert it."),
1137 from_utf8(fn.absFileName())));
1138 return LyX2LyXNewerFormat;
1145 // Should probably be moved to somewhere else: BufferView? GuiView?
1146 bool Buffer::save() const
1148 docstring const file = makeDisplayPath(absFileName(), 20);
1149 d->filename.refresh();
1151 // check the read-only status before moving the file as a backup
1152 if (d->filename.exists()) {
1153 bool const read_only = !d->filename.isWritable();
1155 Alert::warning(_("File is read-only"),
1156 bformat(_("The file %1$s cannot be written because it "
1157 "is marked as read-only."), file));
1162 // ask if the disk file has been externally modified (use checksum method)
1163 if (fileName().exists() && isExternallyModified(checksum_method)) {
1165 bformat(_("Document %1$s has been externally modified. "
1166 "Are you sure you want to overwrite this file?"), file);
1167 int const ret = Alert::prompt(_("Overwrite modified file?"),
1168 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1173 // We don't need autosaves in the immediate future. (Asger)
1174 resetAutosaveTimers();
1176 FileName backupName;
1177 bool madeBackup = false;
1179 // make a backup if the file already exists
1180 if (lyxrc.make_backup && fileName().exists()) {
1181 backupName = FileName(absFileName() + '~');
1182 if (!lyxrc.backupdir_path.empty()) {
1183 string const mangledName =
1184 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1185 backupName = FileName(addName(lyxrc.backupdir_path,
1189 // Except file is symlink do not copy because of #6587.
1190 // Hard links have bad luck.
1191 if (fileName().isSymLink())
1192 madeBackup = fileName().copyTo(backupName);
1194 madeBackup = fileName().moveTo(backupName);
1197 Alert::error(_("Backup failure"),
1198 bformat(_("Cannot create backup file %1$s.\n"
1199 "Please check whether the directory exists and is writable."),
1200 from_utf8(backupName.absFileName())));
1201 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1205 if (writeFile(d->filename)) {
1209 // Saving failed, so backup is not backup
1211 backupName.moveTo(d->filename);
1217 bool Buffer::writeFile(FileName const & fname) const
1219 // FIXME Do we need to do these here? I don't think writing
1220 // the LyX file depends upon it. (RGH)
1222 // updateMacroInstances();
1224 if (d->read_only && fname == d->filename)
1227 bool retval = false;
1229 docstring const str = bformat(_("Saving document %1$s..."),
1230 makeDisplayPath(fname.absFileName()));
1233 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1235 if (params().compressed) {
1236 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1237 retval = ofs && write(ofs);
1239 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1240 retval = ofs && write(ofs);
1244 message(str + _(" could not write file!"));
1249 // removeAutosaveFile();
1252 message(str + _(" done."));
1258 docstring Buffer::emergencyWrite()
1260 // No need to save if the buffer has not changed.
1264 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1266 docstring user_message = bformat(
1267 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1269 // We try to save three places:
1270 // 1) Same place as document. Unless it is an unnamed doc.
1272 string s = absFileName();
1275 if (writeFile(FileName(s))) {
1277 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1278 return user_message;
1280 user_message += " " + _("Save failed! Trying again...\n");
1284 // 2) In HOME directory.
1285 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1287 lyxerr << ' ' << s << endl;
1288 if (writeFile(FileName(s))) {
1290 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1291 return user_message;
1294 user_message += " " + _("Save failed! Trying yet again...\n");
1296 // 3) In "/tmp" directory.
1297 // MakeAbsPath to prepend the current
1298 // drive letter on OS/2
1299 s = addName(package().temp_dir().absFileName(), absFileName());
1301 lyxerr << ' ' << s << endl;
1302 if (writeFile(FileName(s))) {
1304 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1305 return user_message;
1308 user_message += " " + _("Save failed! Bummer. Document is lost.");
1311 return user_message;
1315 bool Buffer::write(ostream & ofs) const
1318 // Use the standard "C" locale for file output.
1319 ofs.imbue(locale::classic());
1322 // The top of the file should not be written by params().
1324 // write out a comment in the top of the file
1325 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1326 << " created this file. For more info see http://www.lyx.org/\n"
1327 << "\\lyxformat " << LYX_FORMAT << "\n"
1328 << "\\begin_document\n";
1330 /// For each author, set 'used' to true if there is a change
1331 /// by this author in the document; otherwise set it to 'false'.
1332 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1333 AuthorList::Authors::const_iterator a_end = params().authors().end();
1334 for (; a_it != a_end; ++a_it)
1335 a_it->setUsed(false);
1337 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1338 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1339 for ( ; it != end; ++it)
1340 it->checkAuthors(params().authors());
1342 // now write out the buffer parameters.
1343 ofs << "\\begin_header\n";
1344 params().writeFile(ofs);
1345 ofs << "\\end_header\n";
1348 ofs << "\n\\begin_body\n";
1350 ofs << "\n\\end_body\n";
1352 // Write marker that shows file is complete
1353 ofs << "\\end_document" << endl;
1355 // Shouldn't really be needed....
1358 // how to check if close went ok?
1359 // Following is an attempt... (BE 20001011)
1361 // good() returns false if any error occured, including some
1362 // formatting error.
1363 // bad() returns true if something bad happened in the buffer,
1364 // which should include file system full errors.
1369 lyxerr << "File was not closed properly." << endl;
1376 bool Buffer::makeLaTeXFile(FileName const & fname,
1377 string const & original_path,
1378 OutputParams const & runparams_in,
1379 OutputWhat output) const
1381 OutputParams runparams = runparams_in;
1383 // This is necessary for LuaTeX/XeTeX with tex fonts.
1384 // See FIXME in BufferParams::encoding()
1385 if (runparams.isFullUnicode())
1386 runparams.encoding = encodings.fromLyXName("utf8-plain");
1388 string const encoding = runparams.encoding->iconvName();
1389 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1392 try { ofs.reset(encoding); }
1393 catch (iconv_codecvt_facet_exception & e) {
1394 lyxerr << "Caught iconv exception: " << e.what() << endl;
1395 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1396 "verify that the support software for your encoding (%1$s) is "
1397 "properly installed"), from_ascii(encoding)));
1400 if (!openFileWrite(ofs, fname))
1403 //TexStream ts(ofs.rdbuf(), &texrow());
1404 ErrorList & errorList = d->errorLists["Export"];
1406 bool failed_export = false;
1407 otexstream os(ofs, d->texrow);
1409 // make sure we are ready to export
1410 // this needs to be done before we validate
1411 // FIXME Do we need to do this all the time? I.e., in children
1412 // of a master we are exporting?
1414 updateMacroInstances(OutputUpdate);
1417 os.texrow().reset();
1418 writeLaTeXSource(os, original_path, runparams, output);
1420 catch (EncodingException & e) {
1421 odocstringstream ods;
1422 ods.put(e.failed_char);
1424 oss << "0x" << hex << e.failed_char << dec;
1425 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1426 " (code point %2$s)"),
1427 ods.str(), from_utf8(oss.str()));
1428 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1429 "representable in the chosen encoding.\n"
1430 "Changing the document encoding to utf8 could help."),
1431 e.par_id, e.pos, e.pos + 1));
1432 failed_export = true;
1434 catch (iconv_codecvt_facet_exception & e) {
1435 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1436 _(e.what()), -1, 0, 0));
1437 failed_export = true;
1439 catch (exception const & e) {
1440 errorList.push_back(ErrorItem(_("conversion failed"),
1441 _(e.what()), -1, 0, 0));
1442 failed_export = true;
1445 lyxerr << "Caught some really weird exception..." << endl;
1451 failed_export = true;
1452 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1456 return !failed_export;
1460 void Buffer::writeLaTeXSource(otexstream & os,
1461 string const & original_path,
1462 OutputParams const & runparams_in,
1463 OutputWhat output) const
1465 // The child documents, if any, shall be already loaded at this point.
1467 OutputParams runparams = runparams_in;
1469 // Classify the unicode characters appearing in math insets
1470 Encodings::initUnicodeMath(*this);
1472 // validate the buffer.
1473 LYXERR(Debug::LATEX, " Validating buffer...");
1474 LaTeXFeatures features(*this, params(), runparams);
1476 LYXERR(Debug::LATEX, " Buffer validation done.");
1478 bool const output_preamble =
1479 output == FullSource || output == OnlyPreamble;
1480 bool const output_body =
1481 output == FullSource || output == OnlyBody;
1483 // The starting paragraph of the coming rows is the
1484 // first paragraph of the document. (Asger)
1485 if (output_preamble && runparams.nice) {
1486 os << "%% LyX " << lyx_version << " created this file. "
1487 "For more info, see http://www.lyx.org/.\n"
1488 "%% Do not edit unless you really know what "
1491 LYXERR(Debug::INFO, "lyx document header finished");
1493 // There are a few differences between nice LaTeX and usual files:
1494 // usual files have \batchmode and special input@path to allow
1495 // inclusion of figures specified by an explicitly relative path
1496 // (i.e., a path starting with './' or '../') with either \input or
1497 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1498 // input@path is set when the actual parameter original_path is set.
1499 // This is done for usual tex-file, but not for nice-latex-file.
1500 // (Matthias 250696)
1501 // Note that input@path is only needed for something the user does
1502 // in the preamble, included .tex files or ERT, files included by
1503 // LyX work without it.
1504 if (output_preamble) {
1505 if (!runparams.nice) {
1506 // code for usual, NOT nice-latex-file
1507 os << "\\batchmode\n"; // changed from \nonstopmode
1509 if (!original_path.empty()) {
1511 // We don't know the encoding of inputpath
1512 docstring const inputpath = from_utf8(original_path);
1513 docstring uncodable_glyphs;
1514 Encoding const * const enc = runparams.encoding;
1516 for (size_t n = 0; n < inputpath.size(); ++n) {
1517 if (!enc->encodable(inputpath[n])) {
1518 docstring const glyph(1, inputpath[n]);
1519 LYXERR0("Uncodable character '"
1521 << "' in input path!");
1522 uncodable_glyphs += glyph;
1527 // warn user if we found uncodable glyphs.
1528 if (!uncodable_glyphs.empty()) {
1529 frontend::Alert::warning(
1530 _("Uncodable character in file path"),
1532 _("The path of your document\n"
1534 "contains glyphs that are unknown "
1535 "in the current document encoding "
1536 "(namely %2$s). This may result in "
1537 "incomplete output, unless "
1538 "TEXINPUTS contains the document "
1539 "directory and you don't use "
1540 "explicitly relative paths (i.e., "
1541 "paths starting with './' or "
1542 "'../') in the preamble or in ERT."
1543 "\n\nIn case of problems, choose "
1544 "an appropriate document encoding\n"
1545 "(such as utf8) or change the "
1547 inputpath, uncodable_glyphs));
1550 support::latex_path(original_path);
1551 if (contains(docdir, '#')) {
1552 docdir = subst(docdir, "#", "\\#");
1553 os << "\\catcode`\\#=11"
1554 "\\def\\#{#}\\catcode`\\#=6\n";
1556 if (contains(docdir, '%')) {
1557 docdir = subst(docdir, "%", "\\%");
1558 os << "\\catcode`\\%=11"
1559 "\\def\\%{%}\\catcode`\\%=14\n";
1561 os << "\\makeatletter\n"
1562 << "\\def\\input@path{{"
1563 << docdir << "/}}\n"
1564 << "\\makeatother\n";
1568 // get parent macros (if this buffer has a parent) which will be
1569 // written at the document begin further down.
1570 MacroSet parentMacros;
1571 listParentMacros(parentMacros, features);
1573 runparams.use_polyglossia = features.usePolyglossia();
1574 // Write the preamble
1575 runparams.use_babel = params().writeLaTeX(os, features,
1576 d->filename.onlyPath());
1578 runparams.use_japanese = features.isRequired("japanese");
1584 os << "\\begin{document}\n";
1586 // output the parent macros
1587 MacroSet::iterator it = parentMacros.begin();
1588 MacroSet::iterator end = parentMacros.end();
1589 for (; it != end; ++it) {
1590 int num_lines = (*it)->write(os.os(), true);
1591 os.texrow().newlines(num_lines);
1594 } // output_preamble
1596 os.texrow().start(paragraphs().begin()->id(), 0);
1598 LYXERR(Debug::INFO, "preamble finished, now the body.");
1600 // if we are doing a real file with body, even if this is the
1601 // child of some other buffer, let's cut the link here.
1602 // This happens for example if only a child document is printed.
1603 Buffer const * save_parent = 0;
1604 if (output_preamble) {
1605 save_parent = d->parent();
1610 latexParagraphs(*this, text(), os, runparams);
1612 // Restore the parenthood if needed
1613 if (output_preamble)
1614 d->setParent(save_parent);
1616 // add this just in case after all the paragraphs
1619 if (output_preamble) {
1620 os << "\\end{document}\n";
1621 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1623 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1625 runparams_in.encoding = runparams.encoding;
1627 // Just to be sure. (Asger)
1628 os.texrow().newline();
1630 //for (int i = 0; i<d->texrow.rows(); i++) {
1632 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1633 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1636 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1637 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1641 void Buffer::makeDocBookFile(FileName const & fname,
1642 OutputParams const & runparams,
1643 OutputWhat output) const
1645 LYXERR(Debug::LATEX, "makeDocBookFile...");
1648 if (!openFileWrite(ofs, fname))
1651 // make sure we are ready to export
1652 // this needs to be done before we validate
1654 updateMacroInstances(OutputUpdate);
1656 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1660 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1664 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1665 OutputParams const & runparams,
1666 OutputWhat output) const
1668 LaTeXFeatures features(*this, params(), runparams);
1673 DocumentClass const & tclass = params().documentClass();
1674 string const top_element = tclass.latexname();
1676 bool const output_preamble =
1677 output == FullSource || output == OnlyPreamble;
1678 bool const output_body =
1679 output == FullSource || output == OnlyBody;
1681 if (output_preamble) {
1682 if (runparams.flavor == OutputParams::XML)
1683 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1686 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1689 if (! tclass.class_header().empty())
1690 os << from_ascii(tclass.class_header());
1691 else if (runparams.flavor == OutputParams::XML)
1692 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1693 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1695 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1697 docstring preamble = from_utf8(params().preamble);
1698 if (runparams.flavor != OutputParams::XML ) {
1699 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1700 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1701 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1702 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1705 string const name = runparams.nice
1706 ? changeExtension(absFileName(), ".sgml") : fname;
1707 preamble += features.getIncludedFiles(name);
1708 preamble += features.getLyXSGMLEntities();
1710 if (!preamble.empty()) {
1711 os << "\n [ " << preamble << " ]";
1717 string top = top_element;
1719 if (runparams.flavor == OutputParams::XML)
1720 top += params().language->code();
1722 top += params().language->code().substr(0, 2);
1725 if (!params().options.empty()) {
1727 top += params().options;
1730 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1731 << " file was created by LyX " << lyx_version
1732 << "\n See http://www.lyx.org/ for more information -->\n";
1734 params().documentClass().counters().reset();
1736 sgml::openTag(os, top);
1738 docbookParagraphs(text(), *this, os, runparams);
1739 sgml::closeTag(os, top_element);
1744 void Buffer::makeLyXHTMLFile(FileName const & fname,
1745 OutputParams const & runparams) const
1747 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1750 if (!openFileWrite(ofs, fname))
1753 // make sure we are ready to export
1754 // this has to be done before we validate
1755 updateBuffer(UpdateMaster, OutputUpdate);
1756 updateMacroInstances(OutputUpdate);
1758 writeLyXHTMLSource(ofs, runparams, FullSource);
1762 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1766 void Buffer::writeLyXHTMLSource(odocstream & os,
1767 OutputParams const & runparams,
1768 OutputWhat output) const
1770 LaTeXFeatures features(*this, params(), runparams);
1772 d->bibinfo_.makeCitationLabels(*this);
1774 bool const output_preamble =
1775 output == FullSource || output == OnlyPreamble;
1776 bool const output_body =
1777 output == FullSource || output == OnlyBody || output == IncludedFile;
1779 if (output_preamble) {
1780 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1781 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n"
1782 // FIXME Language should be set properly.
1783 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1785 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1786 // FIXME Presumably need to set this right
1787 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1789 docstring const & doctitle = features.htmlTitle();
1791 << (doctitle.empty() ?
1792 from_ascii("LyX Document") :
1793 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1796 docstring styles = features.getTClassHTMLPreamble();
1797 if (!styles.empty())
1798 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1800 styles = from_utf8(features.getPreambleSnippets());
1801 if (!styles.empty())
1802 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1804 // we will collect CSS information in a stream, and then output it
1805 // either here, as part of the header, or else in a separate file.
1806 odocstringstream css;
1807 styles = from_utf8(features.getCSSSnippets());
1808 if (!styles.empty())
1809 css << "/* LyX Provided Styles */\n" << styles << '\n';
1811 styles = features.getTClassHTMLStyles();
1812 if (!styles.empty())
1813 css << "/* Layout-provided Styles */\n" << styles << '\n';
1815 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1816 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1817 if (needfg || needbg) {
1818 css << "\nbody {\n";
1821 << from_ascii(X11hexname(params().fontcolor))
1824 css << " background-color: "
1825 << from_ascii(X11hexname(params().backgroundcolor))
1830 docstring const dstyles = css.str();
1831 if (!dstyles.empty()) {
1832 bool written = false;
1833 if (params().html_css_as_file) {
1834 // open a file for CSS info
1836 string const fcssname = addName(temppath(), "docstyle.css");
1837 FileName const fcssfile = FileName(fcssname);
1838 if (openFileWrite(ocss, fcssfile)) {
1842 // write link to header
1843 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1845 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1848 // we are here if the CSS is supposed to be written to the header
1849 // or if we failed to write it to an external file.
1851 os << "<style type='text/css'>\n"
1860 bool const output_body_tag = (output != IncludedFile);
1861 if (output_body_tag)
1864 params().documentClass().counters().reset();
1865 xhtmlParagraphs(text(), *this, xs, runparams);
1866 if (output_body_tag)
1870 if (output_preamble)
1875 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1876 // Other flags: -wall -v0 -x
1877 int Buffer::runChktex()
1881 // get LaTeX-Filename
1882 FileName const path(temppath());
1883 string const name = addName(path.absFileName(), latexName());
1884 string const org_path = filePath();
1886 PathChanger p(path); // path to LaTeX file
1887 message(_("Running chktex..."));
1889 // Generate the LaTeX file if neccessary
1890 OutputParams runparams(¶ms().encoding());
1891 runparams.flavor = OutputParams::LATEX;
1892 runparams.nice = false;
1893 runparams.linelen = lyxrc.plaintext_linelen;
1894 makeLaTeXFile(FileName(name), org_path, runparams);
1897 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1898 int const res = chktex.run(terr); // run chktex
1901 Alert::error(_("chktex failure"),
1902 _("Could not run chktex successfully."));
1903 } else if (res > 0) {
1904 ErrorList & errlist = d->errorLists["ChkTeX"];
1906 bufferErrors(terr, errlist);
1917 void Buffer::validate(LaTeXFeatures & features) const
1919 params().validate(features);
1921 for_each(paragraphs().begin(), paragraphs().end(),
1922 bind(&Paragraph::validate, _1, ref(features)));
1924 if (lyxerr.debugging(Debug::LATEX)) {
1925 features.showStruct();
1930 void Buffer::getLabelList(vector<docstring> & list) const
1932 // If this is a child document, use the master's list instead.
1934 masterBuffer()->getLabelList(list);
1939 Toc & toc = d->toc_backend.toc("label");
1940 TocIterator toc_it = toc.begin();
1941 TocIterator end = toc.end();
1942 for (; toc_it != end; ++toc_it) {
1943 if (toc_it->depth() == 0)
1944 list.push_back(toc_it->str());
1949 void Buffer::updateBibfilesCache(UpdateScope scope) const
1951 // FIXME This is probably unnecssary, given where we call this.
1952 // If this is a child document, use the parent's cache instead.
1953 if (parent() && scope != UpdateChildOnly) {
1954 masterBuffer()->updateBibfilesCache();
1958 d->bibfiles_cache_.clear();
1959 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1960 if (it->lyxCode() == BIBTEX_CODE) {
1961 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1962 support::FileNameList const bibfiles = inset.getBibFiles();
1963 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1966 } else if (it->lyxCode() == INCLUDE_CODE) {
1967 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1968 Buffer const * const incbuf = inset.getChildBuffer();
1971 support::FileNameList const & bibfiles =
1972 incbuf->getBibfilesCache(UpdateChildOnly);
1973 if (!bibfiles.empty()) {
1974 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1980 d->bibfile_cache_valid_ = true;
1981 d->bibinfo_cache_valid_ = false;
1982 d->cite_labels_valid_ = false;
1986 void Buffer::invalidateBibinfoCache() const
1988 d->bibinfo_cache_valid_ = false;
1989 d->cite_labels_valid_ = false;
1990 // also invalidate the cache for the parent buffer
1991 Buffer const * const pbuf = d->parent();
1993 pbuf->invalidateBibinfoCache();
1997 void Buffer::invalidateBibfileCache() const
1999 d->bibfile_cache_valid_ = false;
2000 d->bibinfo_cache_valid_ = false;
2001 d->cite_labels_valid_ = false;
2002 // also invalidate the cache for the parent buffer
2003 Buffer const * const pbuf = d->parent();
2005 pbuf->invalidateBibfileCache();
2009 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2011 // FIXME This is probably unnecessary, given where we call this.
2012 // If this is a child document, use the master's cache instead.
2013 Buffer const * const pbuf = masterBuffer();
2014 if (pbuf != this && scope != UpdateChildOnly)
2015 return pbuf->getBibfilesCache();
2017 if (!d->bibfile_cache_valid_)
2018 this->updateBibfilesCache(scope);
2020 return d->bibfiles_cache_;
2024 BiblioInfo const & Buffer::masterBibInfo() const
2026 Buffer const * const tmp = masterBuffer();
2028 return tmp->masterBibInfo();
2033 void Buffer::checkIfBibInfoCacheIsValid() const
2035 // use the master's cache
2036 Buffer const * const tmp = masterBuffer();
2038 tmp->checkIfBibInfoCacheIsValid();
2042 // compare the cached timestamps with the actual ones.
2043 FileNameList const & bibfiles_cache = getBibfilesCache();
2044 FileNameList::const_iterator ei = bibfiles_cache.begin();
2045 FileNameList::const_iterator en = bibfiles_cache.end();
2046 for (; ei != en; ++ ei) {
2047 time_t lastw = ei->lastModified();
2048 time_t prevw = d->bibfile_status_[*ei];
2049 if (lastw != prevw) {
2050 d->bibinfo_cache_valid_ = false;
2051 d->cite_labels_valid_ = false;
2052 d->bibfile_status_[*ei] = lastw;
2058 void Buffer::reloadBibInfoCache() const
2060 // use the master's cache
2061 Buffer const * const tmp = masterBuffer();
2063 tmp->reloadBibInfoCache();
2067 checkIfBibInfoCacheIsValid();
2068 if (d->bibinfo_cache_valid_)
2071 d->bibinfo_.clear();
2073 d->bibinfo_cache_valid_ = true;
2077 void Buffer::collectBibKeys() const
2079 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2080 it->collectBibKeys(it);
2084 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2086 Buffer const * tmp = masterBuffer();
2087 BiblioInfo & masterbi = (tmp == this) ?
2088 d->bibinfo_ : tmp->d->bibinfo_;
2089 masterbi.mergeBiblioInfo(bi);
2093 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2095 Buffer const * tmp = masterBuffer();
2096 BiblioInfo & masterbi = (tmp == this) ?
2097 d->bibinfo_ : tmp->d->bibinfo_;
2102 bool Buffer::citeLabelsValid() const
2104 return masterBuffer()->d->cite_labels_valid_;
2108 void Buffer::removeBiblioTempFiles() const
2110 // We remove files that contain LaTeX commands specific to the
2111 // particular bibliographic style being used, in order to avoid
2112 // LaTeX errors when we switch style.
2113 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2114 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2115 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2116 aux_file.removeFile();
2117 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2118 bbl_file.removeFile();
2119 // Also for the parent buffer
2120 Buffer const * const pbuf = parent();
2122 pbuf->removeBiblioTempFiles();
2126 bool Buffer::isDepClean(string const & name) const
2128 DepClean::const_iterator const it = d->dep_clean.find(name);
2129 if (it == d->dep_clean.end())
2135 void Buffer::markDepClean(string const & name)
2137 d->dep_clean[name] = true;
2141 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2144 // FIXME? if there is an Buffer LFUN that can be dispatched even
2145 // if internal, put a switch '(cmd.action)' here.
2151 switch (cmd.action()) {
2153 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2154 flag.setOnOff(isReadonly());
2157 // FIXME: There is need for a command-line import.
2158 //case LFUN_BUFFER_IMPORT:
2160 case LFUN_BUFFER_AUTO_SAVE:
2163 case LFUN_BUFFER_EXPORT_CUSTOM:
2164 // FIXME: Nothing to check here?
2167 case LFUN_BUFFER_EXPORT: {
2168 docstring const arg = cmd.argument();
2169 if (arg == "custom") {
2173 string format = to_utf8(arg);
2174 size_t pos = format.find(' ');
2175 if (pos != string::npos)
2176 format = format.substr(0, pos);
2177 enable = params().isExportable(format);
2179 flag.message(bformat(
2180 _("Don't know how to export to format: %1$s"), arg));
2184 case LFUN_BUFFER_CHKTEX:
2185 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2188 case LFUN_BUILD_PROGRAM:
2189 enable = params().isExportable("program");
2192 case LFUN_BRANCH_ADD:
2193 case LFUN_BRANCHES_RENAME:
2194 case LFUN_BUFFER_PRINT:
2195 // if no Buffer is present, then of course we won't be called!
2198 case LFUN_BUFFER_LANGUAGE:
2199 enable = !isReadonly();
2205 flag.setEnabled(enable);
2210 void Buffer::dispatch(string const & command, DispatchResult & result)
2212 return dispatch(lyxaction.lookupFunc(command), result);
2216 // NOTE We can end up here even if we have no GUI, because we are called
2217 // by LyX::exec to handled command-line requests. So we may need to check
2218 // whether we have a GUI or not. The boolean use_gui holds this information.
2219 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2222 // FIXME? if there is an Buffer LFUN that can be dispatched even
2223 // if internal, put a switch '(cmd.action())' here.
2224 dr.dispatched(false);
2227 string const argument = to_utf8(func.argument());
2228 // We'll set this back to false if need be.
2229 bool dispatched = true;
2230 undo().beginUndoGroup();
2232 switch (func.action()) {
2233 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2234 if (lyxvc().inUse())
2235 lyxvc().toggleReadOnly();
2237 setReadonly(!isReadonly());
2240 case LFUN_BUFFER_EXPORT: {
2241 ExportStatus const status = doExport(argument, false);
2242 dr.setError(status != ExportSuccess);
2243 if (status != ExportSuccess)
2244 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2249 case LFUN_BUILD_PROGRAM:
2250 doExport("program", true);
2253 case LFUN_BUFFER_CHKTEX:
2257 case LFUN_BUFFER_EXPORT_CUSTOM: {
2259 string command = split(argument, format_name, ' ');
2260 Format const * format = formats.getFormat(format_name);
2262 lyxerr << "Format \"" << format_name
2263 << "\" not recognized!"
2268 // The name of the file created by the conversion process
2271 // Output to filename
2272 if (format->name() == "lyx") {
2273 string const latexname = latexName(false);
2274 filename = changeExtension(latexname,
2275 format->extension());
2276 filename = addName(temppath(), filename);
2278 if (!writeFile(FileName(filename)))
2282 doExport(format_name, true, filename);
2285 // Substitute $$FName for filename
2286 if (!contains(command, "$$FName"))
2287 command = "( " + command + " ) < $$FName";
2288 command = subst(command, "$$FName", filename);
2290 // Execute the command in the background
2292 call.startscript(Systemcall::DontWait, command, filePath());
2296 // FIXME: There is need for a command-line import.
2298 case LFUN_BUFFER_IMPORT:
2303 case LFUN_BUFFER_AUTO_SAVE:
2305 resetAutosaveTimers();
2308 case LFUN_BRANCH_ADD: {
2309 docstring branch_name = func.argument();
2310 if (branch_name.empty()) {
2314 BranchList & branch_list = params().branchlist();
2315 vector<docstring> const branches =
2316 getVectorFromString(branch_name, branch_list.separator());
2318 for (vector<docstring>::const_iterator it = branches.begin();
2319 it != branches.end(); ++it) {
2321 Branch * branch = branch_list.find(branch_name);
2323 LYXERR0("Branch " << branch_name << " already exists.");
2327 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2329 branch_list.add(branch_name);
2330 branch = branch_list.find(branch_name);
2331 string const x11hexname = X11hexname(branch->color());
2332 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2333 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2335 dr.screenUpdate(Update::Force);
2343 case LFUN_BRANCHES_RENAME: {
2344 if (func.argument().empty())
2347 docstring const oldname = from_utf8(func.getArg(0));
2348 docstring const newname = from_utf8(func.getArg(1));
2349 InsetIterator it = inset_iterator_begin(inset());
2350 InsetIterator const end = inset_iterator_end(inset());
2351 bool success = false;
2352 for (; it != end; ++it) {
2353 if (it->lyxCode() == BRANCH_CODE) {
2354 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2355 if (ins.branch() == oldname) {
2356 undo().recordUndo(it);
2357 ins.rename(newname);
2362 if (it->lyxCode() == INCLUDE_CODE) {
2363 // get buffer of external file
2364 InsetInclude const & ins =
2365 static_cast<InsetInclude const &>(*it);
2366 Buffer * child = ins.getChildBuffer();
2369 child->dispatch(func, dr);
2374 dr.screenUpdate(Update::Force);
2375 dr.forceBufferUpdate();
2380 case LFUN_BUFFER_PRINT: {
2381 // we'll assume there's a problem until we succeed
2383 string target = func.getArg(0);
2384 string target_name = func.getArg(1);
2385 string command = func.getArg(2);
2388 || target_name.empty()
2389 || command.empty()) {
2390 LYXERR0("Unable to parse " << func.argument());
2391 docstring const msg =
2392 bformat(_("Unable to parse \"%1$s\""), func.argument());
2396 if (target != "printer" && target != "file") {
2397 LYXERR0("Unrecognized target \"" << target << '"');
2398 docstring const msg =
2399 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2404 if (!doExport("dvi", true)) {
2405 showPrintError(absFileName());
2406 dr.setMessage(_("Error exporting to DVI."));
2410 // Push directory path.
2411 string const path = temppath();
2412 // Prevent the compiler from optimizing away p
2416 // there are three cases here:
2417 // 1. we print to a file
2418 // 2. we print directly to a printer
2419 // 3. we print using a spool command (print to file first)
2422 string const dviname = changeExtension(latexName(true), "dvi");
2424 if (target == "printer") {
2425 if (!lyxrc.print_spool_command.empty()) {
2426 // case 3: print using a spool
2427 string const psname = changeExtension(dviname,".ps");
2428 command += ' ' + lyxrc.print_to_file
2431 + quoteName(dviname);
2433 string command2 = lyxrc.print_spool_command + ' ';
2434 if (target_name != "default") {
2435 command2 += lyxrc.print_spool_printerprefix
2439 command2 += quoteName(psname);
2441 // If successful, then spool command
2442 res = one.startscript(Systemcall::Wait, command,
2446 // If there's no GUI, we have to wait on this command. Otherwise,
2447 // LyX deletes the temporary directory, and with it the spooled
2448 // file, before it can be printed!!
2449 Systemcall::Starttype stype = use_gui ?
2450 Systemcall::DontWait : Systemcall::Wait;
2451 res = one.startscript(stype, command2,
2455 // case 2: print directly to a printer
2456 if (target_name != "default")
2457 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2459 Systemcall::Starttype stype = use_gui ?
2460 Systemcall::DontWait : Systemcall::Wait;
2461 res = one.startscript(stype, command +
2462 quoteName(dviname), filePath());
2466 // case 1: print to a file
2467 FileName const filename(makeAbsPath(target_name, filePath()));
2468 FileName const dvifile(makeAbsPath(dviname, path));
2469 if (filename.exists()) {
2470 docstring text = bformat(
2471 _("The file %1$s already exists.\n\n"
2472 "Do you want to overwrite that file?"),
2473 makeDisplayPath(filename.absFileName()));
2474 if (Alert::prompt(_("Overwrite file?"),
2475 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2478 command += ' ' + lyxrc.print_to_file
2479 + quoteName(filename.toFilesystemEncoding())
2481 + quoteName(dvifile.toFilesystemEncoding());
2483 Systemcall::Starttype stype = use_gui ?
2484 Systemcall::DontWait : Systemcall::Wait;
2485 res = one.startscript(stype, command, filePath());
2491 dr.setMessage(_("Error running external commands."));
2492 showPrintError(absFileName());
2501 dr.dispatched(dispatched);
2502 undo().endUndoGroup();
2506 void Buffer::changeLanguage(Language const * from, Language const * to)
2508 LASSERT(from, /**/);
2511 for_each(par_iterator_begin(),
2513 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2517 bool Buffer::isMultiLingual() const
2519 ParConstIterator end = par_iterator_end();
2520 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2521 if (it->isMultiLingual(params()))
2528 std::set<Language const *> Buffer::getLanguages() const
2530 std::set<Language const *> languages;
2531 getLanguages(languages);
2536 void Buffer::getLanguages(std::set<Language const *> & languages) const
2538 ParConstIterator end = par_iterator_end();
2539 // add the buffer language, even if it's not actively used
2540 languages.insert(language());
2541 // iterate over the paragraphs
2542 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2543 it->getLanguages(languages);
2545 ListOfBuffers clist = getDescendents();
2546 ListOfBuffers::const_iterator cit = clist.begin();
2547 ListOfBuffers::const_iterator const cen = clist.end();
2548 for (; cit != cen; ++cit)
2549 (*cit)->getLanguages(languages);
2553 DocIterator Buffer::getParFromID(int const id) const
2555 Buffer * buf = const_cast<Buffer *>(this);
2557 // John says this is called with id == -1 from undo
2558 lyxerr << "getParFromID(), id: " << id << endl;
2559 return doc_iterator_end(buf);
2562 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2563 if (it.paragraph().id() == id)
2566 return doc_iterator_end(buf);
2570 bool Buffer::hasParWithID(int const id) const
2572 return !getParFromID(id).atEnd();
2576 ParIterator Buffer::par_iterator_begin()
2578 return ParIterator(doc_iterator_begin(this));
2582 ParIterator Buffer::par_iterator_end()
2584 return ParIterator(doc_iterator_end(this));
2588 ParConstIterator Buffer::par_iterator_begin() const
2590 return ParConstIterator(doc_iterator_begin(this));
2594 ParConstIterator Buffer::par_iterator_end() const
2596 return ParConstIterator(doc_iterator_end(this));
2600 Language const * Buffer::language() const
2602 return params().language;
2606 docstring const Buffer::B_(string const & l10n) const
2608 return params().B_(l10n);
2612 bool Buffer::isClean() const
2614 return d->lyx_clean;
2618 bool Buffer::isExternallyModified(CheckMethod method) const
2620 LASSERT(d->filename.exists(), /**/);
2621 // if method == timestamp, check timestamp before checksum
2622 return (method == checksum_method
2623 || d->timestamp_ != d->filename.lastModified())
2624 && d->checksum_ != d->filename.checksum();
2628 void Buffer::saveCheckSum() const
2630 FileName const & file = d->filename;
2633 if (file.exists()) {
2634 d->timestamp_ = file.lastModified();
2635 d->checksum_ = file.checksum();
2637 // in the case of save to a new file.
2644 void Buffer::markClean() const
2646 if (!d->lyx_clean) {
2647 d->lyx_clean = true;
2650 // if the .lyx file has been saved, we don't need an
2652 d->bak_clean = true;
2653 d->undo_.markDirty();
2657 void Buffer::setUnnamed(bool flag)
2663 bool Buffer::isUnnamed() const
2670 /// Don't check unnamed, here: isInternal() is used in
2671 /// newBuffer(), where the unnamed flag has not been set by anyone
2672 /// yet. Also, for an internal buffer, there should be no need for
2673 /// retrieving fileName() nor for checking if it is unnamed or not.
2674 bool Buffer::isInternal() const
2676 return d->internal_buffer;
2680 void Buffer::setInternal(bool flag)
2682 d->internal_buffer = flag;
2686 void Buffer::markDirty()
2689 d->lyx_clean = false;
2692 d->bak_clean = false;
2694 DepClean::iterator it = d->dep_clean.begin();
2695 DepClean::const_iterator const end = d->dep_clean.end();
2697 for (; it != end; ++it)
2702 FileName Buffer::fileName() const
2708 string Buffer::absFileName() const
2710 return d->filename.absFileName();
2714 string Buffer::filePath() const
2716 return d->filename.onlyPath().absFileName() + "/";
2720 bool Buffer::isReadonly() const
2722 return d->read_only;
2726 void Buffer::setParent(Buffer const * buffer)
2728 // Avoids recursive include.
2729 d->setParent(buffer == this ? 0 : buffer);
2734 Buffer const * Buffer::parent() const
2740 ListOfBuffers Buffer::allRelatives() const
2742 ListOfBuffers lb = masterBuffer()->getDescendents();
2743 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2748 Buffer const * Buffer::masterBuffer() const
2750 // FIXME Should be make sure we are not in some kind
2751 // of recursive include? A -> B -> A will crash this.
2752 Buffer const * const pbuf = d->parent();
2756 return pbuf->masterBuffer();
2760 bool Buffer::isChild(Buffer * child) const
2762 return d->children_positions.find(child) != d->children_positions.end();
2766 DocIterator Buffer::firstChildPosition(Buffer const * child)
2768 Impl::BufferPositionMap::iterator it;
2769 it = d->children_positions.find(child);
2770 if (it == d->children_positions.end())
2771 return DocIterator(this);
2776 bool Buffer::hasChildren() const
2778 return !d->children_positions.empty();
2782 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2784 // loop over children
2785 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2786 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2787 for (; it != end; ++it) {
2788 Buffer * child = const_cast<Buffer *>(it->first);
2790 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2791 if (bit != clist.end())
2793 clist.push_back(child);
2795 // there might be grandchildren
2796 child->collectChildren(clist, true);
2801 ListOfBuffers Buffer::getChildren() const
2804 collectChildren(v, false);
2805 // Make sure we have not included ourselves.
2806 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2807 if (bit != v.end()) {
2808 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2815 ListOfBuffers Buffer::getDescendents() const
2818 collectChildren(v, true);
2819 // Make sure we have not included ourselves.
2820 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2821 if (bit != v.end()) {
2822 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2829 template<typename M>
2830 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2835 typename M::const_iterator it = m.lower_bound(x);
2836 if (it == m.begin())
2844 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2845 DocIterator const & pos) const
2847 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2849 // if paragraphs have no macro context set, pos will be empty
2853 // we haven't found anything yet
2854 DocIterator bestPos = owner_->par_iterator_begin();
2855 MacroData const * bestData = 0;
2857 // find macro definitions for name
2858 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2859 if (nameIt != macros.end()) {
2860 // find last definition in front of pos or at pos itself
2861 PositionScopeMacroMap::const_iterator it
2862 = greatest_below(nameIt->second, pos);
2863 if (it != nameIt->second.end()) {
2865 // scope ends behind pos?
2866 if (pos < it->second.first) {
2867 // Looks good, remember this. If there
2868 // is no external macro behind this,
2869 // we found the right one already.
2870 bestPos = it->first;
2871 bestData = &it->second.second;
2875 // try previous macro if there is one
2876 if (it == nameIt->second.begin())
2883 // find macros in included files
2884 PositionScopeBufferMap::const_iterator it
2885 = greatest_below(position_to_children, pos);
2886 if (it == position_to_children.end())
2887 // no children before
2891 // do we know something better (i.e. later) already?
2892 if (it->first < bestPos )
2895 // scope ends behind pos?
2896 if (pos < it->second.first
2897 && (cloned_buffer_ ||
2898 theBufferList().isLoaded(it->second.second))) {
2899 // look for macro in external file
2901 MacroData const * data
2902 = it->second.second->getMacro(name, false);
2905 bestPos = it->first;
2911 // try previous file if there is one
2912 if (it == position_to_children.begin())
2917 // return the best macro we have found
2922 MacroData const * Buffer::getMacro(docstring const & name,
2923 DocIterator const & pos, bool global) const
2928 // query buffer macros
2929 MacroData const * data = d->getBufferMacro(name, pos);
2933 // If there is a master buffer, query that
2934 Buffer const * const pbuf = d->parent();
2936 d->macro_lock = true;
2937 MacroData const * macro = pbuf->getMacro(
2938 name, *this, false);
2939 d->macro_lock = false;
2945 data = MacroTable::globalMacros().get(name);
2954 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2956 // set scope end behind the last paragraph
2957 DocIterator scope = par_iterator_begin();
2958 scope.pit() = scope.lastpit() + 1;
2960 return getMacro(name, scope, global);
2964 MacroData const * Buffer::getMacro(docstring const & name,
2965 Buffer const & child, bool global) const
2967 // look where the child buffer is included first
2968 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2969 if (it == d->children_positions.end())
2972 // check for macros at the inclusion position
2973 return getMacro(name, it->second, global);
2977 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2979 pit_type const lastpit = it.lastpit();
2981 // look for macros in each paragraph
2982 while (it.pit() <= lastpit) {
2983 Paragraph & par = it.paragraph();
2985 // iterate over the insets of the current paragraph
2986 InsetList const & insets = par.insetList();
2987 InsetList::const_iterator iit = insets.begin();
2988 InsetList::const_iterator end = insets.end();
2989 for (; iit != end; ++iit) {
2990 it.pos() = iit->pos;
2992 // is it a nested text inset?
2993 if (iit->inset->asInsetText()) {
2994 // Inset needs its own scope?
2995 InsetText const * itext = iit->inset->asInsetText();
2996 bool newScope = itext->isMacroScope();
2998 // scope which ends just behind the inset
2999 DocIterator insetScope = it;
3002 // collect macros in inset
3003 it.push_back(CursorSlice(*iit->inset));
3004 updateMacros(it, newScope ? insetScope : scope);
3009 if (iit->inset->asInsetTabular()) {
3010 CursorSlice slice(*iit->inset);
3011 size_t const numcells = slice.nargs();
3012 for (; slice.idx() < numcells; slice.forwardIdx()) {
3013 it.push_back(slice);
3014 updateMacros(it, scope);
3020 // is it an external file?
3021 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3022 // get buffer of external file
3023 InsetInclude const & inset =
3024 static_cast<InsetInclude const &>(*iit->inset);
3026 Buffer * child = inset.getChildBuffer();
3031 // register its position, but only when it is
3032 // included first in the buffer
3033 if (children_positions.find(child) ==
3034 children_positions.end())
3035 children_positions[child] = it;
3037 // register child with its scope
3038 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3042 InsetMath * im = iit->inset->asInsetMath();
3043 if (doing_export && im) {
3044 InsetMathHull * hull = im->asHullInset();
3046 hull->recordLocation(it);
3049 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3053 MathMacroTemplate & macroTemplate =
3054 *iit->inset->asInsetMath()->asMacroTemplate();
3055 MacroContext mc(owner_, it);
3056 macroTemplate.updateToContext(mc);
3059 bool valid = macroTemplate.validMacro();
3060 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3061 // then the BufferView's cursor will be invalid in
3062 // some cases which leads to crashes.
3067 // FIXME (Abdel), I don't understandt why we pass 'it' here
3068 // instead of 'macroTemplate' defined above... is this correct?
3069 macros[macroTemplate.name()][it] =
3070 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3080 void Buffer::updateMacros() const
3085 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3087 // start with empty table
3089 d->children_positions.clear();
3090 d->position_to_children.clear();
3092 // Iterate over buffer, starting with first paragraph
3093 // The scope must be bigger than any lookup DocIterator
3094 // later. For the global lookup, lastpit+1 is used, hence
3095 // we use lastpit+2 here.
3096 DocIterator it = par_iterator_begin();
3097 DocIterator outerScope = it;
3098 outerScope.pit() = outerScope.lastpit() + 2;
3099 d->updateMacros(it, outerScope);
3103 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3105 InsetIterator it = inset_iterator_begin(inset());
3106 InsetIterator const end = inset_iterator_end(inset());
3107 for (; it != end; ++it) {
3108 if (it->lyxCode() == BRANCH_CODE) {
3109 InsetBranch & br = static_cast<InsetBranch &>(*it);
3110 docstring const name = br.branch();
3111 if (!from_master && !params().branchlist().find(name))
3112 result.push_back(name);
3113 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3114 result.push_back(name);
3117 if (it->lyxCode() == INCLUDE_CODE) {
3118 // get buffer of external file
3119 InsetInclude const & ins =
3120 static_cast<InsetInclude const &>(*it);
3121 Buffer * child = ins.getChildBuffer();
3124 child->getUsedBranches(result, true);
3127 // remove duplicates
3132 void Buffer::updateMacroInstances(UpdateType utype) const
3134 LYXERR(Debug::MACROS, "updateMacroInstances for "
3135 << d->filename.onlyFileName());
3136 DocIterator it = doc_iterator_begin(this);
3138 DocIterator const end = doc_iterator_end(this);
3139 for (; it != end; it.forwardInset()) {
3140 // look for MathData cells in InsetMathNest insets
3141 InsetMath * minset = it.nextInset()->asInsetMath();
3145 // update macro in all cells of the InsetMathNest
3146 DocIterator::idx_type n = minset->nargs();
3147 MacroContext mc = MacroContext(this, it);
3148 for (DocIterator::idx_type i = 0; i < n; ++i) {
3149 MathData & data = minset->cell(i);
3150 data.updateMacros(0, mc, utype);
3156 void Buffer::listMacroNames(MacroNameSet & macros) const
3161 d->macro_lock = true;
3163 // loop over macro names
3164 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3165 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3166 for (; nameIt != nameEnd; ++nameIt)
3167 macros.insert(nameIt->first);
3169 // loop over children
3170 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3171 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3172 for (; it != end; ++it)
3173 it->first->listMacroNames(macros);
3176 Buffer const * const pbuf = d->parent();
3178 pbuf->listMacroNames(macros);
3180 d->macro_lock = false;
3184 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3186 Buffer const * const pbuf = d->parent();
3191 pbuf->listMacroNames(names);
3194 MacroNameSet::iterator it = names.begin();
3195 MacroNameSet::iterator end = names.end();
3196 for (; it != end; ++it) {
3198 MacroData const * data =
3199 pbuf->getMacro(*it, *this, false);
3201 macros.insert(data);
3203 // we cannot access the original MathMacroTemplate anymore
3204 // here to calls validate method. So we do its work here manually.
3205 // FIXME: somehow make the template accessible here.
3206 if (data->optionals() > 0)
3207 features.require("xargs");
3213 Buffer::References & Buffer::references(docstring const & label)
3216 return const_cast<Buffer *>(masterBuffer())->references(label);
3218 RefCache::iterator it = d->ref_cache_.find(label);
3219 if (it != d->ref_cache_.end())
3220 return it->second.second;
3222 static InsetLabel const * dummy_il = 0;
3223 static References const dummy_refs;
3224 it = d->ref_cache_.insert(
3225 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3226 return it->second.second;
3230 Buffer::References const & Buffer::references(docstring const & label) const
3232 return const_cast<Buffer *>(this)->references(label);
3236 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3238 masterBuffer()->d->ref_cache_[label].first = il;
3242 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3244 return masterBuffer()->d->ref_cache_[label].first;
3248 void Buffer::clearReferenceCache() const
3251 d->ref_cache_.clear();
3255 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3258 //FIXME: This does not work for child documents yet.
3259 LASSERT(code == CITE_CODE, /**/);
3261 reloadBibInfoCache();
3263 // Check if the label 'from' appears more than once
3264 BiblioInfo const & keys = masterBibInfo();
3265 BiblioInfo::const_iterator bit = keys.begin();
3266 BiblioInfo::const_iterator bend = keys.end();
3267 vector<docstring> labels;
3269 for (; bit != bend; ++bit)
3271 labels.push_back(bit->first);
3273 if (count(labels.begin(), labels.end(), from) > 1)
3276 string const paramName = "key";
3277 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3278 if (it->lyxCode() == code) {
3279 InsetCommand * inset = it->asInsetCommand();
3282 docstring const oldValue = inset->getParam(paramName);
3283 if (oldValue == from)
3284 inset->setParam(paramName, to);
3290 void Buffer::getSourceCode(odocstream & os, string const format,
3291 pit_type par_begin, pit_type par_end,
3292 OutputWhat output) const
3294 OutputParams runparams(¶ms().encoding());
3295 runparams.nice = true;
3296 runparams.flavor = params().getOutputFlavor(format);
3297 runparams.linelen = lyxrc.plaintext_linelen;
3298 // No side effect of file copying and image conversion
3299 runparams.dryrun = true;
3301 if (output == CurrentParagraph) {
3302 runparams.par_begin = par_begin;
3303 runparams.par_end = par_end;
3304 if (par_begin + 1 == par_end) {
3306 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3310 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3311 convert<docstring>(par_begin),
3312 convert<docstring>(par_end - 1))
3319 // output paragraphs
3320 if (runparams.flavor == OutputParams::HTML) {
3322 setMathFlavor(runparams);
3323 xhtmlParagraphs(text(), *this, xs, runparams);
3324 } else if (runparams.flavor == OutputParams::TEXT) {
3326 // FIXME Handles only one paragraph, unlike the others.
3327 // Probably should have some routine with a signature like them.
3328 writePlaintextParagraph(*this,
3329 text().paragraphs()[par_begin], os, runparams, dummy);
3330 } else if (params().isDocBook()) {
3331 docbookParagraphs(text(), *this, os, runparams);
3333 // latex or literate
3334 otexstream ots(os, texrow);
3335 latexParagraphs(*this, text(), ots, runparams);
3339 if (output == FullSource)
3340 os << _("Preview source code");
3341 else if (output == OnlyPreamble)
3342 os << _("Preview preamble");
3343 else if (output == OnlyBody)
3344 os << _("Preview body");
3347 d->texrow.newline();
3348 d->texrow.newline();
3349 if (runparams.flavor == OutputParams::HTML) {
3350 writeLyXHTMLSource(os, runparams, output);
3351 } else if (runparams.flavor == OutputParams::TEXT) {
3352 if (output == OnlyPreamble) {
3353 os << _("% Plaintext does not have a preamble.");
3355 writePlaintextFile(*this, os, runparams);
3356 } else if (params().isDocBook()) {
3357 writeDocBookSource(os, absFileName(), runparams, output);
3359 // latex or literate
3360 otexstream ots(os, d->texrow);
3361 writeLaTeXSource(ots, string(), runparams, output);
3367 ErrorList & Buffer::errorList(string const & type) const
3369 return d->errorLists[type];
3373 void Buffer::updateTocItem(std::string const & type,
3374 DocIterator const & dit) const
3377 d->gui_->updateTocItem(type, dit);
3381 void Buffer::structureChanged() const
3384 d->gui_->structureChanged();
3388 void Buffer::errors(string const & err, bool from_master) const
3391 d->gui_->errors(err, from_master);
3395 void Buffer::message(docstring const & msg) const
3398 d->gui_->message(msg);
3402 void Buffer::setBusy(bool on) const
3405 d->gui_->setBusy(on);
3409 void Buffer::updateTitles() const
3412 d->wa_->updateTitles();
3416 void Buffer::resetAutosaveTimers() const
3419 d->gui_->resetAutosaveTimers();
3423 bool Buffer::hasGuiDelegate() const
3429 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3438 class AutoSaveBuffer : public ForkedProcess {
3441 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3442 : buffer_(buffer), fname_(fname) {}
3444 virtual shared_ptr<ForkedProcess> clone() const
3446 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3451 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3452 from_utf8(fname_.absFileName())));
3453 return run(DontWait);
3457 virtual int generateChild();
3459 Buffer const & buffer_;
3464 int AutoSaveBuffer::generateChild()
3466 #if defined(__APPLE__)
3467 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3468 * We should use something else like threads.
3470 * Since I do not know how to determine at run time what is the OS X
3471 * version, I just disable forking altogether for now (JMarc)
3473 pid_t const pid = -1;
3475 // tmp_ret will be located (usually) in /tmp
3476 // will that be a problem?
3477 // Note that this calls ForkedCalls::fork(), so it's
3478 // ok cross-platform.
3479 pid_t const pid = fork();
3480 // If you want to debug the autosave
3481 // you should set pid to -1, and comment out the fork.
3482 if (pid != 0 && pid != -1)
3486 // pid = -1 signifies that lyx was unable
3487 // to fork. But we will do the save
3489 bool failed = false;
3490 FileName const tmp_ret = FileName::tempName("lyxauto");
3491 if (!tmp_ret.empty()) {
3492 buffer_.writeFile(tmp_ret);
3493 // assume successful write of tmp_ret
3494 if (!tmp_ret.moveTo(fname_))
3500 // failed to write/rename tmp_ret so try writing direct
3501 if (!buffer_.writeFile(fname_)) {
3502 // It is dangerous to do this in the child,
3503 // but safe in the parent, so...
3504 if (pid == -1) // emit message signal.
3505 buffer_.message(_("Autosave failed!"));
3509 if (pid == 0) // we are the child so...
3518 FileName Buffer::getEmergencyFileName() const
3520 return FileName(d->filename.absFileName() + ".emergency");
3524 FileName Buffer::getAutosaveFileName() const
3526 // if the document is unnamed try to save in the backup dir, else
3527 // in the default document path, and as a last try in the filePath,
3528 // which will most often be the temporary directory
3531 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3532 : lyxrc.backupdir_path;
3533 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3536 string const fname = "#" + d->filename.onlyFileName() + "#";
3538 return makeAbsPath(fname, fpath);
3542 void Buffer::removeAutosaveFile() const
3544 FileName const f = getAutosaveFileName();
3550 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3552 FileName const newauto = getAutosaveFileName();
3554 if (newauto != oldauto && oldauto.exists())
3555 if (!oldauto.moveTo(newauto))
3556 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3560 bool Buffer::autoSave() const
3562 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3563 if (buf->d->bak_clean || isReadonly())
3566 message(_("Autosaving current document..."));
3567 buf->d->bak_clean = true;
3569 FileName const fname = getAutosaveFileName();
3570 if (d->cloned_buffer_) {
3571 // If this buffer is cloned, we assume that
3572 // we are running in a separate thread already.
3573 FileName const tmp_ret = FileName::tempName("lyxauto");
3574 if (!tmp_ret.empty()) {
3576 // assume successful write of tmp_ret
3577 if (tmp_ret.moveTo(fname))
3580 // failed to write/rename tmp_ret so try writing direct
3581 return writeFile(fname);
3583 /// This function is deprecated as the frontend needs to take care
3584 /// of cloning the buffer and autosaving it in another thread. It
3585 /// is still here to allow (QT_VERSION < 0x040400).
3586 AutoSaveBuffer autosave(*this, fname);
3593 // helper class, to guarantee this gets reset properly
3594 class Buffer::MarkAsExporting {
3596 MarkAsExporting(Buffer const * buf) : buf_(buf)
3598 LASSERT(buf_, /* */);
3599 buf_->setExportStatus(true);
3603 buf_->setExportStatus(false);
3606 Buffer const * const buf_;
3611 void Buffer::setExportStatus(bool e) const
3613 d->doing_export = e;
3614 ListOfBuffers clist = getDescendents();
3615 ListOfBuffers::const_iterator cit = clist.begin();
3616 ListOfBuffers::const_iterator const cen = clist.end();
3617 for (; cit != cen; ++cit)
3618 (*cit)->d->doing_export = e;
3622 bool Buffer::isExporting() const
3624 return d->doing_export;
3628 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3632 return doExport(target, put_in_tempdir, result_file);
3635 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3636 string & result_file) const
3638 bool const update_unincluded =
3639 params().maintain_unincluded_children
3640 && !params().getIncludedChildren().empty();
3642 // (1) export with all included children (omit \includeonly)
3643 if (update_unincluded) {
3644 ExportStatus const status =
3645 doExport(target, put_in_tempdir, true, result_file);
3646 if (status != ExportSuccess)
3649 // (2) export with included children only
3650 return doExport(target, put_in_tempdir, false, result_file);
3654 void Buffer::setMathFlavor(OutputParams & op) const
3656 switch (params().html_math_output) {
3657 case BufferParams::MathML:
3658 op.math_flavor = OutputParams::MathAsMathML;
3660 case BufferParams::HTML:
3661 op.math_flavor = OutputParams::MathAsHTML;
3663 case BufferParams::Images:
3664 op.math_flavor = OutputParams::MathAsImages;
3666 case BufferParams::LaTeX:
3667 op.math_flavor = OutputParams::MathAsLaTeX;
3673 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3674 bool includeall, string & result_file) const
3676 LYXERR(Debug::FILES, "target=" << target);
3677 OutputParams runparams(¶ms().encoding());
3678 string format = target;
3679 string dest_filename;
3680 size_t pos = target.find(' ');
3681 if (pos != string::npos) {
3682 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3683 format = target.substr(0, pos);
3684 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3685 FileName(dest_filename).onlyPath().createPath();
3686 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3688 MarkAsExporting exporting(this);
3689 string backend_format;
3690 runparams.flavor = OutputParams::LATEX;
3691 runparams.linelen = lyxrc.plaintext_linelen;
3692 runparams.includeall = includeall;
3693 vector<string> backs = params().backends();
3694 Converters converters = theConverters();
3695 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3696 // Get shortest path to format
3697 converters.buildGraph();
3698 Graph::EdgePath path;
3699 for (vector<string>::const_iterator it = backs.begin();
3700 it != backs.end(); ++it) {
3701 Graph::EdgePath p = converters.getPath(*it, format);
3702 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3703 backend_format = *it;
3708 if (!put_in_tempdir) {
3709 // Only show this alert if this is an export to a non-temporary
3710 // file (not for previewing).
3711 Alert::error(_("Couldn't export file"), bformat(
3712 _("No information for exporting the format %1$s."),
3713 formats.prettyName(format)));
3715 return ExportNoPathToFormat;
3717 runparams.flavor = converters.getFlavor(path, this);
3720 backend_format = format;
3721 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3722 // FIXME: Don't hardcode format names here, but use a flag
3723 if (backend_format == "pdflatex")
3724 runparams.flavor = OutputParams::PDFLATEX;
3725 else if (backend_format == "luatex")
3726 runparams.flavor = OutputParams::LUATEX;
3727 else if (backend_format == "dviluatex")
3728 runparams.flavor = OutputParams::DVILUATEX;
3729 else if (backend_format == "xetex")
3730 runparams.flavor = OutputParams::XETEX;
3733 string filename = latexName(false);
3734 filename = addName(temppath(), filename);
3735 filename = changeExtension(filename,
3736 formats.extension(backend_format));
3737 LYXERR(Debug::FILES, "filename=" << filename);
3739 // Plain text backend
3740 if (backend_format == "text") {
3741 runparams.flavor = OutputParams::TEXT;
3742 writePlaintextFile(*this, FileName(filename), runparams);
3745 else if (backend_format == "xhtml") {
3746 runparams.flavor = OutputParams::HTML;
3747 setMathFlavor(runparams);
3748 makeLyXHTMLFile(FileName(filename), runparams);
3749 } else if (backend_format == "lyx")
3750 writeFile(FileName(filename));
3752 else if (params().isDocBook()) {
3753 runparams.nice = !put_in_tempdir;
3754 makeDocBookFile(FileName(filename), runparams);
3757 else if (backend_format == format) {
3758 runparams.nice = true;
3759 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3760 if (d->cloned_buffer_)
3761 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3764 } else if (!lyxrc.tex_allows_spaces
3765 && contains(filePath(), ' ')) {
3766 Alert::error(_("File name error"),
3767 _("The directory path to the document cannot contain spaces."));
3768 return ExportTexPathHasSpaces;
3770 runparams.nice = false;
3771 bool const success = makeLaTeXFile(
3772 FileName(filename), filePath(), runparams);
3773 if (d->cloned_buffer_)
3774 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3779 string const error_type = (format == "program")
3780 ? "Build" : params().bufferFormat();
3781 ErrorList & error_list = d->errorLists[error_type];
3782 string const ext = formats.extension(format);
3783 FileName const tmp_result_file(changeExtension(filename, ext));
3784 bool const success = converters.convert(this, FileName(filename),
3785 tmp_result_file, FileName(absFileName()), backend_format, format,
3788 // Emit the signal to show the error list or copy it back to the
3789 // cloned Buffer so that it can be emitted afterwards.
3790 if (format != backend_format) {
3791 if (d->cloned_buffer_) {
3792 d->cloned_buffer_->d->errorLists[error_type] =
3793 d->errorLists[error_type];
3796 // also to the children, in case of master-buffer-view
3797 ListOfBuffers clist = getDescendents();
3798 ListOfBuffers::const_iterator cit = clist.begin();
3799 ListOfBuffers::const_iterator const cen = clist.end();
3800 for (; cit != cen; ++cit) {
3801 if (d->cloned_buffer_) {
3802 // Enable reverse search by copying back the
3803 // texrow object to the cloned buffer.
3804 // FIXME: this is not thread safe.
3805 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3806 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3807 (*cit)->d->errorLists[error_type];
3809 (*cit)->errors(error_type, true);
3813 if (d->cloned_buffer_) {
3814 // Enable reverse dvi or pdf to work by copying back the texrow
3815 // object to the cloned buffer.
3816 // FIXME: There is a possibility of concurrent access to texrow
3817 // here from the main GUI thread that should be securized.
3818 d->cloned_buffer_->d->texrow = d->texrow;
3819 string const error_type = params().bufferFormat();
3820 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3824 return ExportConverterError;
3826 if (put_in_tempdir) {
3827 result_file = tmp_result_file.absFileName();
3828 return ExportSuccess;
3831 if (dest_filename.empty())
3832 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3834 result_file = dest_filename;
3835 // We need to copy referenced files (e. g. included graphics
3836 // if format == "dvi") to the result dir.
3837 vector<ExportedFile> const files =
3838 runparams.exportdata->externalFiles(format);
3839 string const dest = runparams.export_folder.empty() ?
3840 onlyPath(result_file) : runparams.export_folder;
3841 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3842 : force_overwrite == ALL_FILES;
3843 CopyStatus status = use_force ? FORCE : SUCCESS;
3845 vector<ExportedFile>::const_iterator it = files.begin();
3846 vector<ExportedFile>::const_iterator const en = files.end();
3847 for (; it != en && status != CANCEL; ++it) {
3848 string const fmt = formats.getFormatFromFile(it->sourceName);
3849 string fixedName = it->exportName;
3850 if (!runparams.export_folder.empty()) {
3851 // Relative pathnames starting with ../ will be sanitized
3852 // if exporting to a different folder
3853 while (fixedName.substr(0, 3) == "../")
3854 fixedName = fixedName.substr(3, fixedName.length() - 3);
3856 FileName fixedFileName = makeAbsPath(fixedName, dest);
3857 fixedFileName.onlyPath().createPath();
3858 status = copyFile(fmt, it->sourceName,
3860 it->exportName, status == FORCE,
3861 runparams.export_folder.empty());
3864 if (status == CANCEL) {
3865 message(_("Document export cancelled."));
3866 return ExportCancel;
3869 if (tmp_result_file.exists()) {
3870 // Finally copy the main file
3871 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3872 : force_overwrite != NO_FILES;
3873 if (status == SUCCESS && use_force)
3875 status = copyFile(format, tmp_result_file,
3876 FileName(result_file), result_file,
3878 if (status == CANCEL) {
3879 message(_("Document export cancelled."));
3880 return ExportCancel;
3882 message(bformat(_("Document exported as %1$s "
3884 formats.prettyName(format),
3885 makeDisplayPath(result_file)));
3888 // This must be a dummy converter like fax (bug 1888)
3889 message(bformat(_("Document exported as %1$s"),
3890 formats.prettyName(format)));
3893 return ExportSuccess;
3897 Buffer::ExportStatus Buffer::preview(string const & format) const
3899 bool const update_unincluded =
3900 params().maintain_unincluded_children
3901 && !params().getIncludedChildren().empty();
3902 return preview(format, update_unincluded);
3905 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3907 MarkAsExporting exporting(this);
3909 // (1) export with all included children (omit \includeonly)
3911 ExportStatus const status = doExport(format, true, true, result_file);
3912 if (status != ExportSuccess)
3915 // (2) export with included children only
3916 ExportStatus const status = doExport(format, true, false, result_file);
3917 if (status != ExportSuccess)
3919 if (!formats.view(*this, FileName(result_file), format))
3920 return PreviewError;
3921 return PreviewSuccess;
3925 Buffer::ReadStatus Buffer::extractFromVC()
3927 bool const found = LyXVC::file_not_found_hook(d->filename);
3929 return ReadFileNotFound;
3930 if (!d->filename.isReadableFile())
3936 Buffer::ReadStatus Buffer::loadEmergency()
3938 FileName const emergencyFile = getEmergencyFileName();
3939 if (!emergencyFile.exists()
3940 || emergencyFile.lastModified() <= d->filename.lastModified())
3941 return ReadFileNotFound;
3943 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3944 docstring const text = bformat(_("An emergency save of the document "
3945 "%1$s exists.\n\nRecover emergency save?"), file);
3947 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3948 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3954 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3955 bool const success = (ret_llf == ReadSuccess);
3958 Alert::warning(_("File is read-only"),
3959 bformat(_("An emergency file is successfully loaded, "
3960 "but the original file %1$s is marked read-only. "
3961 "Please make sure to save the document as a different "
3962 "file."), from_utf8(d->filename.absFileName())));
3965 str = _("Document was successfully recovered.");
3967 str = _("Document was NOT successfully recovered.");
3968 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3969 makeDisplayPath(emergencyFile.absFileName()));
3971 int const del_emerg =
3972 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3973 _("&Remove"), _("&Keep"));
3974 if (del_emerg == 0) {
3975 emergencyFile.removeFile();
3977 Alert::warning(_("Emergency file deleted"),
3978 _("Do not forget to save your file now!"), true);
3980 return success ? ReadSuccess : ReadEmergencyFailure;
3983 int const del_emerg =
3984 Alert::prompt(_("Delete emergency file?"),
3985 _("Remove emergency file now?"), 1, 1,
3986 _("&Remove"), _("&Keep"));
3988 emergencyFile.removeFile();
3989 return ReadOriginal;
3999 Buffer::ReadStatus Buffer::loadAutosave()
4001 // Now check if autosave file is newer.
4002 FileName const autosaveFile = getAutosaveFileName();
4003 if (!autosaveFile.exists()
4004 || autosaveFile.lastModified() <= d->filename.lastModified())
4005 return ReadFileNotFound;
4007 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4008 docstring const text = bformat(_("The backup of the document %1$s "
4009 "is newer.\n\nLoad the backup instead?"), file);
4010 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4011 _("&Load backup"), _("Load &original"), _("&Cancel"));
4016 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4017 // the file is not saved if we load the autosave file.
4018 if (ret_llf == ReadSuccess) {
4020 Alert::warning(_("File is read-only"),
4021 bformat(_("A backup file is successfully loaded, "
4022 "but the original file %1$s is marked read-only. "
4023 "Please make sure to save the document as a "
4025 from_utf8(d->filename.absFileName())));
4030 return ReadAutosaveFailure;
4033 // Here we delete the autosave
4034 autosaveFile.removeFile();
4035 return ReadOriginal;
4043 Buffer::ReadStatus Buffer::loadLyXFile()
4045 if (!d->filename.isReadableFile()) {
4046 ReadStatus const ret_rvc = extractFromVC();
4047 if (ret_rvc != ReadSuccess)
4051 ReadStatus const ret_re = loadEmergency();
4052 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4055 ReadStatus const ret_ra = loadAutosave();
4056 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4059 return loadThisLyXFile(d->filename);
4063 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4065 return readFile(fn);
4069 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4071 TeXErrors::Errors::const_iterator it = terr.begin();
4072 TeXErrors::Errors::const_iterator end = terr.end();
4073 ListOfBuffers clist = getDescendents();
4074 ListOfBuffers::const_iterator cen = clist.end();
4076 for (; it != end; ++it) {
4079 int errorRow = it->error_in_line;
4080 Buffer const * buf = 0;
4082 if (it->child_name.empty())
4083 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4085 // The error occurred in a child
4086 ListOfBuffers::const_iterator cit = clist.begin();
4087 for (; cit != cen; ++cit) {
4088 string const child_name =
4089 DocFileName(changeExtension(
4090 (*cit)->absFileName(), "tex")).
4092 if (it->child_name != child_name)
4094 (*cit)->d->texrow.getIdFromRow(errorRow,
4095 id_start, pos_start);
4096 if (id_start != -1) {
4097 buf = d->cloned_buffer_
4098 ? (*cit)->d->cloned_buffer_->d->owner_
4099 : (*cit)->d->owner_;
4110 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4111 } while (found && id_start == id_end && pos_start == pos_end);
4113 if (id_start != id_end) {
4114 // Next registered position is outside the inset where
4115 // the error occurred, so signal end-of-paragraph
4119 errorList.push_back(ErrorItem(it->error_desc,
4120 it->error_text, id_start, pos_start, pos_end, buf));
4125 void Buffer::setBuffersForInsets() const
4127 inset().setBuffer(const_cast<Buffer &>(*this));
4131 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4133 // Use the master text class also for child documents
4134 Buffer const * const master = masterBuffer();
4135 DocumentClass const & textclass = master->params().documentClass();
4137 // do this only if we are the top-level Buffer
4139 reloadBibInfoCache();
4141 // keep the buffers to be children in this set. If the call from the
4142 // master comes back we can see which of them were actually seen (i.e.
4143 // via an InsetInclude). The remaining ones in the set need still be updated.
4144 static std::set<Buffer const *> bufToUpdate;
4145 if (scope == UpdateMaster) {
4146 // If this is a child document start with the master
4147 if (master != this) {
4148 bufToUpdate.insert(this);
4149 master->updateBuffer(UpdateMaster, utype);
4150 // Do this here in case the master has no gui associated with it. Then,
4151 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4152 if (!master->d->gui_)
4155 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4156 if (bufToUpdate.find(this) == bufToUpdate.end())
4160 // start over the counters in the master
4161 textclass.counters().reset();
4164 // update will be done below for this buffer
4165 bufToUpdate.erase(this);
4167 // update all caches
4168 clearReferenceCache();
4171 Buffer & cbuf = const_cast<Buffer &>(*this);
4173 LASSERT(!text().paragraphs().empty(), /**/);
4176 ParIterator parit = cbuf.par_iterator_begin();
4177 updateBuffer(parit, utype);
4180 // TocBackend update will be done later.
4183 d->bibinfo_cache_valid_ = true;
4184 d->cite_labels_valid_ = true;
4185 cbuf.tocBackend().update();
4186 if (scope == UpdateMaster)
4187 cbuf.structureChanged();
4191 static depth_type getDepth(DocIterator const & it)
4193 depth_type depth = 0;
4194 for (size_t i = 0 ; i < it.depth() ; ++i)
4195 if (!it[i].inset().inMathed())
4196 depth += it[i].paragraph().getDepth() + 1;
4197 // remove 1 since the outer inset does not count
4201 static depth_type getItemDepth(ParIterator const & it)
4203 Paragraph const & par = *it;
4204 LabelType const labeltype = par.layout().labeltype;
4206 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4209 // this will hold the lowest depth encountered up to now.
4210 depth_type min_depth = getDepth(it);
4211 ParIterator prev_it = it;
4214 --prev_it.top().pit();
4216 // start of nested inset: go to outer par
4218 if (prev_it.empty()) {
4219 // start of document: nothing to do
4224 // We search for the first paragraph with same label
4225 // that is not more deeply nested.
4226 Paragraph & prev_par = *prev_it;
4227 depth_type const prev_depth = getDepth(prev_it);
4228 if (labeltype == prev_par.layout().labeltype) {
4229 if (prev_depth < min_depth)
4230 return prev_par.itemdepth + 1;
4231 if (prev_depth == min_depth)
4232 return prev_par.itemdepth;
4234 min_depth = min(min_depth, prev_depth);
4235 // small optimization: if we are at depth 0, we won't
4236 // find anything else
4237 if (prev_depth == 0)
4243 static bool needEnumCounterReset(ParIterator const & it)
4245 Paragraph const & par = *it;
4246 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4247 depth_type const cur_depth = par.getDepth();
4248 ParIterator prev_it = it;
4249 while (prev_it.pit()) {
4250 --prev_it.top().pit();
4251 Paragraph const & prev_par = *prev_it;
4252 if (prev_par.getDepth() <= cur_depth)
4253 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4255 // start of nested inset: reset
4260 // set the label of a paragraph. This includes the counters.
4261 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4263 BufferParams const & bp = owner_->masterBuffer()->params();
4264 DocumentClass const & textclass = bp.documentClass();
4265 Paragraph & par = it.paragraph();
4266 Layout const & layout = par.layout();
4267 Counters & counters = textclass.counters();
4269 if (par.params().startOfAppendix()) {
4270 // FIXME: only the counter corresponding to toplevel
4271 // sectioning should be reset
4273 counters.appendix(true);
4275 par.params().appendix(counters.appendix());
4277 // Compute the item depth of the paragraph
4278 par.itemdepth = getItemDepth(it);
4280 if (layout.margintype == MARGIN_MANUAL) {
4281 if (par.params().labelWidthString().empty())
4282 par.params().labelWidthString(par.expandLabel(layout, bp));
4283 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4284 // we do not need to do anything here, since the empty case is
4285 // handled during export.
4287 par.params().labelWidthString(docstring());
4290 switch(layout.labeltype) {
4292 if (layout.toclevel <= bp.secnumdepth
4293 && (layout.latextype != LATEX_ENVIRONMENT
4294 || it.text()->isFirstInSequence(it.pit()))) {
4295 if (counters.hasCounter(layout.counter))
4296 counters.step(layout.counter, utype);
4297 par.params().labelString(par.expandLabel(layout, bp));
4299 par.params().labelString(docstring());
4302 case LABEL_ITEMIZE: {
4303 // At some point of time we should do something more
4304 // clever here, like:
4305 // par.params().labelString(
4306 // bp.user_defined_bullet(par.itemdepth).getText());
4307 // for now, use a simple hardcoded label
4308 docstring itemlabel;
4309 switch (par.itemdepth) {
4311 itemlabel = char_type(0x2022);
4314 itemlabel = char_type(0x2013);
4317 itemlabel = char_type(0x2217);
4320 itemlabel = char_type(0x2219); // or 0x00b7
4323 par.params().labelString(itemlabel);
4327 case LABEL_ENUMERATE: {
4328 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4330 switch (par.itemdepth) {
4339 enumcounter += "iv";
4342 // not a valid enumdepth...
4346 // Maybe we have to reset the enumeration counter.
4347 if (needEnumCounterReset(it))
4348 counters.reset(enumcounter);
4349 counters.step(enumcounter, utype);
4351 string const & lang = par.getParLanguage(bp)->code();
4352 par.params().labelString(counters.theCounter(enumcounter, lang));
4357 case LABEL_SENSITIVE: {
4358 string const & type = counters.current_float();
4359 docstring full_label;
4361 full_label = owner_->B_("Senseless!!! ");
4363 docstring name = owner_->B_(textclass.floats().getType(type).name());
4364 if (counters.hasCounter(from_utf8(type))) {
4365 string const & lang = par.getParLanguage(bp)->code();
4366 counters.step(from_utf8(type), utype);
4367 full_label = bformat(from_ascii("%1$s %2$s:"),
4369 counters.theCounter(from_utf8(type), lang));
4371 full_label = bformat(from_ascii("%1$s #:"), name);
4373 par.params().labelString(full_label);
4377 case LABEL_NO_LABEL:
4378 par.params().labelString(docstring());
4382 case LABEL_TOP_ENVIRONMENT:
4383 case LABEL_CENTERED_TOP_ENVIRONMENT:
4386 par.params().labelString(par.expandLabel(layout, bp));
4392 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4394 LASSERT(parit.pit() == 0, /**/);
4396 // Set the position of the text in the buffer to be able
4397 // to resolve macros in it.
4398 parit.text()->setMacrocontextPosition(parit);
4400 depth_type maxdepth = 0;
4401 pit_type const lastpit = parit.lastpit();
4402 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4403 // reduce depth if necessary
4404 parit->params().depth(min(parit->params().depth(), maxdepth));
4405 maxdepth = parit->getMaxDepthAfter();
4407 if (utype == OutputUpdate) {
4408 // track the active counters
4409 // we have to do this for the master buffer, since the local
4410 // buffer isn't tracking anything.
4411 masterBuffer()->params().documentClass().counters().
4412 setActiveLayout(parit->layout());
4415 // set the counter for this paragraph
4416 d->setLabel(parit, utype);
4419 InsetList::const_iterator iit = parit->insetList().begin();
4420 InsetList::const_iterator end = parit->insetList().end();
4421 for (; iit != end; ++iit) {
4422 parit.pos() = iit->pos;
4423 iit->inset->updateBuffer(parit, utype);
4429 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4430 WordLangTuple & word_lang, docstring_list & suggestions) const
4434 suggestions.clear();
4435 word_lang = WordLangTuple();
4436 bool const to_end = to.empty();
4437 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4438 // OK, we start from here.
4439 for (; from != end; from.forwardPos()) {
4440 // We are only interested in text so remove the math CursorSlice.
4441 while (from.inMathed()) {
4445 // If from is at the end of the document (which is possible
4446 // when leaving the mathed) LyX will crash later otherwise.
4447 if (from.atEnd() || (!to_end && from >= end))
4450 from.paragraph().spellCheck();
4451 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4452 if (SpellChecker::misspelled(res)) {
4457 // Do not increase progress when from == to, otherwise the word
4458 // count will be wrong.
4468 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4470 bool inword = false;
4475 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4476 if (!dit.inTexted()) {
4481 Paragraph const & par = dit.paragraph();
4482 pos_type const pos = dit.pos();
4484 // Copied and adapted from isWordSeparator() in Paragraph
4485 if (pos == dit.lastpos()) {
4488 Inset const * ins = par.getInset(pos);
4489 if (ins && skipNoOutput && !ins->producesOutput()) {
4492 // stop if end of range was skipped
4493 if (!to.atEnd() && dit >= to)
4496 } else if (!par.isDeleted(pos)) {
4497 if (par.isWordSeparator(pos))
4503 if (ins && ins->isLetter())
4505 else if (ins && ins->isSpace())
4508 char_type const c = par.getChar(pos);
4509 if (isPrintableNonspace(c))
4511 else if (isSpace(c))
4521 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4523 d->updateStatistics(from, to, skipNoOutput);
4527 int Buffer::wordCount() const
4529 return d->wordCount();
4533 int Buffer::charCount(bool with_blanks) const
4535 return d->charCount(with_blanks);
4539 Buffer::ReadStatus Buffer::reload()
4542 // c.f. bug http://www.lyx.org/trac/ticket/6587
4543 removeAutosaveFile();
4544 // e.g., read-only status could have changed due to version control
4545 d->filename.refresh();
4546 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4548 // clear parent. this will get reset if need be.
4550 ReadStatus const status = loadLyXFile();
4551 if (status == ReadSuccess) {
4556 message(bformat(_("Document %1$s reloaded."), disp_fn));
4559 message(bformat(_("Could not reload document %1$s."), disp_fn));
4569 bool Buffer::saveAs(FileName const & fn)
4571 FileName const old_name = fileName();
4572 FileName const old_auto = getAutosaveFileName();
4573 bool const old_unnamed = isUnnamed();
4580 // bring the autosave file with us, just in case.
4581 moveAutosaveFile(old_auto);
4582 // validate version control data and
4583 // correct buffer title
4584 lyxvc().file_found_hook(fileName());
4586 // the file has now been saved to the new location.
4587 // we need to check that the locations of child buffers
4589 checkChildBuffers();
4593 // reset the old filename and unnamed state
4594 setFileName(old_name);
4595 setUnnamed(old_unnamed);
4601 // FIXME We could do better here, but it is complicated. What would be
4602 // nice is to offer either (a) to save the child buffer to an appropriate
4603 // location, so that it would "move with the master", or else (b) to update
4604 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4605 // complicated, because the code for this lives in GuiView.
4606 void Buffer::checkChildBuffers()
4608 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4609 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4610 for (; it != en; ++it) {
4611 DocIterator dit = it->second;
4612 Buffer * cbuf = const_cast<Buffer *>(it->first);
4613 if (!cbuf || !theBufferList().isLoaded(cbuf))
4615 Inset * inset = dit.nextInset();
4616 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4617 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4618 docstring const & incfile = inset_inc->getParam("filename");
4619 string oldloc = cbuf->absFileName();
4620 string newloc = makeAbsPath(to_utf8(incfile),
4621 onlyPath(absFileName())).absFileName();
4622 if (oldloc == newloc)
4624 // the location of the child file is incorrect.
4625 Alert::warning(_("Included File Invalid"),
4626 bformat(_("Saving this document to a new location has made the file:\n"
4628 "inaccessible. You will need to update the included filename."),
4629 from_utf8(oldloc)));
4631 inset_inc->setChildBuffer(0);
4633 // invalidate cache of children
4634 d->children_positions.clear();
4635 d->position_to_children.clear();