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/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "frontends/alert.h"
82 #include "frontends/Delegates.h"
83 #include "frontends/WorkAreaManager.h"
85 #include "graphics/Previews.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
120 using namespace lyx::support;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 // Do not remove the comment below, so we get merge conflict in
130 // independent branches. Instead add your own.
131 int const LYX_FORMAT = 404; // rgh: refstyle
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this a unnamed file (New...)?
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
208 mutable TocBackend toc_backend;
211 typedef pair<DocIterator, MacroData> ScopeMacro;
212 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
213 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
214 /// map from the macro name to the position map,
215 /// which maps the macro definition position to the scope and the MacroData.
216 NamePositionScopeMacroMap macros;
217 /// This seem to change the way Buffer::getMacro() works
218 mutable bool macro_lock;
220 /// positions of child buffers in the buffer
221 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
222 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
223 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
224 /// position of children buffers in this buffer
225 BufferPositionMap children_positions;
226 /// map from children inclusion positions to their scope and their buffer
227 PositionScopeBufferMap position_to_children;
229 /// Container for all sort of Buffer dependant errors.
230 map<string, ErrorList> errorLists;
232 /// timestamp and checksum used to test if the file has been externally
233 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
235 unsigned long checksum_;
238 frontend::WorkAreaManager * wa_;
240 frontend::GuiBufferDelegate * gui_;
245 /// A cache for the bibfiles (including bibfiles of loaded child
246 /// documents), needed for appropriate update of natbib labels.
247 mutable support::FileNameList bibfiles_cache_;
249 // FIXME The caching mechanism could be improved. At present, we have a
250 // cache for each Buffer, that caches all the bibliography info for that
251 // Buffer. A more efficient solution would be to have a global cache per
252 // file, and then to construct the Buffer's bibinfo from that.
253 /// A cache for bibliography info
254 mutable BiblioInfo bibinfo_;
255 /// whether the bibinfo cache is valid
256 mutable bool bibinfo_cache_valid_;
257 /// whether the bibfile cache is valid
258 mutable bool bibfile_cache_valid_;
259 /// Cache of timestamps of .bib files
260 map<FileName, time_t> bibfile_status_;
262 mutable RefCache ref_cache_;
264 /// our Text that should be wrapped in an InsetText
267 /// This is here to force the test to be done whenever parent_buffer
269 Buffer const * parent() const {
270 // if parent_buffer is not loaded, then it has been unloaded,
271 // which means that parent_buffer is an invalid pointer. So we
272 // set it to null in that case.
273 // however, the BufferList doesn't know about cloned buffers, so
274 // they will always be regarded as unloaded. in that case, we hope
276 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
278 return parent_buffer;
282 void setParent(Buffer const * pb) {
283 if (parent_buffer == pb)
286 if (!cloned_buffer_ && parent_buffer && pb)
287 LYXERR0("Warning: a buffer should not have two parents!");
289 if (!cloned_buffer_ && parent_buffer) {
290 parent_buffer->invalidateBibfileCache();
291 parent_buffer->invalidateBibinfoCache();
295 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
296 /// This one is useful for preview detached in a thread.
297 Buffer const * cloned_buffer_;
298 /// are we in the process of exporting this buffer?
299 mutable bool doing_export;
302 /// So we can force access via the accessors.
303 mutable Buffer const * parent_buffer;
308 /// Creates the per buffer temporary directory
309 static FileName createBufferTmpDir()
312 // We are in our own directory. Why bother to mangle name?
313 // In fact I wrote this code to circumvent a problematic behaviour
314 // (bug?) of EMX mkstemp().
315 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
316 convert<string>(count++));
318 if (!tmpfl.createDirectory(0777)) {
319 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
320 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
321 from_utf8(tmpfl.absFileName())));
327 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
328 Buffer const * cloned_buffer)
329 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
330 read_only(readonly_), filename(file), file_fully_loaded(false),
331 toc_backend(owner), macro_lock(false), timestamp_(0),
332 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
333 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
334 doing_export(false), parent_buffer(0)
336 if (!cloned_buffer_) {
337 temppath = createBufferTmpDir();
338 lyxvc.setBuffer(owner_);
340 wa_ = new frontend::WorkAreaManager;
343 temppath = cloned_buffer_->d->temppath;
344 file_fully_loaded = true;
345 params = cloned_buffer_->d->params;
346 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
347 bibinfo_ = cloned_buffer_->d->bibinfo_;
348 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
349 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
350 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
354 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
355 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
357 LYXERR(Debug::INFO, "Buffer::Buffer()");
359 d->inset = new InsetText(*cloned_buffer->d->inset);
360 d->inset->setBuffer(*this);
361 // FIXME: optimize this loop somewhat, maybe by creating a new
362 // general recursive Inset::setId().
363 DocIterator it = doc_iterator_begin(this);
364 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
365 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
366 it.paragraph().setId(cloned_it.paragraph().id());
368 d->inset = new InsetText(this);
369 d->inset->setAutoBreakRows(true);
370 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
376 LYXERR(Debug::INFO, "Buffer::~Buffer()");
377 // here the buffer should take care that it is
378 // saved properly, before it goes into the void.
380 // GuiView already destroyed
384 // No need to do additional cleanups for internal buffer.
389 // loop over children
390 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
391 Impl::BufferPositionMap::iterator end = d->children_positions.end();
392 for (; it != end; ++it) {
393 Buffer * child = const_cast<Buffer *>(it->first);
394 if (d->cloned_buffer_)
396 // The child buffer might have been closed already.
397 else if (theBufferList().isLoaded(child))
398 theBufferList().releaseChild(this, child);
402 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
403 msg += emergencyWrite();
404 Alert::warning(_("Attempting to close changed document!"), msg);
407 // clear references to children in macro tables
408 d->children_positions.clear();
409 d->position_to_children.clear();
411 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
412 Alert::warning(_("Could not remove temporary directory"),
413 bformat(_("Could not remove the temporary directory %1$s"),
414 from_utf8(d->temppath.absFileName())));
417 // Remove any previewed LaTeX snippets associated with this buffer.
419 thePreviews().removeLoader(*this);
425 Buffer * Buffer::clone() const
427 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
428 buffer_clone->d->macro_lock = true;
429 buffer_clone->d->children_positions.clear();
430 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
431 // math macro caches need to be rethought and simplified.
432 // I am not sure wether we should handle Buffer cloning here or in BufferList.
433 // Right now BufferList knows nothing about buffer clones.
434 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
435 Impl::BufferPositionMap::iterator end = d->children_positions.end();
436 for (; it != end; ++it) {
437 DocIterator dit = it->second.clone(buffer_clone);
438 dit.setBuffer(buffer_clone);
439 Buffer * child = const_cast<Buffer *>(it->first);
440 Buffer * child_clone = child->clone();
441 Inset * inset = dit.nextInset();
442 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
443 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
444 inset_inc->setChildBuffer(child_clone);
445 child_clone->d->setParent(buffer_clone);
446 buffer_clone->setChild(dit, child_clone);
448 buffer_clone->d->macro_lock = false;
453 bool Buffer::isClone() const
455 return d->cloned_buffer_;
459 void Buffer::changed(bool update_metrics) const
462 d->wa_->redrawAll(update_metrics);
466 frontend::WorkAreaManager & Buffer::workAreaManager() const
468 LASSERT(d->wa_, /**/);
473 Text & Buffer::text() const
475 return d->inset->text();
479 Inset & Buffer::inset() const
485 BufferParams & Buffer::params()
491 BufferParams const & Buffer::params() const
497 ParagraphList & Buffer::paragraphs()
499 return text().paragraphs();
503 ParagraphList const & Buffer::paragraphs() const
505 return text().paragraphs();
509 LyXVC & Buffer::lyxvc()
515 LyXVC const & Buffer::lyxvc() const
521 string const Buffer::temppath() const
523 return d->temppath.absFileName();
527 TexRow & Buffer::texrow()
533 TexRow const & Buffer::texrow() const
539 TocBackend & Buffer::tocBackend() const
541 return d->toc_backend;
545 Undo & Buffer::undo()
551 void Buffer::setChild(DocIterator const & dit, Buffer * child)
553 d->children_positions[child] = dit;
557 string Buffer::latexName(bool const no_path) const
559 FileName latex_name =
560 makeLatexName(d->exportFileName());
561 return no_path ? latex_name.onlyFileName()
562 : latex_name.absFileName();
566 FileName Buffer::Impl::exportFileName() const
568 docstring const branch_suffix =
569 params.branchlist().getFileNameSuffix();
570 if (branch_suffix.empty())
573 string const name = filename.onlyFileNameWithoutExt()
574 + to_utf8(branch_suffix);
575 FileName res(filename.onlyPath().absFileName() + "/" + name);
576 res.changeExtension(filename.extension());
582 string Buffer::logName(LogType * type) const
584 string const filename = latexName(false);
586 if (filename.empty()) {
592 string const path = temppath();
594 FileName const fname(addName(temppath(),
595 onlyFileName(changeExtension(filename,
598 // FIXME: how do we know this is the name of the build log?
599 FileName const bname(
600 addName(path, onlyFileName(
601 changeExtension(filename,
602 formats.extension(bufferFormat()) + ".out"))));
604 // Also consider the master buffer log file
605 FileName masterfname = fname;
607 if (masterBuffer() != this) {
608 string const mlogfile = masterBuffer()->logName(&mtype);
609 masterfname = FileName(mlogfile);
612 // If no Latex log or Build log is newer, show Build log
613 if (bname.exists() &&
614 ((!fname.exists() && !masterfname.exists())
615 || (fname.lastModified() < bname.lastModified()
616 && masterfname.lastModified() < bname.lastModified()))) {
617 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
620 return bname.absFileName();
621 // If we have a newer master file log or only a master log, show this
622 } else if (fname != masterfname
623 && (!fname.exists() && (masterfname.exists()
624 || fname.lastModified() < masterfname.lastModified()))) {
625 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
628 return masterfname.absFileName();
630 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
633 return fname.absFileName();
637 void Buffer::setReadonly(bool const flag)
639 if (d->read_only != flag) {
646 void Buffer::setFileName(string const & newfile)
648 d->filename = makeAbsPath(newfile);
649 setReadonly(d->filename.isReadOnly());
654 int Buffer::readHeader(Lexer & lex)
656 int unknown_tokens = 0;
658 int begin_header_line = -1;
660 // Initialize parameters that may be/go lacking in header:
661 params().branchlist().clear();
662 params().preamble.erase();
663 params().options.erase();
664 params().master.erase();
665 params().float_placement.erase();
666 params().paperwidth.erase();
667 params().paperheight.erase();
668 params().leftmargin.erase();
669 params().rightmargin.erase();
670 params().topmargin.erase();
671 params().bottommargin.erase();
672 params().headheight.erase();
673 params().headsep.erase();
674 params().footskip.erase();
675 params().columnsep.erase();
676 params().fontsCJK.erase();
677 params().listings_params.clear();
678 params().clearLayoutModules();
679 params().clearRemovedModules();
680 params().clearIncludedChildren();
681 params().pdfoptions().clear();
682 params().indiceslist().clear();
683 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
684 params().isbackgroundcolor = false;
685 params().fontcolor = lyx::rgbFromHexName("#000000");
686 params().isfontcolor = false;
687 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
688 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
689 params().html_latex_start.clear();
690 params().html_latex_end.clear();
691 params().html_math_img_scale = 1.0;
692 params().output_sync_macro.erase();
694 for (int i = 0; i < 4; ++i) {
695 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
696 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
699 ErrorList & errorList = d->errorLists["Parse"];
708 if (token == "\\end_header")
712 if (token == "\\begin_header") {
713 begin_header_line = line;
717 LYXERR(Debug::PARSER, "Handling document header token: `"
720 string unknown = params().readToken(lex, token, d->filename.onlyPath());
721 if (!unknown.empty()) {
722 if (unknown[0] != '\\' && token == "\\textclass") {
723 Alert::warning(_("Unknown document class"),
724 bformat(_("Using the default document class, because the "
725 "class %1$s is unknown."), from_utf8(unknown)));
728 docstring const s = bformat(_("Unknown token: "
732 errorList.push_back(ErrorItem(_("Document header error"),
737 if (begin_header_line) {
738 docstring const s = _("\\begin_header is missing");
739 errorList.push_back(ErrorItem(_("Document header error"),
743 params().makeDocumentClass();
745 return unknown_tokens;
750 // changed to be public and have one parameter
751 // Returns true if "\end_document" is not read (Asger)
752 bool Buffer::readDocument(Lexer & lex)
754 ErrorList & errorList = d->errorLists["Parse"];
757 if (!lex.checkFor("\\begin_document")) {
758 docstring const s = _("\\begin_document is missing");
759 errorList.push_back(ErrorItem(_("Document header error"),
763 // we are reading in a brand new document
764 LASSERT(paragraphs().empty(), /**/);
768 if (params().outputChanges) {
769 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
770 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
771 LaTeXFeatures::isAvailable("xcolor");
773 if (!dvipost && !xcolorulem) {
774 Alert::warning(_("Changes not shown in LaTeX output"),
775 _("Changes will not be highlighted in LaTeX output, "
776 "because neither dvipost nor xcolor/ulem are installed.\n"
777 "Please install these packages or redefine "
778 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
779 } else if (!xcolorulem) {
780 Alert::warning(_("Changes not shown in LaTeX output"),
781 _("Changes will not be highlighted in LaTeX output "
782 "when using pdflatex, because xcolor and ulem are not installed.\n"
783 "Please install both packages or redefine "
784 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
788 if (!params().master.empty()) {
789 FileName const master_file = makeAbsPath(params().master,
790 onlyPath(absFileName()));
791 if (isLyXFileName(master_file.absFileName())) {
793 checkAndLoadLyXFile(master_file, true);
795 // necessary e.g. after a reload
796 // to re-register the child (bug 5873)
797 // FIXME: clean up updateMacros (here, only
798 // child registering is needed).
799 master->updateMacros();
800 // set master as master buffer, but only
801 // if we are a real child
802 if (master->isChild(this))
804 // if the master is not fully loaded
805 // it is probably just loading this
806 // child. No warning needed then.
807 else if (master->isFullyLoaded())
808 LYXERR0("The master '"
810 << "' assigned to this document ("
812 << ") does not include "
813 "this document. Ignoring the master assignment.");
818 // assure we have a default index
819 params().indiceslist().addDefault(B_("Index"));
822 bool const res = text().read(lex, errorList, d->inset);
826 updateMacroInstances();
831 bool Buffer::readString(string const & s)
833 params().compressed = false;
835 // remove dummy empty par
836 paragraphs().clear();
840 FileName const name = FileName::tempName("Buffer_readString");
841 switch (readFile(lex, name, true)) {
845 case ReadWrongVersion: {
846 // We need to call lyx2lyx, so write the input to a file
847 ofstream os(name.toFilesystemEncoding().c_str());
850 return readFile(name);
860 bool Buffer::readFile(FileName const & filename)
862 FileName fname(filename);
864 params().compressed = fname.isZippedFile();
866 // remove dummy empty par
867 paragraphs().clear();
870 if (readFile(lex, fname) != ReadSuccess)
873 d->read_only = !fname.isWritable();
878 bool Buffer::isFullyLoaded() const
880 return d->file_fully_loaded;
884 void Buffer::setFullyLoaded(bool value)
886 d->file_fully_loaded = value;
890 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
893 LASSERT(!filename.empty(), /**/);
895 // the first (non-comment) token _must_ be...
896 if (!lex.checkFor("\\lyxformat")) {
897 Alert::error(_("Document format failure"),
898 bformat(_("%1$s is not a readable LyX document."),
899 from_utf8(filename.absFileName())));
905 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
906 // if present remove ".," from string.
907 size_t dot = tmp_format.find_first_of(".,");
908 //lyxerr << " dot found at " << dot << endl;
909 if (dot != string::npos)
910 tmp_format.erase(dot, 1);
911 int const file_format = convert<int>(tmp_format);
912 //lyxerr << "format: " << file_format << endl;
914 // save timestamp and checksum of the original disk file, making sure
915 // to not overwrite them with those of the file created in the tempdir
916 // when it has to be converted to the current format.
918 // Save the timestamp and checksum of disk file. If filename is an
919 // emergency file, save the timestamp and checksum of the original lyx file
920 // because isExternallyModified will check for this file. (BUG4193)
921 string diskfile = filename.absFileName();
922 if (suffixIs(diskfile, ".emergency"))
923 diskfile = diskfile.substr(0, diskfile.size() - 10);
924 saveCheckSum(FileName(diskfile));
927 if (file_format != LYX_FORMAT) {
930 // lyx2lyx would fail
931 return ReadWrongVersion;
933 FileName const tmpfile = FileName::tempName("Buffer_readFile");
934 if (tmpfile.empty()) {
935 Alert::error(_("Conversion failed"),
936 bformat(_("%1$s is from a different"
937 " version of LyX, but a temporary"
938 " file for converting it could"
940 from_utf8(filename.absFileName())));
943 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
944 if (lyx2lyx.empty()) {
945 Alert::error(_("Conversion script not found"),
946 bformat(_("%1$s is from a different"
947 " version of LyX, but the"
948 " conversion script lyx2lyx"
949 " could not be found."),
950 from_utf8(filename.absFileName())));
953 ostringstream command;
954 command << os::python()
955 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
956 << " -t " << convert<string>(LYX_FORMAT)
957 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
958 << ' ' << quoteName(filename.toSafeFilesystemEncoding());
959 string const command_str = command.str();
961 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
963 cmd_ret const ret = runCommand(command_str);
964 if (ret.first != 0) {
965 if (file_format < LYX_FORMAT)
966 Alert::error(_("Conversion script failed"),
967 bformat(_("%1$s is from an older version"
968 " of LyX, but the lyx2lyx script"
969 " failed to convert it."),
970 from_utf8(filename.absFileName())));
972 Alert::error(_("Conversion script failed"),
973 bformat(_("%1$s is from a newer version"
974 " of LyX and cannot be converted by the"
976 from_utf8(filename.absFileName())));
979 bool const ret = readFile(tmpfile);
980 // Do stuff with tmpfile name and buffer name here.
981 return ret ? ReadSuccess : ReadFailure;
986 if (readDocument(lex)) {
987 Alert::error(_("Document format failure"),
988 bformat(_("%1$s ended unexpectedly, which means"
989 " that it is probably corrupted."),
990 from_utf8(filename.absFileName())));
994 d->file_fully_loaded = true;
999 // Should probably be moved to somewhere else: BufferView? GuiView?
1000 bool Buffer::save() const
1002 // ask if the disk file has been externally modified (use checksum method)
1003 if (fileName().exists() && isExternallyModified(checksum_method)) {
1004 docstring const file = makeDisplayPath(absFileName(), 20);
1005 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1006 "you want to overwrite this file?"), file);
1007 int const ret = Alert::prompt(_("Overwrite modified file?"),
1008 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1013 // We don't need autosaves in the immediate future. (Asger)
1014 resetAutosaveTimers();
1016 FileName backupName;
1017 bool madeBackup = false;
1019 // make a backup if the file already exists
1020 if (lyxrc.make_backup && fileName().exists()) {
1021 backupName = FileName(absFileName() + '~');
1022 if (!lyxrc.backupdir_path.empty()) {
1023 string const mangledName =
1024 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1025 backupName = FileName(addName(lyxrc.backupdir_path,
1028 // do not copy because of #6587
1029 if (fileName().moveTo(backupName)) {
1032 Alert::error(_("Backup failure"),
1033 bformat(_("Cannot create backup file %1$s.\n"
1034 "Please check whether the directory exists and is writeable."),
1035 from_utf8(backupName.absFileName())));
1036 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1040 if (writeFile(d->filename)) {
1044 // Saving failed, so backup is not backup
1046 backupName.moveTo(d->filename);
1052 bool Buffer::writeFile(FileName const & fname) const
1054 if (d->read_only && fname == d->filename)
1057 bool retval = false;
1059 docstring const str = bformat(_("Saving document %1$s..."),
1060 makeDisplayPath(fname.absFileName()));
1063 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1065 if (params().compressed) {
1066 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1067 retval = ofs && write(ofs);
1069 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1070 retval = ofs && write(ofs);
1074 message(str + _(" could not write file!"));
1079 // removeAutosaveFile();
1081 saveCheckSum(d->filename);
1082 message(str + _(" done."));
1088 docstring Buffer::emergencyWrite()
1090 // No need to save if the buffer has not changed.
1094 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1096 docstring user_message = bformat(
1097 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1099 // We try to save three places:
1100 // 1) Same place as document. Unless it is an unnamed doc.
1102 string s = absFileName();
1105 if (writeFile(FileName(s))) {
1107 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1108 return user_message;
1110 user_message += _(" Save failed! Trying again...\n");
1114 // 2) In HOME directory.
1115 string s = addName(package().home_dir().absFileName(), absFileName());
1117 lyxerr << ' ' << s << endl;
1118 if (writeFile(FileName(s))) {
1120 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1121 return user_message;
1124 user_message += _(" Save failed! Trying yet again...\n");
1126 // 3) In "/tmp" directory.
1127 // MakeAbsPath to prepend the current
1128 // drive letter on OS/2
1129 s = addName(package().temp_dir().absFileName(), absFileName());
1131 lyxerr << ' ' << s << endl;
1132 if (writeFile(FileName(s))) {
1134 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1135 return user_message;
1138 user_message += _(" Save failed! Bummer. Document is lost.");
1141 return user_message;
1145 bool Buffer::write(ostream & ofs) const
1148 // Use the standard "C" locale for file output.
1149 ofs.imbue(locale::classic());
1152 // The top of the file should not be written by params().
1154 // write out a comment in the top of the file
1155 ofs << "#LyX " << lyx_version
1156 << " created this file. For more info see http://www.lyx.org/\n"
1157 << "\\lyxformat " << LYX_FORMAT << "\n"
1158 << "\\begin_document\n";
1160 /// For each author, set 'used' to true if there is a change
1161 /// by this author in the document; otherwise set it to 'false'.
1162 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1163 AuthorList::Authors::const_iterator a_end = params().authors().end();
1164 for (; a_it != a_end; ++a_it)
1165 a_it->setUsed(false);
1167 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1168 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1169 for ( ; it != end; ++it)
1170 it->checkAuthors(params().authors());
1172 // now write out the buffer parameters.
1173 ofs << "\\begin_header\n";
1174 params().writeFile(ofs);
1175 ofs << "\\end_header\n";
1178 ofs << "\n\\begin_body\n";
1180 ofs << "\n\\end_body\n";
1182 // Write marker that shows file is complete
1183 ofs << "\\end_document" << endl;
1185 // Shouldn't really be needed....
1188 // how to check if close went ok?
1189 // Following is an attempt... (BE 20001011)
1191 // good() returns false if any error occured, including some
1192 // formatting error.
1193 // bad() returns true if something bad happened in the buffer,
1194 // which should include file system full errors.
1199 lyxerr << "File was not closed properly." << endl;
1206 bool Buffer::makeLaTeXFile(FileName const & fname,
1207 string const & original_path,
1208 OutputParams const & runparams_in,
1209 bool output_preamble, bool output_body) const
1211 OutputParams runparams = runparams_in;
1212 if (params().useXetex)
1213 runparams.flavor = OutputParams::XETEX;
1215 string const encoding = runparams.encoding->iconvName();
1216 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1219 try { ofs.reset(encoding); }
1220 catch (iconv_codecvt_facet_exception & e) {
1221 lyxerr << "Caught iconv exception: " << e.what() << endl;
1222 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1223 "verify that the support software for your encoding (%1$s) is "
1224 "properly installed"), from_ascii(encoding)));
1227 if (!openFileWrite(ofs, fname))
1230 //TexStream ts(ofs.rdbuf(), &texrow());
1231 ErrorList & errorList = d->errorLists["Export"];
1233 bool failed_export = false;
1236 writeLaTeXSource(ofs, original_path,
1237 runparams, output_preamble, output_body);
1239 catch (EncodingException & e) {
1240 odocstringstream ods;
1241 ods.put(e.failed_char);
1243 oss << "0x" << hex << e.failed_char << dec;
1244 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1245 " (code point %2$s)"),
1246 ods.str(), from_utf8(oss.str()));
1247 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1248 "representable in the chosen encoding.\n"
1249 "Changing the document encoding to utf8 could help."),
1250 e.par_id, e.pos, e.pos + 1));
1251 failed_export = true;
1253 catch (iconv_codecvt_facet_exception & e) {
1254 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1255 _(e.what()), -1, 0, 0));
1256 failed_export = true;
1258 catch (exception const & e) {
1259 errorList.push_back(ErrorItem(_("conversion failed"),
1260 _(e.what()), -1, 0, 0));
1261 failed_export = true;
1264 lyxerr << "Caught some really weird exception..." << endl;
1270 failed_export = true;
1271 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1275 return !failed_export;
1279 void Buffer::writeLaTeXSource(odocstream & os,
1280 string const & original_path,
1281 OutputParams const & runparams_in,
1282 bool const output_preamble, bool const output_body) const
1284 // The child documents, if any, shall be already loaded at this point.
1286 OutputParams runparams = runparams_in;
1288 // Classify the unicode characters appearing in math insets
1289 Encodings::initUnicodeMath(*this);
1291 // validate the buffer.
1292 LYXERR(Debug::LATEX, " Validating buffer...");
1293 LaTeXFeatures features(*this, params(), runparams);
1295 LYXERR(Debug::LATEX, " Buffer validation done.");
1297 // The starting paragraph of the coming rows is the
1298 // first paragraph of the document. (Asger)
1299 if (output_preamble && runparams.nice) {
1300 os << "%% LyX " << lyx_version << " created this file. "
1301 "For more info, see http://www.lyx.org/.\n"
1302 "%% Do not edit unless you really know what "
1304 d->texrow.newline();
1305 d->texrow.newline();
1307 LYXERR(Debug::INFO, "lyx document header finished");
1309 // Don't move this behind the parent_buffer=0 code below,
1310 // because then the macros will not get the right "redefinition"
1311 // flag as they don't see the parent macros which are output before.
1314 // fold macros if possible, still with parent buffer as the
1315 // macros will be put in the prefix anyway.
1316 updateMacroInstances();
1318 // There are a few differences between nice LaTeX and usual files:
1319 // usual is \batchmode and has a
1320 // special input@path to allow the including of figures
1321 // with either \input or \includegraphics (what figinsets do).
1322 // input@path is set when the actual parameter
1323 // original_path is set. This is done for usual tex-file, but not
1324 // for nice-latex-file. (Matthias 250696)
1325 // Note that input@path is only needed for something the user does
1326 // in the preamble, included .tex files or ERT, files included by
1327 // LyX work without it.
1328 if (output_preamble) {
1329 if (!runparams.nice) {
1330 // code for usual, NOT nice-latex-file
1331 os << "\\batchmode\n"; // changed
1332 // from \nonstopmode
1333 d->texrow.newline();
1335 if (!original_path.empty()) {
1337 // We don't know the encoding of inputpath
1338 docstring const inputpath = from_utf8(support::latex_path(original_path));
1339 docstring uncodable_glyphs;
1340 Encoding const * const enc = runparams.encoding;
1342 for (size_t n = 0; n < inputpath.size(); ++n) {
1343 docstring const glyph =
1344 docstring(1, inputpath[n]);
1345 if (enc->latexChar(inputpath[n], true) != glyph) {
1346 LYXERR0("Uncodable character '"
1348 << "' in input path!");
1349 uncodable_glyphs += glyph;
1354 // warn user if we found uncodable glyphs.
1355 if (!uncodable_glyphs.empty()) {
1356 frontend::Alert::warning(_("Uncodable character in file path"),
1357 support::bformat(_("The path of your document\n"
1359 "contains glyphs that are unknown in the\n"
1360 "current document encoding (namely %2$s).\n"
1361 "This will likely result in incomplete output.\n\n"
1362 "Choose an appropriate document encoding (such as utf8)\n"
1363 "or change the file path name."), inputpath, uncodable_glyphs));
1365 os << "\\makeatletter\n"
1366 << "\\def\\input@path{{"
1367 << inputpath << "/}}\n"
1368 << "\\makeatother\n";
1369 d->texrow.newline();
1370 d->texrow.newline();
1371 d->texrow.newline();
1375 // get parent macros (if this buffer has a parent) which will be
1376 // written at the document begin further down.
1377 MacroSet parentMacros;
1378 listParentMacros(parentMacros, features);
1380 // Write the preamble
1381 runparams.use_babel = params().writeLaTeX(os, features,
1383 d->filename.onlyPath());
1385 runparams.use_japanese = features.isRequired("japanese");
1391 os << "\\begin{document}\n";
1392 d->texrow.newline();
1394 // output the parent macros
1395 MacroSet::iterator it = parentMacros.begin();
1396 MacroSet::iterator end = parentMacros.end();
1397 for (; it != end; ++it) {
1398 int num_lines = (*it)->write(os, true);
1399 d->texrow.newlines(num_lines);
1402 } // output_preamble
1404 d->texrow.start(paragraphs().begin()->id(), 0);
1406 LYXERR(Debug::INFO, "preamble finished, now the body.");
1408 // if we are doing a real file with body, even if this is the
1409 // child of some other buffer, let's cut the link here.
1410 // This happens for example if only a child document is printed.
1411 Buffer const * save_parent = 0;
1412 if (output_preamble) {
1413 save_parent = d->parent();
1418 latexParagraphs(*this, text(), os, d->texrow, runparams);
1420 // Restore the parenthood if needed
1421 if (output_preamble)
1422 d->setParent(save_parent);
1424 // add this just in case after all the paragraphs
1426 d->texrow.newline();
1428 if (output_preamble) {
1429 os << "\\end{document}\n";
1430 d->texrow.newline();
1431 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1433 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1435 runparams_in.encoding = runparams.encoding;
1437 // Just to be sure. (Asger)
1438 d->texrow.newline();
1440 //for (int i = 0; i<d->texrow.rows(); i++) {
1442 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1443 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1446 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1447 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1451 bool Buffer::isLatex() const
1453 return params().documentClass().outputType() == LATEX;
1457 bool Buffer::isLiterate() const
1459 return params().documentClass().outputType() == LITERATE;
1463 bool Buffer::isDocBook() const
1465 return params().documentClass().outputType() == DOCBOOK;
1469 void Buffer::makeDocBookFile(FileName const & fname,
1470 OutputParams const & runparams,
1471 bool const body_only) const
1473 LYXERR(Debug::LATEX, "makeDocBookFile...");
1476 if (!openFileWrite(ofs, fname))
1479 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1483 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1487 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1488 OutputParams const & runparams,
1489 bool const only_body) const
1491 LaTeXFeatures features(*this, params(), runparams);
1496 DocumentClass const & tclass = params().documentClass();
1497 string const top_element = tclass.latexname();
1500 if (runparams.flavor == OutputParams::XML)
1501 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1504 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1507 if (! tclass.class_header().empty())
1508 os << from_ascii(tclass.class_header());
1509 else if (runparams.flavor == OutputParams::XML)
1510 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1511 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1513 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1515 docstring preamble = from_utf8(params().preamble);
1516 if (runparams.flavor != OutputParams::XML ) {
1517 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1518 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1519 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1520 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1523 string const name = runparams.nice
1524 ? changeExtension(absFileName(), ".sgml") : fname;
1525 preamble += features.getIncludedFiles(name);
1526 preamble += features.getLyXSGMLEntities();
1528 if (!preamble.empty()) {
1529 os << "\n [ " << preamble << " ]";
1534 string top = top_element;
1536 if (runparams.flavor == OutputParams::XML)
1537 top += params().language->code();
1539 top += params().language->code().substr(0, 2);
1542 if (!params().options.empty()) {
1544 top += params().options;
1547 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1548 << " file was created by LyX " << lyx_version
1549 << "\n See http://www.lyx.org/ for more information -->\n";
1551 params().documentClass().counters().reset();
1555 sgml::openTag(os, top);
1557 docbookParagraphs(text(), *this, os, runparams);
1558 sgml::closeTag(os, top_element);
1562 void Buffer::makeLyXHTMLFile(FileName const & fname,
1563 OutputParams const & runparams,
1564 bool const body_only) const
1566 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1569 if (!openFileWrite(ofs, fname))
1572 writeLyXHTMLSource(ofs, runparams, body_only);
1576 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1580 void Buffer::writeLyXHTMLSource(odocstream & os,
1581 OutputParams const & runparams,
1582 bool const only_body) const
1584 LaTeXFeatures features(*this, params(), runparams);
1586 updateBuffer(UpdateMaster, OutputUpdate);
1587 d->bibinfo_.makeCitationLabels(*this);
1589 updateMacroInstances();
1592 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1593 << "<!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"
1594 // FIXME Language should be set properly.
1595 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1597 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1598 // FIXME Presumably need to set this right
1599 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1601 docstring const & doctitle = features.htmlTitle();
1603 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1606 os << "\n<!-- Text Class Preamble -->\n"
1607 << features.getTClassHTMLPreamble()
1608 << "\n<!-- Premable Snippets -->\n"
1609 << from_utf8(features.getPreambleSnippets());
1611 os << "\n<!-- Layout-provided Styles -->\n";
1612 docstring const styleinfo = features.getTClassHTMLStyles();
1613 if (!styleinfo.empty()) {
1614 os << "<style type='text/css'>\n"
1618 os << "</head>\n<body>\n";
1622 params().documentClass().counters().reset();
1623 xhtmlParagraphs(text(), *this, xs, runparams);
1625 os << "</body>\n</html>\n";
1629 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1630 // Other flags: -wall -v0 -x
1631 int Buffer::runChktex()
1635 // get LaTeX-Filename
1636 FileName const path(temppath());
1637 string const name = addName(path.absFileName(), latexName());
1638 string const org_path = filePath();
1640 PathChanger p(path); // path to LaTeX file
1641 message(_("Running chktex..."));
1643 // Generate the LaTeX file if neccessary
1644 OutputParams runparams(¶ms().encoding());
1645 runparams.flavor = OutputParams::LATEX;
1646 runparams.nice = false;
1647 runparams.linelen = lyxrc.plaintext_linelen;
1648 makeLaTeXFile(FileName(name), org_path, runparams);
1651 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1652 int const res = chktex.run(terr); // run chktex
1655 Alert::error(_("chktex failure"),
1656 _("Could not run chktex successfully."));
1657 } else if (res > 0) {
1658 ErrorList & errlist = d->errorLists["ChkTeX"];
1660 bufferErrors(terr, errlist);
1671 void Buffer::validate(LaTeXFeatures & features) const
1673 params().validate(features);
1677 for_each(paragraphs().begin(), paragraphs().end(),
1678 bind(&Paragraph::validate, _1, ref(features)));
1680 if (lyxerr.debugging(Debug::LATEX)) {
1681 features.showStruct();
1686 void Buffer::getLabelList(vector<docstring> & list) const
1688 // If this is a child document, use the master's list instead.
1690 masterBuffer()->getLabelList(list);
1695 Toc & toc = d->toc_backend.toc("label");
1696 TocIterator toc_it = toc.begin();
1697 TocIterator end = toc.end();
1698 for (; toc_it != end; ++toc_it) {
1699 if (toc_it->depth() == 0)
1700 list.push_back(toc_it->str());
1705 void Buffer::updateBibfilesCache(UpdateScope scope) const
1707 // FIXME This is probably unnecssary, given where we call this.
1708 // If this is a child document, use the parent's cache instead.
1709 if (parent() && scope != UpdateChildOnly) {
1710 masterBuffer()->updateBibfilesCache();
1714 d->bibfiles_cache_.clear();
1715 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1716 if (it->lyxCode() == BIBTEX_CODE) {
1717 InsetBibtex const & inset =
1718 static_cast<InsetBibtex const &>(*it);
1719 support::FileNameList const bibfiles = inset.getBibFiles();
1720 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1723 } else if (it->lyxCode() == INCLUDE_CODE) {
1724 InsetInclude & inset =
1725 static_cast<InsetInclude &>(*it);
1726 Buffer const * const incbuf = inset.getChildBuffer();
1729 support::FileNameList const & bibfiles =
1730 incbuf->getBibfilesCache(UpdateChildOnly);
1731 if (!bibfiles.empty()) {
1732 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1738 d->bibfile_cache_valid_ = true;
1739 d->bibinfo_cache_valid_ = false;
1743 void Buffer::invalidateBibinfoCache() const
1745 d->bibinfo_cache_valid_ = false;
1746 // also invalidate the cache for the parent buffer
1747 Buffer const * const pbuf = d->parent();
1749 pbuf->invalidateBibinfoCache();
1753 void Buffer::invalidateBibfileCache() const
1755 d->bibfile_cache_valid_ = false;
1756 d->bibinfo_cache_valid_ = false;
1757 // also invalidate the cache for the parent buffer
1758 Buffer const * const pbuf = d->parent();
1760 pbuf->invalidateBibfileCache();
1764 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1766 // FIXME This is probably unnecessary, given where we call this.
1767 // If this is a child document, use the master's cache instead.
1768 Buffer const * const pbuf = masterBuffer();
1769 if (pbuf != this && scope != UpdateChildOnly)
1770 return pbuf->getBibfilesCache();
1772 if (!d->bibfile_cache_valid_)
1773 this->updateBibfilesCache(scope);
1775 return d->bibfiles_cache_;
1779 BiblioInfo const & Buffer::masterBibInfo() const
1781 Buffer const * const tmp = masterBuffer();
1783 return tmp->masterBibInfo();
1788 void Buffer::checkBibInfoCache() const
1790 // use the master's cache
1791 Buffer const * const tmp = masterBuffer();
1793 tmp->checkBibInfoCache();
1797 // this will also reload the cache if it is invalid
1798 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1800 // compare the cached timestamps with the actual ones.
1801 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1802 support::FileNameList::const_iterator en = bibfiles_cache.end();
1803 for (; ei != en; ++ ei) {
1804 time_t lastw = ei->lastModified();
1805 time_t prevw = d->bibfile_status_[*ei];
1806 if (lastw != prevw) {
1807 d->bibinfo_cache_valid_ = false;
1808 d->bibfile_status_[*ei] = lastw;
1812 // if not valid, then reload the info
1813 if (!d->bibinfo_cache_valid_) {
1814 d->bibinfo_.clear();
1815 fillWithBibKeys(d->bibinfo_);
1816 d->bibinfo_cache_valid_ = true;
1821 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1823 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1824 it->fillWithBibKeys(keys, it);
1828 bool Buffer::isDepClean(string const & name) const
1830 DepClean::const_iterator const it = d->dep_clean.find(name);
1831 if (it == d->dep_clean.end())
1837 void Buffer::markDepClean(string const & name)
1839 d->dep_clean[name] = true;
1843 bool Buffer::isExportableFormat(string const & format) const
1845 typedef vector<Format const *> Formats;
1847 formats = exportableFormats(true);
1848 Formats::const_iterator fit = formats.begin();
1849 Formats::const_iterator end = formats.end();
1850 for (; fit != end ; ++fit) {
1851 if ((*fit)->name() == format)
1858 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1861 // FIXME? if there is an Buffer LFUN that can be dispatched even
1862 // if internal, put a switch '(cmd.action)' here.
1868 switch (cmd.action()) {
1870 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1871 flag.setOnOff(isReadonly());
1874 // FIXME: There is need for a command-line import.
1875 //case LFUN_BUFFER_IMPORT:
1877 case LFUN_BUFFER_AUTO_SAVE:
1880 case LFUN_BUFFER_EXPORT_CUSTOM:
1881 // FIXME: Nothing to check here?
1884 case LFUN_BUFFER_EXPORT: {
1885 docstring const arg = cmd.argument();
1886 enable = arg == "custom" || isExportable(to_utf8(arg));
1888 flag.message(bformat(
1889 _("Don't know how to export to format: %1$s"), arg));
1893 case LFUN_BUFFER_CHKTEX:
1894 enable = isLatex() && !lyxrc.chktex_command.empty();
1897 case LFUN_BUILD_PROGRAM:
1898 enable = isExportable("program");
1901 case LFUN_BRANCH_ACTIVATE:
1902 case LFUN_BRANCH_DEACTIVATE: {
1903 BranchList const & branchList = params().branchlist();
1904 docstring const branchName = cmd.argument();
1905 enable = !branchName.empty() && branchList.find(branchName);
1909 case LFUN_BRANCH_ADD:
1910 case LFUN_BRANCHES_RENAME:
1911 case LFUN_BUFFER_PRINT:
1912 // if no Buffer is present, then of course we won't be called!
1915 case LFUN_BUFFER_LANGUAGE:
1916 enable = !isReadonly();
1922 flag.setEnabled(enable);
1927 void Buffer::dispatch(string const & command, DispatchResult & result)
1929 return dispatch(lyxaction.lookupFunc(command), result);
1933 // NOTE We can end up here even if we have no GUI, because we are called
1934 // by LyX::exec to handled command-line requests. So we may need to check
1935 // whether we have a GUI or not. The boolean use_gui holds this information.
1936 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1939 // FIXME? if there is an Buffer LFUN that can be dispatched even
1940 // if internal, put a switch '(cmd.action())' here.
1941 dr.dispatched(false);
1944 string const argument = to_utf8(func.argument());
1945 // We'll set this back to false if need be.
1946 bool dispatched = true;
1947 undo().beginUndoGroup();
1949 switch (func.action()) {
1950 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1951 if (lyxvc().inUse())
1952 lyxvc().toggleReadOnly();
1954 setReadonly(!isReadonly());
1957 case LFUN_BUFFER_EXPORT: {
1958 bool success = doExport(argument, false, false);
1959 dr.setError(!success);
1961 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1966 case LFUN_BUILD_PROGRAM:
1967 doExport("program", true, false);
1970 case LFUN_BUFFER_CHKTEX:
1974 case LFUN_BUFFER_EXPORT_CUSTOM: {
1976 string command = split(argument, format_name, ' ');
1977 Format const * format = formats.getFormat(format_name);
1979 lyxerr << "Format \"" << format_name
1980 << "\" not recognized!"
1985 // The name of the file created by the conversion process
1988 // Output to filename
1989 if (format->name() == "lyx") {
1990 string const latexname = latexName(false);
1991 filename = changeExtension(latexname,
1992 format->extension());
1993 filename = addName(temppath(), filename);
1995 if (!writeFile(FileName(filename)))
1999 doExport(format_name, true, false, filename);
2002 // Substitute $$FName for filename
2003 if (!contains(command, "$$FName"))
2004 command = "( " + command + " ) < $$FName";
2005 command = subst(command, "$$FName", filename);
2007 // Execute the command in the background
2009 call.startscript(Systemcall::DontWait, command);
2013 // FIXME: There is need for a command-line import.
2015 case LFUN_BUFFER_IMPORT:
2020 case LFUN_BUFFER_AUTO_SAVE:
2024 case LFUN_BRANCH_ADD: {
2025 docstring branch_name = func.argument();
2026 if (branch_name.empty()) {
2030 BranchList & branch_list = params().branchlist();
2031 vector<docstring> const branches =
2032 getVectorFromString(branch_name, branch_list.separator());
2034 for (vector<docstring>::const_iterator it = branches.begin();
2035 it != branches.end(); ++it) {
2037 Branch * branch = branch_list.find(branch_name);
2039 LYXERR0("Branch " << branch_name << " already exists.");
2043 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2045 branch_list.add(branch_name);
2046 branch = branch_list.find(branch_name);
2047 string const x11hexname = X11hexname(branch->color());
2048 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2049 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2051 dr.screenUpdate(Update::Force);
2059 case LFUN_BRANCH_ACTIVATE:
2060 case LFUN_BRANCH_DEACTIVATE: {
2061 BranchList & branchList = params().branchlist();
2062 docstring const branchName = func.argument();
2063 // the case without a branch name is handled elsewhere
2064 if (branchName.empty()) {
2068 Branch * branch = branchList.find(branchName);
2070 LYXERR0("Branch " << branchName << " does not exist.");
2072 docstring const msg =
2073 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2076 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2078 dr.screenUpdate(Update::Force);
2079 dr.forceBufferUpdate();
2084 case LFUN_BRANCHES_RENAME: {
2085 if (func.argument().empty())
2088 docstring const oldname = from_utf8(func.getArg(0));
2089 docstring const newname = from_utf8(func.getArg(1));
2090 InsetIterator it = inset_iterator_begin(inset());
2091 InsetIterator const end = inset_iterator_end(inset());
2092 bool success = false;
2093 for (; it != end; ++it) {
2094 if (it->lyxCode() == BRANCH_CODE) {
2095 InsetBranch & ins = dynamic_cast<InsetBranch &>(*it);
2096 if (ins.branch() == oldname) {
2097 undo().recordUndo(it);
2098 ins.rename(newname);
2103 if (it->lyxCode() == INCLUDE_CODE) {
2104 // get buffer of external file
2105 InsetInclude const & ins =
2106 static_cast<InsetInclude const &>(*it);
2107 Buffer * child = ins.getChildBuffer();
2110 child->dispatch(func, dr);
2115 dr.screenUpdate(Update::Force);
2116 dr.forceBufferUpdate();
2121 case LFUN_BUFFER_PRINT: {
2122 // we'll assume there's a problem until we succeed
2124 string target = func.getArg(0);
2125 string target_name = func.getArg(1);
2126 string command = func.getArg(2);
2129 || target_name.empty()
2130 || command.empty()) {
2131 LYXERR0("Unable to parse " << func.argument());
2132 docstring const msg =
2133 bformat(_("Unable to parse \"%1$s\""), func.argument());
2137 if (target != "printer" && target != "file") {
2138 LYXERR0("Unrecognized target \"" << target << '"');
2139 docstring const msg =
2140 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2145 bool const update_unincluded =
2146 params().maintain_unincluded_children
2147 && !params().getIncludedChildren().empty();
2148 if (!doExport("dvi", true, update_unincluded)) {
2149 showPrintError(absFileName());
2150 dr.setMessage(_("Error exporting to DVI."));
2154 // Push directory path.
2155 string const path = temppath();
2156 // Prevent the compiler from optimizing away p
2160 // there are three cases here:
2161 // 1. we print to a file
2162 // 2. we print directly to a printer
2163 // 3. we print using a spool command (print to file first)
2166 string const dviname = changeExtension(latexName(true), "dvi");
2168 if (target == "printer") {
2169 if (!lyxrc.print_spool_command.empty()) {
2170 // case 3: print using a spool
2171 string const psname = changeExtension(dviname,".ps");
2172 command += ' ' + lyxrc.print_to_file
2175 + quoteName(dviname);
2177 string command2 = lyxrc.print_spool_command + ' ';
2178 if (target_name != "default") {
2179 command2 += lyxrc.print_spool_printerprefix
2183 command2 += quoteName(psname);
2185 // If successful, then spool command
2186 res = one.startscript(Systemcall::Wait, command);
2189 // If there's no GUI, we have to wait on this command. Otherwise,
2190 // LyX deletes the temporary directory, and with it the spooled
2191 // file, before it can be printed!!
2192 Systemcall::Starttype stype = use_gui ?
2193 Systemcall::DontWait : Systemcall::Wait;
2194 res = one.startscript(stype, command2);
2197 // case 2: print directly to a printer
2198 if (target_name != "default")
2199 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2201 Systemcall::Starttype stype = use_gui ?
2202 Systemcall::DontWait : Systemcall::Wait;
2203 res = one.startscript(stype, command + quoteName(dviname));
2207 // case 1: print to a file
2208 FileName const filename(makeAbsPath(target_name, filePath()));
2209 FileName const dvifile(makeAbsPath(dviname, path));
2210 if (filename.exists()) {
2211 docstring text = bformat(
2212 _("The file %1$s already exists.\n\n"
2213 "Do you want to overwrite that file?"),
2214 makeDisplayPath(filename.absFileName()));
2215 if (Alert::prompt(_("Overwrite file?"),
2216 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2219 command += ' ' + lyxrc.print_to_file
2220 + quoteName(filename.toFilesystemEncoding())
2222 + quoteName(dvifile.toFilesystemEncoding());
2224 Systemcall::Starttype stype = use_gui ?
2225 Systemcall::DontWait : Systemcall::Wait;
2226 res = one.startscript(stype, command);
2232 dr.setMessage(_("Error running external commands."));
2233 showPrintError(absFileName());
2238 case LFUN_BUFFER_LANGUAGE: {
2239 Language const * oldL = params().language;
2240 Language const * newL = languages.getLanguage(argument);
2241 if (!newL || oldL == newL)
2243 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2244 changeLanguage(oldL, newL);
2245 dr.forceBufferUpdate();
2254 dr.dispatched(dispatched);
2255 undo().endUndoGroup();
2259 void Buffer::changeLanguage(Language const * from, Language const * to)
2261 LASSERT(from, /**/);
2264 for_each(par_iterator_begin(),
2266 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2270 bool Buffer::isMultiLingual() const
2272 ParConstIterator end = par_iterator_end();
2273 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2274 if (it->isMultiLingual(params()))
2281 std::set<Language const *> Buffer::getLanguages() const
2283 std::set<Language const *> languages;
2284 getLanguages(languages);
2289 void Buffer::getLanguages(std::set<Language const *> & languages) const
2291 ParConstIterator end = par_iterator_end();
2292 // add the buffer language, even if it's not actively used
2293 languages.insert(language());
2294 // iterate over the paragraphs
2295 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2296 it->getLanguages(languages);
2298 ListOfBuffers clist = getDescendents();
2299 ListOfBuffers::const_iterator cit = clist.begin();
2300 ListOfBuffers::const_iterator const cen = clist.end();
2301 for (; cit != cen; ++cit)
2302 (*cit)->getLanguages(languages);
2306 DocIterator Buffer::getParFromID(int const id) const
2308 Buffer * buf = const_cast<Buffer *>(this);
2310 // John says this is called with id == -1 from undo
2311 lyxerr << "getParFromID(), id: " << id << endl;
2312 return doc_iterator_end(buf);
2315 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2316 if (it.paragraph().id() == id)
2319 return doc_iterator_end(buf);
2323 bool Buffer::hasParWithID(int const id) const
2325 return !getParFromID(id).atEnd();
2329 ParIterator Buffer::par_iterator_begin()
2331 return ParIterator(doc_iterator_begin(this));
2335 ParIterator Buffer::par_iterator_end()
2337 return ParIterator(doc_iterator_end(this));
2341 ParConstIterator Buffer::par_iterator_begin() const
2343 return ParConstIterator(doc_iterator_begin(this));
2347 ParConstIterator Buffer::par_iterator_end() const
2349 return ParConstIterator(doc_iterator_end(this));
2353 Language const * Buffer::language() const
2355 return params().language;
2359 docstring const Buffer::B_(string const & l10n) const
2361 return params().B_(l10n);
2365 bool Buffer::isClean() const
2367 return d->lyx_clean;
2371 bool Buffer::isExternallyModified(CheckMethod method) const
2373 LASSERT(d->filename.exists(), /**/);
2374 // if method == timestamp, check timestamp before checksum
2375 return (method == checksum_method
2376 || d->timestamp_ != d->filename.lastModified())
2377 && d->checksum_ != d->filename.checksum();
2381 void Buffer::saveCheckSum(FileName const & file) const
2383 if (file.exists()) {
2384 d->timestamp_ = file.lastModified();
2385 d->checksum_ = file.checksum();
2387 // in the case of save to a new file.
2394 void Buffer::markClean() const
2396 if (!d->lyx_clean) {
2397 d->lyx_clean = true;
2400 // if the .lyx file has been saved, we don't need an
2402 d->bak_clean = true;
2403 d->undo_.markDirty();
2407 void Buffer::setUnnamed(bool flag)
2413 bool Buffer::isUnnamed() const
2420 /// Don't check unnamed, here: isInternal() is used in
2421 /// newBuffer(), where the unnamed flag has not been set by anyone
2422 /// yet. Also, for an internal buffer, there should be no need for
2423 /// retrieving fileName() nor for checking if it is unnamed or not.
2424 bool Buffer::isInternal() const
2426 return fileName().extension() == "internal";
2430 void Buffer::markDirty()
2433 d->lyx_clean = false;
2436 d->bak_clean = false;
2438 DepClean::iterator it = d->dep_clean.begin();
2439 DepClean::const_iterator const end = d->dep_clean.end();
2441 for (; it != end; ++it)
2446 FileName Buffer::fileName() const
2452 string Buffer::absFileName() const
2454 return d->filename.absFileName();
2458 string Buffer::filePath() const
2460 return d->filename.onlyPath().absFileName() + "/";
2464 bool Buffer::isReadonly() const
2466 return d->read_only;
2470 void Buffer::setParent(Buffer const * buffer)
2472 // Avoids recursive include.
2473 d->setParent(buffer == this ? 0 : buffer);
2478 Buffer const * Buffer::parent() const
2484 ListOfBuffers Buffer::allRelatives() const
2486 ListOfBuffers lb = masterBuffer()->getDescendents();
2487 lb.push_front(const_cast<Buffer *>(this));
2492 Buffer const * Buffer::masterBuffer() const
2494 // FIXME Should be make sure we are not in some kind
2495 // of recursive include? A -> B -> A will crash this.
2496 Buffer const * const pbuf = d->parent();
2500 return pbuf->masterBuffer();
2504 bool Buffer::isChild(Buffer * child) const
2506 return d->children_positions.find(child) != d->children_positions.end();
2510 DocIterator Buffer::firstChildPosition(Buffer const * child)
2512 Impl::BufferPositionMap::iterator it;
2513 it = d->children_positions.find(child);
2514 if (it == d->children_positions.end())
2515 return DocIterator(this);
2520 bool Buffer::hasChildren() const
2522 return !d->children_positions.empty();
2526 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2528 // loop over children
2529 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2530 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2531 for (; it != end; ++it) {
2532 Buffer * child = const_cast<Buffer *>(it->first);
2534 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2535 if (bit != clist.end())
2537 clist.push_back(child);
2539 // there might be grandchildren
2540 child->collectChildren(clist, true);
2545 ListOfBuffers Buffer::getChildren() const
2548 collectChildren(v, false);
2553 ListOfBuffers Buffer::getDescendents() const
2556 collectChildren(v, true);
2561 template<typename M>
2562 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2567 typename M::const_iterator it = m.lower_bound(x);
2568 if (it == m.begin())
2576 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2577 DocIterator const & pos) const
2579 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2581 // if paragraphs have no macro context set, pos will be empty
2585 // we haven't found anything yet
2586 DocIterator bestPos = owner_->par_iterator_begin();
2587 MacroData const * bestData = 0;
2589 // find macro definitions for name
2590 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2591 if (nameIt != macros.end()) {
2592 // find last definition in front of pos or at pos itself
2593 PositionScopeMacroMap::const_iterator it
2594 = greatest_below(nameIt->second, pos);
2595 if (it != nameIt->second.end()) {
2597 // scope ends behind pos?
2598 if (pos < it->second.first) {
2599 // Looks good, remember this. If there
2600 // is no external macro behind this,
2601 // we found the right one already.
2602 bestPos = it->first;
2603 bestData = &it->second.second;
2607 // try previous macro if there is one
2608 if (it == nameIt->second.begin())
2615 // find macros in included files
2616 PositionScopeBufferMap::const_iterator it
2617 = greatest_below(position_to_children, pos);
2618 if (it == position_to_children.end())
2619 // no children before
2623 // do we know something better (i.e. later) already?
2624 if (it->first < bestPos )
2627 // scope ends behind pos?
2628 if (pos < it->second.first) {
2629 // look for macro in external file
2631 MacroData const * data
2632 = it->second.second->getMacro(name, false);
2635 bestPos = it->first;
2641 // try previous file if there is one
2642 if (it == position_to_children.begin())
2647 // return the best macro we have found
2652 MacroData const * Buffer::getMacro(docstring const & name,
2653 DocIterator const & pos, bool global) const
2658 // query buffer macros
2659 MacroData const * data = d->getBufferMacro(name, pos);
2663 // If there is a master buffer, query that
2664 Buffer const * const pbuf = d->parent();
2666 d->macro_lock = true;
2667 MacroData const * macro = pbuf->getMacro(
2668 name, *this, false);
2669 d->macro_lock = false;
2675 data = MacroTable::globalMacros().get(name);
2684 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2686 // set scope end behind the last paragraph
2687 DocIterator scope = par_iterator_begin();
2688 scope.pit() = scope.lastpit() + 1;
2690 return getMacro(name, scope, global);
2694 MacroData const * Buffer::getMacro(docstring const & name,
2695 Buffer const & child, bool global) const
2697 // look where the child buffer is included first
2698 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2699 if (it == d->children_positions.end())
2702 // check for macros at the inclusion position
2703 return getMacro(name, it->second, global);
2707 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2709 pit_type const lastpit = it.lastpit();
2711 // look for macros in each paragraph
2712 while (it.pit() <= lastpit) {
2713 Paragraph & par = it.paragraph();
2715 // iterate over the insets of the current paragraph
2716 InsetList const & insets = par.insetList();
2717 InsetList::const_iterator iit = insets.begin();
2718 InsetList::const_iterator end = insets.end();
2719 for (; iit != end; ++iit) {
2720 it.pos() = iit->pos;
2722 // is it a nested text inset?
2723 if (iit->inset->asInsetText()) {
2724 // Inset needs its own scope?
2725 InsetText const * itext = iit->inset->asInsetText();
2726 bool newScope = itext->isMacroScope();
2728 // scope which ends just behind the inset
2729 DocIterator insetScope = it;
2732 // collect macros in inset
2733 it.push_back(CursorSlice(*iit->inset));
2734 updateMacros(it, newScope ? insetScope : scope);
2739 if (iit->inset->asInsetTabular()) {
2740 CursorSlice slice(*iit->inset);
2741 size_t const numcells = slice.nargs();
2742 for (; slice.idx() < numcells; slice.forwardIdx()) {
2743 it.push_back(slice);
2744 updateMacros(it, scope);
2750 // is it an external file?
2751 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2752 // get buffer of external file
2753 InsetInclude const & inset =
2754 static_cast<InsetInclude const &>(*iit->inset);
2756 Buffer * child = inset.getChildBuffer();
2761 // register its position, but only when it is
2762 // included first in the buffer
2763 if (children_positions.find(child) ==
2764 children_positions.end())
2765 children_positions[child] = it;
2767 // register child with its scope
2768 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2772 if (doing_export && iit->inset->asInsetMath()) {
2773 InsetMath * im = static_cast<InsetMath *>(iit->inset);
2774 if (im->asHullInset()) {
2775 InsetMathHull * hull = static_cast<InsetMathHull *>(im);
2776 hull->recordLocation(it);
2780 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2784 MathMacroTemplate & macroTemplate =
2785 static_cast<MathMacroTemplate &>(*iit->inset);
2786 MacroContext mc(owner_, it);
2787 macroTemplate.updateToContext(mc);
2790 bool valid = macroTemplate.validMacro();
2791 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2792 // then the BufferView's cursor will be invalid in
2793 // some cases which leads to crashes.
2798 // FIXME (Abdel), I don't understandt why we pass 'it' here
2799 // instead of 'macroTemplate' defined above... is this correct?
2800 macros[macroTemplate.name()][it] =
2801 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2811 void Buffer::updateMacros() const
2816 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2818 // start with empty table
2820 d->children_positions.clear();
2821 d->position_to_children.clear();
2823 // Iterate over buffer, starting with first paragraph
2824 // The scope must be bigger than any lookup DocIterator
2825 // later. For the global lookup, lastpit+1 is used, hence
2826 // we use lastpit+2 here.
2827 DocIterator it = par_iterator_begin();
2828 DocIterator outerScope = it;
2829 outerScope.pit() = outerScope.lastpit() + 2;
2830 d->updateMacros(it, outerScope);
2834 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2836 InsetIterator it = inset_iterator_begin(inset());
2837 InsetIterator const end = inset_iterator_end(inset());
2838 for (; it != end; ++it) {
2839 if (it->lyxCode() == BRANCH_CODE) {
2840 InsetBranch & br = dynamic_cast<InsetBranch &>(*it);
2841 docstring const name = br.branch();
2842 if (!from_master && !params().branchlist().find(name))
2843 result.push_back(name);
2844 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2845 result.push_back(name);
2848 if (it->lyxCode() == INCLUDE_CODE) {
2849 // get buffer of external file
2850 InsetInclude const & ins =
2851 static_cast<InsetInclude const &>(*it);
2852 Buffer * child = ins.getChildBuffer();
2855 child->getUsedBranches(result, true);
2858 // remove duplicates
2863 void Buffer::updateMacroInstances() const
2865 LYXERR(Debug::MACROS, "updateMacroInstances for "
2866 << d->filename.onlyFileName());
2867 DocIterator it = doc_iterator_begin(this);
2869 DocIterator const end = doc_iterator_end(this);
2870 for (; it != end; it.forwardInset()) {
2871 // look for MathData cells in InsetMathNest insets
2872 InsetMath * minset = it.nextInset()->asInsetMath();
2876 // update macro in all cells of the InsetMathNest
2877 DocIterator::idx_type n = minset->nargs();
2878 MacroContext mc = MacroContext(this, it);
2879 for (DocIterator::idx_type i = 0; i < n; ++i) {
2880 MathData & data = minset->cell(i);
2881 data.updateMacros(0, mc);
2887 void Buffer::listMacroNames(MacroNameSet & macros) const
2892 d->macro_lock = true;
2894 // loop over macro names
2895 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2896 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2897 for (; nameIt != nameEnd; ++nameIt)
2898 macros.insert(nameIt->first);
2900 // loop over children
2901 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2902 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2903 for (; it != end; ++it)
2904 it->first->listMacroNames(macros);
2907 Buffer const * const pbuf = d->parent();
2909 pbuf->listMacroNames(macros);
2911 d->macro_lock = false;
2915 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2917 Buffer const * const pbuf = d->parent();
2922 pbuf->listMacroNames(names);
2925 MacroNameSet::iterator it = names.begin();
2926 MacroNameSet::iterator end = names.end();
2927 for (; it != end; ++it) {
2929 MacroData const * data =
2930 pbuf->getMacro(*it, *this, false);
2932 macros.insert(data);
2934 // we cannot access the original MathMacroTemplate anymore
2935 // here to calls validate method. So we do its work here manually.
2936 // FIXME: somehow make the template accessible here.
2937 if (data->optionals() > 0)
2938 features.require("xargs");
2944 Buffer::References & Buffer::references(docstring const & label)
2947 return const_cast<Buffer *>(masterBuffer())->references(label);
2949 RefCache::iterator it = d->ref_cache_.find(label);
2950 if (it != d->ref_cache_.end())
2951 return it->second.second;
2953 static InsetLabel const * dummy_il = 0;
2954 static References const dummy_refs;
2955 it = d->ref_cache_.insert(
2956 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2957 return it->second.second;
2961 Buffer::References const & Buffer::references(docstring const & label) const
2963 return const_cast<Buffer *>(this)->references(label);
2967 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2969 masterBuffer()->d->ref_cache_[label].first = il;
2973 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2975 return masterBuffer()->d->ref_cache_[label].first;
2979 void Buffer::clearReferenceCache() const
2982 d->ref_cache_.clear();
2986 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2989 //FIXME: This does not work for child documents yet.
2990 LASSERT(code == CITE_CODE, /**/);
2991 // Check if the label 'from' appears more than once
2992 vector<docstring> labels;
2994 checkBibInfoCache();
2995 BiblioInfo const & keys = masterBibInfo();
2996 BiblioInfo::const_iterator bit = keys.begin();
2997 BiblioInfo::const_iterator bend = keys.end();
2999 for (; bit != bend; ++bit)
3001 labels.push_back(bit->first);
3004 if (count(labels.begin(), labels.end(), from) > 1)
3007 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3008 if (it->lyxCode() == code) {
3009 InsetCommand & inset = static_cast<InsetCommand &>(*it);
3010 docstring const oldValue = inset.getParam(paramName);
3011 if (oldValue == from)
3012 inset.setParam(paramName, to);
3018 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3019 pit_type par_end, bool full_source) const
3021 OutputParams runparams(¶ms().encoding());
3022 runparams.nice = true;
3023 runparams.flavor = params().useXetex ?
3024 OutputParams::XETEX : OutputParams::LATEX;
3025 runparams.linelen = lyxrc.plaintext_linelen;
3026 // No side effect of file copying and image conversion
3027 runparams.dryrun = true;
3030 os << "% " << _("Preview source code") << "\n\n";
3032 d->texrow.newline();
3033 d->texrow.newline();
3035 writeDocBookSource(os, absFileName(), runparams, false);
3037 // latex or literate
3038 writeLaTeXSource(os, string(), runparams, true, true);
3040 runparams.par_begin = par_begin;
3041 runparams.par_end = par_end;
3042 if (par_begin + 1 == par_end) {
3044 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3048 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3049 convert<docstring>(par_begin),
3050 convert<docstring>(par_end - 1))
3057 // output paragraphs
3059 docbookParagraphs(text(), *this, os, runparams);
3061 // latex or literate
3062 latexParagraphs(*this, text(), os, texrow, runparams);
3067 ErrorList & Buffer::errorList(string const & type) const
3069 static ErrorList emptyErrorList;
3070 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3071 if (it == d->errorLists.end())
3072 return emptyErrorList;
3078 void Buffer::updateTocItem(std::string const & type,
3079 DocIterator const & dit) const
3082 d->gui_->updateTocItem(type, dit);
3086 void Buffer::structureChanged() const
3089 d->gui_->structureChanged();
3093 void Buffer::errors(string const & err, bool from_master) const
3096 d->gui_->errors(err, from_master);
3100 void Buffer::message(docstring const & msg) const
3103 d->gui_->message(msg);
3107 void Buffer::setBusy(bool on) const
3110 d->gui_->setBusy(on);
3114 void Buffer::updateTitles() const
3117 d->wa_->updateTitles();
3121 void Buffer::resetAutosaveTimers() const
3124 d->gui_->resetAutosaveTimers();
3128 bool Buffer::hasGuiDelegate() const
3134 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3143 class AutoSaveBuffer : public ForkedProcess {
3146 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3147 : buffer_(buffer), fname_(fname) {}
3149 virtual shared_ptr<ForkedProcess> clone() const
3151 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3156 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3157 from_utf8(fname_.absFileName())));
3158 return run(DontWait);
3162 virtual int generateChild();
3164 Buffer const & buffer_;
3169 int AutoSaveBuffer::generateChild()
3171 #if defined(__APPLE__)
3172 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3173 * We should use something else like threads.
3175 * Since I do not know how to determine at run time what is the OS X
3176 * version, I just disable forking altogether for now (JMarc)
3178 pid_t const pid = -1;
3180 // tmp_ret will be located (usually) in /tmp
3181 // will that be a problem?
3182 // Note that this calls ForkedCalls::fork(), so it's
3183 // ok cross-platform.
3184 pid_t const pid = fork();
3185 // If you want to debug the autosave
3186 // you should set pid to -1, and comment out the fork.
3187 if (pid != 0 && pid != -1)
3191 // pid = -1 signifies that lyx was unable
3192 // to fork. But we will do the save
3194 bool failed = false;
3195 FileName const tmp_ret = FileName::tempName("lyxauto");
3196 if (!tmp_ret.empty()) {
3197 buffer_.writeFile(tmp_ret);
3198 // assume successful write of tmp_ret
3199 if (!tmp_ret.moveTo(fname_))
3205 // failed to write/rename tmp_ret so try writing direct
3206 if (!buffer_.writeFile(fname_)) {
3207 // It is dangerous to do this in the child,
3208 // but safe in the parent, so...
3209 if (pid == -1) // emit message signal.
3210 buffer_.message(_("Autosave failed!"));
3214 if (pid == 0) // we are the child so...
3223 FileName Buffer::getAutosaveFileName() const
3225 // if the document is unnamed try to save in the backup dir, else
3226 // in the default document path, and as a last try in the filePath,
3227 // which will most often be the temporary directory
3230 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3231 : lyxrc.backupdir_path;
3232 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3235 string const fname = "#" + d->filename.onlyFileName() + "#";
3236 return makeAbsPath(fname, fpath);
3240 void Buffer::removeAutosaveFile() const
3242 FileName const f = getAutosaveFileName();
3248 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3250 FileName const newauto = getAutosaveFileName();
3252 if (newauto != oldauto && oldauto.exists())
3253 if (!oldauto.moveTo(newauto))
3254 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3258 // Perfect target for a thread...
3259 void Buffer::autoSave() const
3261 if (d->bak_clean || isReadonly()) {
3262 // We don't save now, but we'll try again later
3263 resetAutosaveTimers();
3267 // emit message signal.
3268 message(_("Autosaving current document..."));
3269 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3272 d->bak_clean = true;
3274 resetAutosaveTimers();
3278 string Buffer::bufferFormat() const
3280 string format = params().documentClass().outputFormat();
3281 if (format == "latex") {
3282 if (params().useXetex)
3284 if (params().encoding().package() == Encoding::japanese)
3291 string Buffer::getDefaultOutputFormat() const
3293 if (!params().defaultOutputFormat.empty()
3294 && params().defaultOutputFormat != "default")
3295 return params().defaultOutputFormat;
3296 typedef vector<Format const *> Formats;
3297 Formats formats = exportableFormats(true);
3300 || params().useXetex
3301 || params().encoding().package() == Encoding::japanese) {
3302 if (formats.empty())
3304 // return the first we find
3305 return formats.front()->name();
3307 return lyxrc.default_view_format;
3312 // helper class, to guarantee this gets reset properly
3313 class MarkAsExporting {
3315 MarkAsExporting(Buffer const * buf) : buf_(buf)
3317 LASSERT(buf_, /* */);
3318 buf_->setExportStatus(true);
3322 buf_->setExportStatus(false);
3325 Buffer const * const buf_;
3330 void Buffer::setExportStatus(bool e) const
3332 d->doing_export = e;
3336 bool Buffer::isExporting() const
3338 return d->doing_export;
3342 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3343 bool includeall, string & result_file) const
3345 MarkAsExporting exporting(this);
3346 string backend_format;
3347 OutputParams runparams(¶ms().encoding());
3348 runparams.flavor = OutputParams::LATEX;
3349 runparams.linelen = lyxrc.plaintext_linelen;
3350 runparams.includeall = includeall;
3351 vector<string> backs = backends();
3352 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3353 // Get shortest path to format
3354 Graph::EdgePath path;
3355 for (vector<string>::const_iterator it = backs.begin();
3356 it != backs.end(); ++it) {
3357 Graph::EdgePath p = theConverters().getPath(*it, format);
3358 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3359 backend_format = *it;
3364 if (!put_in_tempdir) {
3365 // Only show this alert if this is an export to a non-temporary
3366 // file (not for previewing).
3367 Alert::error(_("Couldn't export file"), bformat(
3368 _("No information for exporting the format %1$s."),
3369 formats.prettyName(format)));
3373 runparams.flavor = theConverters().getFlavor(path);
3376 backend_format = format;
3377 // FIXME: Don't hardcode format names here, but use a flag
3378 if (backend_format == "pdflatex")
3379 runparams.flavor = OutputParams::PDFLATEX;
3382 string filename = latexName(false);
3383 filename = addName(temppath(), filename);
3384 filename = changeExtension(filename,
3385 formats.extension(backend_format));
3388 updateMacroInstances();
3390 // Plain text backend
3391 if (backend_format == "text") {
3392 runparams.flavor = OutputParams::TEXT;
3393 writePlaintextFile(*this, FileName(filename), runparams);
3396 else if (backend_format == "xhtml") {
3397 runparams.flavor = OutputParams::HTML;
3398 switch (params().html_math_output) {
3399 case BufferParams::MathML:
3400 runparams.math_flavor = OutputParams::MathAsMathML;
3402 case BufferParams::HTML:
3403 runparams.math_flavor = OutputParams::MathAsHTML;
3405 case BufferParams::Images:
3406 runparams.math_flavor = OutputParams::MathAsImages;
3408 case BufferParams::LaTeX:
3409 runparams.math_flavor = OutputParams::MathAsLaTeX;
3413 makeLyXHTMLFile(FileName(filename), runparams);
3414 } else if (backend_format == "lyx")
3415 writeFile(FileName(filename));
3417 else if (isDocBook()) {
3418 runparams.nice = !put_in_tempdir;
3419 makeDocBookFile(FileName(filename), runparams);
3422 else if (backend_format == format) {
3423 runparams.nice = true;
3424 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3426 } else if (!lyxrc.tex_allows_spaces
3427 && contains(filePath(), ' ')) {
3428 Alert::error(_("File name error"),
3429 _("The directory path to the document cannot contain spaces."));
3432 runparams.nice = false;
3433 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3437 string const error_type = (format == "program")
3438 ? "Build" : bufferFormat();
3439 ErrorList & error_list = d->errorLists[error_type];
3440 string const ext = formats.extension(format);
3441 FileName const tmp_result_file(changeExtension(filename, ext));
3442 bool const success = theConverters().convert(this, FileName(filename),
3443 tmp_result_file, FileName(absFileName()), backend_format, format,
3446 // Emit the signal to show the error list or copy it back to the
3447 // cloned Buffer so that it cab be emitted afterwards.
3448 if (format != backend_format) {
3449 if (d->cloned_buffer_) {
3450 d->cloned_buffer_->d->errorLists[error_type] =
3451 d->errorLists[error_type];
3454 // also to the children, in case of master-buffer-view
3455 ListOfBuffers clist = getDescendents();
3456 ListOfBuffers::const_iterator cit = clist.begin();
3457 ListOfBuffers::const_iterator const cen = clist.end();
3458 for (; cit != cen; ++cit) {
3459 if (d->cloned_buffer_) {
3460 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3461 (*cit)->d->errorLists[error_type];
3463 (*cit)->errors(error_type, true);
3467 if (d->cloned_buffer_) {
3468 // Enable reverse dvi or pdf to work by copying back the texrow
3469 // object to the cloned buffer.
3470 // FIXME: There is a possibility of concurrent access to texrow
3471 // here from the main GUI thread that should be securized.
3472 d->cloned_buffer_->d->texrow = d->texrow;
3473 string const error_type = bufferFormat();
3474 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3480 if (put_in_tempdir) {
3481 result_file = tmp_result_file.absFileName();
3485 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3486 // We need to copy referenced files (e. g. included graphics
3487 // if format == "dvi") to the result dir.
3488 vector<ExportedFile> const files =
3489 runparams.exportdata->externalFiles(format);
3490 string const dest = onlyPath(result_file);
3491 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3492 : force_overwrite == ALL_FILES;
3493 CopyStatus status = use_force ? FORCE : SUCCESS;
3495 vector<ExportedFile>::const_iterator it = files.begin();
3496 vector<ExportedFile>::const_iterator const en = files.end();
3497 for (; it != en && status != CANCEL; ++it) {
3498 string const fmt = formats.getFormatFromFile(it->sourceName);
3499 status = copyFile(fmt, it->sourceName,
3500 makeAbsPath(it->exportName, dest),
3501 it->exportName, status == FORCE);
3504 if (status == CANCEL) {
3505 message(_("Document export cancelled."));
3506 } else if (tmp_result_file.exists()) {
3507 // Finally copy the main file
3508 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3509 : force_overwrite != NO_FILES;
3510 if (status == SUCCESS && use_force)
3512 status = copyFile(format, tmp_result_file,
3513 FileName(result_file), result_file,
3515 message(bformat(_("Document exported as %1$s "
3517 formats.prettyName(format),
3518 makeDisplayPath(result_file)));
3520 // This must be a dummy converter like fax (bug 1888)
3521 message(bformat(_("Document exported as %1$s"),
3522 formats.prettyName(format)));
3529 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3530 bool includeall) const
3533 // (1) export with all included children (omit \includeonly)
3534 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3536 // (2) export with included children only
3537 return doExport(format, put_in_tempdir, false, result_file);
3541 bool Buffer::preview(string const & format, bool includeall) const
3543 MarkAsExporting exporting(this);
3545 // (1) export with all included children (omit \includeonly)
3546 if (includeall && !doExport(format, true, true))
3548 // (2) export with included children only
3549 if (!doExport(format, true, false, result_file))
3551 return formats.view(*this, FileName(result_file), format);
3555 bool Buffer::isExportable(string const & format) const
3557 vector<string> backs = backends();
3558 for (vector<string>::const_iterator it = backs.begin();
3559 it != backs.end(); ++it)
3560 if (theConverters().isReachable(*it, format))
3566 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3568 vector<string> const backs = backends();
3569 vector<Format const *> result =
3570 theConverters().getReachable(backs[0], only_viewable, true);
3571 for (vector<string>::const_iterator it = backs.begin() + 1;
3572 it != backs.end(); ++it) {
3573 vector<Format const *> r =
3574 theConverters().getReachable(*it, only_viewable, false);
3575 result.insert(result.end(), r.begin(), r.end());
3581 vector<string> Buffer::backends() const
3584 v.push_back(bufferFormat());
3585 // FIXME: Don't hardcode format names here, but use a flag
3586 if (v.back() == "latex")
3587 v.push_back("pdflatex");
3588 v.push_back("xhtml");
3589 v.push_back("text");
3595 Buffer::ReadStatus Buffer::readFromVC(FileName const & fn)
3597 bool const found = LyXVC::file_not_found_hook(fn);
3599 return ReadFileNotFound;
3600 if (!fn.isReadableFile())
3606 Buffer::ReadStatus Buffer::readEmergency(FileName const & fn)
3608 FileName const emergencyFile(fn.absFileName() + ".emergency");
3609 if (!emergencyFile.exists()
3610 || emergencyFile.lastModified() <= fn.lastModified())
3611 return ReadFileNotFound;
3613 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3614 docstring const text =
3615 bformat(_("An emergency save of the document "
3617 "Recover emergency save?"), file);
3619 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3620 _("&Recover"), _("&Load Original"),
3624 // the file is not saved if we load the emergency file.
3627 bool const res = readFile(emergencyFile);
3629 str = _("Document was successfully recovered.");
3631 str = _("Document was NOT successfully recovered.");
3632 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3633 makeDisplayPath(emergencyFile.absFileName()));
3635 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3636 _("&Remove"), _("&Keep"))) {
3637 emergencyFile.removeFile();
3639 Alert::warning(_("Emergency file deleted"),
3640 _("Do not forget to save your file now!"), true);
3642 return res ? ReadSuccess : ReadEmergencyFailure;
3645 if (!Alert::prompt(_("Delete emergency file?"),
3646 _("Remove emergency file now?"), 1, 1,
3647 _("&Remove"), _("&Keep")))
3648 emergencyFile.removeFile();
3649 return ReadOriginal;
3659 Buffer::ReadStatus Buffer::readAutosave(FileName const & fn)
3661 // Now check if autosave file is newer.
3662 FileName const autosaveFile(onlyPath(fn.absFileName())
3663 + '#' + onlyFileName(fn.absFileName()) + '#');
3664 if (autosaveFile.exists()
3665 && autosaveFile.lastModified() > fn.lastModified()) {
3666 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3667 docstring const text =
3668 bformat(_("The backup of the document "
3669 "%1$s is newer.\n\nLoad the "
3670 "backup instead?"), file);
3671 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3672 _("&Load backup"), _("Load &original"),
3676 // the file is not saved if we load the autosave file.
3678 return readFile(autosaveFile) ? ReadSuccess
3679 : ReadAutosaveFailure;
3681 // Here we delete the autosave
3682 autosaveFile.removeFile();
3683 return ReadOriginal;
3688 return ReadFileNotFound;
3692 Buffer::ReadStatus Buffer::loadLyXFile(FileName const & fn)
3694 if (!fn.isReadableFile()) {
3695 ReadStatus const ret_rvc = readFromVC(fn);
3696 if (ret_rvc != ReadSuccess)
3699 // InsetInfo needs to know if file is under VCS
3700 lyxvc().file_found_hook(fn);
3702 ReadStatus const ret_re = readEmergency(fn);
3703 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3706 ReadStatus const ret_ra = readAutosave(fn);
3707 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3716 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3718 TeXErrors::Errors::const_iterator cit = terr.begin();
3719 TeXErrors::Errors::const_iterator end = terr.end();
3721 for (; cit != end; ++cit) {
3724 int errorRow = cit->error_in_line;
3725 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3731 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3732 } while (found && id_start == id_end && pos_start == pos_end);
3734 errorList.push_back(ErrorItem(cit->error_desc,
3735 cit->error_text, id_start, pos_start, pos_end));
3740 void Buffer::setBuffersForInsets() const
3742 inset().setBuffer(const_cast<Buffer &>(*this));
3746 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3748 // Use the master text class also for child documents
3749 Buffer const * const master = masterBuffer();
3750 DocumentClass const & textclass = master->params().documentClass();
3752 // do this only if we are the top-level Buffer
3754 checkBibInfoCache();
3756 // keep the buffers to be children in this set. If the call from the
3757 // master comes back we can see which of them were actually seen (i.e.
3758 // via an InsetInclude). The remaining ones in the set need still be updated.
3759 static std::set<Buffer const *> bufToUpdate;
3760 if (scope == UpdateMaster) {
3761 // If this is a child document start with the master
3762 if (master != this) {
3763 bufToUpdate.insert(this);
3764 master->updateBuffer(UpdateMaster, utype);
3765 // Do this here in case the master has no gui associated with it. Then,
3766 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3767 if (!master->d->gui_)
3770 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3771 if (bufToUpdate.find(this) == bufToUpdate.end())
3775 // start over the counters in the master
3776 textclass.counters().reset();
3779 // update will be done below for this buffer
3780 bufToUpdate.erase(this);
3782 // update all caches
3783 clearReferenceCache();
3786 Buffer & cbuf = const_cast<Buffer &>(*this);
3788 LASSERT(!text().paragraphs().empty(), /**/);
3791 ParIterator parit = cbuf.par_iterator_begin();
3792 updateBuffer(parit, utype);
3795 // TocBackend update will be done later.
3798 cbuf.tocBackend().update();
3799 if (scope == UpdateMaster)
3800 cbuf.structureChanged();
3804 static depth_type getDepth(DocIterator const & it)
3806 depth_type depth = 0;
3807 for (size_t i = 0 ; i < it.depth() ; ++i)
3808 if (!it[i].inset().inMathed())
3809 depth += it[i].paragraph().getDepth() + 1;
3810 // remove 1 since the outer inset does not count
3814 static depth_type getItemDepth(ParIterator const & it)
3816 Paragraph const & par = *it;
3817 LabelType const labeltype = par.layout().labeltype;
3819 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3822 // this will hold the lowest depth encountered up to now.
3823 depth_type min_depth = getDepth(it);
3824 ParIterator prev_it = it;
3827 --prev_it.top().pit();
3829 // start of nested inset: go to outer par
3831 if (prev_it.empty()) {
3832 // start of document: nothing to do
3837 // We search for the first paragraph with same label
3838 // that is not more deeply nested.
3839 Paragraph & prev_par = *prev_it;
3840 depth_type const prev_depth = getDepth(prev_it);
3841 if (labeltype == prev_par.layout().labeltype) {
3842 if (prev_depth < min_depth)
3843 return prev_par.itemdepth + 1;
3844 if (prev_depth == min_depth)
3845 return prev_par.itemdepth;
3847 min_depth = min(min_depth, prev_depth);
3848 // small optimization: if we are at depth 0, we won't
3849 // find anything else
3850 if (prev_depth == 0)
3856 static bool needEnumCounterReset(ParIterator const & it)
3858 Paragraph const & par = *it;
3859 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3860 depth_type const cur_depth = par.getDepth();
3861 ParIterator prev_it = it;
3862 while (prev_it.pit()) {
3863 --prev_it.top().pit();
3864 Paragraph const & prev_par = *prev_it;
3865 if (prev_par.getDepth() <= cur_depth)
3866 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3868 // start of nested inset: reset
3873 // set the label of a paragraph. This includes the counters.
3874 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3876 BufferParams const & bp = owner_->masterBuffer()->params();
3877 DocumentClass const & textclass = bp.documentClass();
3878 Paragraph & par = it.paragraph();
3879 Layout const & layout = par.layout();
3880 Counters & counters = textclass.counters();
3882 if (par.params().startOfAppendix()) {
3883 // FIXME: only the counter corresponding to toplevel
3884 // sectioning should be reset
3886 counters.appendix(true);
3888 par.params().appendix(counters.appendix());
3890 // Compute the item depth of the paragraph
3891 par.itemdepth = getItemDepth(it);
3893 if (layout.margintype == MARGIN_MANUAL
3894 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3895 if (par.params().labelWidthString().empty())
3896 par.params().labelWidthString(par.expandLabel(layout, bp));
3898 par.params().labelWidthString(docstring());
3901 switch(layout.labeltype) {
3903 if (layout.toclevel <= bp.secnumdepth
3904 && (layout.latextype != LATEX_ENVIRONMENT
3905 || it.text()->isFirstInSequence(it.pit()))) {
3906 counters.step(layout.counter, utype);
3907 par.params().labelString(
3908 par.expandLabel(layout, bp));
3910 par.params().labelString(docstring());
3913 case LABEL_ITEMIZE: {
3914 // At some point of time we should do something more
3915 // clever here, like:
3916 // par.params().labelString(
3917 // bp.user_defined_bullet(par.itemdepth).getText());
3918 // for now, use a simple hardcoded label
3919 docstring itemlabel;
3920 switch (par.itemdepth) {
3922 itemlabel = char_type(0x2022);
3925 itemlabel = char_type(0x2013);
3928 itemlabel = char_type(0x2217);
3931 itemlabel = char_type(0x2219); // or 0x00b7
3934 par.params().labelString(itemlabel);
3938 case LABEL_ENUMERATE: {
3939 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3941 switch (par.itemdepth) {
3950 enumcounter += "iv";
3953 // not a valid enumdepth...
3957 // Maybe we have to reset the enumeration counter.
3958 if (needEnumCounterReset(it))
3959 counters.reset(enumcounter);
3960 counters.step(enumcounter, utype);
3962 string const & lang = par.getParLanguage(bp)->code();
3963 par.params().labelString(counters.theCounter(enumcounter, lang));
3968 case LABEL_SENSITIVE: {
3969 string const & type = counters.current_float();
3970 docstring full_label;
3972 full_label = owner_->B_("Senseless!!! ");
3974 docstring name = owner_->B_(textclass.floats().getType(type).name());
3975 if (counters.hasCounter(from_utf8(type))) {
3976 string const & lang = par.getParLanguage(bp)->code();
3977 counters.step(from_utf8(type), utype);
3978 full_label = bformat(from_ascii("%1$s %2$s:"),
3980 counters.theCounter(from_utf8(type), lang));
3982 full_label = bformat(from_ascii("%1$s #:"), name);
3984 par.params().labelString(full_label);
3988 case LABEL_NO_LABEL:
3989 par.params().labelString(docstring());
3993 case LABEL_TOP_ENVIRONMENT:
3994 case LABEL_CENTERED_TOP_ENVIRONMENT:
3997 par.params().labelString(par.expandLabel(layout, bp));
4003 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4005 LASSERT(parit.pit() == 0, /**/);
4007 // Set the position of the text in the buffer to be able
4008 // to resolve macros in it.
4009 parit.text()->setMacrocontextPosition(parit);
4011 depth_type maxdepth = 0;
4012 pit_type const lastpit = parit.lastpit();
4013 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4014 // reduce depth if necessary
4015 parit->params().depth(min(parit->params().depth(), maxdepth));
4016 maxdepth = parit->getMaxDepthAfter();
4018 if (utype == OutputUpdate) {
4019 // track the active counters
4020 // we have to do this for the master buffer, since the local
4021 // buffer isn't tracking anything.
4022 masterBuffer()->params().documentClass().counters().
4023 setActiveLayout(parit->layout());
4026 // set the counter for this paragraph
4027 d->setLabel(parit, utype);
4030 InsetList::const_iterator iit = parit->insetList().begin();
4031 InsetList::const_iterator end = parit->insetList().end();
4032 for (; iit != end; ++iit) {
4033 parit.pos() = iit->pos;
4034 iit->inset->updateBuffer(parit, utype);
4040 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4041 WordLangTuple & word_lang, docstring_list & suggestions) const
4045 suggestions.clear();
4046 word_lang = WordLangTuple();
4047 // OK, we start from here.
4048 DocIterator const end = doc_iterator_end(this);
4049 for (; from != end; from.forwardPos()) {
4050 // We are only interested in text so remove the math CursorSlice.
4051 while (from.inMathed()) {
4055 // If from is at the end of the document (which is possible
4056 // when leaving the mathed) LyX will crash later.
4060 from.paragraph().spellCheck();
4061 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4062 if (SpellChecker::misspelled(res)) {
4067 // Do not increase progress when from == to, otherwise the word
4068 // count will be wrong.
4078 bool Buffer::reload()
4082 removeAutosaveFile();
4083 // e.g., read-only status could have changed due to version control
4084 d->filename.refresh();
4085 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4087 bool const success = (loadLyXFile(d->filename) == ReadSuccess);
4093 saveCheckSum(d->filename);
4094 message(bformat(_("Document %1$s reloaded."), disp_fn));
4096 message(bformat(_("Could not reload document %1$s."), disp_fn));
4099 thePreviews().removeLoader(*this);
4100 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
4101 thePreviews().generateBufferPreviews(*this);
4107 // FIXME We could do better here, but it is complicated. What would be
4108 // nice is to offer either (a) to save the child buffer to an appropriate
4109 // location, so that it would "move with the master", or else (b) to update
4110 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4111 // complicated, because the code for this lives in GuiView.
4112 void Buffer::checkChildBuffers()
4114 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4115 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4116 for (; it != en; ++it) {
4117 DocIterator dit = it->second;
4118 Buffer * cbuf = const_cast<Buffer *>(it->first);
4119 if (!cbuf || !theBufferList().isLoaded(cbuf))
4121 Inset * inset = dit.nextInset();
4122 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4123 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4124 docstring const & incfile = inset_inc->getParam("filename");
4125 string oldloc = cbuf->absFileName();
4126 string newloc = makeAbsPath(to_utf8(incfile),
4127 onlyPath(absFileName())).absFileName();
4128 if (oldloc == newloc)
4130 // the location of the child file is incorrect.
4131 Alert::warning(_("Included File Invalid"),
4132 bformat(_("Saving this document to a new location has made the file:\n"
4134 "inaccessible. You will need to update the included filename."),
4135 from_utf8(oldloc)));
4137 inset_inc->setChildBuffer(0);
4139 // invalidate cache of children
4140 d->children_positions.clear();
4141 d->position_to_children.clear();