3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 376; // jspitzm: support for unincluded file maintenance
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 void collectRelatives(BufferSet & bufs) const;
173 /** If we have branches that use the file suffix
174 feature, return the file name with suffix appended.
176 support::FileName exportFileName() const;
183 mutable TexRow texrow;
185 /// need to regenerate .tex?
189 mutable bool lyx_clean;
191 /// is autosave needed?
192 mutable bool bak_clean;
194 /// is this a unnamed file (New...)?
200 /// name of the file the buffer is associated with.
203 /** Set to true only when the file is fully loaded.
204 * Used to prevent the premature generation of previews
205 * and by the citation inset.
207 bool file_fully_loaded;
210 mutable TocBackend toc_backend;
213 typedef pair<DocIterator, MacroData> ScopeMacro;
214 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
215 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
216 /// map from the macro name to the position map,
217 /// which maps the macro definition position to the scope and the MacroData.
218 NamePositionScopeMacroMap macros;
219 /// This seem to change the way Buffer::getMacro() works
220 mutable bool macro_lock;
222 /// positions of child buffers in the buffer
223 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
224 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
225 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
226 /// position of children buffers in this buffer
227 BufferPositionMap children_positions;
228 /// map from children inclusion positions to their scope and their buffer
229 PositionScopeBufferMap position_to_children;
231 /// Container for all sort of Buffer dependant errors.
232 map<string, ErrorList> errorLists;
234 /// timestamp and checksum used to test if the file has been externally
235 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
237 unsigned long checksum_;
240 frontend::WorkAreaManager * wa_;
242 frontend::GuiBufferDelegate * gui_;
247 /// A cache for the bibfiles (including bibfiles of loaded child
248 /// documents), needed for appropriate update of natbib labels.
249 mutable support::FileNameList bibfiles_cache_;
251 // FIXME The caching mechanism could be improved. At present, we have a
252 // cache for each Buffer, that caches all the bibliography info for that
253 // Buffer. A more efficient solution would be to have a global cache per
254 // file, and then to construct the Buffer's bibinfo from that.
255 /// A cache for bibliography info
256 mutable BiblioInfo bibinfo_;
257 /// whether the bibinfo cache is valid
258 bool bibinfo_cache_valid_;
259 /// Cache of timestamps of .bib files
260 map<FileName, time_t> bibfile_status_;
262 mutable RefCache ref_cache_;
264 /// our Text that should be wrapped in an InsetText
267 /// This is here to force the test to be done whenever parent_buffer
269 Buffer const * parent() const {
270 // if parent_buffer is not loaded, then it has been unloaded,
271 // which means that parent_buffer is an invalid pointer. So we
272 // set it to null in that case.
273 // however, the BufferList doesn't know about cloned buffers, so
274 // they will always be regarded as unloaded. in that case, we hope
276 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
278 return parent_buffer;
281 void setParent(Buffer const * pb) {
282 if (parent_buffer && pb && parent_buffer != pb)
283 LYXERR0("Warning: a buffer should not have two parents!");
287 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
288 /// This one is useful for preview detached in a thread.
289 Buffer const * cloned_buffer_;
292 /// So we can force access via the accessors.
293 mutable Buffer const * parent_buffer;
298 /// Creates the per buffer temporary directory
299 static FileName createBufferTmpDir()
302 // We are in our own directory. Why bother to mangle name?
303 // In fact I wrote this code to circumvent a problematic behaviour
304 // (bug?) of EMX mkstemp().
305 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
306 convert<string>(count++));
308 if (!tmpfl.createDirectory(0777)) {
309 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
310 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
311 from_utf8(tmpfl.absFilename())));
317 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
318 Buffer const * cloned_buffer)
319 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
320 read_only(readonly_), filename(file), file_fully_loaded(false),
321 toc_backend(owner), macro_lock(false), timestamp_(0),
322 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
323 cloned_buffer_(cloned_buffer), parent_buffer(0)
325 if (!cloned_buffer_) {
326 temppath = createBufferTmpDir();
327 lyxvc.setBuffer(owner_);
329 wa_ = new frontend::WorkAreaManager;
332 temppath = cloned_buffer_->d->temppath;
333 file_fully_loaded = true;
334 params = cloned_buffer_->d->params;
335 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
336 bibinfo_ = cloned_buffer_->d->bibinfo_;
337 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
338 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
342 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
343 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
345 LYXERR(Debug::INFO, "Buffer::Buffer()");
347 d->inset = new InsetText(*cloned_buffer->d->inset);
348 d->inset->setBuffer(*this);
349 // FIXME: optimize this loop somewhat, maybe by creating a new
350 // general recursive Inset::setId().
351 DocIterator it = doc_iterator_begin(this);
352 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
353 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
354 it.paragraph().setId(cloned_it.paragraph().id());
356 d->inset = new InsetText(this);
357 d->inset->setAutoBreakRows(true);
358 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
364 LYXERR(Debug::INFO, "Buffer::~Buffer()");
365 // here the buffer should take care that it is
366 // saved properly, before it goes into the void.
368 // GuiView already destroyed
372 // No need to do additional cleanups for internal buffer.
377 // loop over children
378 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
379 Impl::BufferPositionMap::iterator end = d->children_positions.end();
380 for (; it != end; ++it) {
381 Buffer * child = const_cast<Buffer *>(it->first);
382 if (d->cloned_buffer_)
384 // The child buffer might have been closed already.
385 else if (theBufferList().isLoaded(child))
386 theBufferList().releaseChild(this, child);
390 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
391 msg += emergencyWrite();
392 Alert::warning(_("Attempting to close changed document!"), msg);
395 // clear references to children in macro tables
396 d->children_positions.clear();
397 d->position_to_children.clear();
399 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
400 Alert::warning(_("Could not remove temporary directory"),
401 bformat(_("Could not remove the temporary directory %1$s"),
402 from_utf8(d->temppath.absFilename())));
405 // Remove any previewed LaTeX snippets associated with this buffer.
406 thePreviews().removeLoader(*this);
412 Buffer * Buffer::clone() const
414 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
415 buffer_clone->d->macro_lock = true;
416 buffer_clone->d->children_positions.clear();
417 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
418 // math macro caches need to be rethought and simplified.
419 // I am not sure wether we should handle Buffer cloning here or in BufferList.
420 // Right now BufferList knows nothing about buffer clones.
421 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
422 Impl::BufferPositionMap::iterator end = d->children_positions.end();
423 for (; it != end; ++it) {
424 DocIterator dit = it->second.clone(buffer_clone);
425 dit.setBuffer(buffer_clone);
426 Buffer * child = const_cast<Buffer *>(it->first);
427 Buffer * child_clone = child->clone();
428 Inset * inset = dit.nextInset();
429 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
430 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
431 inset_inc->setChildBuffer(child_clone);
432 child_clone->d->setParent(buffer_clone);
433 buffer_clone->setChild(dit, child_clone);
435 buffer_clone->d->macro_lock = false;
440 bool Buffer::isClone() const
442 return d->cloned_buffer_;
446 void Buffer::changed(bool update_metrics) const
449 d->wa_->redrawAll(update_metrics);
453 frontend::WorkAreaManager & Buffer::workAreaManager() const
455 LASSERT(d->wa_, /**/);
460 Text & Buffer::text() const
462 return d->inset->text();
466 Inset & Buffer::inset() const
472 BufferParams & Buffer::params()
478 BufferParams const & Buffer::params() const
484 ParagraphList & Buffer::paragraphs()
486 return text().paragraphs();
490 ParagraphList const & Buffer::paragraphs() const
492 return text().paragraphs();
496 LyXVC & Buffer::lyxvc()
502 LyXVC const & Buffer::lyxvc() const
508 string const Buffer::temppath() const
510 return d->temppath.absFilename();
514 TexRow & Buffer::texrow()
520 TexRow const & Buffer::texrow() const
526 TocBackend & Buffer::tocBackend() const
528 return d->toc_backend;
532 Undo & Buffer::undo()
538 void Buffer::setChild(DocIterator const & dit, Buffer * child)
540 d->children_positions[child] = dit;
544 string Buffer::latexName(bool const no_path) const
546 FileName latex_name =
547 makeLatexName(d->exportFileName());
548 return no_path ? latex_name.onlyFileName()
549 : latex_name.absFilename();
553 FileName Buffer::Impl::exportFileName() const
555 docstring const branch_suffix =
556 params.branchlist().getFilenameSuffix();
557 if (branch_suffix.empty())
560 string const name = filename.onlyFileNameWithoutExt()
561 + to_utf8(branch_suffix);
562 FileName res(filename.onlyPath().absFilename() + "/" + name);
563 res.changeExtension(filename.extension());
569 string Buffer::logName(LogType * type) const
571 string const filename = latexName(false);
573 if (filename.empty()) {
579 string const path = temppath();
581 FileName const fname(addName(temppath(),
582 onlyFilename(changeExtension(filename,
585 // FIXME: how do we know this is the name of the build log?
586 FileName const bname(
587 addName(path, onlyFilename(
588 changeExtension(filename,
589 formats.extension(bufferFormat()) + ".out"))));
591 // Also consider the master buffer log file
592 FileName masterfname = fname;
594 if (masterBuffer() != this) {
595 string const mlogfile = masterBuffer()->logName(&mtype);
596 masterfname = FileName(mlogfile);
599 // If no Latex log or Build log is newer, show Build log
600 if (bname.exists() &&
601 ((!fname.exists() && !masterfname.exists())
602 || (fname.lastModified() < bname.lastModified()
603 && masterfname.lastModified() < bname.lastModified()))) {
604 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
607 return bname.absFilename();
608 // If we have a newer master file log or only a master log, show this
609 } else if (fname != masterfname
610 && (!fname.exists() && (masterfname.exists()
611 || fname.lastModified() < masterfname.lastModified()))) {
612 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
615 return masterfname.absFilename();
617 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
620 return fname.absFilename();
624 void Buffer::setReadonly(bool const flag)
626 if (d->read_only != flag) {
633 void Buffer::setFileName(string const & newfile)
635 d->filename = makeAbsPath(newfile);
636 setReadonly(d->filename.isReadOnly());
641 int Buffer::readHeader(Lexer & lex)
643 int unknown_tokens = 0;
645 int begin_header_line = -1;
647 // Initialize parameters that may be/go lacking in header:
648 params().branchlist().clear();
649 params().preamble.erase();
650 params().options.erase();
651 params().master.erase();
652 params().float_placement.erase();
653 params().paperwidth.erase();
654 params().paperheight.erase();
655 params().leftmargin.erase();
656 params().rightmargin.erase();
657 params().topmargin.erase();
658 params().bottommargin.erase();
659 params().headheight.erase();
660 params().headsep.erase();
661 params().footskip.erase();
662 params().columnsep.erase();
663 params().fontsCJK.erase();
664 params().listings_params.clear();
665 params().clearLayoutModules();
666 params().clearRemovedModules();
667 params().clearIncludedChildren();
668 params().pdfoptions().clear();
669 params().indiceslist().clear();
670 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
672 for (int i = 0; i < 4; ++i) {
673 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
674 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
677 ErrorList & errorList = d->errorLists["Parse"];
686 if (token == "\\end_header")
690 if (token == "\\begin_header") {
691 begin_header_line = line;
695 LYXERR(Debug::PARSER, "Handling document header token: `"
698 string unknown = params().readToken(lex, token, d->filename.onlyPath());
699 if (!unknown.empty()) {
700 if (unknown[0] != '\\' && token == "\\textclass") {
701 Alert::warning(_("Unknown document class"),
702 bformat(_("Using the default document class, because the "
703 "class %1$s is unknown."), from_utf8(unknown)));
706 docstring const s = bformat(_("Unknown token: "
710 errorList.push_back(ErrorItem(_("Document header error"),
715 if (begin_header_line) {
716 docstring const s = _("\\begin_header is missing");
717 errorList.push_back(ErrorItem(_("Document header error"),
721 params().makeDocumentClass();
723 return unknown_tokens;
728 // changed to be public and have one parameter
729 // Returns true if "\end_document" is not read (Asger)
730 bool Buffer::readDocument(Lexer & lex)
732 ErrorList & errorList = d->errorLists["Parse"];
735 if (!lex.checkFor("\\begin_document")) {
736 docstring const s = _("\\begin_document is missing");
737 errorList.push_back(ErrorItem(_("Document header error"),
741 // we are reading in a brand new document
742 LASSERT(paragraphs().empty(), /**/);
746 if (params().outputChanges) {
747 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
748 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
749 LaTeXFeatures::isAvailable("xcolor");
751 if (!dvipost && !xcolorulem) {
752 Alert::warning(_("Changes not shown in LaTeX output"),
753 _("Changes will not be highlighted in LaTeX output, "
754 "because neither dvipost nor xcolor/ulem are installed.\n"
755 "Please install these packages or redefine "
756 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
757 } else if (!xcolorulem) {
758 Alert::warning(_("Changes not shown in LaTeX output"),
759 _("Changes will not be highlighted in LaTeX output "
760 "when using pdflatex, because xcolor and ulem are not installed.\n"
761 "Please install both packages or redefine "
762 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
766 if (!params().master.empty()) {
767 FileName const master_file = makeAbsPath(params().master,
768 onlyPath(absFileName()));
769 if (isLyXFilename(master_file.absFilename())) {
771 checkAndLoadLyXFile(master_file, true);
773 // necessary e.g. after a reload
774 // to re-register the child (bug 5873)
775 // FIXME: clean up updateMacros (here, only
776 // child registering is needed).
777 master->updateMacros();
778 // set master as master buffer, but only
779 // if we are a real child
780 if (master->isChild(this))
782 // if the master is not fully loaded
783 // it is probably just loading this
784 // child. No warning needed then.
785 else if (master->isFullyLoaded())
786 LYXERR0("The master '"
788 << "' assigned to this document ("
790 << ") does not include "
791 "this document. Ignoring the master assignment.");
796 // assure we have a default index
797 params().indiceslist().addDefault(B_("Index"));
800 bool const res = text().read(lex, errorList, d->inset);
804 updateMacroInstances();
809 bool Buffer::readString(string const & s)
811 params().compressed = false;
813 // remove dummy empty par
814 paragraphs().clear();
818 FileName const name = FileName::tempName("Buffer_readString");
819 switch (readFile(lex, name, true)) {
823 // We need to call lyx2lyx, so write the input to a file
824 ofstream os(name.toFilesystemEncoding().c_str());
827 return readFile(name);
837 bool Buffer::readFile(FileName const & filename)
839 FileName fname(filename);
841 params().compressed = fname.isZippedFile();
843 // remove dummy empty par
844 paragraphs().clear();
847 if (readFile(lex, fname) != success)
854 bool Buffer::isFullyLoaded() const
856 return d->file_fully_loaded;
860 void Buffer::setFullyLoaded(bool value)
862 d->file_fully_loaded = value;
866 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
869 LASSERT(!filename.empty(), /**/);
871 // the first (non-comment) token _must_ be...
872 if (!lex.checkFor("\\lyxformat")) {
873 Alert::error(_("Document format failure"),
874 bformat(_("%1$s is not a readable LyX document."),
875 from_utf8(filename.absFilename())));
881 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
882 // if present remove ".," from string.
883 size_t dot = tmp_format.find_first_of(".,");
884 //lyxerr << " dot found at " << dot << endl;
885 if (dot != string::npos)
886 tmp_format.erase(dot, 1);
887 int const file_format = convert<int>(tmp_format);
888 //lyxerr << "format: " << file_format << endl;
890 // save timestamp and checksum of the original disk file, making sure
891 // to not overwrite them with those of the file created in the tempdir
892 // when it has to be converted to the current format.
894 // Save the timestamp and checksum of disk file. If filename is an
895 // emergency file, save the timestamp and checksum of the original lyx file
896 // because isExternallyModified will check for this file. (BUG4193)
897 string diskfile = filename.absFilename();
898 if (suffixIs(diskfile, ".emergency"))
899 diskfile = diskfile.substr(0, diskfile.size() - 10);
900 saveCheckSum(FileName(diskfile));
903 if (file_format != LYX_FORMAT) {
906 // lyx2lyx would fail
909 FileName const tmpfile = FileName::tempName("Buffer_readFile");
910 if (tmpfile.empty()) {
911 Alert::error(_("Conversion failed"),
912 bformat(_("%1$s is from a different"
913 " version of LyX, but a temporary"
914 " file for converting it could"
916 from_utf8(filename.absFilename())));
919 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
920 if (lyx2lyx.empty()) {
921 Alert::error(_("Conversion script not found"),
922 bformat(_("%1$s is from a different"
923 " version of LyX, but the"
924 " conversion script lyx2lyx"
925 " could not be found."),
926 from_utf8(filename.absFilename())));
929 ostringstream command;
930 command << os::python()
931 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
932 << " -t " << convert<string>(LYX_FORMAT)
933 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
934 << ' ' << quoteName(filename.toFilesystemEncoding());
935 string const command_str = command.str();
937 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
939 cmd_ret const ret = runCommand(command_str);
940 if (ret.first != 0) {
941 if (file_format < LYX_FORMAT)
942 Alert::error(_("Conversion script failed"),
943 bformat(_("%1$s is from an older version"
944 " of LyX, but the lyx2lyx script"
945 " failed to convert it."),
946 from_utf8(filename.absFilename())));
948 Alert::error(_("Conversion script failed"),
949 bformat(_("%1$s is from a newer version"
950 " of LyX and cannot be converted by the"
952 from_utf8(filename.absFilename())));
955 bool const ret = readFile(tmpfile);
956 // Do stuff with tmpfile name and buffer name here.
957 return ret ? success : failure;
962 if (readDocument(lex)) {
963 Alert::error(_("Document format failure"),
964 bformat(_("%1$s ended unexpectedly, which means"
965 " that it is probably corrupted."),
966 from_utf8(filename.absFilename())));
970 d->file_fully_loaded = true;
975 // Should probably be moved to somewhere else: BufferView? LyXView?
976 bool Buffer::save() const
978 // We don't need autosaves in the immediate future. (Asger)
979 resetAutosaveTimers();
981 string const encodedFilename = d->filename.toFilesystemEncoding();
984 bool madeBackup = false;
986 // make a backup if the file already exists
987 if (lyxrc.make_backup && fileName().exists()) {
988 backupName = FileName(absFileName() + '~');
989 if (!lyxrc.backupdir_path.empty()) {
990 string const mangledName =
991 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
992 backupName = FileName(addName(lyxrc.backupdir_path,
995 if (fileName().copyTo(backupName)) {
998 Alert::error(_("Backup failure"),
999 bformat(_("Cannot create backup file %1$s.\n"
1000 "Please check whether the directory exists and is writeable."),
1001 from_utf8(backupName.absFilename())));
1002 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1006 // ask if the disk file has been externally modified (use checksum method)
1007 if (fileName().exists() && isExternallyModified(checksum_method)) {
1008 docstring const file = makeDisplayPath(absFileName(), 20);
1009 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1010 "you want to overwrite this file?"), file);
1011 int const ret = Alert::prompt(_("Overwrite modified file?"),
1012 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1017 if (writeFile(d->filename)) {
1021 // Saving failed, so backup is not backup
1023 backupName.moveTo(d->filename);
1029 bool Buffer::writeFile(FileName const & fname) const
1031 if (d->read_only && fname == d->filename)
1034 bool retval = false;
1036 docstring const str = bformat(_("Saving document %1$s..."),
1037 makeDisplayPath(fname.absFilename()));
1040 if (params().compressed) {
1041 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1042 retval = ofs && write(ofs);
1044 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1045 retval = ofs && write(ofs);
1049 message(str + _(" could not write file!"));
1053 removeAutosaveFile();
1055 saveCheckSum(d->filename);
1056 message(str + _(" done."));
1062 docstring Buffer::emergencyWrite()
1064 // No need to save if the buffer has not changed.
1068 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1070 docstring user_message = bformat(
1071 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1073 // We try to save three places:
1074 // 1) Same place as document. Unless it is an unnamed doc.
1076 string s = absFileName();
1079 if (writeFile(FileName(s))) {
1081 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1082 return user_message;
1084 user_message += _(" Save failed! Trying again...\n");
1088 // 2) In HOME directory.
1089 string s = addName(package().home_dir().absFilename(), absFileName());
1091 lyxerr << ' ' << s << endl;
1092 if (writeFile(FileName(s))) {
1094 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1095 return user_message;
1098 user_message += _(" Save failed! Trying yet again...\n");
1100 // 3) In "/tmp" directory.
1101 // MakeAbsPath to prepend the current
1102 // drive letter on OS/2
1103 s = addName(package().temp_dir().absFilename(), absFileName());
1105 lyxerr << ' ' << s << endl;
1106 if (writeFile(FileName(s))) {
1108 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1109 return user_message;
1112 user_message += _(" Save failed! Bummer. Document is lost.");
1115 return user_message;
1119 bool Buffer::write(ostream & ofs) const
1122 // Use the standard "C" locale for file output.
1123 ofs.imbue(locale::classic());
1126 // The top of the file should not be written by params().
1128 // write out a comment in the top of the file
1129 ofs << "#LyX " << lyx_version
1130 << " created this file. For more info see http://www.lyx.org/\n"
1131 << "\\lyxformat " << LYX_FORMAT << "\n"
1132 << "\\begin_document\n";
1134 /// For each author, set 'used' to true if there is a change
1135 /// by this author in the document; otherwise set it to 'false'.
1136 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1137 AuthorList::Authors::const_iterator a_end = params().authors().end();
1138 for (; a_it != a_end; ++a_it)
1139 a_it->setUsed(false);
1141 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1142 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1143 for ( ; it != end; ++it)
1144 it->checkAuthors(params().authors());
1146 // now write out the buffer parameters.
1147 ofs << "\\begin_header\n";
1148 params().writeFile(ofs);
1149 ofs << "\\end_header\n";
1152 ofs << "\n\\begin_body\n";
1154 ofs << "\n\\end_body\n";
1156 // Write marker that shows file is complete
1157 ofs << "\\end_document" << endl;
1159 // Shouldn't really be needed....
1162 // how to check if close went ok?
1163 // Following is an attempt... (BE 20001011)
1165 // good() returns false if any error occured, including some
1166 // formatting error.
1167 // bad() returns true if something bad happened in the buffer,
1168 // which should include file system full errors.
1173 lyxerr << "File was not closed properly." << endl;
1180 bool Buffer::makeLaTeXFile(FileName const & fname,
1181 string const & original_path,
1182 OutputParams const & runparams_in,
1183 bool output_preamble, bool output_body) const
1185 OutputParams runparams = runparams_in;
1186 if (params().useXetex)
1187 runparams.flavor = OutputParams::XETEX;
1189 string const encoding = runparams.encoding->iconvName();
1190 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1193 try { ofs.reset(encoding); }
1194 catch (iconv_codecvt_facet_exception & e) {
1195 lyxerr << "Caught iconv exception: " << e.what() << endl;
1196 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1197 "verify that the support software for your encoding (%1$s) is "
1198 "properly installed"), from_ascii(encoding)));
1201 if (!openFileWrite(ofs, fname))
1204 //TexStream ts(ofs.rdbuf(), &texrow());
1205 ErrorList & errorList = d->errorLists["Export"];
1207 bool failed_export = false;
1210 writeLaTeXSource(ofs, original_path,
1211 runparams, output_preamble, output_body);
1213 catch (EncodingException & e) {
1214 odocstringstream ods;
1215 ods.put(e.failed_char);
1217 oss << "0x" << hex << e.failed_char << dec;
1218 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1219 " (code point %2$s)"),
1220 ods.str(), from_utf8(oss.str()));
1221 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1222 "representable in the chosen encoding.\n"
1223 "Changing the document encoding to utf8 could help."),
1224 e.par_id, e.pos, e.pos + 1));
1225 failed_export = true;
1227 catch (iconv_codecvt_facet_exception & e) {
1228 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1229 _(e.what()), -1, 0, 0));
1230 failed_export = true;
1232 catch (exception const & e) {
1233 errorList.push_back(ErrorItem(_("conversion failed"),
1234 _(e.what()), -1, 0, 0));
1235 failed_export = true;
1238 lyxerr << "Caught some really weird exception..." << endl;
1244 failed_export = true;
1245 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1249 return !failed_export;
1253 void Buffer::writeLaTeXSource(odocstream & os,
1254 string const & original_path,
1255 OutputParams const & runparams_in,
1256 bool const output_preamble, bool const output_body) const
1258 // The child documents, if any, shall be already loaded at this point.
1260 OutputParams runparams = runparams_in;
1262 // Classify the unicode characters appearing in math insets
1263 Encodings::initUnicodeMath(*this);
1265 // validate the buffer.
1266 LYXERR(Debug::LATEX, " Validating buffer...");
1267 LaTeXFeatures features(*this, params(), runparams);
1269 LYXERR(Debug::LATEX, " Buffer validation done.");
1271 // The starting paragraph of the coming rows is the
1272 // first paragraph of the document. (Asger)
1273 if (output_preamble && runparams.nice) {
1274 os << "%% LyX " << lyx_version << " created this file. "
1275 "For more info, see http://www.lyx.org/.\n"
1276 "%% Do not edit unless you really know what "
1278 d->texrow.newline();
1279 d->texrow.newline();
1281 LYXERR(Debug::INFO, "lyx document header finished");
1283 // Don't move this behind the parent_buffer=0 code below,
1284 // because then the macros will not get the right "redefinition"
1285 // flag as they don't see the parent macros which are output before.
1288 // fold macros if possible, still with parent buffer as the
1289 // macros will be put in the prefix anyway.
1290 updateMacroInstances();
1292 // There are a few differences between nice LaTeX and usual files:
1293 // usual is \batchmode and has a
1294 // special input@path to allow the including of figures
1295 // with either \input or \includegraphics (what figinsets do).
1296 // input@path is set when the actual parameter
1297 // original_path is set. This is done for usual tex-file, but not
1298 // for nice-latex-file. (Matthias 250696)
1299 // Note that input@path is only needed for something the user does
1300 // in the preamble, included .tex files or ERT, files included by
1301 // LyX work without it.
1302 if (output_preamble) {
1303 if (!runparams.nice) {
1304 // code for usual, NOT nice-latex-file
1305 os << "\\batchmode\n"; // changed
1306 // from \nonstopmode
1307 d->texrow.newline();
1309 if (!original_path.empty()) {
1311 // We don't know the encoding of inputpath
1312 docstring const inputpath = from_utf8(latex_path(original_path));
1313 os << "\\makeatletter\n"
1314 << "\\def\\input@path{{"
1315 << inputpath << "/}}\n"
1316 << "\\makeatother\n";
1317 d->texrow.newline();
1318 d->texrow.newline();
1319 d->texrow.newline();
1322 // get parent macros (if this buffer has a parent) which will be
1323 // written at the document begin further down.
1324 MacroSet parentMacros;
1325 listParentMacros(parentMacros, features);
1327 // Write the preamble
1328 runparams.use_babel = params().writeLaTeX(os, features,
1330 d->filename.onlyPath());
1332 runparams.use_japanese = features.isRequired("japanese");
1338 os << "\\begin{document}\n";
1339 d->texrow.newline();
1341 // output the parent macros
1342 MacroSet::iterator it = parentMacros.begin();
1343 MacroSet::iterator end = parentMacros.end();
1344 for (; it != end; ++it) {
1345 int num_lines = (*it)->write(os, true);
1346 d->texrow.newlines(num_lines);
1349 } // output_preamble
1351 d->texrow.start(paragraphs().begin()->id(), 0);
1353 LYXERR(Debug::INFO, "preamble finished, now the body.");
1355 // if we are doing a real file with body, even if this is the
1356 // child of some other buffer, let's cut the link here.
1357 // This happens for example if only a child document is printed.
1358 Buffer const * save_parent = 0;
1359 if (output_preamble) {
1360 save_parent = d->parent();
1365 latexParagraphs(*this, text(), os, d->texrow, runparams);
1367 // Restore the parenthood if needed
1368 if (output_preamble)
1369 d->setParent(save_parent);
1371 // add this just in case after all the paragraphs
1373 d->texrow.newline();
1375 if (output_preamble) {
1376 os << "\\end{document}\n";
1377 d->texrow.newline();
1378 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1380 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1382 runparams_in.encoding = runparams.encoding;
1384 // Just to be sure. (Asger)
1385 d->texrow.newline();
1387 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1388 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1392 bool Buffer::isLatex() const
1394 return params().documentClass().outputType() == LATEX;
1398 bool Buffer::isLiterate() const
1400 return params().documentClass().outputType() == LITERATE;
1404 bool Buffer::isDocBook() const
1406 return params().documentClass().outputType() == DOCBOOK;
1410 void Buffer::makeDocBookFile(FileName const & fname,
1411 OutputParams const & runparams,
1412 bool const body_only) const
1414 LYXERR(Debug::LATEX, "makeDocBookFile...");
1417 if (!openFileWrite(ofs, fname))
1420 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1424 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1428 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1429 OutputParams const & runparams,
1430 bool const only_body) const
1432 LaTeXFeatures features(*this, params(), runparams);
1437 DocumentClass const & tclass = params().documentClass();
1438 string const top_element = tclass.latexname();
1441 if (runparams.flavor == OutputParams::XML)
1442 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1445 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1448 if (! tclass.class_header().empty())
1449 os << from_ascii(tclass.class_header());
1450 else if (runparams.flavor == OutputParams::XML)
1451 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1452 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1454 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1456 docstring preamble = from_utf8(params().preamble);
1457 if (runparams.flavor != OutputParams::XML ) {
1458 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1459 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1460 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1461 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1464 string const name = runparams.nice
1465 ? changeExtension(absFileName(), ".sgml") : fname;
1466 preamble += features.getIncludedFiles(name);
1467 preamble += features.getLyXSGMLEntities();
1469 if (!preamble.empty()) {
1470 os << "\n [ " << preamble << " ]";
1475 string top = top_element;
1477 if (runparams.flavor == OutputParams::XML)
1478 top += params().language->code();
1480 top += params().language->code().substr(0, 2);
1483 if (!params().options.empty()) {
1485 top += params().options;
1488 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1489 << " file was created by LyX " << lyx_version
1490 << "\n See http://www.lyx.org/ for more information -->\n";
1492 params().documentClass().counters().reset();
1496 sgml::openTag(os, top);
1498 docbookParagraphs(text(), *this, os, runparams);
1499 sgml::closeTag(os, top_element);
1503 void Buffer::makeLyXHTMLFile(FileName const & fname,
1504 OutputParams const & runparams,
1505 bool const body_only) const
1507 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1510 if (!openFileWrite(ofs, fname))
1513 writeLyXHTMLSource(ofs, runparams, body_only);
1517 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1521 void Buffer::writeLyXHTMLSource(odocstream & os,
1522 OutputParams const & runparams,
1523 bool const only_body) const
1525 LaTeXFeatures features(*this, params(), runparams);
1527 updateLabels(UpdateMaster, OutputUpdate);
1528 checkBibInfoCache();
1529 d->bibinfo_.makeCitationLabels(*this);
1531 updateMacroInstances();
1534 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1535 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";
1536 // FIXME Language should be set properly.
1537 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1539 // FIXME Presumably need to set this right
1540 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1541 os << "<title>" << features.htmlTitle() << "</title>\n";
1543 os << "\n<!-- Text Class Preamble -->\n"
1544 << features.getTClassHTMLPreamble()
1545 << "\n<!-- Premable Snippets -->\n"
1546 << from_utf8(features.getPreambleSnippets());
1548 os << "\n<!-- Layout-provided Styles -->\n";
1549 docstring const styleinfo = features.getTClassHTMLStyles();
1550 if (!styleinfo.empty()) {
1551 os << "<style type='text/css'>\n"
1555 os << "</head>\n<body>\n";
1559 params().documentClass().counters().reset();
1560 xhtmlParagraphs(text(), *this, xs, runparams);
1562 os << "</body>\n</html>\n";
1566 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1567 // Other flags: -wall -v0 -x
1568 int Buffer::runChktex()
1572 // get LaTeX-Filename
1573 FileName const path(temppath());
1574 string const name = addName(path.absFilename(), latexName());
1575 string const org_path = filePath();
1577 PathChanger p(path); // path to LaTeX file
1578 message(_("Running chktex..."));
1580 // Generate the LaTeX file if neccessary
1581 OutputParams runparams(¶ms().encoding());
1582 runparams.flavor = OutputParams::LATEX;
1583 runparams.nice = false;
1584 makeLaTeXFile(FileName(name), org_path, runparams);
1587 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1588 int const res = chktex.run(terr); // run chktex
1591 Alert::error(_("chktex failure"),
1592 _("Could not run chktex successfully."));
1593 } else if (res > 0) {
1594 ErrorList & errlist = d->errorLists["ChkTeX"];
1596 bufferErrors(terr, errlist);
1607 void Buffer::validate(LaTeXFeatures & features) const
1609 params().validate(features);
1613 for_each(paragraphs().begin(), paragraphs().end(),
1614 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1616 if (lyxerr.debugging(Debug::LATEX)) {
1617 features.showStruct();
1622 void Buffer::getLabelList(vector<docstring> & list) const
1624 // If this is a child document, use the parent's list instead.
1625 Buffer const * const pbuf = d->parent();
1627 pbuf->getLabelList(list);
1632 Toc & toc = d->toc_backend.toc("label");
1633 TocIterator toc_it = toc.begin();
1634 TocIterator end = toc.end();
1635 for (; toc_it != end; ++toc_it) {
1636 if (toc_it->depth() == 0)
1637 list.push_back(toc_it->str());
1642 void Buffer::updateBibfilesCache(UpdateScope scope) const
1644 // If this is a child document, use the parent's cache instead.
1645 Buffer const * const pbuf = d->parent();
1646 if (pbuf && scope != UpdateChildOnly) {
1647 pbuf->updateBibfilesCache();
1651 d->bibfiles_cache_.clear();
1652 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1653 if (it->lyxCode() == BIBTEX_CODE) {
1654 InsetBibtex const & inset =
1655 static_cast<InsetBibtex const &>(*it);
1656 support::FileNameList const bibfiles = inset.getBibFiles();
1657 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1660 } else if (it->lyxCode() == INCLUDE_CODE) {
1661 InsetInclude & inset =
1662 static_cast<InsetInclude &>(*it);
1663 inset.updateBibfilesCache();
1664 support::FileNameList const & bibfiles =
1665 inset.getBibfilesCache();
1666 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1671 // the bibinfo cache is now invalid
1672 d->bibinfo_cache_valid_ = false;
1676 void Buffer::invalidateBibinfoCache()
1678 d->bibinfo_cache_valid_ = false;
1682 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1684 // If this is a child document, use the parent's cache instead.
1685 Buffer const * const pbuf = d->parent();
1686 if (pbuf && scope != UpdateChildOnly)
1687 return pbuf->getBibfilesCache();
1689 // We update the cache when first used instead of at loading time.
1690 if (d->bibfiles_cache_.empty())
1691 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1693 return d->bibfiles_cache_;
1697 BiblioInfo const & Buffer::masterBibInfo() const
1699 // if this is a child document and the parent is already loaded
1700 // use the parent's list instead [ale990412]
1701 Buffer const * const tmp = masterBuffer();
1704 return tmp->masterBibInfo();
1705 return localBibInfo();
1709 BiblioInfo const & Buffer::localBibInfo() const
1715 void Buffer::checkBibInfoCache() const
1717 support::FileNameList const & bibfilesCache = getBibfilesCache();
1718 // compare the cached timestamps with the actual ones.
1719 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1720 support::FileNameList::const_iterator en = bibfilesCache.end();
1721 for (; ei != en; ++ ei) {
1722 time_t lastw = ei->lastModified();
1723 time_t prevw = d->bibfile_status_[*ei];
1724 if (lastw != prevw) {
1725 d->bibinfo_cache_valid_ = false;
1726 d->bibfile_status_[*ei] = lastw;
1730 if (!d->bibinfo_cache_valid_) {
1731 d->bibinfo_.clear();
1732 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1733 it->fillWithBibKeys(d->bibinfo_, it);
1734 d->bibinfo_cache_valid_ = true;
1739 bool Buffer::isDepClean(string const & name) const
1741 DepClean::const_iterator const it = d->dep_clean.find(name);
1742 if (it == d->dep_clean.end())
1748 void Buffer::markDepClean(string const & name)
1750 d->dep_clean[name] = true;
1754 bool Buffer::isExportableFormat(string const & format) const
1756 typedef vector<Format const *> Formats;
1758 formats = exportableFormats(true);
1759 Formats::const_iterator fit = formats.begin();
1760 Formats::const_iterator end = formats.end();
1761 for (; fit != end ; ++fit) {
1762 if ((*fit)->name() == format)
1769 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1772 // FIXME? if there is an Buffer LFUN that can be dispatched even
1773 // if internal, put a switch '(cmd.action)' here.
1779 switch (cmd.action) {
1781 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1782 flag.setOnOff(isReadonly());
1785 // FIXME: There is need for a command-line import.
1786 //case LFUN_BUFFER_IMPORT:
1788 case LFUN_BUFFER_AUTO_SAVE:
1791 case LFUN_BUFFER_EXPORT_CUSTOM:
1792 // FIXME: Nothing to check here?
1795 case LFUN_BUFFER_EXPORT: {
1796 docstring const arg = cmd.argument();
1797 enable = arg == "custom" || isExportable(to_utf8(arg));
1799 flag.message(bformat(
1800 _("Don't know how to export to format: %1$s"), arg));
1804 case LFUN_BUFFER_CHKTEX:
1805 enable = isLatex() && !lyxrc.chktex_command.empty();
1808 case LFUN_BUILD_PROGRAM:
1809 enable = isExportable("program");
1812 case LFUN_BRANCH_ACTIVATE:
1813 case LFUN_BRANCH_DEACTIVATE: {
1814 BranchList const & branchList = params().branchlist();
1815 docstring const branchName = cmd.argument();
1816 enable = !branchName.empty() && branchList.find(branchName);
1820 case LFUN_BRANCH_ADD:
1821 case LFUN_BRANCHES_RENAME:
1822 case LFUN_BUFFER_PRINT:
1823 // if no Buffer is present, then of course we won't be called!
1826 case LFUN_BUFFER_LANGUAGE:
1827 enable = !isReadonly();
1833 flag.setEnabled(enable);
1838 void Buffer::dispatch(string const & command, DispatchResult & result)
1840 return dispatch(lyxaction.lookupFunc(command), result);
1844 // NOTE We can end up here even if we have no GUI, because we are called
1845 // by LyX::exec to handled command-line requests. So we may need to check
1846 // whether we have a GUI or not. The boolean use_gui holds this information.
1847 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1850 // FIXME? if there is an Buffer LFUN that can be dispatched even
1851 // if internal, put a switch '(cmd.action)' here.
1852 dr.dispatched(false);
1855 string const argument = to_utf8(func.argument());
1856 // We'll set this back to false if need be.
1857 bool dispatched = true;
1858 undo().beginUndoGroup();
1860 switch (func.action) {
1861 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1862 if (lyxvc().inUse())
1863 lyxvc().toggleReadOnly();
1865 setReadonly(!isReadonly());
1868 case LFUN_BUFFER_EXPORT: {
1869 bool success = doExport(argument, false, false);
1870 dr.setError(success);
1872 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1877 case LFUN_BUILD_PROGRAM:
1878 doExport("program", true, false);
1881 case LFUN_BUFFER_CHKTEX:
1885 case LFUN_BUFFER_EXPORT_CUSTOM: {
1887 string command = split(argument, format_name, ' ');
1888 Format const * format = formats.getFormat(format_name);
1890 lyxerr << "Format \"" << format_name
1891 << "\" not recognized!"
1896 // The name of the file created by the conversion process
1899 // Output to filename
1900 if (format->name() == "lyx") {
1901 string const latexname = latexName(false);
1902 filename = changeExtension(latexname,
1903 format->extension());
1904 filename = addName(temppath(), filename);
1906 if (!writeFile(FileName(filename)))
1910 doExport(format_name, true, false, filename);
1913 // Substitute $$FName for filename
1914 if (!contains(command, "$$FName"))
1915 command = "( " + command + " ) < $$FName";
1916 command = subst(command, "$$FName", filename);
1918 // Execute the command in the background
1920 call.startscript(Systemcall::DontWait, command);
1924 // FIXME: There is need for a command-line import.
1926 case LFUN_BUFFER_IMPORT:
1931 case LFUN_BUFFER_AUTO_SAVE:
1935 case LFUN_BRANCH_ADD: {
1936 docstring const branch_name = func.argument();
1937 if (branch_name.empty()) {
1941 BranchList & branch_list = params().branchlist();
1942 Branch * branch = branch_list.find(branch_name);
1944 LYXERR0("Branch " << branch_name << " already exists.");
1946 docstring const msg =
1947 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1950 branch_list.add(branch_name);
1951 branch = branch_list.find(branch_name);
1952 string const x11hexname = X11hexname(branch->color());
1953 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1954 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1956 dr.update(Update::Force);
1961 case LFUN_BRANCH_ACTIVATE:
1962 case LFUN_BRANCH_DEACTIVATE: {
1963 BranchList & branchList = params().branchlist();
1964 docstring const branchName = func.argument();
1965 // the case without a branch name is handled elsewhere
1966 if (branchName.empty()) {
1970 Branch * branch = branchList.find(branchName);
1972 LYXERR0("Branch " << branchName << " does not exist.");
1974 docstring const msg =
1975 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1978 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1980 dr.update(Update::Force);
1985 case LFUN_BRANCHES_RENAME: {
1986 if (func.argument().empty())
1989 docstring const oldname = from_utf8(func.getArg(0));
1990 docstring const newname = from_utf8(func.getArg(1));
1991 InsetIterator it = inset_iterator_begin(inset());
1992 InsetIterator const end = inset_iterator_end(inset());
1993 bool success = false;
1994 for (; it != end; ++it) {
1995 if (it->lyxCode() == BRANCH_CODE) {
1996 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1997 if (ins.branch() == oldname) {
1998 undo().recordUndo(it);
1999 ins.rename(newname);
2004 if (it->lyxCode() == INCLUDE_CODE) {
2005 // get buffer of external file
2006 InsetInclude const & ins =
2007 static_cast<InsetInclude const &>(*it);
2008 Buffer * child = ins.getChildBuffer();
2011 child->dispatch(func, dr);
2016 dr.update(Update::Force);
2020 case LFUN_BUFFER_PRINT: {
2021 // we'll assume there's a problem until we succeed
2023 string target = func.getArg(0);
2024 string target_name = func.getArg(1);
2025 string command = func.getArg(2);
2028 || target_name.empty()
2029 || command.empty()) {
2030 LYXERR0("Unable to parse " << func.argument());
2031 docstring const msg =
2032 bformat(_("Unable to parse \"%1$s\""), func.argument());
2036 if (target != "printer" && target != "file") {
2037 LYXERR0("Unrecognized target \"" << target << '"');
2038 docstring const msg =
2039 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2044 bool const update_unincluded =
2045 params().maintain_unincluded_children
2046 && !params().getIncludedChildren().empty();
2047 if (!doExport("dvi", true, update_unincluded)) {
2048 showPrintError(absFileName());
2049 dr.setMessage(_("Error exporting to DVI."));
2053 // Push directory path.
2054 string const path = temppath();
2055 // Prevent the compiler from optimizing away p
2059 // there are three cases here:
2060 // 1. we print to a file
2061 // 2. we print directly to a printer
2062 // 3. we print using a spool command (print to file first)
2065 string const dviname = changeExtension(latexName(true), "dvi");
2067 if (target == "printer") {
2068 if (!lyxrc.print_spool_command.empty()) {
2069 // case 3: print using a spool
2070 string const psname = changeExtension(dviname,".ps");
2071 command += ' ' + lyxrc.print_to_file
2074 + quoteName(dviname);
2076 string command2 = lyxrc.print_spool_command + ' ';
2077 if (target_name != "default") {
2078 command2 += lyxrc.print_spool_printerprefix
2082 command2 += quoteName(psname);
2084 // If successful, then spool command
2085 res = one.startscript(Systemcall::Wait, command);
2088 // If there's no GUI, we have to wait on this command. Otherwise,
2089 // LyX deletes the temporary directory, and with it the spooled
2090 // file, before it can be printed!!
2091 Systemcall::Starttype stype = use_gui ?
2092 Systemcall::DontWait : Systemcall::Wait;
2093 res = one.startscript(stype, command2);
2096 // case 2: print directly to a printer
2097 if (target_name != "default")
2098 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2100 Systemcall::Starttype stype = use_gui ?
2101 Systemcall::DontWait : Systemcall::Wait;
2102 res = one.startscript(stype, command + quoteName(dviname));
2106 // case 1: print to a file
2107 FileName const filename(makeAbsPath(target_name, filePath()));
2108 FileName const dvifile(makeAbsPath(dviname, path));
2109 if (filename.exists()) {
2110 docstring text = bformat(
2111 _("The file %1$s already exists.\n\n"
2112 "Do you want to overwrite that file?"),
2113 makeDisplayPath(filename.absFilename()));
2114 if (Alert::prompt(_("Overwrite file?"),
2115 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2118 command += ' ' + lyxrc.print_to_file
2119 + quoteName(filename.toFilesystemEncoding())
2121 + quoteName(dvifile.toFilesystemEncoding());
2123 Systemcall::Starttype stype = use_gui ?
2124 Systemcall::DontWait : Systemcall::Wait;
2125 res = one.startscript(stype, command);
2131 dr.setMessage(_("Error running external commands."));
2132 showPrintError(absFileName());
2137 case LFUN_BUFFER_LANGUAGE: {
2138 Language const * oldL = params().language;
2139 Language const * newL = languages.getLanguage(argument);
2140 if (!newL || oldL == newL)
2142 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2143 changeLanguage(oldL, newL);
2151 dr.dispatched(dispatched);
2152 undo().endUndoGroup();
2156 void Buffer::changeLanguage(Language const * from, Language const * to)
2158 LASSERT(from, /**/);
2161 for_each(par_iterator_begin(),
2163 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2167 bool Buffer::isMultiLingual() const
2169 ParConstIterator end = par_iterator_end();
2170 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2171 if (it->isMultiLingual(params()))
2178 std::set<Language const *> Buffer::getLanguages() const
2180 std::set<Language const *> languages;
2181 getLanguages(languages);
2186 void Buffer::getLanguages(std::set<Language const *> & languages) const
2188 ParConstIterator end = par_iterator_end();
2189 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2190 it->getLanguages(languages);
2192 std::vector<Buffer *> clist = getChildren();
2193 for (vector<Buffer *>::const_iterator cit = clist.begin();
2194 cit != clist.end(); ++cit)
2195 (*cit)->getLanguages(languages);
2199 DocIterator Buffer::getParFromID(int const id) const
2201 Buffer * buf = const_cast<Buffer *>(this);
2203 // John says this is called with id == -1 from undo
2204 lyxerr << "getParFromID(), id: " << id << endl;
2205 return doc_iterator_end(buf);
2208 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2209 if (it.paragraph().id() == id)
2212 return doc_iterator_end(buf);
2216 bool Buffer::hasParWithID(int const id) const
2218 return !getParFromID(id).atEnd();
2222 ParIterator Buffer::par_iterator_begin()
2224 return ParIterator(doc_iterator_begin(this));
2228 ParIterator Buffer::par_iterator_end()
2230 return ParIterator(doc_iterator_end(this));
2234 ParConstIterator Buffer::par_iterator_begin() const
2236 return ParConstIterator(doc_iterator_begin(this));
2240 ParConstIterator Buffer::par_iterator_end() const
2242 return ParConstIterator(doc_iterator_end(this));
2246 Language const * Buffer::language() const
2248 return params().language;
2252 docstring const Buffer::B_(string const & l10n) const
2254 return params().B_(l10n);
2258 bool Buffer::isClean() const
2260 return d->lyx_clean;
2264 bool Buffer::isExternallyModified(CheckMethod method) const
2266 LASSERT(d->filename.exists(), /**/);
2267 // if method == timestamp, check timestamp before checksum
2268 return (method == checksum_method
2269 || d->timestamp_ != d->filename.lastModified())
2270 && d->checksum_ != d->filename.checksum();
2274 void Buffer::saveCheckSum(FileName const & file) const
2276 if (file.exists()) {
2277 d->timestamp_ = file.lastModified();
2278 d->checksum_ = file.checksum();
2280 // in the case of save to a new file.
2287 void Buffer::markClean() const
2289 if (!d->lyx_clean) {
2290 d->lyx_clean = true;
2293 // if the .lyx file has been saved, we don't need an
2295 d->bak_clean = true;
2299 void Buffer::setUnnamed(bool flag)
2305 bool Buffer::isUnnamed() const
2312 /// Don't check unnamed, here: isInternal() is used in
2313 /// newBuffer(), where the unnamed flag has not been set by anyone
2314 /// yet. Also, for an internal buffer, there should be no need for
2315 /// retrieving fileName() nor for checking if it is unnamed or not.
2316 bool Buffer::isInternal() const
2318 return fileName().extension() == "internal";
2322 void Buffer::markDirty()
2325 d->lyx_clean = false;
2328 d->bak_clean = false;
2330 DepClean::iterator it = d->dep_clean.begin();
2331 DepClean::const_iterator const end = d->dep_clean.end();
2333 for (; it != end; ++it)
2338 FileName Buffer::fileName() const
2344 string Buffer::absFileName() const
2346 return d->filename.absFilename();
2350 string Buffer::filePath() const
2352 return d->filename.onlyPath().absFilename() + "/";
2356 bool Buffer::isReadonly() const
2358 return d->read_only;
2362 void Buffer::setParent(Buffer const * buffer)
2364 // Avoids recursive include.
2365 d->setParent(buffer == this ? 0 : buffer);
2370 Buffer const * Buffer::parent() const
2376 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2378 bufs.insert(owner_);
2380 parent()->d->collectRelatives(bufs);
2382 // loop over children
2383 BufferPositionMap::const_iterator it = children_positions.begin();
2384 BufferPositionMap::const_iterator end = children_positions.end();
2385 for (; it != end; ++it)
2386 bufs.insert(const_cast<Buffer *>(it->first));
2390 std::vector<Buffer const *> Buffer::allRelatives() const
2393 d->collectRelatives(bufs);
2394 BufferSet::iterator it = bufs.begin();
2395 std::vector<Buffer const *> ret;
2396 for (; it != bufs.end(); ++it)
2402 Buffer const * Buffer::masterBuffer() const
2404 Buffer const * const pbuf = d->parent();
2408 return pbuf->masterBuffer();
2412 bool Buffer::isChild(Buffer * child) const
2414 return d->children_positions.find(child) != d->children_positions.end();
2418 DocIterator Buffer::firstChildPosition(Buffer const * child)
2420 Impl::BufferPositionMap::iterator it;
2421 it = d->children_positions.find(child);
2422 if (it == d->children_positions.end())
2423 return DocIterator(this);
2428 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2430 // loop over children
2431 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2432 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2433 for (; it != end; ++it) {
2434 Buffer * child = const_cast<Buffer *>(it->first);
2435 clist.push_back(child);
2436 if (grand_children) {
2437 // there might be grandchildren
2438 std::vector<Buffer *> glist = child->getChildren();
2439 for (vector<Buffer *>::const_iterator git = glist.begin();
2440 git != glist.end(); ++git)
2441 clist.push_back(*git);
2447 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2449 std::vector<Buffer *> v;
2450 getChildren(v, grand_children);
2455 template<typename M>
2456 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2461 typename M::const_iterator it = m.lower_bound(x);
2462 if (it == m.begin())
2470 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2471 DocIterator const & pos) const
2473 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2475 // if paragraphs have no macro context set, pos will be empty
2479 // we haven't found anything yet
2480 DocIterator bestPos = owner_->par_iterator_begin();
2481 MacroData const * bestData = 0;
2483 // find macro definitions for name
2484 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2485 if (nameIt != macros.end()) {
2486 // find last definition in front of pos or at pos itself
2487 PositionScopeMacroMap::const_iterator it
2488 = greatest_below(nameIt->second, pos);
2489 if (it != nameIt->second.end()) {
2491 // scope ends behind pos?
2492 if (pos < it->second.first) {
2493 // Looks good, remember this. If there
2494 // is no external macro behind this,
2495 // we found the right one already.
2496 bestPos = it->first;
2497 bestData = &it->second.second;
2501 // try previous macro if there is one
2502 if (it == nameIt->second.begin())
2509 // find macros in included files
2510 PositionScopeBufferMap::const_iterator it
2511 = greatest_below(position_to_children, pos);
2512 if (it == position_to_children.end())
2513 // no children before
2517 // do we know something better (i.e. later) already?
2518 if (it->first < bestPos )
2521 // scope ends behind pos?
2522 if (pos < it->second.first) {
2523 // look for macro in external file
2525 MacroData const * data
2526 = it->second.second->getMacro(name, false);
2529 bestPos = it->first;
2535 // try previous file if there is one
2536 if (it == position_to_children.begin())
2541 // return the best macro we have found
2546 MacroData const * Buffer::getMacro(docstring const & name,
2547 DocIterator const & pos, bool global) const
2552 // query buffer macros
2553 MacroData const * data = d->getBufferMacro(name, pos);
2557 // If there is a master buffer, query that
2558 Buffer const * const pbuf = d->parent();
2560 d->macro_lock = true;
2561 MacroData const * macro = pbuf->getMacro(
2562 name, *this, false);
2563 d->macro_lock = false;
2569 data = MacroTable::globalMacros().get(name);
2578 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2580 // set scope end behind the last paragraph
2581 DocIterator scope = par_iterator_begin();
2582 scope.pit() = scope.lastpit() + 1;
2584 return getMacro(name, scope, global);
2588 MacroData const * Buffer::getMacro(docstring const & name,
2589 Buffer const & child, bool global) const
2591 // look where the child buffer is included first
2592 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2593 if (it == d->children_positions.end())
2596 // check for macros at the inclusion position
2597 return getMacro(name, it->second, global);
2601 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2603 pit_type const lastpit = it.lastpit();
2605 // look for macros in each paragraph
2606 while (it.pit() <= lastpit) {
2607 Paragraph & par = it.paragraph();
2609 // iterate over the insets of the current paragraph
2610 InsetList const & insets = par.insetList();
2611 InsetList::const_iterator iit = insets.begin();
2612 InsetList::const_iterator end = insets.end();
2613 for (; iit != end; ++iit) {
2614 it.pos() = iit->pos;
2616 // is it a nested text inset?
2617 if (iit->inset->asInsetText()) {
2618 // Inset needs its own scope?
2619 InsetText const * itext = iit->inset->asInsetText();
2620 bool newScope = itext->isMacroScope();
2622 // scope which ends just behind the inset
2623 DocIterator insetScope = it;
2626 // collect macros in inset
2627 it.push_back(CursorSlice(*iit->inset));
2628 updateMacros(it, newScope ? insetScope : scope);
2633 // is it an external file?
2634 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2635 // get buffer of external file
2636 InsetInclude const & inset =
2637 static_cast<InsetInclude const &>(*iit->inset);
2639 Buffer * child = inset.getChildBuffer();
2644 // register its position, but only when it is
2645 // included first in the buffer
2646 if (children_positions.find(child) ==
2647 children_positions.end())
2648 children_positions[child] = it;
2650 // register child with its scope
2651 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2655 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2659 MathMacroTemplate & macroTemplate =
2660 static_cast<MathMacroTemplate &>(*iit->inset);
2661 MacroContext mc(owner_, it);
2662 macroTemplate.updateToContext(mc);
2665 bool valid = macroTemplate.validMacro();
2666 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2667 // then the BufferView's cursor will be invalid in
2668 // some cases which leads to crashes.
2673 // FIXME (Abdel), I don't understandt why we pass 'it' here
2674 // instead of 'macroTemplate' defined above... is this correct?
2675 macros[macroTemplate.name()][it] =
2676 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2686 void Buffer::updateMacros() const
2691 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2693 // start with empty table
2695 d->children_positions.clear();
2696 d->position_to_children.clear();
2698 // Iterate over buffer, starting with first paragraph
2699 // The scope must be bigger than any lookup DocIterator
2700 // later. For the global lookup, lastpit+1 is used, hence
2701 // we use lastpit+2 here.
2702 DocIterator it = par_iterator_begin();
2703 DocIterator outerScope = it;
2704 outerScope.pit() = outerScope.lastpit() + 2;
2705 d->updateMacros(it, outerScope);
2709 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2711 InsetIterator it = inset_iterator_begin(inset());
2712 InsetIterator const end = inset_iterator_end(inset());
2713 for (; it != end; ++it) {
2714 if (it->lyxCode() == BRANCH_CODE) {
2715 InsetBranch & br = static_cast<InsetBranch &>(*it);
2716 docstring const name = br.branch();
2717 if (!from_master && !params().branchlist().find(name))
2718 result.push_back(name);
2719 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2720 result.push_back(name);
2723 if (it->lyxCode() == INCLUDE_CODE) {
2724 // get buffer of external file
2725 InsetInclude const & ins =
2726 static_cast<InsetInclude const &>(*it);
2727 Buffer * child = ins.getChildBuffer();
2730 child->getUsedBranches(result, true);
2733 // remove duplicates
2738 void Buffer::updateMacroInstances() const
2740 LYXERR(Debug::MACROS, "updateMacroInstances for "
2741 << d->filename.onlyFileName());
2742 DocIterator it = doc_iterator_begin(this);
2744 DocIterator const end = doc_iterator_end(this);
2745 for (; it != end; it.forwardInset()) {
2746 // look for MathData cells in InsetMathNest insets
2747 InsetMath * minset = it.nextInset()->asInsetMath();
2751 // update macro in all cells of the InsetMathNest
2752 DocIterator::idx_type n = minset->nargs();
2753 MacroContext mc = MacroContext(this, it);
2754 for (DocIterator::idx_type i = 0; i < n; ++i) {
2755 MathData & data = minset->cell(i);
2756 data.updateMacros(0, mc);
2762 void Buffer::listMacroNames(MacroNameSet & macros) const
2767 d->macro_lock = true;
2769 // loop over macro names
2770 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2771 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2772 for (; nameIt != nameEnd; ++nameIt)
2773 macros.insert(nameIt->first);
2775 // loop over children
2776 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2777 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2778 for (; it != end; ++it)
2779 it->first->listMacroNames(macros);
2782 Buffer const * const pbuf = d->parent();
2784 pbuf->listMacroNames(macros);
2786 d->macro_lock = false;
2790 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2792 Buffer const * const pbuf = d->parent();
2797 pbuf->listMacroNames(names);
2800 MacroNameSet::iterator it = names.begin();
2801 MacroNameSet::iterator end = names.end();
2802 for (; it != end; ++it) {
2804 MacroData const * data =
2805 pbuf->getMacro(*it, *this, false);
2807 macros.insert(data);
2809 // we cannot access the original MathMacroTemplate anymore
2810 // here to calls validate method. So we do its work here manually.
2811 // FIXME: somehow make the template accessible here.
2812 if (data->optionals() > 0)
2813 features.require("xargs");
2819 Buffer::References & Buffer::references(docstring const & label)
2822 return const_cast<Buffer *>(masterBuffer())->references(label);
2824 RefCache::iterator it = d->ref_cache_.find(label);
2825 if (it != d->ref_cache_.end())
2826 return it->second.second;
2828 static InsetLabel const * dummy_il = 0;
2829 static References const dummy_refs;
2830 it = d->ref_cache_.insert(
2831 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2832 return it->second.second;
2836 Buffer::References const & Buffer::references(docstring const & label) const
2838 return const_cast<Buffer *>(this)->references(label);
2842 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2844 masterBuffer()->d->ref_cache_[label].first = il;
2848 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2850 return masterBuffer()->d->ref_cache_[label].first;
2854 void Buffer::clearReferenceCache() const
2857 d->ref_cache_.clear();
2861 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2864 //FIXME: This does not work for child documents yet.
2865 LASSERT(code == CITE_CODE, /**/);
2866 // Check if the label 'from' appears more than once
2867 vector<docstring> labels;
2869 checkBibInfoCache();
2870 BiblioInfo const & keys = masterBibInfo();
2871 BiblioInfo::const_iterator bit = keys.begin();
2872 BiblioInfo::const_iterator bend = keys.end();
2874 for (; bit != bend; ++bit)
2876 labels.push_back(bit->first);
2879 if (count(labels.begin(), labels.end(), from) > 1)
2882 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2883 if (it->lyxCode() == code) {
2884 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2885 docstring const oldValue = inset.getParam(paramName);
2886 if (oldValue == from)
2887 inset.setParam(paramName, to);
2893 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2894 pit_type par_end, bool full_source) const
2896 OutputParams runparams(¶ms().encoding());
2897 runparams.nice = true;
2898 runparams.flavor = params().useXetex ?
2899 OutputParams::XETEX : OutputParams::LATEX;
2900 runparams.linelen = lyxrc.plaintext_linelen;
2901 // No side effect of file copying and image conversion
2902 runparams.dryrun = true;
2905 os << "% " << _("Preview source code") << "\n\n";
2907 d->texrow.newline();
2908 d->texrow.newline();
2910 writeDocBookSource(os, absFileName(), runparams, false);
2912 // latex or literate
2913 writeLaTeXSource(os, string(), runparams, true, true);
2915 runparams.par_begin = par_begin;
2916 runparams.par_end = par_end;
2917 if (par_begin + 1 == par_end) {
2919 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2923 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2924 convert<docstring>(par_begin),
2925 convert<docstring>(par_end - 1))
2932 // output paragraphs
2934 docbookParagraphs(text(), *this, os, runparams);
2936 // latex or literate
2937 latexParagraphs(*this, text(), os, texrow, runparams);
2942 ErrorList & Buffer::errorList(string const & type) const
2944 static ErrorList emptyErrorList;
2945 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2946 if (I == d->errorLists.end())
2947 return emptyErrorList;
2953 void Buffer::updateTocItem(std::string const & type,
2954 DocIterator const & dit) const
2957 d->gui_->updateTocItem(type, dit);
2961 void Buffer::structureChanged() const
2964 d->gui_->structureChanged();
2968 void Buffer::errors(string const & err, bool from_master) const
2971 d->gui_->errors(err, from_master);
2975 void Buffer::message(docstring const & msg) const
2978 d->gui_->message(msg);
2982 void Buffer::setBusy(bool on) const
2985 d->gui_->setBusy(on);
2989 void Buffer::updateTitles() const
2992 d->wa_->updateTitles();
2996 void Buffer::resetAutosaveTimers() const
2999 d->gui_->resetAutosaveTimers();
3003 bool Buffer::hasGuiDelegate() const
3009 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3018 class AutoSaveBuffer : public ForkedProcess {
3021 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3022 : buffer_(buffer), fname_(fname) {}
3024 virtual boost::shared_ptr<ForkedProcess> clone() const
3026 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3031 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3032 from_utf8(fname_.absFilename())));
3033 return run(DontWait);
3037 virtual int generateChild();
3039 Buffer const & buffer_;
3044 int AutoSaveBuffer::generateChild()
3046 #if defined(__APPLE__)
3047 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3048 * We should use something else like threads.
3050 * Since I do not know how to determine at run time what is the OS X
3051 * version, I just disable forking altogether for now (JMarc)
3053 pid_t const pid = -1;
3055 // tmp_ret will be located (usually) in /tmp
3056 // will that be a problem?
3057 // Note that this calls ForkedCalls::fork(), so it's
3058 // ok cross-platform.
3059 pid_t const pid = fork();
3060 // If you want to debug the autosave
3061 // you should set pid to -1, and comment out the fork.
3062 if (pid != 0 && pid != -1)
3066 // pid = -1 signifies that lyx was unable
3067 // to fork. But we will do the save
3069 bool failed = false;
3070 FileName const tmp_ret = FileName::tempName("lyxauto");
3071 if (!tmp_ret.empty()) {
3072 buffer_.writeFile(tmp_ret);
3073 // assume successful write of tmp_ret
3074 if (!tmp_ret.moveTo(fname_))
3080 // failed to write/rename tmp_ret so try writing direct
3081 if (!buffer_.writeFile(fname_)) {
3082 // It is dangerous to do this in the child,
3083 // but safe in the parent, so...
3084 if (pid == -1) // emit message signal.
3085 buffer_.message(_("Autosave failed!"));
3089 if (pid == 0) // we are the child so...
3098 FileName Buffer::getAutosaveFilename() const
3100 // if the document is unnamed try to save in the backup dir, else
3101 // in the default document path, and as a last try in the filePath,
3102 // which will most often be the temporary directory
3105 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3106 : lyxrc.backupdir_path;
3107 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3110 string const fname = "#" + d->filename.onlyFileName() + "#";
3111 return makeAbsPath(fname, fpath);
3115 void Buffer::removeAutosaveFile() const
3117 FileName const f = getAutosaveFilename();
3123 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3125 FileName const newauto = getAutosaveFilename();
3126 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3127 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3131 // Perfect target for a thread...
3132 void Buffer::autoSave() const
3134 if (d->bak_clean || isReadonly()) {
3135 // We don't save now, but we'll try again later
3136 resetAutosaveTimers();
3140 // emit message signal.
3141 message(_("Autosaving current document..."));
3142 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3145 d->bak_clean = true;
3147 resetAutosaveTimers();
3151 string Buffer::bufferFormat() const
3153 string format = params().documentClass().outputFormat();
3154 if (format == "latex") {
3155 if (params().useXetex)
3157 if (params().encoding().package() == Encoding::japanese)
3164 string Buffer::getDefaultOutputFormat() const
3166 if (!params().defaultOutputFormat.empty()
3167 && params().defaultOutputFormat != "default")
3168 return params().defaultOutputFormat;
3169 typedef vector<Format const *> Formats;
3170 Formats formats = exportableFormats(true);
3173 || params().useXetex
3174 || params().encoding().package() == Encoding::japanese) {
3175 if (formats.empty())
3177 // return the first we find
3178 return formats.front()->name();
3180 return lyxrc.default_view_format;
3185 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3186 bool includeall, string & result_file) const
3188 string backend_format;
3189 OutputParams runparams(¶ms().encoding());
3190 runparams.flavor = OutputParams::LATEX;
3191 runparams.linelen = lyxrc.plaintext_linelen;
3192 runparams.includeall = includeall;
3193 vector<string> backs = backends();
3194 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3195 // Get shortest path to format
3196 Graph::EdgePath path;
3197 for (vector<string>::const_iterator it = backs.begin();
3198 it != backs.end(); ++it) {
3199 Graph::EdgePath p = theConverters().getPath(*it, format);
3200 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3201 backend_format = *it;
3206 if (!put_in_tempdir) {
3207 // Only show this alert if this is an export to a non-temporary
3208 // file (not for previewing).
3209 Alert::error(_("Couldn't export file"), bformat(
3210 _("No information for exporting the format %1$s."),
3211 formats.prettyName(format)));
3215 runparams.flavor = theConverters().getFlavor(path);
3218 backend_format = format;
3219 // FIXME: Don't hardcode format names here, but use a flag
3220 if (backend_format == "pdflatex")
3221 runparams.flavor = OutputParams::PDFLATEX;
3224 string filename = latexName(false);
3225 filename = addName(temppath(), filename);
3226 filename = changeExtension(filename,
3227 formats.extension(backend_format));
3230 updateMacroInstances();
3232 // Plain text backend
3233 if (backend_format == "text") {
3234 runparams.flavor = OutputParams::TEXT;
3235 writePlaintextFile(*this, FileName(filename), runparams);
3238 else if (backend_format == "xhtml") {
3239 runparams.flavor = OutputParams::HTML;
3240 makeLyXHTMLFile(FileName(filename), runparams);
3241 } else if (backend_format == "lyx")
3242 writeFile(FileName(filename));
3244 else if (isDocBook()) {
3245 runparams.nice = !put_in_tempdir;
3246 makeDocBookFile(FileName(filename), runparams);
3249 else if (backend_format == format) {
3250 runparams.nice = true;
3251 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3253 } else if (!lyxrc.tex_allows_spaces
3254 && contains(filePath(), ' ')) {
3255 Alert::error(_("File name error"),
3256 _("The directory path to the document cannot contain spaces."));
3259 runparams.nice = false;
3260 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3264 string const error_type = (format == "program")
3265 ? "Build" : bufferFormat();
3266 ErrorList & error_list = d->errorLists[error_type];
3267 string const ext = formats.extension(format);
3268 FileName const tmp_result_file(changeExtension(filename, ext));
3269 bool const success = theConverters().convert(this, FileName(filename),
3270 tmp_result_file, FileName(absFileName()), backend_format, format,
3272 // Emit the signal to show the error list.
3273 if (format != backend_format) {
3275 // also to the children, in case of master-buffer-view
3276 std::vector<Buffer *> clist = getChildren();
3277 for (vector<Buffer *>::const_iterator cit = clist.begin();
3278 cit != clist.end(); ++cit)
3279 (*cit)->errors(error_type, true);
3284 if (d->cloned_buffer_) {
3285 // Enable reverse dvi or pdf to work by copying back the texrow
3286 // object to the cloned buffer.
3287 // FIXME: There is a possibility of concurrent access to texrow
3288 // here from the main GUI thread that should be securized.
3289 d->cloned_buffer_->d->texrow = d->texrow;
3292 if (put_in_tempdir) {
3293 result_file = tmp_result_file.absFilename();
3297 result_file = changeExtension(d->exportFileName().absFilename(), ext);
3298 // We need to copy referenced files (e. g. included graphics
3299 // if format == "dvi") to the result dir.
3300 vector<ExportedFile> const files =
3301 runparams.exportdata->externalFiles(format);
3302 string const dest = onlyPath(result_file);
3303 CopyStatus status = SUCCESS;
3305 vector<ExportedFile>::const_iterator it = files.begin();
3306 vector<ExportedFile>::const_iterator const en = files.end();
3307 for (; it != en && status != CANCEL; ++it) {
3308 string const fmt = formats.getFormatFromFile(it->sourceName);
3309 status = copyFile(fmt, it->sourceName,
3310 makeAbsPath(it->exportName, dest),
3311 it->exportName, status == FORCE);
3314 if (status == CANCEL) {
3315 message(_("Document export cancelled."));
3316 } else if (tmp_result_file.exists()) {
3317 // Finally copy the main file
3318 status = copyFile(format, tmp_result_file,
3319 FileName(result_file), result_file,
3321 message(bformat(_("Document exported as %1$s "
3323 formats.prettyName(format),
3324 makeDisplayPath(result_file)));
3326 // This must be a dummy converter like fax (bug 1888)
3327 message(bformat(_("Document exported as %1$s"),
3328 formats.prettyName(format)));
3335 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3336 bool includeall) const
3339 // (1) export with all included children (omit \includeonly)
3340 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3342 // (2) export with included children only
3343 return doExport(format, put_in_tempdir, false, result_file);
3347 bool Buffer::preview(string const & format, bool includeall) const
3350 // (1) export with all included children (omit \includeonly)
3351 if (includeall && !doExport(format, true, true))
3353 // (2) export with included children only
3354 if (!doExport(format, true, false, result_file))
3356 return formats.view(*this, FileName(result_file), format);
3360 bool Buffer::isExportable(string const & format) const
3362 vector<string> backs = backends();
3363 for (vector<string>::const_iterator it = backs.begin();
3364 it != backs.end(); ++it)
3365 if (theConverters().isReachable(*it, format))
3371 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3373 vector<string> const backs = backends();
3374 vector<Format const *> result =
3375 theConverters().getReachable(backs[0], only_viewable, true);
3376 for (vector<string>::const_iterator it = backs.begin() + 1;
3377 it != backs.end(); ++it) {
3378 vector<Format const *> r =
3379 theConverters().getReachable(*it, only_viewable, false);
3380 result.insert(result.end(), r.begin(), r.end());
3386 vector<string> Buffer::backends() const
3389 v.push_back(bufferFormat());
3390 // FIXME: Don't hardcode format names here, but use a flag
3391 if (v.back() == "latex")
3392 v.push_back("pdflatex");
3393 v.push_back("xhtml");
3394 v.push_back("text");
3400 bool Buffer::readFileHelper(FileName const & s)
3402 // File information about normal file
3404 docstring const file = makeDisplayPath(s.absFilename(), 50);
3405 docstring text = bformat(_("The specified document\n%1$s"
3406 "\ncould not be read."), file);
3407 Alert::error(_("Could not read document"), text);
3411 // Check if emergency save file exists and is newer.
3412 FileName const e(s.absFilename() + ".emergency");
3414 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3415 docstring const file = makeDisplayPath(s.absFilename(), 20);
3416 docstring const text =
3417 bformat(_("An emergency save of the document "
3419 "Recover emergency save?"), file);
3420 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3421 _("&Recover"), _("&Load Original"),
3425 // the file is not saved if we load the emergency file.
3430 if ((res = readFile(e)) == success)
3431 str = _("Document was successfully recovered.");
3433 str = _("Document was NOT successfully recovered.");
3434 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3435 from_utf8(e.absFilename()));
3437 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3438 _("&Remove"), _("&Keep it"))) {
3441 Alert::warning(_("Emergency file deleted"),
3442 _("Do not forget to save your file now!"), true);
3447 if (!Alert::prompt(_("Delete emergency file?"),
3448 _("Remove emergency file now?"), 1, 1,
3449 _("&Remove"), _("&Keep it")))
3457 // Now check if autosave file is newer.
3458 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3460 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3461 docstring const file = makeDisplayPath(s.absFilename(), 20);
3462 docstring const text =
3463 bformat(_("The backup of the document "
3464 "%1$s is newer.\n\nLoad the "
3465 "backup instead?"), file);
3466 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3467 _("&Load backup"), _("Load &original"),
3471 // the file is not saved if we load the autosave file.
3475 // Here we delete the autosave
3486 bool Buffer::loadLyXFile(FileName const & s)
3488 // If the file is not readable, we try to
3489 // retrieve the file from version control.
3490 if (!s.isReadableFile()
3491 && !LyXVC::file_not_found_hook(s))
3494 if (s.isReadableFile()
3495 && readFileHelper(s)) {
3496 lyxvc().file_found_hook(s);
3497 setReadonly(!s.isWritable());
3504 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3506 TeXErrors::Errors::const_iterator cit = terr.begin();
3507 TeXErrors::Errors::const_iterator end = terr.end();
3509 for (; cit != end; ++cit) {
3512 int errorRow = cit->error_in_line;
3513 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3519 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3520 } while (found && id_start == id_end && pos_start == pos_end);
3522 errorList.push_back(ErrorItem(cit->error_desc,
3523 cit->error_text, id_start, pos_start, pos_end));
3528 void Buffer::setBuffersForInsets() const
3530 inset().setBuffer(const_cast<Buffer &>(*this));
3534 void Buffer::updateLabels(UpdateScope scope, UpdateType utype) const
3536 // Use the master text class also for child documents
3537 Buffer const * const master = masterBuffer();
3538 DocumentClass const & textclass = master->params().documentClass();
3540 // do this only if we are the top-level Buffer
3541 if (scope != UpdateMaster || master == this)
3542 checkBibInfoCache();
3544 // keep the buffers to be children in this set. If the call from the
3545 // master comes back we can see which of them were actually seen (i.e.
3546 // via an InsetInclude). The remaining ones in the set need still be updated.
3547 static std::set<Buffer const *> bufToUpdate;
3548 if (scope == UpdateMaster) {
3549 // If this is a child document start with the master
3550 if (master != this) {
3551 bufToUpdate.insert(this);
3552 master->updateLabels(UpdateMaster, utype);
3553 // Do this here in case the master has no gui associated with it. Then,
3554 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3555 if (!master->d->gui_)
3558 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3559 if (bufToUpdate.find(this) == bufToUpdate.end())
3563 // start over the counters in the master
3564 textclass.counters().reset();
3567 // update will be done below for this buffer
3568 bufToUpdate.erase(this);
3570 // update all caches
3571 clearReferenceCache();
3574 Buffer & cbuf = const_cast<Buffer &>(*this);
3576 LASSERT(!text().paragraphs().empty(), /**/);
3579 ParIterator parit = cbuf.par_iterator_begin();
3580 updateLabels(parit, utype);
3583 // TocBackend update will be done later.
3586 cbuf.tocBackend().update();
3587 if (scope == UpdateMaster)
3588 cbuf.structureChanged();
3592 static depth_type getDepth(DocIterator const & it)
3594 depth_type depth = 0;
3595 for (size_t i = 0 ; i < it.depth() ; ++i)
3596 if (!it[i].inset().inMathed())
3597 depth += it[i].paragraph().getDepth() + 1;
3598 // remove 1 since the outer inset does not count
3602 static depth_type getItemDepth(ParIterator const & it)
3604 Paragraph const & par = *it;
3605 LabelType const labeltype = par.layout().labeltype;
3607 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3610 // this will hold the lowest depth encountered up to now.
3611 depth_type min_depth = getDepth(it);
3612 ParIterator prev_it = it;
3615 --prev_it.top().pit();
3617 // start of nested inset: go to outer par
3619 if (prev_it.empty()) {
3620 // start of document: nothing to do
3625 // We search for the first paragraph with same label
3626 // that is not more deeply nested.
3627 Paragraph & prev_par = *prev_it;
3628 depth_type const prev_depth = getDepth(prev_it);
3629 if (labeltype == prev_par.layout().labeltype) {
3630 if (prev_depth < min_depth)
3631 return prev_par.itemdepth + 1;
3632 if (prev_depth == min_depth)
3633 return prev_par.itemdepth;
3635 min_depth = min(min_depth, prev_depth);
3636 // small optimization: if we are at depth 0, we won't
3637 // find anything else
3638 if (prev_depth == 0)
3644 static bool needEnumCounterReset(ParIterator const & it)
3646 Paragraph const & par = *it;
3647 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3648 depth_type const cur_depth = par.getDepth();
3649 ParIterator prev_it = it;
3650 while (prev_it.pit()) {
3651 --prev_it.top().pit();
3652 Paragraph const & prev_par = *prev_it;
3653 if (prev_par.getDepth() <= cur_depth)
3654 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3656 // start of nested inset: reset
3661 // set the label of a paragraph. This includes the counters.
3662 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3664 BufferParams const & bp = owner_->masterBuffer()->params();
3665 DocumentClass const & textclass = bp.documentClass();
3666 Paragraph & par = it.paragraph();
3667 Layout const & layout = par.layout();
3668 Counters & counters = textclass.counters();
3670 if (par.params().startOfAppendix()) {
3671 // FIXME: only the counter corresponding to toplevel
3672 // sectioning should be reset
3674 counters.appendix(true);
3676 par.params().appendix(counters.appendix());
3678 // Compute the item depth of the paragraph
3679 par.itemdepth = getItemDepth(it);
3681 if (layout.margintype == MARGIN_MANUAL
3682 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3683 if (par.params().labelWidthString().empty())
3684 par.params().labelWidthString(par.expandLabel(layout, bp));
3686 par.params().labelWidthString(docstring());
3689 switch(layout.labeltype) {
3691 if (layout.toclevel <= bp.secnumdepth
3692 && (layout.latextype != LATEX_ENVIRONMENT
3693 || it.text()->isFirstInSequence(it.pit()))) {
3694 counters.step(layout.counter, utype);
3695 par.params().labelString(
3696 par.expandLabel(layout, bp));
3698 par.params().labelString(docstring());
3701 case LABEL_ITEMIZE: {
3702 // At some point of time we should do something more
3703 // clever here, like:
3704 // par.params().labelString(
3705 // bp.user_defined_bullet(par.itemdepth).getText());
3706 // for now, use a simple hardcoded label
3707 docstring itemlabel;
3708 switch (par.itemdepth) {
3710 itemlabel = char_type(0x2022);
3713 itemlabel = char_type(0x2013);
3716 itemlabel = char_type(0x2217);
3719 itemlabel = char_type(0x2219); // or 0x00b7
3722 par.params().labelString(itemlabel);
3726 case LABEL_ENUMERATE: {
3727 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3729 switch (par.itemdepth) {
3738 enumcounter += "iv";
3741 // not a valid enumdepth...
3745 // Maybe we have to reset the enumeration counter.
3746 if (needEnumCounterReset(it))
3747 counters.reset(enumcounter);
3748 counters.step(enumcounter, utype);
3750 string const & lang = par.getParLanguage(bp)->code();
3751 par.params().labelString(counters.theCounter(enumcounter, lang));
3756 case LABEL_SENSITIVE: {
3757 string const & type = counters.current_float();
3758 docstring full_label;
3760 full_label = owner_->B_("Senseless!!! ");
3762 docstring name = owner_->B_(textclass.floats().getType(type).name());
3763 if (counters.hasCounter(from_utf8(type))) {
3764 string const & lang = par.getParLanguage(bp)->code();
3765 counters.step(from_utf8(type), utype);
3766 full_label = bformat(from_ascii("%1$s %2$s:"),
3768 counters.theCounter(from_utf8(type), lang));
3770 full_label = bformat(from_ascii("%1$s #:"), name);
3772 par.params().labelString(full_label);
3776 case LABEL_NO_LABEL:
3777 par.params().labelString(docstring());
3781 case LABEL_TOP_ENVIRONMENT:
3782 case LABEL_CENTERED_TOP_ENVIRONMENT:
3785 par.params().labelString(par.expandLabel(layout, bp));
3791 void Buffer::updateLabels(ParIterator & parit, UpdateType utype) const
3793 LASSERT(parit.pit() == 0, /**/);
3795 // set the position of the text in the buffer to be able
3796 // to resolve macros in it. This has nothing to do with
3797 // labels, but by putting it here we avoid implementing
3798 // a whole bunch of traversal routines just for this call.
3799 parit.text()->setMacrocontextPosition(parit);
3801 depth_type maxdepth = 0;
3802 pit_type const lastpit = parit.lastpit();
3803 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3804 // reduce depth if necessary
3805 parit->params().depth(min(parit->params().depth(), maxdepth));
3806 maxdepth = parit->getMaxDepthAfter();
3808 if (utype == OutputUpdate) {
3809 // track the active counters
3810 // we have to do this for the master buffer, since the local
3811 // buffer isn't tracking anything.
3812 masterBuffer()->params().documentClass().counters().
3813 setActiveLayout(parit->layout());
3816 // set the counter for this paragraph
3817 d->setLabel(parit, utype);
3820 InsetList::const_iterator iit = parit->insetList().begin();
3821 InsetList::const_iterator end = parit->insetList().end();
3822 for (; iit != end; ++iit) {
3823 parit.pos() = iit->pos;
3824 iit->inset->updateLabels(parit, utype);
3830 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3831 WordLangTuple & word_lang, docstring_list & suggestions) const
3835 suggestions.clear();
3836 word_lang = WordLangTuple();
3837 // OK, we start from here.
3838 DocIterator const end = doc_iterator_end(this);
3839 for (; from != end; from.forwardPos()) {
3840 // We are only interested in text so remove the math CursorSlice.
3841 while (from.inMathed()) {
3845 // If from is at the end of the document (which is possible
3846 // when leaving the mathed) LyX will crash later.
3850 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3855 // Do not increase progress when from == to, otherwise the word
3856 // count will be wrong.
3866 bool Buffer::reload()
3869 // e.g., read-only status could have changed due to version control
3870 d->filename.refresh();
3871 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3873 bool const success = loadLyXFile(d->filename);
3878 message(bformat(_("Document %1$s reloaded."), disp_fn));
3880 message(bformat(_("Could not reload document %1$s."), disp_fn));