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"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 376; // jspitzm: support for unincluded file maintenance
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
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 void collectRelatives(BufferSet & bufs) const;
173 /** If we have branches that use the file suffix
174 feature, return the file name with suffix appended.
176 support::FileName exportFileName() const;
183 mutable TexRow texrow;
185 /// need to regenerate .tex?
189 mutable bool lyx_clean;
191 /// is autosave needed?
192 mutable bool bak_clean;
194 /// is this a unnamed file (New...)?
200 /// name of the file the buffer is associated with.
203 /** Set to true only when the file is fully loaded.
204 * Used to prevent the premature generation of previews
205 * and by the citation inset.
207 bool file_fully_loaded;
210 mutable TocBackend toc_backend;
213 typedef pair<DocIterator, MacroData> ScopeMacro;
214 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
215 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
216 /// map from the macro name to the position map,
217 /// which maps the macro definition position to the scope and the MacroData.
218 NamePositionScopeMacroMap macros;
219 /// This seem to change the way Buffer::getMacro() works
220 mutable bool macro_lock;
222 /// positions of child buffers in the buffer
223 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
224 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
225 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
226 /// position of children buffers in this buffer
227 BufferPositionMap children_positions;
228 /// map from children inclusion positions to their scope and their buffer
229 PositionScopeBufferMap position_to_children;
231 /// Container for all sort of Buffer dependant errors.
232 map<string, ErrorList> errorLists;
234 /// timestamp and checksum used to test if the file has been externally
235 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
237 unsigned long checksum_;
240 frontend::WorkAreaManager * wa_;
242 frontend::GuiBufferDelegate * gui_;
247 /// A cache for the bibfiles (including bibfiles of loaded child
248 /// documents), needed for appropriate update of natbib labels.
249 mutable support::FileNameList bibfiles_cache_;
251 // FIXME The caching mechanism could be improved. At present, we have a
252 // cache for each Buffer, that caches all the bibliography info for that
253 // Buffer. A more efficient solution would be to have a global cache per
254 // file, and then to construct the Buffer's bibinfo from that.
255 /// A cache for bibliography info
256 mutable BiblioInfo bibinfo_;
257 /// whether the bibinfo cache is valid
258 bool bibinfo_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;
281 void setParent(Buffer const * pb) {
282 if (parent_buffer && pb && parent_buffer != pb)
283 LYXERR0("Warning: a buffer should not have two parents!");
287 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
288 /// This one is useful for preview detached in a thread.
289 Buffer const * cloned_buffer_;
292 /// So we can force access via the accessors.
293 mutable Buffer const * parent_buffer;
298 /// Creates the per buffer temporary directory
299 static FileName createBufferTmpDir()
302 // We are in our own directory. Why bother to mangle name?
303 // In fact I wrote this code to circumvent a problematic behaviour
304 // (bug?) of EMX mkstemp().
305 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
306 convert<string>(count++));
308 if (!tmpfl.createDirectory(0777)) {
309 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
310 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
311 from_utf8(tmpfl.absFilename())));
317 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
318 Buffer const * cloned_buffer)
319 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
320 read_only(readonly_), filename(file), file_fully_loaded(false),
321 toc_backend(owner), macro_lock(false), timestamp_(0),
322 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
323 cloned_buffer_(cloned_buffer), parent_buffer(0)
325 if (!cloned_buffer_) {
326 temppath = createBufferTmpDir();
327 lyxvc.setBuffer(owner_);
329 wa_ = new frontend::WorkAreaManager;
332 temppath = cloned_buffer_->d->temppath;
333 file_fully_loaded = true;
334 params = cloned_buffer_->d->params;
335 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
336 bibinfo_ = cloned_buffer_->d->bibinfo_;
337 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
338 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
342 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
343 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
345 LYXERR(Debug::INFO, "Buffer::Buffer()");
347 d->inset = new InsetText(*cloned_buffer->d->inset);
348 d->inset->setBuffer(*this);
349 // FIXME: optimize this loop somewhat, maybe by creating a new
350 // general recursive Inset::setId().
351 DocIterator it = doc_iterator_begin(this);
352 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
353 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
354 it.paragraph().setId(cloned_it.paragraph().id());
356 d->inset = new InsetText(this);
357 d->inset->setAutoBreakRows(true);
358 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
364 LYXERR(Debug::INFO, "Buffer::~Buffer()");
365 // here the buffer should take care that it is
366 // saved properly, before it goes into the void.
368 // GuiView already destroyed
372 // No need to do additional cleanups for internal buffer.
377 // loop over children
378 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
379 Impl::BufferPositionMap::iterator end = d->children_positions.end();
380 for (; it != end; ++it) {
381 Buffer * child = const_cast<Buffer *>(it->first);
382 if (d->cloned_buffer_)
384 // The child buffer might have been closed already.
385 else if (theBufferList().isLoaded(child))
386 theBufferList().releaseChild(this, child);
390 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
391 msg += emergencyWrite();
392 Alert::warning(_("Attempting to close changed document!"), msg);
395 // clear references to children in macro tables
396 d->children_positions.clear();
397 d->position_to_children.clear();
399 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
400 Alert::warning(_("Could not remove temporary directory"),
401 bformat(_("Could not remove the temporary directory %1$s"),
402 from_utf8(d->temppath.absFilename())));
405 // Remove any previewed LaTeX snippets associated with this buffer.
406 thePreviews().removeLoader(*this);
412 Buffer * Buffer::clone() const
414 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
415 buffer_clone->d->macro_lock = true;
416 buffer_clone->d->children_positions.clear();
417 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
418 // math macro caches need to be rethought and simplified.
419 // I am not sure wether we should handle Buffer cloning here or in BufferList.
420 // Right now BufferList knows nothing about buffer clones.
421 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
422 Impl::BufferPositionMap::iterator end = d->children_positions.end();
423 for (; it != end; ++it) {
424 DocIterator dit = it->second.clone(buffer_clone);
425 dit.setBuffer(buffer_clone);
426 Buffer * child = const_cast<Buffer *>(it->first);
427 Buffer * child_clone = child->clone();
428 Inset * inset = dit.nextInset();
429 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
430 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
431 inset_inc->setChildBuffer(child_clone);
432 child_clone->d->setParent(buffer_clone);
433 buffer_clone->setChild(dit, child_clone);
435 buffer_clone->d->macro_lock = false;
440 bool Buffer::isClone() const
442 return d->cloned_buffer_;
446 void Buffer::changed(bool update_metrics) const
449 d->wa_->redrawAll(update_metrics);
453 frontend::WorkAreaManager & Buffer::workAreaManager() const
455 LASSERT(d->wa_, /**/);
460 Text & Buffer::text() const
462 return d->inset->text();
466 Inset & Buffer::inset() const
472 BufferParams & Buffer::params()
478 BufferParams const & Buffer::params() const
484 ParagraphList & Buffer::paragraphs()
486 return text().paragraphs();
490 ParagraphList const & Buffer::paragraphs() const
492 return text().paragraphs();
496 LyXVC & Buffer::lyxvc()
502 LyXVC const & Buffer::lyxvc() const
508 string const Buffer::temppath() const
510 return d->temppath.absFilename();
514 TexRow & Buffer::texrow()
520 TexRow const & Buffer::texrow() const
526 TocBackend & Buffer::tocBackend() const
528 return d->toc_backend;
532 Undo & Buffer::undo()
538 void Buffer::setChild(DocIterator const & dit, Buffer * child)
540 d->children_positions[child] = dit;
544 string Buffer::latexName(bool const no_path) const
546 FileName latex_name =
547 makeLatexName(d->exportFileName());
548 return no_path ? latex_name.onlyFileName()
549 : latex_name.absFilename();
553 FileName Buffer::Impl::exportFileName() const
555 docstring const branch_suffix =
556 params.branchlist().getFilenameSuffix();
557 if (branch_suffix.empty())
560 string const name = filename.onlyFileNameWithoutExt()
561 + to_utf8(branch_suffix);
562 FileName res(filename.onlyPath().absFilename() + "/" + name);
563 res.changeExtension(filename.extension());
569 string Buffer::logName(LogType * type) const
571 string const filename = latexName(false);
573 if (filename.empty()) {
579 string const path = temppath();
581 FileName const fname(addName(temppath(),
582 onlyFilename(changeExtension(filename,
585 // FIXME: how do we know this is the name of the build log?
586 FileName const bname(
587 addName(path, onlyFilename(
588 changeExtension(filename,
589 formats.extension(bufferFormat()) + ".out"))));
591 // Also consider the master buffer log file
592 FileName masterfname = fname;
594 if (masterBuffer() != this) {
595 string const mlogfile = masterBuffer()->logName(&mtype);
596 masterfname = FileName(mlogfile);
599 // If no Latex log or Build log is newer, show Build log
600 if (bname.exists() &&
601 ((!fname.exists() && !masterfname.exists())
602 || (fname.lastModified() < bname.lastModified()
603 && masterfname.lastModified() < bname.lastModified()))) {
604 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
607 return bname.absFilename();
608 // If we have a newer master file log or only a master log, show this
609 } else if (fname != masterfname
610 && (!fname.exists() && (masterfname.exists()
611 || fname.lastModified() < masterfname.lastModified()))) {
612 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
615 return masterfname.absFilename();
617 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
620 return fname.absFilename();
624 void Buffer::setReadonly(bool const flag)
626 if (d->read_only != flag) {
633 void Buffer::setFileName(string const & newfile)
635 d->filename = makeAbsPath(newfile);
636 setReadonly(d->filename.isReadOnly());
641 int Buffer::readHeader(Lexer & lex)
643 int unknown_tokens = 0;
645 int begin_header_line = -1;
647 // Initialize parameters that may be/go lacking in header:
648 params().branchlist().clear();
649 params().preamble.erase();
650 params().options.erase();
651 params().master.erase();
652 params().float_placement.erase();
653 params().paperwidth.erase();
654 params().paperheight.erase();
655 params().leftmargin.erase();
656 params().rightmargin.erase();
657 params().topmargin.erase();
658 params().bottommargin.erase();
659 params().headheight.erase();
660 params().headsep.erase();
661 params().footskip.erase();
662 params().columnsep.erase();
663 params().fontsCJK.erase();
664 params().listings_params.clear();
665 params().clearLayoutModules();
666 params().clearRemovedModules();
667 params().clearIncludedChildren();
668 params().pdfoptions().clear();
669 params().indiceslist().clear();
670 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
672 for (int i = 0; i < 4; ++i) {
673 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
674 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
677 ErrorList & errorList = d->errorLists["Parse"];
686 if (token == "\\end_header")
690 if (token == "\\begin_header") {
691 begin_header_line = line;
695 LYXERR(Debug::PARSER, "Handling document header token: `"
698 string unknown = params().readToken(lex, token, d->filename.onlyPath());
699 if (!unknown.empty()) {
700 if (unknown[0] != '\\' && token == "\\textclass") {
701 Alert::warning(_("Unknown document class"),
702 bformat(_("Using the default document class, because the "
703 "class %1$s is unknown."), from_utf8(unknown)));
706 docstring const s = bformat(_("Unknown token: "
710 errorList.push_back(ErrorItem(_("Document header error"),
715 if (begin_header_line) {
716 docstring const s = _("\\begin_header is missing");
717 errorList.push_back(ErrorItem(_("Document header error"),
721 params().makeDocumentClass();
723 return unknown_tokens;
728 // changed to be public and have one parameter
729 // Returns true if "\end_document" is not read (Asger)
730 bool Buffer::readDocument(Lexer & lex)
732 ErrorList & errorList = d->errorLists["Parse"];
735 if (!lex.checkFor("\\begin_document")) {
736 docstring const s = _("\\begin_document is missing");
737 errorList.push_back(ErrorItem(_("Document header error"),
741 // we are reading in a brand new document
742 LASSERT(paragraphs().empty(), /**/);
746 if (params().outputChanges) {
747 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
748 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
749 LaTeXFeatures::isAvailable("xcolor");
751 if (!dvipost && !xcolorulem) {
752 Alert::warning(_("Changes not shown in LaTeX output"),
753 _("Changes will not be highlighted in LaTeX output, "
754 "because neither dvipost nor xcolor/ulem are installed.\n"
755 "Please install these packages or redefine "
756 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
757 } else if (!xcolorulem) {
758 Alert::warning(_("Changes not shown in LaTeX output"),
759 _("Changes will not be highlighted in LaTeX output "
760 "when using pdflatex, because xcolor and ulem are not installed.\n"
761 "Please install both packages or redefine "
762 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
766 if (!params().master.empty()) {
767 FileName const master_file = makeAbsPath(params().master,
768 onlyPath(absFileName()));
769 if (isLyXFilename(master_file.absFilename())) {
771 checkAndLoadLyXFile(master_file, true);
773 // necessary e.g. after a reload
774 // to re-register the child (bug 5873)
775 // FIXME: clean up updateMacros (here, only
776 // child registering is needed).
777 master->updateMacros();
778 // set master as master buffer, but only
779 // if we are a real child
780 if (master->isChild(this))
782 // if the master is not fully loaded
783 // it is probably just loading this
784 // child. No warning needed then.
785 else if (master->isFullyLoaded())
786 LYXERR0("The master '"
788 << "' assigned to this document ("
790 << ") does not include "
791 "this document. Ignoring the master assignment.");
796 // assure we have a default index
797 params().indiceslist().addDefault(B_("Index"));
800 bool const res = text().read(lex, errorList, d->inset);
804 updateMacroInstances();
809 bool Buffer::readString(string const & s)
811 params().compressed = false;
813 // remove dummy empty par
814 paragraphs().clear();
818 FileName const name = FileName::tempName("Buffer_readString");
819 switch (readFile(lex, name, true)) {
823 // We need to call lyx2lyx, so write the input to a file
824 ofstream os(name.toFilesystemEncoding().c_str());
827 return readFile(name);
837 bool Buffer::readFile(FileName const & filename)
839 FileName fname(filename);
841 params().compressed = fname.isZippedFile();
843 // remove dummy empty par
844 paragraphs().clear();
847 if (readFile(lex, fname) != success)
854 bool Buffer::isFullyLoaded() const
856 return d->file_fully_loaded;
860 void Buffer::setFullyLoaded(bool value)
862 d->file_fully_loaded = value;
866 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
869 LASSERT(!filename.empty(), /**/);
871 // the first (non-comment) token _must_ be...
872 if (!lex.checkFor("\\lyxformat")) {
873 Alert::error(_("Document format failure"),
874 bformat(_("%1$s is not a readable LyX document."),
875 from_utf8(filename.absFilename())));
881 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
882 // if present remove ".," from string.
883 size_t dot = tmp_format.find_first_of(".,");
884 //lyxerr << " dot found at " << dot << endl;
885 if (dot != string::npos)
886 tmp_format.erase(dot, 1);
887 int const file_format = convert<int>(tmp_format);
888 //lyxerr << "format: " << file_format << endl;
890 // save timestamp and checksum of the original disk file, making sure
891 // to not overwrite them with those of the file created in the tempdir
892 // when it has to be converted to the current format.
894 // Save the timestamp and checksum of disk file. If filename is an
895 // emergency file, save the timestamp and checksum of the original lyx file
896 // because isExternallyModified will check for this file. (BUG4193)
897 string diskfile = filename.absFilename();
898 if (suffixIs(diskfile, ".emergency"))
899 diskfile = diskfile.substr(0, diskfile.size() - 10);
900 saveCheckSum(FileName(diskfile));
903 if (file_format != LYX_FORMAT) {
906 // lyx2lyx would fail
909 FileName const tmpfile = FileName::tempName("Buffer_readFile");
910 if (tmpfile.empty()) {
911 Alert::error(_("Conversion failed"),
912 bformat(_("%1$s is from a different"
913 " version of LyX, but a temporary"
914 " file for converting it could"
916 from_utf8(filename.absFilename())));
919 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
920 if (lyx2lyx.empty()) {
921 Alert::error(_("Conversion script not found"),
922 bformat(_("%1$s is from a different"
923 " version of LyX, but the"
924 " conversion script lyx2lyx"
925 " could not be found."),
926 from_utf8(filename.absFilename())));
929 ostringstream command;
930 command << os::python()
931 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
932 << " -t " << convert<string>(LYX_FORMAT)
933 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
934 << ' ' << quoteName(filename.toFilesystemEncoding());
935 string const command_str = command.str();
937 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
939 cmd_ret const ret = runCommand(command_str);
940 if (ret.first != 0) {
941 if (file_format < LYX_FORMAT)
942 Alert::error(_("Conversion script failed"),
943 bformat(_("%1$s is from an older version"
944 " of LyX, but the lyx2lyx script"
945 " failed to convert it."),
946 from_utf8(filename.absFilename())));
948 Alert::error(_("Conversion script failed"),
949 bformat(_("%1$s is from a newer version"
950 " of LyX and cannot be converted by the"
952 from_utf8(filename.absFilename())));
955 bool const ret = readFile(tmpfile);
956 // Do stuff with tmpfile name and buffer name here.
957 return ret ? success : failure;
962 if (readDocument(lex)) {
963 Alert::error(_("Document format failure"),
964 bformat(_("%1$s ended unexpectedly, which means"
965 " that it is probably corrupted."),
966 from_utf8(filename.absFilename())));
970 d->file_fully_loaded = true;
975 // Should probably be moved to somewhere else: BufferView? LyXView?
976 bool Buffer::save() const
978 // We don't need autosaves in the immediate future. (Asger)
979 resetAutosaveTimers();
981 string const encodedFilename = d->filename.toFilesystemEncoding();
984 bool madeBackup = false;
986 // make a backup if the file already exists
987 if (lyxrc.make_backup && fileName().exists()) {
988 backupName = FileName(absFileName() + '~');
989 if (!lyxrc.backupdir_path.empty()) {
990 string const mangledName =
991 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
992 backupName = FileName(addName(lyxrc.backupdir_path,
995 if (fileName().copyTo(backupName)) {
998 Alert::error(_("Backup failure"),
999 bformat(_("Cannot create backup file %1$s.\n"
1000 "Please check whether the directory exists and is writeable."),
1001 from_utf8(backupName.absFilename())));
1002 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1006 // ask if the disk file has been externally modified (use checksum method)
1007 if (fileName().exists() && isExternallyModified(checksum_method)) {
1008 docstring const file = makeDisplayPath(absFileName(), 20);
1009 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1010 "you want to overwrite this file?"), file);
1011 int const ret = Alert::prompt(_("Overwrite modified file?"),
1012 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1017 if (writeFile(d->filename)) {
1021 // Saving failed, so backup is not backup
1023 backupName.moveTo(d->filename);
1029 bool Buffer::writeFile(FileName const & fname) const
1031 if (d->read_only && fname == d->filename)
1034 bool retval = false;
1036 docstring const str = bformat(_("Saving document %1$s..."),
1037 makeDisplayPath(fname.absFilename()));
1040 if (params().compressed) {
1041 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1042 retval = ofs && write(ofs);
1044 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1045 retval = ofs && write(ofs);
1049 message(str + _(" could not write file!"));
1053 removeAutosaveFile();
1055 saveCheckSum(d->filename);
1056 message(str + _(" done."));
1062 docstring Buffer::emergencyWrite()
1064 // No need to save if the buffer has not changed.
1068 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1070 docstring user_message = bformat(
1071 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1073 // We try to save three places:
1074 // 1) Same place as document. Unless it is an unnamed doc.
1076 string s = absFileName();
1079 if (writeFile(FileName(s))) {
1081 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1082 return user_message;
1084 user_message += _(" Save failed! Trying again...\n");
1088 // 2) In HOME directory.
1089 string s = addName(package().home_dir().absFilename(), absFileName());
1091 lyxerr << ' ' << s << endl;
1092 if (writeFile(FileName(s))) {
1094 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1095 return user_message;
1098 user_message += _(" Save failed! Trying yet again...\n");
1100 // 3) In "/tmp" directory.
1101 // MakeAbsPath to prepend the current
1102 // drive letter on OS/2
1103 s = addName(package().temp_dir().absFilename(), absFileName());
1105 lyxerr << ' ' << s << endl;
1106 if (writeFile(FileName(s))) {
1108 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1109 return user_message;
1112 user_message += _(" Save failed! Bummer. Document is lost.");
1115 return user_message;
1119 bool Buffer::write(ostream & ofs) const
1121 // Do not try to save the buffer if it is for some
1122 // reason not fully loaded.
1123 if (!d->file_fully_loaded) {
1124 LYXERR0("WARNING: file was not fully loaded when trying to save.");
1125 LASSERT(d->file_fully_loaded, return false);
1129 // Use the standard "C" locale for file output.
1130 ofs.imbue(locale::classic());
1133 // The top of the file should not be written by params().
1135 // write out a comment in the top of the file
1136 ofs << "#LyX " << lyx_version
1137 << " created this file. For more info see http://www.lyx.org/\n"
1138 << "\\lyxformat " << LYX_FORMAT << "\n"
1139 << "\\begin_document\n";
1141 /// For each author, set 'used' to true if there is a change
1142 /// by this author in the document; otherwise set it to 'false'.
1143 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1144 AuthorList::Authors::const_iterator a_end = params().authors().end();
1145 for (; a_it != a_end; ++a_it)
1146 a_it->setUsed(false);
1148 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1149 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1150 for ( ; it != end; ++it)
1151 it->checkAuthors(params().authors());
1153 // now write out the buffer parameters.
1154 ofs << "\\begin_header\n";
1155 params().writeFile(ofs);
1156 ofs << "\\end_header\n";
1159 ofs << "\n\\begin_body\n";
1161 ofs << "\n\\end_body\n";
1163 // Write marker that shows file is complete
1164 ofs << "\\end_document" << endl;
1166 // Shouldn't really be needed....
1169 // how to check if close went ok?
1170 // Following is an attempt... (BE 20001011)
1172 // good() returns false if any error occured, including some
1173 // formatting error.
1174 // bad() returns true if something bad happened in the buffer,
1175 // which should include file system full errors.
1180 lyxerr << "File was not closed properly." << endl;
1187 bool Buffer::makeLaTeXFile(FileName const & fname,
1188 string const & original_path,
1189 OutputParams const & runparams_in,
1190 bool output_preamble, bool output_body) const
1192 OutputParams runparams = runparams_in;
1193 if (params().useXetex)
1194 runparams.flavor = OutputParams::XETEX;
1196 string const encoding = runparams.encoding->iconvName();
1197 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1200 try { ofs.reset(encoding); }
1201 catch (iconv_codecvt_facet_exception & e) {
1202 lyxerr << "Caught iconv exception: " << e.what() << endl;
1203 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1204 "verify that the support software for your encoding (%1$s) is "
1205 "properly installed"), from_ascii(encoding)));
1208 if (!openFileWrite(ofs, fname))
1211 //TexStream ts(ofs.rdbuf(), &texrow());
1212 ErrorList & errorList = d->errorLists["Export"];
1214 bool failed_export = false;
1217 writeLaTeXSource(ofs, original_path,
1218 runparams, output_preamble, output_body);
1220 catch (EncodingException & e) {
1221 odocstringstream ods;
1222 ods.put(e.failed_char);
1224 oss << "0x" << hex << e.failed_char << dec;
1225 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1226 " (code point %2$s)"),
1227 ods.str(), from_utf8(oss.str()));
1228 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1229 "representable in the chosen encoding.\n"
1230 "Changing the document encoding to utf8 could help."),
1231 e.par_id, e.pos, e.pos + 1));
1232 failed_export = true;
1234 catch (iconv_codecvt_facet_exception & e) {
1235 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1236 _(e.what()), -1, 0, 0));
1237 failed_export = true;
1239 catch (exception const & e) {
1240 errorList.push_back(ErrorItem(_("conversion failed"),
1241 _(e.what()), -1, 0, 0));
1242 failed_export = true;
1245 lyxerr << "Caught some really weird exception..." << endl;
1251 failed_export = true;
1252 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1256 return !failed_export;
1260 void Buffer::writeLaTeXSource(odocstream & os,
1261 string const & original_path,
1262 OutputParams const & runparams_in,
1263 bool const output_preamble, bool const output_body) const
1265 // The child documents, if any, shall be already loaded at this point.
1267 OutputParams runparams = runparams_in;
1269 // Classify the unicode characters appearing in math insets
1270 Encodings::initUnicodeMath(*this);
1272 // validate the buffer.
1273 LYXERR(Debug::LATEX, " Validating buffer...");
1274 LaTeXFeatures features(*this, params(), runparams);
1276 LYXERR(Debug::LATEX, " Buffer validation done.");
1278 // The starting paragraph of the coming rows is the
1279 // first paragraph of the document. (Asger)
1280 if (output_preamble && runparams.nice) {
1281 os << "%% LyX " << lyx_version << " created this file. "
1282 "For more info, see http://www.lyx.org/.\n"
1283 "%% Do not edit unless you really know what "
1285 d->texrow.newline();
1286 d->texrow.newline();
1288 LYXERR(Debug::INFO, "lyx document header finished");
1290 // Don't move this behind the parent_buffer=0 code below,
1291 // because then the macros will not get the right "redefinition"
1292 // flag as they don't see the parent macros which are output before.
1295 // fold macros if possible, still with parent buffer as the
1296 // macros will be put in the prefix anyway.
1297 updateMacroInstances();
1299 // There are a few differences between nice LaTeX and usual files:
1300 // usual is \batchmode and has a
1301 // special input@path to allow the including of figures
1302 // with either \input or \includegraphics (what figinsets do).
1303 // input@path is set when the actual parameter
1304 // original_path is set. This is done for usual tex-file, but not
1305 // for nice-latex-file. (Matthias 250696)
1306 // Note that input@path is only needed for something the user does
1307 // in the preamble, included .tex files or ERT, files included by
1308 // LyX work without it.
1309 if (output_preamble) {
1310 if (!runparams.nice) {
1311 // code for usual, NOT nice-latex-file
1312 os << "\\batchmode\n"; // changed
1313 // from \nonstopmode
1314 d->texrow.newline();
1316 if (!original_path.empty()) {
1318 // We don't know the encoding of inputpath
1319 docstring const inputpath = from_utf8(latex_path(original_path));
1320 os << "\\makeatletter\n"
1321 << "\\def\\input@path{{"
1322 << inputpath << "/}}\n"
1323 << "\\makeatother\n";
1324 d->texrow.newline();
1325 d->texrow.newline();
1326 d->texrow.newline();
1329 // get parent macros (if this buffer has a parent) which will be
1330 // written at the document begin further down.
1331 MacroSet parentMacros;
1332 listParentMacros(parentMacros, features);
1334 // Write the preamble
1335 runparams.use_babel = params().writeLaTeX(os, features,
1337 d->filename.onlyPath());
1339 runparams.use_japanese = features.isRequired("japanese");
1345 os << "\\begin{document}\n";
1346 d->texrow.newline();
1348 // output the parent macros
1349 MacroSet::iterator it = parentMacros.begin();
1350 MacroSet::iterator end = parentMacros.end();
1351 for (; it != end; ++it)
1352 (*it)->write(os, true);
1353 } // output_preamble
1355 d->texrow.start(paragraphs().begin()->id(), 0);
1357 LYXERR(Debug::INFO, "preamble finished, now the body.");
1359 // if we are doing a real file with body, even if this is the
1360 // child of some other buffer, let's cut the link here.
1361 // This happens for example if only a child document is printed.
1362 Buffer const * save_parent = 0;
1363 if (output_preamble) {
1364 save_parent = d->parent();
1369 latexParagraphs(*this, text(), os, d->texrow, runparams);
1371 // Restore the parenthood if needed
1372 if (output_preamble)
1373 d->setParent(save_parent);
1375 // add this just in case after all the paragraphs
1377 d->texrow.newline();
1379 if (output_preamble) {
1380 os << "\\end{document}\n";
1381 d->texrow.newline();
1382 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1384 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1386 runparams_in.encoding = runparams.encoding;
1388 // Just to be sure. (Asger)
1389 d->texrow.newline();
1391 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1392 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1396 bool Buffer::isLatex() const
1398 return params().documentClass().outputType() == LATEX;
1402 bool Buffer::isLiterate() const
1404 return params().documentClass().outputType() == LITERATE;
1408 bool Buffer::isDocBook() const
1410 return params().documentClass().outputType() == DOCBOOK;
1414 void Buffer::makeDocBookFile(FileName const & fname,
1415 OutputParams const & runparams,
1416 bool const body_only) const
1418 LYXERR(Debug::LATEX, "makeDocBookFile...");
1421 if (!openFileWrite(ofs, fname))
1424 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1428 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1432 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1433 OutputParams const & runparams,
1434 bool const only_body) const
1436 LaTeXFeatures features(*this, params(), runparams);
1441 DocumentClass const & tclass = params().documentClass();
1442 string const top_element = tclass.latexname();
1445 if (runparams.flavor == OutputParams::XML)
1446 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1449 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1452 if (! tclass.class_header().empty())
1453 os << from_ascii(tclass.class_header());
1454 else if (runparams.flavor == OutputParams::XML)
1455 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1456 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1458 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1460 docstring preamble = from_utf8(params().preamble);
1461 if (runparams.flavor != OutputParams::XML ) {
1462 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1463 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1464 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1465 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1468 string const name = runparams.nice
1469 ? changeExtension(absFileName(), ".sgml") : fname;
1470 preamble += features.getIncludedFiles(name);
1471 preamble += features.getLyXSGMLEntities();
1473 if (!preamble.empty()) {
1474 os << "\n [ " << preamble << " ]";
1479 string top = top_element;
1481 if (runparams.flavor == OutputParams::XML)
1482 top += params().language->code();
1484 top += params().language->code().substr(0, 2);
1487 if (!params().options.empty()) {
1489 top += params().options;
1492 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1493 << " file was created by LyX " << lyx_version
1494 << "\n See http://www.lyx.org/ for more information -->\n";
1496 params().documentClass().counters().reset();
1500 sgml::openTag(os, top);
1502 docbookParagraphs(text(), *this, os, runparams);
1503 sgml::closeTag(os, top_element);
1507 void Buffer::makeLyXHTMLFile(FileName const & fname,
1508 OutputParams const & runparams,
1509 bool const body_only) const
1511 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1514 if (!openFileWrite(ofs, fname))
1517 writeLyXHTMLSource(ofs, runparams, body_only);
1521 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1525 void Buffer::writeLyXHTMLSource(odocstream & os,
1526 OutputParams const & runparams,
1527 bool const only_body) const
1529 LaTeXFeatures features(*this, params(), runparams);
1531 updateLabels(UpdateMaster, OutputUpdate);
1532 checkBibInfoCache();
1533 d->bibinfo_.makeCitationLabels(*this);
1535 updateMacroInstances();
1538 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1539 os << "<!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";
1540 // FIXME Language should be set properly.
1541 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1543 // FIXME Presumably need to set this right
1544 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1545 os << "<title>" << features.htmlTitle() << "</title>\n";
1547 os << "\n<!-- Text Class Preamble -->\n"
1548 << features.getTClassHTMLPreamble()
1549 << "\n<!-- Premable Snippets -->\n"
1550 << from_utf8(features.getPreambleSnippets());
1552 os << "\n<!-- Layout-provided Styles -->\n";
1553 docstring const styleinfo = features.getTClassHTMLStyles();
1554 if (!styleinfo.empty()) {
1555 os << "<style type='text/css'>\n"
1559 os << "</head>\n<body>\n";
1563 params().documentClass().counters().reset();
1564 xhtmlParagraphs(text(), *this, xs, runparams);
1566 os << "</body>\n</html>\n";
1570 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1571 // Other flags: -wall -v0 -x
1572 int Buffer::runChktex()
1576 // get LaTeX-Filename
1577 FileName const path(temppath());
1578 string const name = addName(path.absFilename(), latexName());
1579 string const org_path = filePath();
1581 PathChanger p(path); // path to LaTeX file
1582 message(_("Running chktex..."));
1584 // Generate the LaTeX file if neccessary
1585 OutputParams runparams(¶ms().encoding());
1586 runparams.flavor = OutputParams::LATEX;
1587 runparams.nice = false;
1588 makeLaTeXFile(FileName(name), org_path, runparams);
1591 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1592 int const res = chktex.run(terr); // run chktex
1595 Alert::error(_("chktex failure"),
1596 _("Could not run chktex successfully."));
1597 } else if (res > 0) {
1598 ErrorList & errlist = d->errorLists["ChkTeX"];
1600 bufferErrors(terr, errlist);
1611 void Buffer::validate(LaTeXFeatures & features) const
1613 params().validate(features);
1617 for_each(paragraphs().begin(), paragraphs().end(),
1618 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1620 if (lyxerr.debugging(Debug::LATEX)) {
1621 features.showStruct();
1626 void Buffer::getLabelList(vector<docstring> & list) const
1628 // If this is a child document, use the parent's list instead.
1629 Buffer const * const pbuf = d->parent();
1631 pbuf->getLabelList(list);
1636 Toc & toc = d->toc_backend.toc("label");
1637 TocIterator toc_it = toc.begin();
1638 TocIterator end = toc.end();
1639 for (; toc_it != end; ++toc_it) {
1640 if (toc_it->depth() == 0)
1641 list.push_back(toc_it->str());
1646 void Buffer::updateBibfilesCache(UpdateScope scope) const
1648 // If this is a child document, use the parent's cache instead.
1649 Buffer const * const pbuf = d->parent();
1650 if (pbuf && scope != UpdateChildOnly) {
1651 pbuf->updateBibfilesCache();
1655 d->bibfiles_cache_.clear();
1656 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1657 if (it->lyxCode() == BIBTEX_CODE) {
1658 InsetBibtex const & inset =
1659 static_cast<InsetBibtex const &>(*it);
1660 support::FileNameList const bibfiles = inset.getBibFiles();
1661 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1664 } else if (it->lyxCode() == INCLUDE_CODE) {
1665 InsetInclude & inset =
1666 static_cast<InsetInclude &>(*it);
1667 inset.updateBibfilesCache();
1668 support::FileNameList const & bibfiles =
1669 inset.getBibfilesCache();
1670 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1675 // the bibinfo cache is now invalid
1676 d->bibinfo_cache_valid_ = false;
1680 void Buffer::invalidateBibinfoCache()
1682 d->bibinfo_cache_valid_ = false;
1686 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1688 // If this is a child document, use the parent's cache instead.
1689 Buffer const * const pbuf = d->parent();
1690 if (pbuf && scope != UpdateChildOnly)
1691 return pbuf->getBibfilesCache();
1693 // We update the cache when first used instead of at loading time.
1694 if (d->bibfiles_cache_.empty())
1695 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1697 return d->bibfiles_cache_;
1701 BiblioInfo const & Buffer::masterBibInfo() const
1703 // if this is a child document and the parent is already loaded
1704 // use the parent's list instead [ale990412]
1705 Buffer const * const tmp = masterBuffer();
1708 return tmp->masterBibInfo();
1709 return localBibInfo();
1713 BiblioInfo const & Buffer::localBibInfo() const
1719 void Buffer::checkBibInfoCache() const
1721 support::FileNameList const & bibfilesCache = getBibfilesCache();
1722 // compare the cached timestamps with the actual ones.
1723 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1724 support::FileNameList::const_iterator en = bibfilesCache.end();
1725 for (; ei != en; ++ ei) {
1726 time_t lastw = ei->lastModified();
1727 time_t prevw = d->bibfile_status_[*ei];
1728 if (lastw != prevw) {
1729 d->bibinfo_cache_valid_ = false;
1730 d->bibfile_status_[*ei] = lastw;
1734 if (!d->bibinfo_cache_valid_) {
1735 d->bibinfo_.clear();
1736 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1737 it->fillWithBibKeys(d->bibinfo_, it);
1738 d->bibinfo_cache_valid_ = true;
1743 bool Buffer::isDepClean(string const & name) const
1745 DepClean::const_iterator const it = d->dep_clean.find(name);
1746 if (it == d->dep_clean.end())
1752 void Buffer::markDepClean(string const & name)
1754 d->dep_clean[name] = true;
1758 bool Buffer::isExportableFormat(string const & format) const
1760 typedef vector<Format const *> Formats;
1762 formats = exportableFormats(true);
1763 Formats::const_iterator fit = formats.begin();
1764 Formats::const_iterator end = formats.end();
1765 for (; fit != end ; ++fit) {
1766 if ((*fit)->name() == format)
1773 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1776 // FIXME? if there is an Buffer LFUN that can be dispatched even
1777 // if internal, put a switch '(cmd.action)' here.
1783 switch (cmd.action) {
1785 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1786 flag.setOnOff(isReadonly());
1789 // FIXME: There is need for a command-line import.
1790 //case LFUN_BUFFER_IMPORT:
1792 case LFUN_BUFFER_AUTO_SAVE:
1795 case LFUN_BUFFER_EXPORT_CUSTOM:
1796 // FIXME: Nothing to check here?
1799 case LFUN_BUFFER_EXPORT: {
1800 docstring const arg = cmd.argument();
1801 enable = arg == "custom" || isExportable(to_utf8(arg));
1803 flag.message(bformat(
1804 _("Don't know how to export to format: %1$s"), arg));
1808 case LFUN_BUFFER_CHKTEX:
1809 enable = isLatex() && !lyxrc.chktex_command.empty();
1812 case LFUN_BUILD_PROGRAM:
1813 enable = isExportable("program");
1816 case LFUN_BRANCH_ACTIVATE:
1817 case LFUN_BRANCH_DEACTIVATE: {
1818 BranchList const & branchList = params().branchlist();
1819 docstring const branchName = cmd.argument();
1820 enable = !branchName.empty() && branchList.find(branchName);
1824 case LFUN_BRANCH_ADD:
1825 case LFUN_BRANCHES_RENAME:
1826 case LFUN_BUFFER_PRINT:
1827 // if no Buffer is present, then of course we won't be called!
1830 case LFUN_BUFFER_LANGUAGE:
1831 enable = !isReadonly();
1837 flag.setEnabled(enable);
1842 void Buffer::dispatch(string const & command, DispatchResult & result)
1844 return dispatch(lyxaction.lookupFunc(command), result);
1848 // NOTE We can end up here even if we have no GUI, because we are called
1849 // by LyX::exec to handled command-line requests. So we may need to check
1850 // whether we have a GUI or not. The boolean use_gui holds this information.
1851 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1854 // FIXME? if there is an Buffer LFUN that can be dispatched even
1855 // if internal, put a switch '(cmd.action)' here.
1856 dr.dispatched(false);
1859 string const argument = to_utf8(func.argument());
1860 // We'll set this back to false if need be.
1861 bool dispatched = true;
1862 undo().beginUndoGroup();
1864 switch (func.action) {
1865 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1866 if (lyxvc().inUse())
1867 lyxvc().toggleReadOnly();
1869 setReadonly(!isReadonly());
1872 case LFUN_BUFFER_EXPORT: {
1873 bool success = doExport(argument, false, false);
1874 dr.setError(success);
1876 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1881 case LFUN_BUILD_PROGRAM:
1882 doExport("program", true, false);
1885 case LFUN_BUFFER_CHKTEX:
1889 case LFUN_BUFFER_EXPORT_CUSTOM: {
1891 string command = split(argument, format_name, ' ');
1892 Format const * format = formats.getFormat(format_name);
1894 lyxerr << "Format \"" << format_name
1895 << "\" not recognized!"
1900 // The name of the file created by the conversion process
1903 // Output to filename
1904 if (format->name() == "lyx") {
1905 string const latexname = latexName(false);
1906 filename = changeExtension(latexname,
1907 format->extension());
1908 filename = addName(temppath(), filename);
1910 if (!writeFile(FileName(filename)))
1914 doExport(format_name, true, false, filename);
1917 // Substitute $$FName for filename
1918 if (!contains(command, "$$FName"))
1919 command = "( " + command + " ) < $$FName";
1920 command = subst(command, "$$FName", filename);
1922 // Execute the command in the background
1924 call.startscript(Systemcall::DontWait, command);
1928 // FIXME: There is need for a command-line import.
1930 case LFUN_BUFFER_IMPORT:
1935 case LFUN_BUFFER_AUTO_SAVE:
1939 case LFUN_BRANCH_ADD: {
1940 docstring const branch_name = func.argument();
1941 if (branch_name.empty()) {
1945 BranchList & branch_list = params().branchlist();
1946 Branch * branch = branch_list.find(branch_name);
1948 LYXERR0("Branch " << branch_name << " already exists.");
1950 docstring const msg =
1951 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1954 branch_list.add(branch_name);
1955 branch = branch_list.find(branch_name);
1956 string const x11hexname = X11hexname(branch->color());
1957 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1958 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1960 dr.update(Update::Force);
1965 case LFUN_BRANCH_ACTIVATE:
1966 case LFUN_BRANCH_DEACTIVATE: {
1967 BranchList & branchList = params().branchlist();
1968 docstring const branchName = func.argument();
1969 // the case without a branch name is handled elsewhere
1970 if (branchName.empty()) {
1974 Branch * branch = branchList.find(branchName);
1976 LYXERR0("Branch " << branchName << " does not exist.");
1978 docstring const msg =
1979 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1982 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1984 dr.update(Update::Force);
1989 case LFUN_BRANCHES_RENAME: {
1990 if (func.argument().empty())
1993 docstring const oldname = from_utf8(func.getArg(0));
1994 docstring const newname = from_utf8(func.getArg(1));
1995 InsetIterator it = inset_iterator_begin(inset());
1996 InsetIterator const end = inset_iterator_end(inset());
1997 bool success = false;
1998 for (; it != end; ++it) {
1999 if (it->lyxCode() == BRANCH_CODE) {
2000 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2001 if (ins.branch() == oldname) {
2002 undo().recordUndo(it);
2003 ins.rename(newname);
2008 if (it->lyxCode() == INCLUDE_CODE) {
2009 // get buffer of external file
2010 InsetInclude const & ins =
2011 static_cast<InsetInclude const &>(*it);
2012 Buffer * child = ins.getChildBuffer();
2015 child->dispatch(func, dr);
2020 dr.update(Update::Force);
2024 case LFUN_BUFFER_PRINT: {
2025 // we'll assume there's a problem until we succeed
2027 string target = func.getArg(0);
2028 string target_name = func.getArg(1);
2029 string command = func.getArg(2);
2032 || target_name.empty()
2033 || command.empty()) {
2034 LYXERR0("Unable to parse " << func.argument());
2035 docstring const msg =
2036 bformat(_("Unable to parse \"%1$s\""), func.argument());
2040 if (target != "printer" && target != "file") {
2041 LYXERR0("Unrecognized target \"" << target << '"');
2042 docstring const msg =
2043 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2048 bool const update_unincluded =
2049 params().maintain_unincluded_children
2050 && !params().getIncludedChildren().empty();
2051 if (!doExport("dvi", true, update_unincluded)) {
2052 showPrintError(absFileName());
2053 dr.setMessage(_("Error exporting to DVI."));
2057 // Push directory path.
2058 string const path = temppath();
2059 // Prevent the compiler from optimizing away p
2063 // there are three cases here:
2064 // 1. we print to a file
2065 // 2. we print directly to a printer
2066 // 3. we print using a spool command (print to file first)
2069 string const dviname = changeExtension(latexName(true), "dvi");
2071 if (target == "printer") {
2072 if (!lyxrc.print_spool_command.empty()) {
2073 // case 3: print using a spool
2074 string const psname = changeExtension(dviname,".ps");
2075 command += ' ' + lyxrc.print_to_file
2078 + quoteName(dviname);
2080 string command2 = lyxrc.print_spool_command + ' ';
2081 if (target_name != "default") {
2082 command2 += lyxrc.print_spool_printerprefix
2086 command2 += quoteName(psname);
2088 // If successful, then spool command
2089 res = one.startscript(Systemcall::Wait, command);
2092 // If there's no GUI, we have to wait on this command. Otherwise,
2093 // LyX deletes the temporary directory, and with it the spooled
2094 // file, before it can be printed!!
2095 Systemcall::Starttype stype = use_gui ?
2096 Systemcall::DontWait : Systemcall::Wait;
2097 res = one.startscript(stype, command2);
2100 // case 2: print directly to a printer
2101 if (target_name != "default")
2102 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2104 Systemcall::Starttype stype = use_gui ?
2105 Systemcall::DontWait : Systemcall::Wait;
2106 res = one.startscript(stype, command + quoteName(dviname));
2110 // case 1: print to a file
2111 FileName const filename(makeAbsPath(target_name, filePath()));
2112 FileName const dvifile(makeAbsPath(dviname, path));
2113 if (filename.exists()) {
2114 docstring text = bformat(
2115 _("The file %1$s already exists.\n\n"
2116 "Do you want to overwrite that file?"),
2117 makeDisplayPath(filename.absFilename()));
2118 if (Alert::prompt(_("Overwrite file?"),
2119 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2122 command += ' ' + lyxrc.print_to_file
2123 + quoteName(filename.toFilesystemEncoding())
2125 + quoteName(dvifile.toFilesystemEncoding());
2127 Systemcall::Starttype stype = use_gui ?
2128 Systemcall::DontWait : Systemcall::Wait;
2129 res = one.startscript(stype, command);
2135 dr.setMessage(_("Error running external commands."));
2136 showPrintError(absFileName());
2141 case LFUN_BUFFER_LANGUAGE: {
2142 Language const * oldL = params().language;
2143 Language const * newL = languages.getLanguage(argument);
2144 if (!newL || oldL == newL)
2146 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2147 changeLanguage(oldL, newL);
2155 dr.dispatched(dispatched);
2156 undo().endUndoGroup();
2160 void Buffer::changeLanguage(Language const * from, Language const * to)
2162 LASSERT(from, /**/);
2165 for_each(par_iterator_begin(),
2167 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2171 bool Buffer::isMultiLingual() const
2173 ParConstIterator end = par_iterator_end();
2174 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2175 if (it->isMultiLingual(params()))
2182 DocIterator Buffer::getParFromID(int const id) const
2184 Buffer * buf = const_cast<Buffer *>(this);
2186 // John says this is called with id == -1 from undo
2187 lyxerr << "getParFromID(), id: " << id << endl;
2188 return doc_iterator_end(buf);
2191 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2192 if (it.paragraph().id() == id)
2195 return doc_iterator_end(buf);
2199 bool Buffer::hasParWithID(int const id) const
2201 return !getParFromID(id).atEnd();
2205 ParIterator Buffer::par_iterator_begin()
2207 return ParIterator(doc_iterator_begin(this));
2211 ParIterator Buffer::par_iterator_end()
2213 return ParIterator(doc_iterator_end(this));
2217 ParConstIterator Buffer::par_iterator_begin() const
2219 return ParConstIterator(doc_iterator_begin(this));
2223 ParConstIterator Buffer::par_iterator_end() const
2225 return ParConstIterator(doc_iterator_end(this));
2229 Language const * Buffer::language() const
2231 return params().language;
2235 docstring const Buffer::B_(string const & l10n) const
2237 return params().B_(l10n);
2241 bool Buffer::isClean() const
2243 return d->lyx_clean;
2247 bool Buffer::isExternallyModified(CheckMethod method) const
2249 LASSERT(d->filename.exists(), /**/);
2250 // if method == timestamp, check timestamp before checksum
2251 return (method == checksum_method
2252 || d->timestamp_ != d->filename.lastModified())
2253 && d->checksum_ != d->filename.checksum();
2257 void Buffer::saveCheckSum(FileName const & file) const
2259 if (file.exists()) {
2260 d->timestamp_ = file.lastModified();
2261 d->checksum_ = file.checksum();
2263 // in the case of save to a new file.
2270 void Buffer::markClean() const
2272 if (!d->lyx_clean) {
2273 d->lyx_clean = true;
2276 // if the .lyx file has been saved, we don't need an
2278 d->bak_clean = true;
2282 void Buffer::setUnnamed(bool flag)
2288 bool Buffer::isUnnamed() const
2295 /// Don't check unnamed, here: isInternal() is used in
2296 /// newBuffer(), where the unnamed flag has not been set by anyone
2297 /// yet. Also, for an internal buffer, there should be no need for
2298 /// retrieving fileName() nor for checking if it is unnamed or not.
2299 bool Buffer::isInternal() const
2301 return fileName().extension() == "internal";
2305 void Buffer::markDirty()
2308 d->lyx_clean = false;
2311 d->bak_clean = false;
2313 DepClean::iterator it = d->dep_clean.begin();
2314 DepClean::const_iterator const end = d->dep_clean.end();
2316 for (; it != end; ++it)
2321 FileName Buffer::fileName() const
2327 string Buffer::absFileName() const
2329 return d->filename.absFilename();
2333 string Buffer::filePath() const
2335 return d->filename.onlyPath().absFilename() + "/";
2339 bool Buffer::isReadonly() const
2341 return d->read_only;
2345 void Buffer::setParent(Buffer const * buffer)
2347 // Avoids recursive include.
2348 d->setParent(buffer == this ? 0 : buffer);
2353 Buffer const * Buffer::parent() const
2359 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2361 bufs.insert(owner_);
2363 parent()->d->collectRelatives(bufs);
2365 // loop over children
2366 BufferPositionMap::const_iterator it = children_positions.begin();
2367 BufferPositionMap::const_iterator end = children_positions.end();
2368 for (; it != end; ++it)
2369 bufs.insert(const_cast<Buffer *>(it->first));
2373 std::vector<Buffer const *> Buffer::allRelatives() const
2376 d->collectRelatives(bufs);
2377 BufferSet::iterator it = bufs.begin();
2378 std::vector<Buffer const *> ret;
2379 for (; it != bufs.end(); ++it)
2385 Buffer const * Buffer::masterBuffer() const
2387 Buffer const * const pbuf = d->parent();
2391 return pbuf->masterBuffer();
2395 bool Buffer::isChild(Buffer * child) const
2397 return d->children_positions.find(child) != d->children_positions.end();
2401 DocIterator Buffer::firstChildPosition(Buffer const * child)
2403 Impl::BufferPositionMap::iterator it;
2404 it = d->children_positions.find(child);
2405 if (it == d->children_positions.end())
2406 return DocIterator(this);
2411 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2413 // loop over children
2414 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2415 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2416 for (; it != end; ++it) {
2417 Buffer * child = const_cast<Buffer *>(it->first);
2418 clist.push_back(child);
2419 if (grand_children) {
2420 // there might be grandchildren
2421 std::vector<Buffer *> glist = child->getChildren();
2422 for (vector<Buffer *>::const_iterator git = glist.begin();
2423 git != glist.end(); ++git)
2424 clist.push_back(*git);
2430 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2432 std::vector<Buffer *> v;
2433 getChildren(v, grand_children);
2438 template<typename M>
2439 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2444 typename M::const_iterator it = m.lower_bound(x);
2445 if (it == m.begin())
2453 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2454 DocIterator const & pos) const
2456 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2458 // if paragraphs have no macro context set, pos will be empty
2462 // we haven't found anything yet
2463 DocIterator bestPos = owner_->par_iterator_begin();
2464 MacroData const * bestData = 0;
2466 // find macro definitions for name
2467 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2468 if (nameIt != macros.end()) {
2469 // find last definition in front of pos or at pos itself
2470 PositionScopeMacroMap::const_iterator it
2471 = greatest_below(nameIt->second, pos);
2472 if (it != nameIt->second.end()) {
2474 // scope ends behind pos?
2475 if (pos < it->second.first) {
2476 // Looks good, remember this. If there
2477 // is no external macro behind this,
2478 // we found the right one already.
2479 bestPos = it->first;
2480 bestData = &it->second.second;
2484 // try previous macro if there is one
2485 if (it == nameIt->second.begin())
2492 // find macros in included files
2493 PositionScopeBufferMap::const_iterator it
2494 = greatest_below(position_to_children, pos);
2495 if (it == position_to_children.end())
2496 // no children before
2500 // do we know something better (i.e. later) already?
2501 if (it->first < bestPos )
2504 // scope ends behind pos?
2505 if (pos < it->second.first) {
2506 // look for macro in external file
2508 MacroData const * data
2509 = it->second.second->getMacro(name, false);
2512 bestPos = it->first;
2518 // try previous file if there is one
2519 if (it == position_to_children.begin())
2524 // return the best macro we have found
2529 MacroData const * Buffer::getMacro(docstring const & name,
2530 DocIterator const & pos, bool global) const
2535 // query buffer macros
2536 MacroData const * data = d->getBufferMacro(name, pos);
2540 // If there is a master buffer, query that
2541 Buffer const * const pbuf = d->parent();
2543 d->macro_lock = true;
2544 MacroData const * macro = pbuf->getMacro(
2545 name, *this, false);
2546 d->macro_lock = false;
2552 data = MacroTable::globalMacros().get(name);
2561 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2563 // set scope end behind the last paragraph
2564 DocIterator scope = par_iterator_begin();
2565 scope.pit() = scope.lastpit() + 1;
2567 return getMacro(name, scope, global);
2571 MacroData const * Buffer::getMacro(docstring const & name,
2572 Buffer const & child, bool global) const
2574 // look where the child buffer is included first
2575 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2576 if (it == d->children_positions.end())
2579 // check for macros at the inclusion position
2580 return getMacro(name, it->second, global);
2584 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2586 pit_type const lastpit = it.lastpit();
2588 // look for macros in each paragraph
2589 while (it.pit() <= lastpit) {
2590 Paragraph & par = it.paragraph();
2592 // iterate over the insets of the current paragraph
2593 InsetList const & insets = par.insetList();
2594 InsetList::const_iterator iit = insets.begin();
2595 InsetList::const_iterator end = insets.end();
2596 for (; iit != end; ++iit) {
2597 it.pos() = iit->pos;
2599 // is it a nested text inset?
2600 if (iit->inset->asInsetText()) {
2601 // Inset needs its own scope?
2602 InsetText const * itext = iit->inset->asInsetText();
2603 bool newScope = itext->isMacroScope();
2605 // scope which ends just behind the inset
2606 DocIterator insetScope = it;
2609 // collect macros in inset
2610 it.push_back(CursorSlice(*iit->inset));
2611 updateMacros(it, newScope ? insetScope : scope);
2616 // is it an external file?
2617 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2618 // get buffer of external file
2619 InsetInclude const & inset =
2620 static_cast<InsetInclude const &>(*iit->inset);
2622 Buffer * child = inset.getChildBuffer();
2627 // register its position, but only when it is
2628 // included first in the buffer
2629 if (children_positions.find(child) ==
2630 children_positions.end())
2631 children_positions[child] = it;
2633 // register child with its scope
2634 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2638 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2642 MathMacroTemplate & macroTemplate =
2643 static_cast<MathMacroTemplate &>(*iit->inset);
2644 MacroContext mc(owner_, it);
2645 macroTemplate.updateToContext(mc);
2648 bool valid = macroTemplate.validMacro();
2649 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2650 // then the BufferView's cursor will be invalid in
2651 // some cases which leads to crashes.
2656 // FIXME (Abdel), I don't understandt why we pass 'it' here
2657 // instead of 'macroTemplate' defined above... is this correct?
2658 macros[macroTemplate.name()][it] =
2659 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2669 void Buffer::updateMacros() const
2674 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2676 // start with empty table
2678 d->children_positions.clear();
2679 d->position_to_children.clear();
2681 // Iterate over buffer, starting with first paragraph
2682 // The scope must be bigger than any lookup DocIterator
2683 // later. For the global lookup, lastpit+1 is used, hence
2684 // we use lastpit+2 here.
2685 DocIterator it = par_iterator_begin();
2686 DocIterator outerScope = it;
2687 outerScope.pit() = outerScope.lastpit() + 2;
2688 d->updateMacros(it, outerScope);
2692 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2694 InsetIterator it = inset_iterator_begin(inset());
2695 InsetIterator const end = inset_iterator_end(inset());
2696 for (; it != end; ++it) {
2697 if (it->lyxCode() == BRANCH_CODE) {
2698 InsetBranch & br = static_cast<InsetBranch &>(*it);
2699 docstring const name = br.branch();
2700 if (!from_master && !params().branchlist().find(name))
2701 result.push_back(name);
2702 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2703 result.push_back(name);
2706 if (it->lyxCode() == INCLUDE_CODE) {
2707 // get buffer of external file
2708 InsetInclude const & ins =
2709 static_cast<InsetInclude const &>(*it);
2710 Buffer * child = ins.getChildBuffer();
2713 child->getUsedBranches(result, true);
2716 // remove duplicates
2721 void Buffer::updateMacroInstances() const
2723 LYXERR(Debug::MACROS, "updateMacroInstances for "
2724 << d->filename.onlyFileName());
2725 DocIterator it = doc_iterator_begin(this);
2727 DocIterator const end = doc_iterator_end(this);
2728 for (; it != end; it.forwardInset()) {
2729 // look for MathData cells in InsetMathNest insets
2730 InsetMath * minset = it.nextInset()->asInsetMath();
2734 // update macro in all cells of the InsetMathNest
2735 DocIterator::idx_type n = minset->nargs();
2736 MacroContext mc = MacroContext(this, it);
2737 for (DocIterator::idx_type i = 0; i < n; ++i) {
2738 MathData & data = minset->cell(i);
2739 data.updateMacros(0, mc);
2745 void Buffer::listMacroNames(MacroNameSet & macros) const
2750 d->macro_lock = true;
2752 // loop over macro names
2753 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2754 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2755 for (; nameIt != nameEnd; ++nameIt)
2756 macros.insert(nameIt->first);
2758 // loop over children
2759 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2760 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2761 for (; it != end; ++it)
2762 it->first->listMacroNames(macros);
2765 Buffer const * const pbuf = d->parent();
2767 pbuf->listMacroNames(macros);
2769 d->macro_lock = false;
2773 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2775 Buffer const * const pbuf = d->parent();
2780 pbuf->listMacroNames(names);
2783 MacroNameSet::iterator it = names.begin();
2784 MacroNameSet::iterator end = names.end();
2785 for (; it != end; ++it) {
2787 MacroData const * data =
2788 pbuf->getMacro(*it, *this, false);
2790 macros.insert(data);
2792 // we cannot access the original MathMacroTemplate anymore
2793 // here to calls validate method. So we do its work here manually.
2794 // FIXME: somehow make the template accessible here.
2795 if (data->optionals() > 0)
2796 features.require("xargs");
2802 Buffer::References & Buffer::references(docstring const & label)
2805 return const_cast<Buffer *>(masterBuffer())->references(label);
2807 RefCache::iterator it = d->ref_cache_.find(label);
2808 if (it != d->ref_cache_.end())
2809 return it->second.second;
2811 static InsetLabel const * dummy_il = 0;
2812 static References const dummy_refs;
2813 it = d->ref_cache_.insert(
2814 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2815 return it->second.second;
2819 Buffer::References const & Buffer::references(docstring const & label) const
2821 return const_cast<Buffer *>(this)->references(label);
2825 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2827 masterBuffer()->d->ref_cache_[label].first = il;
2831 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2833 return masterBuffer()->d->ref_cache_[label].first;
2837 void Buffer::clearReferenceCache() const
2840 d->ref_cache_.clear();
2844 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2847 //FIXME: This does not work for child documents yet.
2848 LASSERT(code == CITE_CODE, /**/);
2849 // Check if the label 'from' appears more than once
2850 vector<docstring> labels;
2852 checkBibInfoCache();
2853 BiblioInfo const & keys = masterBibInfo();
2854 BiblioInfo::const_iterator bit = keys.begin();
2855 BiblioInfo::const_iterator bend = keys.end();
2857 for (; bit != bend; ++bit)
2859 labels.push_back(bit->first);
2862 if (count(labels.begin(), labels.end(), from) > 1)
2865 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2866 if (it->lyxCode() == code) {
2867 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2868 docstring const oldValue = inset.getParam(paramName);
2869 if (oldValue == from)
2870 inset.setParam(paramName, to);
2876 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2877 pit_type par_end, bool full_source) const
2879 OutputParams runparams(¶ms().encoding());
2880 runparams.nice = true;
2881 runparams.flavor = params().useXetex ?
2882 OutputParams::XETEX : OutputParams::LATEX;
2883 runparams.linelen = lyxrc.plaintext_linelen;
2884 // No side effect of file copying and image conversion
2885 runparams.dryrun = true;
2888 os << "% " << _("Preview source code") << "\n\n";
2890 d->texrow.newline();
2891 d->texrow.newline();
2893 writeDocBookSource(os, absFileName(), runparams, false);
2895 // latex or literate
2896 writeLaTeXSource(os, string(), runparams, true, true);
2898 runparams.par_begin = par_begin;
2899 runparams.par_end = par_end;
2900 if (par_begin + 1 == par_end) {
2902 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2906 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2907 convert<docstring>(par_begin),
2908 convert<docstring>(par_end - 1))
2915 // output paragraphs
2917 docbookParagraphs(text(), *this, os, runparams);
2919 // latex or literate
2920 latexParagraphs(*this, text(), os, texrow, runparams);
2925 ErrorList & Buffer::errorList(string const & type) const
2927 static ErrorList emptyErrorList;
2928 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2929 if (I == d->errorLists.end())
2930 return emptyErrorList;
2936 void Buffer::updateTocItem(std::string const & type,
2937 DocIterator const & dit) const
2940 d->gui_->updateTocItem(type, dit);
2944 void Buffer::structureChanged() const
2947 d->gui_->structureChanged();
2951 void Buffer::errors(string const & err, bool from_master) const
2954 d->gui_->errors(err, from_master);
2958 void Buffer::message(docstring const & msg) const
2961 d->gui_->message(msg);
2965 void Buffer::setBusy(bool on) const
2968 d->gui_->setBusy(on);
2972 void Buffer::updateTitles() const
2975 d->wa_->updateTitles();
2979 void Buffer::resetAutosaveTimers() const
2982 d->gui_->resetAutosaveTimers();
2986 bool Buffer::hasGuiDelegate() const
2992 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3001 class AutoSaveBuffer : public ForkedProcess {
3004 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3005 : buffer_(buffer), fname_(fname) {}
3007 virtual boost::shared_ptr<ForkedProcess> clone() const
3009 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3014 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3015 from_utf8(fname_.absFilename())));
3016 return run(DontWait);
3020 virtual int generateChild();
3022 Buffer const & buffer_;
3027 int AutoSaveBuffer::generateChild()
3029 #if defined(__APPLE__)
3030 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3031 * We should use something else like threads.
3033 * Since I do not know how to determine at run time what is the OS X
3034 * version, I just disable forking altogether for now (JMarc)
3036 pid_t const pid = -1;
3038 // tmp_ret will be located (usually) in /tmp
3039 // will that be a problem?
3040 // Note that this calls ForkedCalls::fork(), so it's
3041 // ok cross-platform.
3042 pid_t const pid = fork();
3043 // If you want to debug the autosave
3044 // you should set pid to -1, and comment out the fork.
3045 if (pid != 0 && pid != -1)
3049 // pid = -1 signifies that lyx was unable
3050 // to fork. But we will do the save
3052 bool failed = false;
3053 FileName const tmp_ret = FileName::tempName("lyxauto");
3054 if (!tmp_ret.empty()) {
3055 buffer_.writeFile(tmp_ret);
3056 // assume successful write of tmp_ret
3057 if (!tmp_ret.moveTo(fname_))
3063 // failed to write/rename tmp_ret so try writing direct
3064 if (!buffer_.writeFile(fname_)) {
3065 // It is dangerous to do this in the child,
3066 // but safe in the parent, so...
3067 if (pid == -1) // emit message signal.
3068 buffer_.message(_("Autosave failed!"));
3072 if (pid == 0) // we are the child so...
3081 FileName Buffer::getAutosaveFilename() const
3083 // if the document is unnamed try to save in the backup dir, else
3084 // in the default document path, and as a last try in the filePath,
3085 // which will most often be the temporary directory
3088 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3089 : lyxrc.backupdir_path;
3090 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3093 string const fname = "#" + d->filename.onlyFileName() + "#";
3094 return makeAbsPath(fname, fpath);
3098 void Buffer::removeAutosaveFile() const
3100 FileName const f = getAutosaveFilename();
3106 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3108 FileName const newauto = getAutosaveFilename();
3109 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3110 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3114 // Perfect target for a thread...
3115 void Buffer::autoSave() const
3117 if (d->bak_clean || isReadonly()) {
3118 // We don't save now, but we'll try again later
3119 resetAutosaveTimers();
3123 // emit message signal.
3124 message(_("Autosaving current document..."));
3125 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3128 d->bak_clean = true;
3130 resetAutosaveTimers();
3134 string Buffer::bufferFormat() const
3136 string format = params().documentClass().outputFormat();
3137 if (format == "latex") {
3138 if (params().useXetex)
3140 if (params().encoding().package() == Encoding::japanese)
3147 string Buffer::getDefaultOutputFormat() const
3149 if (!params().defaultOutputFormat.empty()
3150 && params().defaultOutputFormat != "default")
3151 return params().defaultOutputFormat;
3152 typedef vector<Format const *> Formats;
3153 Formats formats = exportableFormats(true);
3156 || params().useXetex
3157 || params().encoding().package() == Encoding::japanese) {
3158 if (formats.empty())
3160 // return the first we find
3161 return formats.front()->name();
3163 return lyxrc.default_view_format;
3168 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3169 bool includeall, string & result_file) const
3171 string backend_format;
3172 OutputParams runparams(¶ms().encoding());
3173 runparams.flavor = OutputParams::LATEX;
3174 runparams.linelen = lyxrc.plaintext_linelen;
3175 runparams.includeall = includeall;
3176 vector<string> backs = backends();
3177 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3178 // Get shortest path to format
3179 Graph::EdgePath path;
3180 for (vector<string>::const_iterator it = backs.begin();
3181 it != backs.end(); ++it) {
3182 Graph::EdgePath p = theConverters().getPath(*it, format);
3183 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3184 backend_format = *it;
3189 if (!put_in_tempdir) {
3190 // Only show this alert if this is an export to a non-temporary
3191 // file (not for previewing).
3192 Alert::error(_("Couldn't export file"), bformat(
3193 _("No information for exporting the format %1$s."),
3194 formats.prettyName(format)));
3198 runparams.flavor = theConverters().getFlavor(path);
3201 backend_format = format;
3202 // FIXME: Don't hardcode format names here, but use a flag
3203 if (backend_format == "pdflatex")
3204 runparams.flavor = OutputParams::PDFLATEX;
3207 string filename = latexName(false);
3208 filename = addName(temppath(), filename);
3209 filename = changeExtension(filename,
3210 formats.extension(backend_format));
3213 updateMacroInstances();
3215 // Plain text backend
3216 if (backend_format == "text") {
3217 runparams.flavor = OutputParams::TEXT;
3218 writePlaintextFile(*this, FileName(filename), runparams);
3221 else if (backend_format == "xhtml") {
3222 runparams.flavor = OutputParams::HTML;
3223 makeLyXHTMLFile(FileName(filename), runparams);
3224 } else if (backend_format == "lyx")
3225 writeFile(FileName(filename));
3227 else if (isDocBook()) {
3228 runparams.nice = !put_in_tempdir;
3229 makeDocBookFile(FileName(filename), runparams);
3232 else if (backend_format == format) {
3233 runparams.nice = true;
3234 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3236 } else if (!lyxrc.tex_allows_spaces
3237 && contains(filePath(), ' ')) {
3238 Alert::error(_("File name error"),
3239 _("The directory path to the document cannot contain spaces."));
3242 runparams.nice = false;
3243 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3247 string const error_type = (format == "program")
3248 ? "Build" : bufferFormat();
3249 ErrorList & error_list = d->errorLists[error_type];
3250 string const ext = formats.extension(format);
3251 FileName const tmp_result_file(changeExtension(filename, ext));
3252 bool const success = theConverters().convert(this, FileName(filename),
3253 tmp_result_file, FileName(absFileName()), backend_format, format,
3255 // Emit the signal to show the error list.
3256 if (format != backend_format) {
3258 // also to the children, in case of master-buffer-view
3259 std::vector<Buffer *> clist = getChildren();
3260 for (vector<Buffer *>::const_iterator cit = clist.begin();
3261 cit != clist.end(); ++cit)
3262 (*cit)->errors(error_type, true);
3267 if (d->cloned_buffer_) {
3268 // Enable reverse dvi or pdf to work by copying back the texrow
3269 // object to the cloned buffer.
3270 // FIXME: There is a possibility of concurrent access to texrow
3271 // here from the main GUI thread that should be securized.
3272 d->cloned_buffer_->d->texrow = d->texrow;
3275 if (put_in_tempdir) {
3276 result_file = tmp_result_file.absFilename();
3280 result_file = changeExtension(d->exportFileName().absFilename(), ext);
3281 // We need to copy referenced files (e. g. included graphics
3282 // if format == "dvi") to the result dir.
3283 vector<ExportedFile> const files =
3284 runparams.exportdata->externalFiles(format);
3285 string const dest = onlyPath(result_file);
3286 CopyStatus status = SUCCESS;
3288 vector<ExportedFile>::const_iterator it = files.begin();
3289 vector<ExportedFile>::const_iterator const en = files.end();
3290 for (; it != en && status != CANCEL; ++it) {
3291 string const fmt = formats.getFormatFromFile(it->sourceName);
3292 status = copyFile(fmt, it->sourceName,
3293 makeAbsPath(it->exportName, dest),
3294 it->exportName, status == FORCE);
3297 if (status == CANCEL) {
3298 message(_("Document export cancelled."));
3299 } else if (tmp_result_file.exists()) {
3300 // Finally copy the main file
3301 status = copyFile(format, tmp_result_file,
3302 FileName(result_file), result_file,
3304 message(bformat(_("Document exported as %1$s "
3306 formats.prettyName(format),
3307 makeDisplayPath(result_file)));
3309 // This must be a dummy converter like fax (bug 1888)
3310 message(bformat(_("Document exported as %1$s"),
3311 formats.prettyName(format)));
3318 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3319 bool includeall) const
3322 // (1) export with all included children (omit \includeonly)
3323 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3325 // (2) export with included children only
3326 return doExport(format, put_in_tempdir, false, result_file);
3330 bool Buffer::preview(string const & format, bool includeall) const
3333 // (1) export with all included children (omit \includeonly)
3334 if (includeall && !doExport(format, true, true))
3336 // (2) export with included children only
3337 if (!doExport(format, true, false, result_file))
3339 return formats.view(*this, FileName(result_file), format);
3343 bool Buffer::isExportable(string const & format) const
3345 vector<string> backs = backends();
3346 for (vector<string>::const_iterator it = backs.begin();
3347 it != backs.end(); ++it)
3348 if (theConverters().isReachable(*it, format))
3354 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3356 vector<string> const backs = backends();
3357 vector<Format const *> result =
3358 theConverters().getReachable(backs[0], only_viewable, true);
3359 for (vector<string>::const_iterator it = backs.begin() + 1;
3360 it != backs.end(); ++it) {
3361 vector<Format const *> r =
3362 theConverters().getReachable(*it, only_viewable, false);
3363 result.insert(result.end(), r.begin(), r.end());
3369 vector<string> Buffer::backends() const
3372 v.push_back(bufferFormat());
3373 // FIXME: Don't hardcode format names here, but use a flag
3374 if (v.back() == "latex")
3375 v.push_back("pdflatex");
3376 v.push_back("xhtml");
3377 v.push_back("text");
3383 bool Buffer::readFileHelper(FileName const & s)
3385 // File information about normal file
3387 docstring const file = makeDisplayPath(s.absFilename(), 50);
3388 docstring text = bformat(_("The specified document\n%1$s"
3389 "\ncould not be read."), file);
3390 Alert::error(_("Could not read document"), text);
3394 // Check if emergency save file exists and is newer.
3395 FileName const e(s.absFilename() + ".emergency");
3397 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3398 docstring const file = makeDisplayPath(s.absFilename(), 20);
3399 docstring const text =
3400 bformat(_("An emergency save of the document "
3402 "Recover emergency save?"), file);
3403 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3404 _("&Recover"), _("&Load Original"),
3408 // the file is not saved if we load the emergency file.
3413 if ((res = readFile(e)) == success)
3414 str = _("Document was successfully recovered.");
3416 str = _("Document was NOT successfully recovered.");
3417 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3418 from_utf8(e.absFilename()));
3420 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3421 _("&Remove"), _("&Keep it"))) {
3424 Alert::warning(_("Emergency file deleted"),
3425 _("Do not forget to save your file now!"), true);
3430 if (!Alert::prompt(_("Delete emergency file?"),
3431 _("Remove emergency file now?"), 1, 1,
3432 _("&Remove"), _("&Keep it")))
3440 // Now check if autosave file is newer.
3441 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3443 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3444 docstring const file = makeDisplayPath(s.absFilename(), 20);
3445 docstring const text =
3446 bformat(_("The backup of the document "
3447 "%1$s is newer.\n\nLoad the "
3448 "backup instead?"), file);
3449 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3450 _("&Load backup"), _("Load &original"),
3454 // the file is not saved if we load the autosave file.
3458 // Here we delete the autosave
3469 bool Buffer::loadLyXFile(FileName const & s)
3471 // If the file is not readable, we try to
3472 // retrieve the file from version control.
3473 if (!s.isReadableFile()
3474 && !LyXVC::file_not_found_hook(s))
3477 if (s.isReadableFile()
3478 && readFileHelper(s)) {
3479 lyxvc().file_found_hook(s);
3480 setReadonly(!s.isWritable());
3487 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3489 TeXErrors::Errors::const_iterator cit = terr.begin();
3490 TeXErrors::Errors::const_iterator end = terr.end();
3492 for (; cit != end; ++cit) {
3495 int errorRow = cit->error_in_line;
3496 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3502 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3503 } while (found && id_start == id_end && pos_start == pos_end);
3505 errorList.push_back(ErrorItem(cit->error_desc,
3506 cit->error_text, id_start, pos_start, pos_end));
3511 void Buffer::setBuffersForInsets() const
3513 inset().setBuffer(const_cast<Buffer &>(*this));
3517 void Buffer::updateLabels(UpdateScope scope, UpdateType utype) const
3519 // Use the master text class also for child documents
3520 Buffer const * const master = masterBuffer();
3521 DocumentClass const & textclass = master->params().documentClass();
3523 // do this only if we are the top-level Buffer
3524 if (scope != UpdateMaster || master == this)
3525 checkBibInfoCache();
3527 // keep the buffers to be children in this set. If the call from the
3528 // master comes back we can see which of them were actually seen (i.e.
3529 // via an InsetInclude). The remaining ones in the set need still be updated.
3530 static std::set<Buffer const *> bufToUpdate;
3531 if (scope == UpdateMaster) {
3532 // If this is a child document start with the master
3533 if (master != this) {
3534 bufToUpdate.insert(this);
3535 master->updateLabels(UpdateMaster, utype);
3536 // Do this here in case the master has no gui associated with it. Then,
3537 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3538 if (!master->d->gui_)
3541 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3542 if (bufToUpdate.find(this) == bufToUpdate.end())
3546 // start over the counters in the master
3547 textclass.counters().reset();
3550 // update will be done below for this buffer
3551 bufToUpdate.erase(this);
3553 // update all caches
3554 clearReferenceCache();
3557 Buffer & cbuf = const_cast<Buffer &>(*this);
3559 LASSERT(!text().paragraphs().empty(), /**/);
3562 ParIterator parit = cbuf.par_iterator_begin();
3563 updateLabels(parit, utype);
3566 // TocBackend update will be done later.
3569 cbuf.tocBackend().update();
3570 if (scope == UpdateMaster)
3571 cbuf.structureChanged();
3575 static depth_type getDepth(DocIterator const & it)
3577 depth_type depth = 0;
3578 for (size_t i = 0 ; i < it.depth() ; ++i)
3579 if (!it[i].inset().inMathed())
3580 depth += it[i].paragraph().getDepth() + 1;
3581 // remove 1 since the outer inset does not count
3585 static depth_type getItemDepth(ParIterator const & it)
3587 Paragraph const & par = *it;
3588 LabelType const labeltype = par.layout().labeltype;
3590 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3593 // this will hold the lowest depth encountered up to now.
3594 depth_type min_depth = getDepth(it);
3595 ParIterator prev_it = it;
3598 --prev_it.top().pit();
3600 // start of nested inset: go to outer par
3602 if (prev_it.empty()) {
3603 // start of document: nothing to do
3608 // We search for the first paragraph with same label
3609 // that is not more deeply nested.
3610 Paragraph & prev_par = *prev_it;
3611 depth_type const prev_depth = getDepth(prev_it);
3612 if (labeltype == prev_par.layout().labeltype) {
3613 if (prev_depth < min_depth)
3614 return prev_par.itemdepth + 1;
3615 if (prev_depth == min_depth)
3616 return prev_par.itemdepth;
3618 min_depth = min(min_depth, prev_depth);
3619 // small optimization: if we are at depth 0, we won't
3620 // find anything else
3621 if (prev_depth == 0)
3627 static bool needEnumCounterReset(ParIterator const & it)
3629 Paragraph const & par = *it;
3630 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3631 depth_type const cur_depth = par.getDepth();
3632 ParIterator prev_it = it;
3633 while (prev_it.pit()) {
3634 --prev_it.top().pit();
3635 Paragraph const & prev_par = *prev_it;
3636 if (prev_par.getDepth() <= cur_depth)
3637 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3639 // start of nested inset: reset
3644 // set the label of a paragraph. This includes the counters.
3645 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3647 BufferParams const & bp = owner_->masterBuffer()->params();
3648 DocumentClass const & textclass = bp.documentClass();
3649 Paragraph & par = it.paragraph();
3650 Layout const & layout = par.layout();
3651 Counters & counters = textclass.counters();
3653 if (par.params().startOfAppendix()) {
3654 // FIXME: only the counter corresponding to toplevel
3655 // sectioning should be reset
3657 counters.appendix(true);
3659 par.params().appendix(counters.appendix());
3661 // Compute the item depth of the paragraph
3662 par.itemdepth = getItemDepth(it);
3664 if (layout.margintype == MARGIN_MANUAL
3665 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3666 if (par.params().labelWidthString().empty())
3667 par.params().labelWidthString(par.expandLabel(layout, bp));
3669 par.params().labelWidthString(docstring());
3672 switch(layout.labeltype) {
3674 if (layout.toclevel <= bp.secnumdepth
3675 && (layout.latextype != LATEX_ENVIRONMENT
3676 || it.text()->isFirstInSequence(it.pit()))) {
3677 counters.step(layout.counter, utype);
3678 par.params().labelString(
3679 par.expandLabel(layout, bp));
3681 par.params().labelString(docstring());
3684 case LABEL_ITEMIZE: {
3685 // At some point of time we should do something more
3686 // clever here, like:
3687 // par.params().labelString(
3688 // bp.user_defined_bullet(par.itemdepth).getText());
3689 // for now, use a simple hardcoded label
3690 docstring itemlabel;
3691 switch (par.itemdepth) {
3693 itemlabel = char_type(0x2022);
3696 itemlabel = char_type(0x2013);
3699 itemlabel = char_type(0x2217);
3702 itemlabel = char_type(0x2219); // or 0x00b7
3705 par.params().labelString(itemlabel);
3709 case LABEL_ENUMERATE: {
3710 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3712 switch (par.itemdepth) {
3721 enumcounter += "iv";
3724 // not a valid enumdepth...
3728 // Maybe we have to reset the enumeration counter.
3729 if (needEnumCounterReset(it))
3730 counters.reset(enumcounter);
3731 counters.step(enumcounter, utype);
3733 string const & lang = par.getParLanguage(bp)->code();
3734 par.params().labelString(counters.theCounter(enumcounter, lang));
3739 case LABEL_SENSITIVE: {
3740 string const & type = counters.current_float();
3741 docstring full_label;
3743 full_label = owner_->B_("Senseless!!! ");
3745 docstring name = owner_->B_(textclass.floats().getType(type).name());
3746 if (counters.hasCounter(from_utf8(type))) {
3747 string const & lang = par.getParLanguage(bp)->code();
3748 counters.step(from_utf8(type), utype);
3749 full_label = bformat(from_ascii("%1$s %2$s:"),
3751 counters.theCounter(from_utf8(type), lang));
3753 full_label = bformat(from_ascii("%1$s #:"), name);
3755 par.params().labelString(full_label);
3759 case LABEL_NO_LABEL:
3760 par.params().labelString(docstring());
3764 case LABEL_TOP_ENVIRONMENT:
3765 case LABEL_CENTERED_TOP_ENVIRONMENT:
3768 par.params().labelString(par.expandLabel(layout, bp));
3774 void Buffer::updateLabels(ParIterator & parit, UpdateType utype) const
3776 LASSERT(parit.pit() == 0, /**/);
3778 // set the position of the text in the buffer to be able
3779 // to resolve macros in it. This has nothing to do with
3780 // labels, but by putting it here we avoid implementing
3781 // a whole bunch of traversal routines just for this call.
3782 parit.text()->setMacrocontextPosition(parit);
3784 depth_type maxdepth = 0;
3785 pit_type const lastpit = parit.lastpit();
3786 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3787 // reduce depth if necessary
3788 parit->params().depth(min(parit->params().depth(), maxdepth));
3789 maxdepth = parit->getMaxDepthAfter();
3791 if (utype == OutputUpdate) {
3792 // track the active counters
3793 // we have to do this for the master buffer, since the local
3794 // buffer isn't tracking anything.
3795 masterBuffer()->params().documentClass().counters().
3796 setActiveLayout(parit->layout());
3799 // set the counter for this paragraph
3800 d->setLabel(parit, utype);
3803 InsetList::const_iterator iit = parit->insetList().begin();
3804 InsetList::const_iterator end = parit->insetList().end();
3805 for (; iit != end; ++iit) {
3806 parit.pos() = iit->pos;
3807 iit->inset->updateLabels(parit, utype);
3813 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3814 WordLangTuple & word_lang, docstring_list & suggestions) const
3818 suggestions.clear();
3819 word_lang = WordLangTuple();
3820 // OK, we start from here.
3821 DocIterator const end = doc_iterator_end(this);
3822 for (; from != end; from.forwardPos()) {
3823 // We are only interested in text so remove the math CursorSlice.
3824 while (from.inMathed()) {
3828 // If from is at the end of the document (which is possible
3829 // when leaving the mathed) LyX will crash later.
3833 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3838 // Do not increase progress when from == to, otherwise the word
3839 // count will be wrong.
3849 bool Buffer::reload()
3852 // e.g., read-only status could have changed due to version control
3853 d->filename.refresh();
3854 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3856 bool const success = loadLyXFile(d->filename);
3861 message(bformat(_("Document %1$s reloaded."), disp_fn));
3863 message(bformat(_("Could not reload document %1$s."), disp_fn));