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())));
969 d->file_fully_loaded = true;
974 // Should probably be moved to somewhere else: BufferView? LyXView?
975 bool Buffer::save() const
977 // We don't need autosaves in the immediate future. (Asger)
978 resetAutosaveTimers();
980 string const encodedFilename = d->filename.toFilesystemEncoding();
983 bool madeBackup = false;
985 // make a backup if the file already exists
986 if (lyxrc.make_backup && fileName().exists()) {
987 backupName = FileName(absFileName() + '~');
988 if (!lyxrc.backupdir_path.empty()) {
989 string const mangledName =
990 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
991 backupName = FileName(addName(lyxrc.backupdir_path,
994 if (fileName().copyTo(backupName)) {
997 Alert::error(_("Backup failure"),
998 bformat(_("Cannot create backup file %1$s.\n"
999 "Please check whether the directory exists and is writeable."),
1000 from_utf8(backupName.absFilename())));
1001 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1005 // ask if the disk file has been externally modified (use checksum method)
1006 if (fileName().exists() && isExternallyModified(checksum_method)) {
1007 docstring const file = makeDisplayPath(absFileName(), 20);
1008 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1009 "you want to overwrite this file?"), file);
1010 int const ret = Alert::prompt(_("Overwrite modified file?"),
1011 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1016 if (writeFile(d->filename)) {
1020 // Saving failed, so backup is not backup
1022 backupName.moveTo(d->filename);
1028 bool Buffer::writeFile(FileName const & fname) const
1030 if (d->read_only && fname == d->filename)
1033 bool retval = false;
1035 docstring const str = bformat(_("Saving document %1$s..."),
1036 makeDisplayPath(fname.absFilename()));
1039 if (params().compressed) {
1040 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1041 retval = ofs && write(ofs);
1043 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1044 retval = ofs && write(ofs);
1048 message(str + _(" could not write file!"));
1052 removeAutosaveFile();
1054 saveCheckSum(d->filename);
1055 message(str + _(" done."));
1061 docstring Buffer::emergencyWrite()
1063 // No need to save if the buffer has not changed.
1067 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1069 docstring user_message = bformat(
1070 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1072 // We try to save three places:
1073 // 1) Same place as document. Unless it is an unnamed doc.
1075 string s = absFileName();
1078 if (writeFile(FileName(s))) {
1080 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1081 return user_message;
1083 user_message += _(" Save failed! Trying again...\n");
1087 // 2) In HOME directory.
1088 string s = addName(package().home_dir().absFilename(), absFileName());
1090 lyxerr << ' ' << s << endl;
1091 if (writeFile(FileName(s))) {
1093 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1094 return user_message;
1097 user_message += _(" Save failed! Trying yet again...\n");
1099 // 3) In "/tmp" directory.
1100 // MakeAbsPath to prepend the current
1101 // drive letter on OS/2
1102 s = addName(package().temp_dir().absFilename(), absFileName());
1104 lyxerr << ' ' << s << endl;
1105 if (writeFile(FileName(s))) {
1107 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1108 return user_message;
1111 user_message += _(" Save failed! Bummer. Document is lost.");
1114 return user_message;
1118 bool Buffer::write(ostream & ofs) const
1121 // Use the standard "C" locale for file output.
1122 ofs.imbue(locale::classic());
1125 // The top of the file should not be written by params().
1127 // write out a comment in the top of the file
1128 ofs << "#LyX " << lyx_version
1129 << " created this file. For more info see http://www.lyx.org/\n"
1130 << "\\lyxformat " << LYX_FORMAT << "\n"
1131 << "\\begin_document\n";
1133 /// For each author, set 'used' to true if there is a change
1134 /// by this author in the document; otherwise set it to 'false'.
1135 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1136 AuthorList::Authors::const_iterator a_end = params().authors().end();
1137 for (; a_it != a_end; ++a_it)
1138 a_it->setUsed(false);
1140 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1141 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1142 for ( ; it != end; ++it)
1143 it->checkAuthors(params().authors());
1145 // now write out the buffer parameters.
1146 ofs << "\\begin_header\n";
1147 params().writeFile(ofs);
1148 ofs << "\\end_header\n";
1151 ofs << "\n\\begin_body\n";
1153 ofs << "\n\\end_body\n";
1155 // Write marker that shows file is complete
1156 ofs << "\\end_document" << endl;
1158 // Shouldn't really be needed....
1161 // how to check if close went ok?
1162 // Following is an attempt... (BE 20001011)
1164 // good() returns false if any error occured, including some
1165 // formatting error.
1166 // bad() returns true if something bad happened in the buffer,
1167 // which should include file system full errors.
1172 lyxerr << "File was not closed properly." << endl;
1179 bool Buffer::makeLaTeXFile(FileName const & fname,
1180 string const & original_path,
1181 OutputParams const & runparams_in,
1182 bool output_preamble, bool output_body) const
1184 OutputParams runparams = runparams_in;
1185 if (params().useXetex)
1186 runparams.flavor = OutputParams::XETEX;
1188 string const encoding = runparams.encoding->iconvName();
1189 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1192 try { ofs.reset(encoding); }
1193 catch (iconv_codecvt_facet_exception & e) {
1194 lyxerr << "Caught iconv exception: " << e.what() << endl;
1195 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1196 "verify that the support software for your encoding (%1$s) is "
1197 "properly installed"), from_ascii(encoding)));
1200 if (!openFileWrite(ofs, fname))
1203 //TexStream ts(ofs.rdbuf(), &texrow());
1204 ErrorList & errorList = d->errorLists["Export"];
1206 bool failed_export = false;
1209 writeLaTeXSource(ofs, original_path,
1210 runparams, output_preamble, output_body);
1212 catch (EncodingException & e) {
1213 odocstringstream ods;
1214 ods.put(e.failed_char);
1216 oss << "0x" << hex << e.failed_char << dec;
1217 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1218 " (code point %2$s)"),
1219 ods.str(), from_utf8(oss.str()));
1220 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1221 "representable in the chosen encoding.\n"
1222 "Changing the document encoding to utf8 could help."),
1223 e.par_id, e.pos, e.pos + 1));
1224 failed_export = true;
1226 catch (iconv_codecvt_facet_exception & e) {
1227 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1228 _(e.what()), -1, 0, 0));
1229 failed_export = true;
1231 catch (exception const & e) {
1232 errorList.push_back(ErrorItem(_("conversion failed"),
1233 _(e.what()), -1, 0, 0));
1234 failed_export = true;
1237 lyxerr << "Caught some really weird exception..." << endl;
1243 failed_export = true;
1244 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1248 return !failed_export;
1252 void Buffer::writeLaTeXSource(odocstream & os,
1253 string const & original_path,
1254 OutputParams const & runparams_in,
1255 bool const output_preamble, bool const output_body) const
1257 // The child documents, if any, shall be already loaded at this point.
1259 OutputParams runparams = runparams_in;
1261 // Classify the unicode characters appearing in math insets
1262 Encodings::initUnicodeMath(*this);
1264 // validate the buffer.
1265 LYXERR(Debug::LATEX, " Validating buffer...");
1266 LaTeXFeatures features(*this, params(), runparams);
1268 LYXERR(Debug::LATEX, " Buffer validation done.");
1270 // The starting paragraph of the coming rows is the
1271 // first paragraph of the document. (Asger)
1272 if (output_preamble && runparams.nice) {
1273 os << "%% LyX " << lyx_version << " created this file. "
1274 "For more info, see http://www.lyx.org/.\n"
1275 "%% Do not edit unless you really know what "
1277 d->texrow.newline();
1278 d->texrow.newline();
1280 LYXERR(Debug::INFO, "lyx document header finished");
1282 // Don't move this behind the parent_buffer=0 code below,
1283 // because then the macros will not get the right "redefinition"
1284 // flag as they don't see the parent macros which are output before.
1287 // fold macros if possible, still with parent buffer as the
1288 // macros will be put in the prefix anyway.
1289 updateMacroInstances();
1291 // There are a few differences between nice LaTeX and usual files:
1292 // usual is \batchmode and has a
1293 // special input@path to allow the including of figures
1294 // with either \input or \includegraphics (what figinsets do).
1295 // input@path is set when the actual parameter
1296 // original_path is set. This is done for usual tex-file, but not
1297 // for nice-latex-file. (Matthias 250696)
1298 // Note that input@path is only needed for something the user does
1299 // in the preamble, included .tex files or ERT, files included by
1300 // LyX work without it.
1301 if (output_preamble) {
1302 if (!runparams.nice) {
1303 // code for usual, NOT nice-latex-file
1304 os << "\\batchmode\n"; // changed
1305 // from \nonstopmode
1306 d->texrow.newline();
1308 if (!original_path.empty()) {
1310 // We don't know the encoding of inputpath
1311 docstring const inputpath = from_utf8(latex_path(original_path));
1312 os << "\\makeatletter\n"
1313 << "\\def\\input@path{{"
1314 << inputpath << "/}}\n"
1315 << "\\makeatother\n";
1316 d->texrow.newline();
1317 d->texrow.newline();
1318 d->texrow.newline();
1321 // get parent macros (if this buffer has a parent) which will be
1322 // written at the document begin further down.
1323 MacroSet parentMacros;
1324 listParentMacros(parentMacros, features);
1326 // Write the preamble
1327 runparams.use_babel = params().writeLaTeX(os, features,
1329 d->filename.onlyPath());
1331 runparams.use_japanese = features.isRequired("japanese");
1337 os << "\\begin{document}\n";
1338 d->texrow.newline();
1340 // output the parent macros
1341 MacroSet::iterator it = parentMacros.begin();
1342 MacroSet::iterator end = parentMacros.end();
1343 for (; it != end; ++it)
1344 (*it)->write(os, true);
1345 } // output_preamble
1347 d->texrow.start(paragraphs().begin()->id(), 0);
1349 LYXERR(Debug::INFO, "preamble finished, now the body.");
1351 // if we are doing a real file with body, even if this is the
1352 // child of some other buffer, let's cut the link here.
1353 // This happens for example if only a child document is printed.
1354 Buffer const * save_parent = 0;
1355 if (output_preamble) {
1356 save_parent = d->parent();
1361 latexParagraphs(*this, text(), os, d->texrow, runparams);
1363 // Restore the parenthood if needed
1364 if (output_preamble)
1365 d->setParent(save_parent);
1367 // add this just in case after all the paragraphs
1369 d->texrow.newline();
1371 if (output_preamble) {
1372 os << "\\end{document}\n";
1373 d->texrow.newline();
1374 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1376 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1378 runparams_in.encoding = runparams.encoding;
1380 // Just to be sure. (Asger)
1381 d->texrow.newline();
1383 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1384 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1388 bool Buffer::isLatex() const
1390 return params().documentClass().outputType() == LATEX;
1394 bool Buffer::isLiterate() const
1396 return params().documentClass().outputType() == LITERATE;
1400 bool Buffer::isDocBook() const
1402 return params().documentClass().outputType() == DOCBOOK;
1406 void Buffer::makeDocBookFile(FileName const & fname,
1407 OutputParams const & runparams,
1408 bool const body_only) const
1410 LYXERR(Debug::LATEX, "makeDocBookFile...");
1413 if (!openFileWrite(ofs, fname))
1416 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1420 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1424 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1425 OutputParams const & runparams,
1426 bool const only_body) const
1428 LaTeXFeatures features(*this, params(), runparams);
1433 DocumentClass const & tclass = params().documentClass();
1434 string const top_element = tclass.latexname();
1437 if (runparams.flavor == OutputParams::XML)
1438 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1441 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1444 if (! tclass.class_header().empty())
1445 os << from_ascii(tclass.class_header());
1446 else if (runparams.flavor == OutputParams::XML)
1447 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1448 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1450 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1452 docstring preamble = from_utf8(params().preamble);
1453 if (runparams.flavor != OutputParams::XML ) {
1454 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1455 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1456 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1457 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1460 string const name = runparams.nice
1461 ? changeExtension(absFileName(), ".sgml") : fname;
1462 preamble += features.getIncludedFiles(name);
1463 preamble += features.getLyXSGMLEntities();
1465 if (!preamble.empty()) {
1466 os << "\n [ " << preamble << " ]";
1471 string top = top_element;
1473 if (runparams.flavor == OutputParams::XML)
1474 top += params().language->code();
1476 top += params().language->code().substr(0, 2);
1479 if (!params().options.empty()) {
1481 top += params().options;
1484 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1485 << " file was created by LyX " << lyx_version
1486 << "\n See http://www.lyx.org/ for more information -->\n";
1488 params().documentClass().counters().reset();
1492 sgml::openTag(os, top);
1494 docbookParagraphs(text(), *this, os, runparams);
1495 sgml::closeTag(os, top_element);
1499 void Buffer::makeLyXHTMLFile(FileName const & fname,
1500 OutputParams const & runparams,
1501 bool const body_only) const
1503 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1506 if (!openFileWrite(ofs, fname))
1509 writeLyXHTMLSource(ofs, runparams, body_only);
1513 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1517 void Buffer::writeLyXHTMLSource(odocstream & os,
1518 OutputParams const & runparams,
1519 bool const only_body) const
1521 LaTeXFeatures features(*this, params(), runparams);
1523 updateLabels(UpdateMaster, OutputUpdate);
1524 checkBibInfoCache();
1525 d->bibinfo_.makeCitationLabels(*this);
1527 updateMacroInstances();
1530 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1531 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";
1532 // FIXME Language should be set properly.
1533 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1535 // FIXME Presumably need to set this right
1536 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1537 os << "<title>" << features.htmlTitle() << "</title>\n";
1539 os << "\n<!-- Text Class Preamble -->\n"
1540 << features.getTClassHTMLPreamble()
1541 << "\n<!-- Premable Snippets -->\n"
1542 << from_utf8(features.getPreambleSnippets());
1544 os << "\n<!-- Layout-provided Styles -->\n";
1545 docstring const styleinfo = features.getTClassHTMLStyles();
1546 if (!styleinfo.empty()) {
1547 os << "<style type='text/css'>\n"
1551 os << "</head>\n<body>\n";
1555 params().documentClass().counters().reset();
1556 xhtmlParagraphs(text(), *this, xs, runparams);
1558 os << "</body>\n</html>\n";
1562 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1563 // Other flags: -wall -v0 -x
1564 int Buffer::runChktex()
1568 // get LaTeX-Filename
1569 FileName const path(temppath());
1570 string const name = addName(path.absFilename(), latexName());
1571 string const org_path = filePath();
1573 PathChanger p(path); // path to LaTeX file
1574 message(_("Running chktex..."));
1576 // Generate the LaTeX file if neccessary
1577 OutputParams runparams(¶ms().encoding());
1578 runparams.flavor = OutputParams::LATEX;
1579 runparams.nice = false;
1580 makeLaTeXFile(FileName(name), org_path, runparams);
1583 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1584 int const res = chktex.run(terr); // run chktex
1587 Alert::error(_("chktex failure"),
1588 _("Could not run chktex successfully."));
1589 } else if (res > 0) {
1590 ErrorList & errlist = d->errorLists["ChkTeX"];
1592 bufferErrors(terr, errlist);
1603 void Buffer::validate(LaTeXFeatures & features) const
1605 params().validate(features);
1609 for_each(paragraphs().begin(), paragraphs().end(),
1610 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1612 if (lyxerr.debugging(Debug::LATEX)) {
1613 features.showStruct();
1618 void Buffer::getLabelList(vector<docstring> & list) const
1620 // If this is a child document, use the parent's list instead.
1621 Buffer const * const pbuf = d->parent();
1623 pbuf->getLabelList(list);
1628 Toc & toc = d->toc_backend.toc("label");
1629 TocIterator toc_it = toc.begin();
1630 TocIterator end = toc.end();
1631 for (; toc_it != end; ++toc_it) {
1632 if (toc_it->depth() == 0)
1633 list.push_back(toc_it->str());
1638 void Buffer::updateBibfilesCache(UpdateScope scope) const
1640 // If this is a child document, use the parent's cache instead.
1641 Buffer const * const pbuf = d->parent();
1642 if (pbuf && scope != UpdateChildOnly) {
1643 pbuf->updateBibfilesCache();
1647 d->bibfiles_cache_.clear();
1648 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1649 if (it->lyxCode() == BIBTEX_CODE) {
1650 InsetBibtex const & inset =
1651 static_cast<InsetBibtex const &>(*it);
1652 support::FileNameList const bibfiles = inset.getBibFiles();
1653 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1656 } else if (it->lyxCode() == INCLUDE_CODE) {
1657 InsetInclude & inset =
1658 static_cast<InsetInclude &>(*it);
1659 inset.updateBibfilesCache();
1660 support::FileNameList const & bibfiles =
1661 inset.getBibfilesCache();
1662 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1667 // the bibinfo cache is now invalid
1668 d->bibinfo_cache_valid_ = false;
1672 void Buffer::invalidateBibinfoCache()
1674 d->bibinfo_cache_valid_ = false;
1678 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1680 // If this is a child document, use the parent's cache instead.
1681 Buffer const * const pbuf = d->parent();
1682 if (pbuf && scope != UpdateChildOnly)
1683 return pbuf->getBibfilesCache();
1685 // We update the cache when first used instead of at loading time.
1686 if (d->bibfiles_cache_.empty())
1687 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1689 return d->bibfiles_cache_;
1693 BiblioInfo const & Buffer::masterBibInfo() const
1695 // if this is a child document and the parent is already loaded
1696 // use the parent's list instead [ale990412]
1697 Buffer const * const tmp = masterBuffer();
1700 return tmp->masterBibInfo();
1701 return localBibInfo();
1705 BiblioInfo const & Buffer::localBibInfo() const
1711 void Buffer::checkBibInfoCache() const
1713 support::FileNameList const & bibfilesCache = getBibfilesCache();
1714 // compare the cached timestamps with the actual ones.
1715 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1716 support::FileNameList::const_iterator en = bibfilesCache.end();
1717 for (; ei != en; ++ ei) {
1718 time_t lastw = ei->lastModified();
1719 time_t prevw = d->bibfile_status_[*ei];
1720 if (lastw != prevw) {
1721 d->bibinfo_cache_valid_ = false;
1722 d->bibfile_status_[*ei] = lastw;
1726 if (!d->bibinfo_cache_valid_) {
1727 d->bibinfo_.clear();
1728 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1729 it->fillWithBibKeys(d->bibinfo_, it);
1730 d->bibinfo_cache_valid_ = true;
1735 bool Buffer::isDepClean(string const & name) const
1737 DepClean::const_iterator const it = d->dep_clean.find(name);
1738 if (it == d->dep_clean.end())
1744 void Buffer::markDepClean(string const & name)
1746 d->dep_clean[name] = true;
1750 bool Buffer::isExportableFormat(string const & format) const
1752 typedef vector<Format const *> Formats;
1754 formats = exportableFormats(true);
1755 Formats::const_iterator fit = formats.begin();
1756 Formats::const_iterator end = formats.end();
1757 for (; fit != end ; ++fit) {
1758 if ((*fit)->name() == format)
1765 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1768 // FIXME? if there is an Buffer LFUN that can be dispatched even
1769 // if internal, put a switch '(cmd.action)' here.
1775 switch (cmd.action) {
1777 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1778 flag.setOnOff(isReadonly());
1781 // FIXME: There is need for a command-line import.
1782 //case LFUN_BUFFER_IMPORT:
1784 case LFUN_BUFFER_AUTO_SAVE:
1787 case LFUN_BUFFER_EXPORT_CUSTOM:
1788 // FIXME: Nothing to check here?
1791 case LFUN_BUFFER_EXPORT: {
1792 docstring const arg = cmd.argument();
1793 enable = arg == "custom" || isExportable(to_utf8(arg));
1795 flag.message(bformat(
1796 _("Don't know how to export to format: %1$s"), arg));
1800 case LFUN_BUFFER_CHKTEX:
1801 enable = isLatex() && !lyxrc.chktex_command.empty();
1804 case LFUN_BUILD_PROGRAM:
1805 enable = isExportable("program");
1808 case LFUN_BRANCH_ACTIVATE:
1809 case LFUN_BRANCH_DEACTIVATE: {
1810 BranchList const & branchList = params().branchlist();
1811 docstring const branchName = cmd.argument();
1812 enable = !branchName.empty() && branchList.find(branchName);
1816 case LFUN_BRANCH_ADD:
1817 case LFUN_BRANCHES_RENAME:
1818 case LFUN_BUFFER_PRINT:
1819 // if no Buffer is present, then of course we won't be called!
1822 case LFUN_BUFFER_LANGUAGE:
1823 enable = !isReadonly();
1829 flag.setEnabled(enable);
1834 void Buffer::dispatch(string const & command, DispatchResult & result)
1836 return dispatch(lyxaction.lookupFunc(command), result);
1840 // NOTE We can end up here even if we have no GUI, because we are called
1841 // by LyX::exec to handled command-line requests. So we may need to check
1842 // whether we have a GUI or not. The boolean use_gui holds this information.
1843 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1846 // FIXME? if there is an Buffer LFUN that can be dispatched even
1847 // if internal, put a switch '(cmd.action)' here.
1848 dr.dispatched(false);
1851 string const argument = to_utf8(func.argument());
1852 // We'll set this back to false if need be.
1853 bool dispatched = true;
1854 undo().beginUndoGroup();
1856 switch (func.action) {
1857 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1858 if (lyxvc().inUse())
1859 lyxvc().toggleReadOnly();
1861 setReadonly(!isReadonly());
1864 case LFUN_BUFFER_EXPORT: {
1865 bool success = doExport(argument, false, false);
1866 dr.setError(success);
1868 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1873 case LFUN_BUILD_PROGRAM:
1874 doExport("program", true, false);
1877 case LFUN_BUFFER_CHKTEX:
1881 case LFUN_BUFFER_EXPORT_CUSTOM: {
1883 string command = split(argument, format_name, ' ');
1884 Format const * format = formats.getFormat(format_name);
1886 lyxerr << "Format \"" << format_name
1887 << "\" not recognized!"
1892 // The name of the file created by the conversion process
1895 // Output to filename
1896 if (format->name() == "lyx") {
1897 string const latexname = latexName(false);
1898 filename = changeExtension(latexname,
1899 format->extension());
1900 filename = addName(temppath(), filename);
1902 if (!writeFile(FileName(filename)))
1906 doExport(format_name, true, false, filename);
1909 // Substitute $$FName for filename
1910 if (!contains(command, "$$FName"))
1911 command = "( " + command + " ) < $$FName";
1912 command = subst(command, "$$FName", filename);
1914 // Execute the command in the background
1916 call.startscript(Systemcall::DontWait, command);
1920 // FIXME: There is need for a command-line import.
1922 case LFUN_BUFFER_IMPORT:
1927 case LFUN_BUFFER_AUTO_SAVE:
1931 case LFUN_BRANCH_ADD: {
1932 docstring const branch_name = func.argument();
1933 if (branch_name.empty()) {
1937 BranchList & branch_list = params().branchlist();
1938 Branch * branch = branch_list.find(branch_name);
1940 LYXERR0("Branch " << branch_name << " already exists.");
1942 docstring const msg =
1943 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1946 branch_list.add(branch_name);
1947 branch = branch_list.find(branch_name);
1948 string const x11hexname = X11hexname(branch->color());
1949 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1950 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1952 dr.update(Update::Force);
1957 case LFUN_BRANCH_ACTIVATE:
1958 case LFUN_BRANCH_DEACTIVATE: {
1959 BranchList & branchList = params().branchlist();
1960 docstring const branchName = func.argument();
1961 // the case without a branch name is handled elsewhere
1962 if (branchName.empty()) {
1966 Branch * branch = branchList.find(branchName);
1968 LYXERR0("Branch " << branchName << " does not exist.");
1970 docstring const msg =
1971 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1974 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1976 dr.update(Update::Force);
1981 case LFUN_BRANCHES_RENAME: {
1982 if (func.argument().empty())
1985 docstring const oldname = from_utf8(func.getArg(0));
1986 docstring const newname = from_utf8(func.getArg(1));
1987 InsetIterator it = inset_iterator_begin(inset());
1988 InsetIterator const end = inset_iterator_end(inset());
1989 bool success = false;
1990 for (; it != end; ++it) {
1991 if (it->lyxCode() == BRANCH_CODE) {
1992 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1993 if (ins.branch() == oldname) {
1994 undo().recordUndo(it);
1995 ins.rename(newname);
2000 if (it->lyxCode() == INCLUDE_CODE) {
2001 // get buffer of external file
2002 InsetInclude const & ins =
2003 static_cast<InsetInclude const &>(*it);
2004 Buffer * child = ins.getChildBuffer();
2007 child->dispatch(func, dr);
2012 dr.update(Update::Force);
2016 case LFUN_BUFFER_PRINT: {
2017 // we'll assume there's a problem until we succeed
2019 string target = func.getArg(0);
2020 string target_name = func.getArg(1);
2021 string command = func.getArg(2);
2024 || target_name.empty()
2025 || command.empty()) {
2026 LYXERR0("Unable to parse " << func.argument());
2027 docstring const msg =
2028 bformat(_("Unable to parse \"%1$s\""), func.argument());
2032 if (target != "printer" && target != "file") {
2033 LYXERR0("Unrecognized target \"" << target << '"');
2034 docstring const msg =
2035 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2040 bool const update_unincluded =
2041 params().maintain_unincluded_children
2042 && !params().getIncludedChildren().empty();
2043 if (!doExport("dvi", true, update_unincluded)) {
2044 showPrintError(absFileName());
2045 dr.setMessage(_("Error exporting to DVI."));
2049 // Push directory path.
2050 string const path = temppath();
2051 // Prevent the compiler from optimizing away p
2055 // there are three cases here:
2056 // 1. we print to a file
2057 // 2. we print directly to a printer
2058 // 3. we print using a spool command (print to file first)
2061 string const dviname = changeExtension(latexName(true), "dvi");
2063 if (target == "printer") {
2064 if (!lyxrc.print_spool_command.empty()) {
2065 // case 3: print using a spool
2066 string const psname = changeExtension(dviname,".ps");
2067 command += ' ' + lyxrc.print_to_file
2070 + quoteName(dviname);
2072 string command2 = lyxrc.print_spool_command + ' ';
2073 if (target_name != "default") {
2074 command2 += lyxrc.print_spool_printerprefix
2078 command2 += quoteName(psname);
2080 // If successful, then spool command
2081 res = one.startscript(Systemcall::Wait, command);
2084 // If there's no GUI, we have to wait on this command. Otherwise,
2085 // LyX deletes the temporary directory, and with it the spooled
2086 // file, before it can be printed!!
2087 Systemcall::Starttype stype = use_gui ?
2088 Systemcall::DontWait : Systemcall::Wait;
2089 res = one.startscript(stype, command2);
2092 // case 2: print directly to a printer
2093 if (target_name != "default")
2094 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2096 Systemcall::Starttype stype = use_gui ?
2097 Systemcall::DontWait : Systemcall::Wait;
2098 res = one.startscript(stype, command + quoteName(dviname));
2102 // case 1: print to a file
2103 FileName const filename(makeAbsPath(target_name, filePath()));
2104 FileName const dvifile(makeAbsPath(dviname, path));
2105 if (filename.exists()) {
2106 docstring text = bformat(
2107 _("The file %1$s already exists.\n\n"
2108 "Do you want to overwrite that file?"),
2109 makeDisplayPath(filename.absFilename()));
2110 if (Alert::prompt(_("Overwrite file?"),
2111 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2114 command += ' ' + lyxrc.print_to_file
2115 + quoteName(filename.toFilesystemEncoding())
2117 + quoteName(dvifile.toFilesystemEncoding());
2119 Systemcall::Starttype stype = use_gui ?
2120 Systemcall::DontWait : Systemcall::Wait;
2121 res = one.startscript(stype, command);
2127 dr.setMessage(_("Error running external commands."));
2128 showPrintError(absFileName());
2133 case LFUN_BUFFER_LANGUAGE: {
2134 Language const * oldL = params().language;
2135 Language const * newL = languages.getLanguage(argument);
2136 if (!newL || oldL == newL)
2138 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2139 changeLanguage(oldL, newL);
2147 dr.dispatched(dispatched);
2148 undo().endUndoGroup();
2152 void Buffer::changeLanguage(Language const * from, Language const * to)
2154 LASSERT(from, /**/);
2157 for_each(par_iterator_begin(),
2159 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2163 bool Buffer::isMultiLingual() const
2165 ParConstIterator end = par_iterator_end();
2166 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2167 if (it->isMultiLingual(params()))
2174 DocIterator Buffer::getParFromID(int const id) const
2176 Buffer * buf = const_cast<Buffer *>(this);
2178 // John says this is called with id == -1 from undo
2179 lyxerr << "getParFromID(), id: " << id << endl;
2180 return doc_iterator_end(buf);
2183 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2184 if (it.paragraph().id() == id)
2187 return doc_iterator_end(buf);
2191 bool Buffer::hasParWithID(int const id) const
2193 return !getParFromID(id).atEnd();
2197 ParIterator Buffer::par_iterator_begin()
2199 return ParIterator(doc_iterator_begin(this));
2203 ParIterator Buffer::par_iterator_end()
2205 return ParIterator(doc_iterator_end(this));
2209 ParConstIterator Buffer::par_iterator_begin() const
2211 return ParConstIterator(doc_iterator_begin(this));
2215 ParConstIterator Buffer::par_iterator_end() const
2217 return ParConstIterator(doc_iterator_end(this));
2221 Language const * Buffer::language() const
2223 return params().language;
2227 docstring const Buffer::B_(string const & l10n) const
2229 return params().B_(l10n);
2233 bool Buffer::isClean() const
2235 return d->lyx_clean;
2239 bool Buffer::isExternallyModified(CheckMethod method) const
2241 LASSERT(d->filename.exists(), /**/);
2242 // if method == timestamp, check timestamp before checksum
2243 return (method == checksum_method
2244 || d->timestamp_ != d->filename.lastModified())
2245 && d->checksum_ != d->filename.checksum();
2249 void Buffer::saveCheckSum(FileName const & file) const
2251 if (file.exists()) {
2252 d->timestamp_ = file.lastModified();
2253 d->checksum_ = file.checksum();
2255 // in the case of save to a new file.
2262 void Buffer::markClean() const
2264 if (!d->lyx_clean) {
2265 d->lyx_clean = true;
2268 // if the .lyx file has been saved, we don't need an
2270 d->bak_clean = true;
2274 void Buffer::setUnnamed(bool flag)
2280 bool Buffer::isUnnamed() const
2287 /// Don't check unnamed, here: isInternal() is used in
2288 /// newBuffer(), where the unnamed flag has not been set by anyone
2289 /// yet. Also, for an internal buffer, there should be no need for
2290 /// retrieving fileName() nor for checking if it is unnamed or not.
2291 bool Buffer::isInternal() const
2293 return fileName().extension() == "internal";
2297 void Buffer::markDirty()
2300 d->lyx_clean = false;
2303 d->bak_clean = false;
2305 DepClean::iterator it = d->dep_clean.begin();
2306 DepClean::const_iterator const end = d->dep_clean.end();
2308 for (; it != end; ++it)
2313 FileName Buffer::fileName() const
2319 string Buffer::absFileName() const
2321 return d->filename.absFilename();
2325 string Buffer::filePath() const
2327 return d->filename.onlyPath().absFilename() + "/";
2331 bool Buffer::isReadonly() const
2333 return d->read_only;
2337 void Buffer::setParent(Buffer const * buffer)
2339 // Avoids recursive include.
2340 d->setParent(buffer == this ? 0 : buffer);
2345 Buffer const * Buffer::parent() const
2351 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2353 bufs.insert(owner_);
2355 parent()->d->collectRelatives(bufs);
2357 // loop over children
2358 BufferPositionMap::const_iterator it = children_positions.begin();
2359 BufferPositionMap::const_iterator end = children_positions.end();
2360 for (; it != end; ++it)
2361 bufs.insert(const_cast<Buffer *>(it->first));
2365 std::vector<Buffer const *> Buffer::allRelatives() const
2368 d->collectRelatives(bufs);
2369 BufferSet::iterator it = bufs.begin();
2370 std::vector<Buffer const *> ret;
2371 for (; it != bufs.end(); ++it)
2377 Buffer const * Buffer::masterBuffer() const
2379 Buffer const * const pbuf = d->parent();
2383 return pbuf->masterBuffer();
2387 bool Buffer::isChild(Buffer * child) const
2389 return d->children_positions.find(child) != d->children_positions.end();
2393 DocIterator Buffer::firstChildPosition(Buffer const * child)
2395 Impl::BufferPositionMap::iterator it;
2396 it = d->children_positions.find(child);
2397 if (it == d->children_positions.end())
2398 return DocIterator(this);
2403 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2405 // loop over children
2406 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2407 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2408 for (; it != end; ++it) {
2409 Buffer * child = const_cast<Buffer *>(it->first);
2410 clist.push_back(child);
2411 if (grand_children) {
2412 // there might be grandchildren
2413 std::vector<Buffer *> glist = child->getChildren();
2414 for (vector<Buffer *>::const_iterator git = glist.begin();
2415 git != glist.end(); ++git)
2416 clist.push_back(*git);
2422 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2424 std::vector<Buffer *> v;
2425 getChildren(v, grand_children);
2430 template<typename M>
2431 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2436 typename M::const_iterator it = m.lower_bound(x);
2437 if (it == m.begin())
2445 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2446 DocIterator const & pos) const
2448 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2450 // if paragraphs have no macro context set, pos will be empty
2454 // we haven't found anything yet
2455 DocIterator bestPos = owner_->par_iterator_begin();
2456 MacroData const * bestData = 0;
2458 // find macro definitions for name
2459 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2460 if (nameIt != macros.end()) {
2461 // find last definition in front of pos or at pos itself
2462 PositionScopeMacroMap::const_iterator it
2463 = greatest_below(nameIt->second, pos);
2464 if (it != nameIt->second.end()) {
2466 // scope ends behind pos?
2467 if (pos < it->second.first) {
2468 // Looks good, remember this. If there
2469 // is no external macro behind this,
2470 // we found the right one already.
2471 bestPos = it->first;
2472 bestData = &it->second.second;
2476 // try previous macro if there is one
2477 if (it == nameIt->second.begin())
2484 // find macros in included files
2485 PositionScopeBufferMap::const_iterator it
2486 = greatest_below(position_to_children, pos);
2487 if (it == position_to_children.end())
2488 // no children before
2492 // do we know something better (i.e. later) already?
2493 if (it->first < bestPos )
2496 // scope ends behind pos?
2497 if (pos < it->second.first) {
2498 // look for macro in external file
2500 MacroData const * data
2501 = it->second.second->getMacro(name, false);
2504 bestPos = it->first;
2510 // try previous file if there is one
2511 if (it == position_to_children.begin())
2516 // return the best macro we have found
2521 MacroData const * Buffer::getMacro(docstring const & name,
2522 DocIterator const & pos, bool global) const
2527 // query buffer macros
2528 MacroData const * data = d->getBufferMacro(name, pos);
2532 // If there is a master buffer, query that
2533 Buffer const * const pbuf = d->parent();
2535 d->macro_lock = true;
2536 MacroData const * macro = pbuf->getMacro(
2537 name, *this, false);
2538 d->macro_lock = false;
2544 data = MacroTable::globalMacros().get(name);
2553 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2555 // set scope end behind the last paragraph
2556 DocIterator scope = par_iterator_begin();
2557 scope.pit() = scope.lastpit() + 1;
2559 return getMacro(name, scope, global);
2563 MacroData const * Buffer::getMacro(docstring const & name,
2564 Buffer const & child, bool global) const
2566 // look where the child buffer is included first
2567 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2568 if (it == d->children_positions.end())
2571 // check for macros at the inclusion position
2572 return getMacro(name, it->second, global);
2576 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2578 pit_type const lastpit = it.lastpit();
2580 // look for macros in each paragraph
2581 while (it.pit() <= lastpit) {
2582 Paragraph & par = it.paragraph();
2584 // iterate over the insets of the current paragraph
2585 InsetList const & insets = par.insetList();
2586 InsetList::const_iterator iit = insets.begin();
2587 InsetList::const_iterator end = insets.end();
2588 for (; iit != end; ++iit) {
2589 it.pos() = iit->pos;
2591 // is it a nested text inset?
2592 if (iit->inset->asInsetText()) {
2593 // Inset needs its own scope?
2594 InsetText const * itext = iit->inset->asInsetText();
2595 bool newScope = itext->isMacroScope();
2597 // scope which ends just behind the inset
2598 DocIterator insetScope = it;
2601 // collect macros in inset
2602 it.push_back(CursorSlice(*iit->inset));
2603 updateMacros(it, newScope ? insetScope : scope);
2608 // is it an external file?
2609 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2610 // get buffer of external file
2611 InsetInclude const & inset =
2612 static_cast<InsetInclude const &>(*iit->inset);
2614 Buffer * child = inset.getChildBuffer();
2619 // register its position, but only when it is
2620 // included first in the buffer
2621 if (children_positions.find(child) ==
2622 children_positions.end())
2623 children_positions[child] = it;
2625 // register child with its scope
2626 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2630 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2634 MathMacroTemplate & macroTemplate =
2635 static_cast<MathMacroTemplate &>(*iit->inset);
2636 MacroContext mc(owner_, it);
2637 macroTemplate.updateToContext(mc);
2640 bool valid = macroTemplate.validMacro();
2641 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2642 // then the BufferView's cursor will be invalid in
2643 // some cases which leads to crashes.
2648 // FIXME (Abdel), I don't understandt why we pass 'it' here
2649 // instead of 'macroTemplate' defined above... is this correct?
2650 macros[macroTemplate.name()][it] =
2651 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2661 void Buffer::updateMacros() const
2666 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2668 // start with empty table
2670 d->children_positions.clear();
2671 d->position_to_children.clear();
2673 // Iterate over buffer, starting with first paragraph
2674 // The scope must be bigger than any lookup DocIterator
2675 // later. For the global lookup, lastpit+1 is used, hence
2676 // we use lastpit+2 here.
2677 DocIterator it = par_iterator_begin();
2678 DocIterator outerScope = it;
2679 outerScope.pit() = outerScope.lastpit() + 2;
2680 d->updateMacros(it, outerScope);
2684 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2686 InsetIterator it = inset_iterator_begin(inset());
2687 InsetIterator const end = inset_iterator_end(inset());
2688 for (; it != end; ++it) {
2689 if (it->lyxCode() == BRANCH_CODE) {
2690 InsetBranch & br = static_cast<InsetBranch &>(*it);
2691 docstring const name = br.branch();
2692 if (!from_master && !params().branchlist().find(name))
2693 result.push_back(name);
2694 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2695 result.push_back(name);
2698 if (it->lyxCode() == INCLUDE_CODE) {
2699 // get buffer of external file
2700 InsetInclude const & ins =
2701 static_cast<InsetInclude const &>(*it);
2702 Buffer * child = ins.getChildBuffer();
2705 child->getUsedBranches(result, true);
2708 // remove duplicates
2713 void Buffer::updateMacroInstances() const
2715 LYXERR(Debug::MACROS, "updateMacroInstances for "
2716 << d->filename.onlyFileName());
2717 DocIterator it = doc_iterator_begin(this);
2719 DocIterator const end = doc_iterator_end(this);
2720 for (; it != end; it.forwardInset()) {
2721 // look for MathData cells in InsetMathNest insets
2722 InsetMath * minset = it.nextInset()->asInsetMath();
2726 // update macro in all cells of the InsetMathNest
2727 DocIterator::idx_type n = minset->nargs();
2728 MacroContext mc = MacroContext(this, it);
2729 for (DocIterator::idx_type i = 0; i < n; ++i) {
2730 MathData & data = minset->cell(i);
2731 data.updateMacros(0, mc);
2737 void Buffer::listMacroNames(MacroNameSet & macros) const
2742 d->macro_lock = true;
2744 // loop over macro names
2745 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2746 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2747 for (; nameIt != nameEnd; ++nameIt)
2748 macros.insert(nameIt->first);
2750 // loop over children
2751 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2752 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2753 for (; it != end; ++it)
2754 it->first->listMacroNames(macros);
2757 Buffer const * const pbuf = d->parent();
2759 pbuf->listMacroNames(macros);
2761 d->macro_lock = false;
2765 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2767 Buffer const * const pbuf = d->parent();
2772 pbuf->listMacroNames(names);
2775 MacroNameSet::iterator it = names.begin();
2776 MacroNameSet::iterator end = names.end();
2777 for (; it != end; ++it) {
2779 MacroData const * data =
2780 pbuf->getMacro(*it, *this, false);
2782 macros.insert(data);
2784 // we cannot access the original MathMacroTemplate anymore
2785 // here to calls validate method. So we do its work here manually.
2786 // FIXME: somehow make the template accessible here.
2787 if (data->optionals() > 0)
2788 features.require("xargs");
2794 Buffer::References & Buffer::references(docstring const & label)
2797 return const_cast<Buffer *>(masterBuffer())->references(label);
2799 RefCache::iterator it = d->ref_cache_.find(label);
2800 if (it != d->ref_cache_.end())
2801 return it->second.second;
2803 static InsetLabel const * dummy_il = 0;
2804 static References const dummy_refs;
2805 it = d->ref_cache_.insert(
2806 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2807 return it->second.second;
2811 Buffer::References const & Buffer::references(docstring const & label) const
2813 return const_cast<Buffer *>(this)->references(label);
2817 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2819 masterBuffer()->d->ref_cache_[label].first = il;
2823 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2825 return masterBuffer()->d->ref_cache_[label].first;
2829 void Buffer::clearReferenceCache() const
2832 d->ref_cache_.clear();
2836 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2839 //FIXME: This does not work for child documents yet.
2840 LASSERT(code == CITE_CODE, /**/);
2841 // Check if the label 'from' appears more than once
2842 vector<docstring> labels;
2844 checkBibInfoCache();
2845 BiblioInfo const & keys = masterBibInfo();
2846 BiblioInfo::const_iterator bit = keys.begin();
2847 BiblioInfo::const_iterator bend = keys.end();
2849 for (; bit != bend; ++bit)
2851 labels.push_back(bit->first);
2854 if (count(labels.begin(), labels.end(), from) > 1)
2857 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2858 if (it->lyxCode() == code) {
2859 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2860 docstring const oldValue = inset.getParam(paramName);
2861 if (oldValue == from)
2862 inset.setParam(paramName, to);
2868 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2869 pit_type par_end, bool full_source) const
2871 OutputParams runparams(¶ms().encoding());
2872 runparams.nice = true;
2873 runparams.flavor = params().useXetex ?
2874 OutputParams::XETEX : OutputParams::LATEX;
2875 runparams.linelen = lyxrc.plaintext_linelen;
2876 // No side effect of file copying and image conversion
2877 runparams.dryrun = true;
2880 os << "% " << _("Preview source code") << "\n\n";
2882 d->texrow.newline();
2883 d->texrow.newline();
2885 writeDocBookSource(os, absFileName(), runparams, false);
2887 // latex or literate
2888 writeLaTeXSource(os, string(), runparams, true, true);
2890 runparams.par_begin = par_begin;
2891 runparams.par_end = par_end;
2892 if (par_begin + 1 == par_end) {
2894 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2898 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2899 convert<docstring>(par_begin),
2900 convert<docstring>(par_end - 1))
2907 // output paragraphs
2909 docbookParagraphs(text(), *this, os, runparams);
2911 // latex or literate
2912 latexParagraphs(*this, text(), os, texrow, runparams);
2917 ErrorList & Buffer::errorList(string const & type) const
2919 static ErrorList emptyErrorList;
2920 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2921 if (I == d->errorLists.end())
2922 return emptyErrorList;
2928 void Buffer::updateTocItem(std::string const & type,
2929 DocIterator const & dit) const
2932 d->gui_->updateTocItem(type, dit);
2936 void Buffer::structureChanged() const
2939 d->gui_->structureChanged();
2943 void Buffer::errors(string const & err, bool from_master) const
2946 d->gui_->errors(err, from_master);
2950 void Buffer::message(docstring const & msg) const
2953 d->gui_->message(msg);
2957 void Buffer::setBusy(bool on) const
2960 d->gui_->setBusy(on);
2964 void Buffer::updateTitles() const
2967 d->wa_->updateTitles();
2971 void Buffer::resetAutosaveTimers() const
2974 d->gui_->resetAutosaveTimers();
2978 bool Buffer::hasGuiDelegate() const
2984 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2993 class AutoSaveBuffer : public ForkedProcess {
2996 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2997 : buffer_(buffer), fname_(fname) {}
2999 virtual boost::shared_ptr<ForkedProcess> clone() const
3001 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3006 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3007 from_utf8(fname_.absFilename())));
3008 return run(DontWait);
3012 virtual int generateChild();
3014 Buffer const & buffer_;
3019 int AutoSaveBuffer::generateChild()
3021 #if defined(__APPLE__)
3022 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3023 * We should use something else like threads.
3025 * Since I do not know how to determine at run time what is the OS X
3026 * version, I just disable forking altogether for now (JMarc)
3028 pid_t const pid = -1;
3030 // tmp_ret will be located (usually) in /tmp
3031 // will that be a problem?
3032 // Note that this calls ForkedCalls::fork(), so it's
3033 // ok cross-platform.
3034 pid_t const pid = fork();
3035 // If you want to debug the autosave
3036 // you should set pid to -1, and comment out the fork.
3037 if (pid != 0 && pid != -1)
3041 // pid = -1 signifies that lyx was unable
3042 // to fork. But we will do the save
3044 bool failed = false;
3045 FileName const tmp_ret = FileName::tempName("lyxauto");
3046 if (!tmp_ret.empty()) {
3047 buffer_.writeFile(tmp_ret);
3048 // assume successful write of tmp_ret
3049 if (!tmp_ret.moveTo(fname_))
3055 // failed to write/rename tmp_ret so try writing direct
3056 if (!buffer_.writeFile(fname_)) {
3057 // It is dangerous to do this in the child,
3058 // but safe in the parent, so...
3059 if (pid == -1) // emit message signal.
3060 buffer_.message(_("Autosave failed!"));
3064 if (pid == 0) // we are the child so...
3073 FileName Buffer::getAutosaveFilename() const
3075 // if the document is unnamed try to save in the backup dir, else
3076 // in the default document path, and as a last try in the filePath,
3077 // which will most often be the temporary directory
3080 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3081 : lyxrc.backupdir_path;
3082 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3085 string const fname = "#" + d->filename.onlyFileName() + "#";
3086 return makeAbsPath(fname, fpath);
3090 void Buffer::removeAutosaveFile() const
3092 FileName const f = getAutosaveFilename();
3098 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3100 FileName const newauto = getAutosaveFilename();
3101 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3102 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3106 // Perfect target for a thread...
3107 void Buffer::autoSave() const
3109 if (d->bak_clean || isReadonly()) {
3110 // We don't save now, but we'll try again later
3111 resetAutosaveTimers();
3115 // emit message signal.
3116 message(_("Autosaving current document..."));
3117 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3120 d->bak_clean = true;
3122 resetAutosaveTimers();
3126 string Buffer::bufferFormat() const
3128 string format = params().documentClass().outputFormat();
3129 if (format == "latex") {
3130 if (params().useXetex)
3132 if (params().encoding().package() == Encoding::japanese)
3139 string Buffer::getDefaultOutputFormat() const
3141 if (!params().defaultOutputFormat.empty()
3142 && params().defaultOutputFormat != "default")
3143 return params().defaultOutputFormat;
3144 typedef vector<Format const *> Formats;
3145 Formats formats = exportableFormats(true);
3148 || params().useXetex
3149 || params().encoding().package() == Encoding::japanese) {
3150 if (formats.empty())
3152 // return the first we find
3153 return formats.front()->name();
3155 return lyxrc.default_view_format;
3160 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3161 bool includeall, string & result_file) const
3163 string backend_format;
3164 OutputParams runparams(¶ms().encoding());
3165 runparams.flavor = OutputParams::LATEX;
3166 runparams.linelen = lyxrc.plaintext_linelen;
3167 runparams.includeall = includeall;
3168 vector<string> backs = backends();
3169 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3170 // Get shortest path to format
3171 Graph::EdgePath path;
3172 for (vector<string>::const_iterator it = backs.begin();
3173 it != backs.end(); ++it) {
3174 Graph::EdgePath p = theConverters().getPath(*it, format);
3175 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3176 backend_format = *it;
3181 if (!put_in_tempdir) {
3182 // Only show this alert if this is an export to a non-temporary
3183 // file (not for previewing).
3184 Alert::error(_("Couldn't export file"), bformat(
3185 _("No information for exporting the format %1$s."),
3186 formats.prettyName(format)));
3190 runparams.flavor = theConverters().getFlavor(path);
3193 backend_format = format;
3194 // FIXME: Don't hardcode format names here, but use a flag
3195 if (backend_format == "pdflatex")
3196 runparams.flavor = OutputParams::PDFLATEX;
3199 string filename = latexName(false);
3200 filename = addName(temppath(), filename);
3201 filename = changeExtension(filename,
3202 formats.extension(backend_format));
3205 updateMacroInstances();
3207 // Plain text backend
3208 if (backend_format == "text") {
3209 runparams.flavor = OutputParams::TEXT;
3210 writePlaintextFile(*this, FileName(filename), runparams);
3213 else if (backend_format == "xhtml") {
3214 runparams.flavor = OutputParams::HTML;
3215 makeLyXHTMLFile(FileName(filename), runparams);
3216 } else if (backend_format == "lyx")
3217 writeFile(FileName(filename));
3219 else if (isDocBook()) {
3220 runparams.nice = !put_in_tempdir;
3221 makeDocBookFile(FileName(filename), runparams);
3224 else if (backend_format == format) {
3225 runparams.nice = true;
3226 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3228 } else if (!lyxrc.tex_allows_spaces
3229 && contains(filePath(), ' ')) {
3230 Alert::error(_("File name error"),
3231 _("The directory path to the document cannot contain spaces."));
3234 runparams.nice = false;
3235 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3239 string const error_type = (format == "program")
3240 ? "Build" : bufferFormat();
3241 ErrorList & error_list = d->errorLists[error_type];
3242 string const ext = formats.extension(format);
3243 FileName const tmp_result_file(changeExtension(filename, ext));
3244 bool const success = theConverters().convert(this, FileName(filename),
3245 tmp_result_file, FileName(absFileName()), backend_format, format,
3247 // Emit the signal to show the error list.
3248 if (format != backend_format) {
3250 // also to the children, in case of master-buffer-view
3251 std::vector<Buffer *> clist = getChildren();
3252 for (vector<Buffer *>::const_iterator cit = clist.begin();
3253 cit != clist.end(); ++cit)
3254 (*cit)->errors(error_type, true);
3259 if (d->cloned_buffer_) {
3260 // Enable reverse dvi or pdf to work by copying back the texrow
3261 // object to the cloned buffer.
3262 // FIXME: There is a possibility of concurrent access to texrow
3263 // here from the main GUI thread that should be securized.
3264 d->cloned_buffer_->d->texrow = d->texrow;
3267 if (put_in_tempdir) {
3268 result_file = tmp_result_file.absFilename();
3272 result_file = changeExtension(d->exportFileName().absFilename(), ext);
3273 // We need to copy referenced files (e. g. included graphics
3274 // if format == "dvi") to the result dir.
3275 vector<ExportedFile> const files =
3276 runparams.exportdata->externalFiles(format);
3277 string const dest = onlyPath(result_file);
3278 CopyStatus status = SUCCESS;
3280 vector<ExportedFile>::const_iterator it = files.begin();
3281 vector<ExportedFile>::const_iterator const en = files.end();
3282 for (; it != en && status != CANCEL; ++it) {
3283 string const fmt = formats.getFormatFromFile(it->sourceName);
3284 status = copyFile(fmt, it->sourceName,
3285 makeAbsPath(it->exportName, dest),
3286 it->exportName, status == FORCE);
3289 if (status == CANCEL) {
3290 message(_("Document export cancelled."));
3291 } else if (tmp_result_file.exists()) {
3292 // Finally copy the main file
3293 status = copyFile(format, tmp_result_file,
3294 FileName(result_file), result_file,
3296 message(bformat(_("Document exported as %1$s "
3298 formats.prettyName(format),
3299 makeDisplayPath(result_file)));
3301 // This must be a dummy converter like fax (bug 1888)
3302 message(bformat(_("Document exported as %1$s"),
3303 formats.prettyName(format)));
3310 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3311 bool includeall) const
3314 // (1) export with all included children (omit \includeonly)
3315 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3317 // (2) export with included children only
3318 return doExport(format, put_in_tempdir, false, result_file);
3322 bool Buffer::preview(string const & format, bool includeall) const
3325 // (1) export with all included children (omit \includeonly)
3326 if (includeall && !doExport(format, true, true))
3328 // (2) export with included children only
3329 if (!doExport(format, true, false, result_file))
3331 return formats.view(*this, FileName(result_file), format);
3335 bool Buffer::isExportable(string const & format) const
3337 vector<string> backs = backends();
3338 for (vector<string>::const_iterator it = backs.begin();
3339 it != backs.end(); ++it)
3340 if (theConverters().isReachable(*it, format))
3346 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3348 vector<string> const backs = backends();
3349 vector<Format const *> result =
3350 theConverters().getReachable(backs[0], only_viewable, true);
3351 for (vector<string>::const_iterator it = backs.begin() + 1;
3352 it != backs.end(); ++it) {
3353 vector<Format const *> r =
3354 theConverters().getReachable(*it, only_viewable, false);
3355 result.insert(result.end(), r.begin(), r.end());
3361 vector<string> Buffer::backends() const
3364 v.push_back(bufferFormat());
3365 // FIXME: Don't hardcode format names here, but use a flag
3366 if (v.back() == "latex")
3367 v.push_back("pdflatex");
3368 v.push_back("xhtml");
3369 v.push_back("text");
3375 bool Buffer::readFileHelper(FileName const & s)
3377 // File information about normal file
3379 docstring const file = makeDisplayPath(s.absFilename(), 50);
3380 docstring text = bformat(_("The specified document\n%1$s"
3381 "\ncould not be read."), file);
3382 Alert::error(_("Could not read document"), text);
3386 // Check if emergency save file exists and is newer.
3387 FileName const e(s.absFilename() + ".emergency");
3389 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3390 docstring const file = makeDisplayPath(s.absFilename(), 20);
3391 docstring const text =
3392 bformat(_("An emergency save of the document "
3394 "Recover emergency save?"), file);
3395 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3396 _("&Recover"), _("&Load Original"),
3400 // the file is not saved if we load the emergency file.
3405 if ((res = readFile(e)) == success)
3406 str = _("Document was successfully recovered.");
3408 str = _("Document was NOT successfully recovered.");
3409 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3410 from_utf8(e.absFilename()));
3412 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3413 _("&Remove"), _("&Keep it"))) {
3416 Alert::warning(_("Emergency file deleted"),
3417 _("Do not forget to save your file now!"), true);
3422 if (!Alert::prompt(_("Delete emergency file?"),
3423 _("Remove emergency file now?"), 1, 1,
3424 _("&Remove"), _("&Keep it")))
3432 // Now check if autosave file is newer.
3433 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3435 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3436 docstring const file = makeDisplayPath(s.absFilename(), 20);
3437 docstring const text =
3438 bformat(_("The backup of the document "
3439 "%1$s is newer.\n\nLoad the "
3440 "backup instead?"), file);
3441 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3442 _("&Load backup"), _("Load &original"),
3446 // the file is not saved if we load the autosave file.
3450 // Here we delete the autosave
3461 bool Buffer::loadLyXFile(FileName const & s)
3463 // If the file is not readable, we try to
3464 // retrieve the file from version control.
3465 if (!s.isReadableFile()
3466 && !LyXVC::file_not_found_hook(s))
3469 if (s.isReadableFile()
3470 && readFileHelper(s)) {
3471 lyxvc().file_found_hook(s);
3472 setReadonly(!s.isWritable());
3479 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3481 TeXErrors::Errors::const_iterator cit = terr.begin();
3482 TeXErrors::Errors::const_iterator end = terr.end();
3484 for (; cit != end; ++cit) {
3487 int errorRow = cit->error_in_line;
3488 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3494 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3495 } while (found && id_start == id_end && pos_start == pos_end);
3497 errorList.push_back(ErrorItem(cit->error_desc,
3498 cit->error_text, id_start, pos_start, pos_end));
3503 void Buffer::setBuffersForInsets() const
3505 inset().setBuffer(const_cast<Buffer &>(*this));
3509 void Buffer::updateLabels(UpdateScope scope, UpdateType utype) const
3511 // Use the master text class also for child documents
3512 Buffer const * const master = masterBuffer();
3513 DocumentClass const & textclass = master->params().documentClass();
3515 // do this only if we are the top-level Buffer
3516 if (scope != UpdateMaster || master == this)
3517 checkBibInfoCache();
3519 // keep the buffers to be children in this set. If the call from the
3520 // master comes back we can see which of them were actually seen (i.e.
3521 // via an InsetInclude). The remaining ones in the set need still be updated.
3522 static std::set<Buffer const *> bufToUpdate;
3523 if (scope == UpdateMaster) {
3524 // If this is a child document start with the master
3525 if (master != this) {
3526 bufToUpdate.insert(this);
3527 master->updateLabels(UpdateMaster, utype);
3528 // Do this here in case the master has no gui associated with it. Then,
3529 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3530 if (!master->d->gui_)
3533 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3534 if (bufToUpdate.find(this) == bufToUpdate.end())
3538 // start over the counters in the master
3539 textclass.counters().reset();
3542 // update will be done below for this buffer
3543 bufToUpdate.erase(this);
3545 // update all caches
3546 clearReferenceCache();
3549 Buffer & cbuf = const_cast<Buffer &>(*this);
3551 LASSERT(!text().paragraphs().empty(), /**/);
3554 ParIterator parit = cbuf.par_iterator_begin();
3555 updateLabels(parit, utype);
3558 // TocBackend update will be done later.
3561 cbuf.tocBackend().update();
3562 if (scope == UpdateMaster)
3563 cbuf.structureChanged();
3567 static depth_type getDepth(DocIterator const & it)
3569 depth_type depth = 0;
3570 for (size_t i = 0 ; i < it.depth() ; ++i)
3571 if (!it[i].inset().inMathed())
3572 depth += it[i].paragraph().getDepth() + 1;
3573 // remove 1 since the outer inset does not count
3577 static depth_type getItemDepth(ParIterator const & it)
3579 Paragraph const & par = *it;
3580 LabelType const labeltype = par.layout().labeltype;
3582 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3585 // this will hold the lowest depth encountered up to now.
3586 depth_type min_depth = getDepth(it);
3587 ParIterator prev_it = it;
3590 --prev_it.top().pit();
3592 // start of nested inset: go to outer par
3594 if (prev_it.empty()) {
3595 // start of document: nothing to do
3600 // We search for the first paragraph with same label
3601 // that is not more deeply nested.
3602 Paragraph & prev_par = *prev_it;
3603 depth_type const prev_depth = getDepth(prev_it);
3604 if (labeltype == prev_par.layout().labeltype) {
3605 if (prev_depth < min_depth)
3606 return prev_par.itemdepth + 1;
3607 if (prev_depth == min_depth)
3608 return prev_par.itemdepth;
3610 min_depth = min(min_depth, prev_depth);
3611 // small optimization: if we are at depth 0, we won't
3612 // find anything else
3613 if (prev_depth == 0)
3619 static bool needEnumCounterReset(ParIterator const & it)
3621 Paragraph const & par = *it;
3622 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3623 depth_type const cur_depth = par.getDepth();
3624 ParIterator prev_it = it;
3625 while (prev_it.pit()) {
3626 --prev_it.top().pit();
3627 Paragraph const & prev_par = *prev_it;
3628 if (prev_par.getDepth() <= cur_depth)
3629 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3631 // start of nested inset: reset
3636 // set the label of a paragraph. This includes the counters.
3637 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3639 BufferParams const & bp = owner_->masterBuffer()->params();
3640 DocumentClass const & textclass = bp.documentClass();
3641 Paragraph & par = it.paragraph();
3642 Layout const & layout = par.layout();
3643 Counters & counters = textclass.counters();
3645 if (par.params().startOfAppendix()) {
3646 // FIXME: only the counter corresponding to toplevel
3647 // sectioning should be reset
3649 counters.appendix(true);
3651 par.params().appendix(counters.appendix());
3653 // Compute the item depth of the paragraph
3654 par.itemdepth = getItemDepth(it);
3656 if (layout.margintype == MARGIN_MANUAL
3657 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3658 if (par.params().labelWidthString().empty())
3659 par.params().labelWidthString(par.expandLabel(layout, bp));
3661 par.params().labelWidthString(docstring());
3664 switch(layout.labeltype) {
3666 if (layout.toclevel <= bp.secnumdepth
3667 && (layout.latextype != LATEX_ENVIRONMENT
3668 || it.text()->isFirstInSequence(it.pit()))) {
3669 counters.step(layout.counter, utype);
3670 par.params().labelString(
3671 par.expandLabel(layout, bp));
3673 par.params().labelString(docstring());
3676 case LABEL_ITEMIZE: {
3677 // At some point of time we should do something more
3678 // clever here, like:
3679 // par.params().labelString(
3680 // bp.user_defined_bullet(par.itemdepth).getText());
3681 // for now, use a simple hardcoded label
3682 docstring itemlabel;
3683 switch (par.itemdepth) {
3685 itemlabel = char_type(0x2022);
3688 itemlabel = char_type(0x2013);
3691 itemlabel = char_type(0x2217);
3694 itemlabel = char_type(0x2219); // or 0x00b7
3697 par.params().labelString(itemlabel);
3701 case LABEL_ENUMERATE: {
3702 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3704 switch (par.itemdepth) {
3713 enumcounter += "iv";
3716 // not a valid enumdepth...
3720 // Maybe we have to reset the enumeration counter.
3721 if (needEnumCounterReset(it))
3722 counters.reset(enumcounter);
3723 counters.step(enumcounter, utype);
3725 string const & lang = par.getParLanguage(bp)->code();
3726 par.params().labelString(counters.theCounter(enumcounter, lang));
3731 case LABEL_SENSITIVE: {
3732 string const & type = counters.current_float();
3733 docstring full_label;
3735 full_label = owner_->B_("Senseless!!! ");
3737 docstring name = owner_->B_(textclass.floats().getType(type).name());
3738 if (counters.hasCounter(from_utf8(type))) {
3739 string const & lang = par.getParLanguage(bp)->code();
3740 counters.step(from_utf8(type), utype);
3741 full_label = bformat(from_ascii("%1$s %2$s:"),
3743 counters.theCounter(from_utf8(type), lang));
3745 full_label = bformat(from_ascii("%1$s #:"), name);
3747 par.params().labelString(full_label);
3751 case LABEL_NO_LABEL:
3752 par.params().labelString(docstring());
3756 case LABEL_TOP_ENVIRONMENT:
3757 case LABEL_CENTERED_TOP_ENVIRONMENT:
3760 par.params().labelString(par.expandLabel(layout, bp));
3766 void Buffer::updateLabels(ParIterator & parit, UpdateType utype) const
3768 LASSERT(parit.pit() == 0, /**/);
3770 // set the position of the text in the buffer to be able
3771 // to resolve macros in it. This has nothing to do with
3772 // labels, but by putting it here we avoid implementing
3773 // a whole bunch of traversal routines just for this call.
3774 parit.text()->setMacrocontextPosition(parit);
3776 depth_type maxdepth = 0;
3777 pit_type const lastpit = parit.lastpit();
3778 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3779 // reduce depth if necessary
3780 parit->params().depth(min(parit->params().depth(), maxdepth));
3781 maxdepth = parit->getMaxDepthAfter();
3783 if (utype == OutputUpdate) {
3784 // track the active counters
3785 // we have to do this for the master buffer, since the local
3786 // buffer isn't tracking anything.
3787 masterBuffer()->params().documentClass().counters().
3788 setActiveLayout(parit->layout());
3791 // set the counter for this paragraph
3792 d->setLabel(parit, utype);
3795 InsetList::const_iterator iit = parit->insetList().begin();
3796 InsetList::const_iterator end = parit->insetList().end();
3797 for (; iit != end; ++iit) {
3798 parit.pos() = iit->pos;
3799 iit->inset->updateLabels(parit, utype);
3805 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3806 WordLangTuple & word_lang, docstring_list & suggestions) const
3810 suggestions.clear();
3811 word_lang = WordLangTuple();
3812 // OK, we start from here.
3813 DocIterator const end = doc_iterator_end(this);
3814 for (; from != end; from.forwardPos()) {
3815 // We are only interested in text so remove the math CursorSlice.
3816 while (from.inMathed()) {
3820 // If from is at the end of the document (which is possible
3821 // when leaving the mathed) LyX will crash later.
3825 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3830 // Do not increase progress when from == to, otherwise the word
3831 // count will be wrong.
3841 bool Buffer::reload()
3844 // e.g., read-only status could have changed due to version control
3845 d->filename.refresh();
3846 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3848 bool const success = loadLyXFile(d->filename);
3853 message(bformat(_("Document %1$s reloaded."), disp_fn));
3855 message(bformat(_("Could not reload document %1$s."), disp_fn));