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 & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfiles_cache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfo_cache_valid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfile_status_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 // however, the BufferList doesn't know about cloned buffers, so
252 // they will always be regarded as unloaded. in that case, we hope
254 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
256 return parent_buffer;
259 void setParent(Buffer const * pb) {
260 if (parent_buffer && pb && parent_buffer != pb)
261 LYXERR0("Warning: a buffer should not have two parents!");
265 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
266 /// This one is useful for preview detached in a thread.
267 Buffer const * cloned_buffer_;
270 /// So we can force access via the accessors.
271 mutable Buffer const * parent_buffer;
276 /// Creates the per buffer temporary directory
277 static FileName createBufferTmpDir()
280 // We are in our own directory. Why bother to mangle name?
281 // In fact I wrote this code to circumvent a problematic behaviour
282 // (bug?) of EMX mkstemp().
283 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
284 convert<string>(count++));
286 if (!tmpfl.createDirectory(0777)) {
287 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
288 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
289 from_utf8(tmpfl.absFilename())));
295 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
296 Buffer const * cloned_buffer)
297 : lyx_clean(true), bak_clean(true), unnamed(false),
298 read_only(readonly_), filename(file), file_fully_loaded(false),
299 toc_backend(&parent), macro_lock(false), timestamp_(0),
300 checksum_(0), wa_(0), undo_(parent), bibinfo_cache_valid_(false),
301 cloned_buffer_(cloned_buffer), parent_buffer(0)
303 if (!cloned_buffer_) {
304 temppath = createBufferTmpDir();
305 lyxvc.setBuffer(&parent);
307 wa_ = new frontend::WorkAreaManager;
310 temppath = cloned_buffer_->d->temppath;
311 file_fully_loaded = true;
312 params = cloned_buffer_->d->params;
313 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
314 bibinfo_ = cloned_buffer_->d->bibinfo_;
315 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
316 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
320 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
321 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
323 LYXERR(Debug::INFO, "Buffer::Buffer()");
325 d->inset = new InsetText(*cloned_buffer->d->inset);
326 d->inset->setBuffer(*this);
327 // FIXME: optimize this loop somewhat, maybe by creating a new
328 // general recursive Inset::setId().
329 DocIterator it = doc_iterator_begin(this);
330 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
331 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
332 it.paragraph().setId(cloned_it.paragraph().id());
334 d->inset = new InsetText(this);
335 d->inset->setAutoBreakRows(true);
336 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
342 LYXERR(Debug::INFO, "Buffer::~Buffer()");
343 // here the buffer should take care that it is
344 // saved properly, before it goes into the void.
346 // GuiView already destroyed
350 // No need to do additional cleanups for internal buffer.
355 // loop over children
356 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
357 Impl::BufferPositionMap::iterator end = d->children_positions.end();
358 for (; it != end; ++it) {
359 Buffer * child = const_cast<Buffer *>(it->first);
360 if (d->cloned_buffer_)
362 // The child buffer might have been closed already.
363 else if (theBufferList().isLoaded(child))
364 theBufferList().releaseChild(this, child);
368 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
369 msg += emergencyWrite();
370 Alert::warning(_("Attempting to close changed document!"), msg);
373 // clear references to children in macro tables
374 d->children_positions.clear();
375 d->position_to_children.clear();
377 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
378 Alert::warning(_("Could not remove temporary directory"),
379 bformat(_("Could not remove the temporary directory %1$s"),
380 from_utf8(d->temppath.absFilename())));
383 // Remove any previewed LaTeX snippets associated with this buffer.
384 thePreviews().removeLoader(*this);
390 Buffer * Buffer::clone() const
392 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
393 buffer_clone->d->macro_lock = true;
394 buffer_clone->d->children_positions.clear();
395 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
396 // math macro caches need to be rethought and simplified.
397 // I am not sure wether we should handle Buffer cloning here or in BufferList.
398 // Right now BufferList knows nothing about buffer clones.
399 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
400 Impl::BufferPositionMap::iterator end = d->children_positions.end();
401 for (; it != end; ++it) {
402 DocIterator dit = it->second.clone(buffer_clone);
403 dit.setBuffer(buffer_clone);
404 Buffer * child = const_cast<Buffer *>(it->first);
405 Buffer * child_clone = child->clone();
406 Inset * inset = dit.nextInset();
407 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
408 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
409 inset_inc->setChildBuffer(child_clone);
410 child_clone->d->setParent(buffer_clone);
411 buffer_clone->setChild(dit, child_clone);
413 buffer_clone->d->macro_lock = false;
418 bool Buffer::isClone() const
420 return d->cloned_buffer_;
424 void Buffer::changed(bool update_metrics) const
427 d->wa_->redrawAll(update_metrics);
431 frontend::WorkAreaManager & Buffer::workAreaManager() const
433 LASSERT(d->wa_, /**/);
438 Text & Buffer::text() const
440 return d->inset->text();
444 Inset & Buffer::inset() const
450 BufferParams & Buffer::params()
456 BufferParams const & Buffer::params() const
462 ParagraphList & Buffer::paragraphs()
464 return text().paragraphs();
468 ParagraphList const & Buffer::paragraphs() const
470 return text().paragraphs();
474 LyXVC & Buffer::lyxvc()
480 LyXVC const & Buffer::lyxvc() const
486 string const Buffer::temppath() const
488 return d->temppath.absFilename();
492 TexRow & Buffer::texrow()
498 TexRow const & Buffer::texrow() const
504 TocBackend & Buffer::tocBackend() const
506 return d->toc_backend;
510 Undo & Buffer::undo()
516 void Buffer::setChild(DocIterator const & dit, Buffer * child)
518 d->children_positions[child] = dit;
522 string Buffer::latexName(bool const no_path) const
524 FileName latex_name =
525 makeLatexName(exportFileName());
526 return no_path ? latex_name.onlyFileName()
527 : latex_name.absFilename();
531 FileName Buffer::exportFileName() const
533 docstring const branch_suffix =
534 params().branchlist().getFilenameSuffix();
535 if (branch_suffix.empty())
538 string const name = fileName().onlyFileNameWithoutExt()
539 + to_utf8(branch_suffix);
540 FileName res(fileName().onlyPath().absFilename() + "/" + name);
541 res.changeExtension(fileName().extension());
547 string Buffer::logName(LogType * type) const
549 string const filename = latexName(false);
551 if (filename.empty()) {
557 string const path = temppath();
559 FileName const fname(addName(temppath(),
560 onlyFilename(changeExtension(filename,
563 // FIXME: how do we know this is the name of the build log?
564 FileName const bname(
565 addName(path, onlyFilename(
566 changeExtension(filename,
567 formats.extension(bufferFormat()) + ".out"))));
569 // Also consider the master buffer log file
570 FileName masterfname = fname;
572 if (masterBuffer() != this) {
573 string const mlogfile = masterBuffer()->logName(&mtype);
574 masterfname = FileName(mlogfile);
577 // If no Latex log or Build log is newer, show Build log
578 if (bname.exists() &&
579 ((!fname.exists() && !masterfname.exists())
580 || (fname.lastModified() < bname.lastModified()
581 && masterfname.lastModified() < bname.lastModified()))) {
582 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
585 return bname.absFilename();
586 // If we have a newer master file log or only a master log, show this
587 } else if (fname != masterfname
588 && (!fname.exists() && (masterfname.exists()
589 || fname.lastModified() < masterfname.lastModified()))) {
590 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
593 return masterfname.absFilename();
595 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
598 return fname.absFilename();
602 void Buffer::setReadonly(bool const flag)
604 if (d->read_only != flag) {
611 void Buffer::setFileName(string const & newfile)
613 d->filename = makeAbsPath(newfile);
614 setReadonly(d->filename.isReadOnly());
619 int Buffer::readHeader(Lexer & lex)
621 int unknown_tokens = 0;
623 int begin_header_line = -1;
625 // Initialize parameters that may be/go lacking in header:
626 params().branchlist().clear();
627 params().preamble.erase();
628 params().options.erase();
629 params().master.erase();
630 params().float_placement.erase();
631 params().paperwidth.erase();
632 params().paperheight.erase();
633 params().leftmargin.erase();
634 params().rightmargin.erase();
635 params().topmargin.erase();
636 params().bottommargin.erase();
637 params().headheight.erase();
638 params().headsep.erase();
639 params().footskip.erase();
640 params().columnsep.erase();
641 params().fontsCJK.erase();
642 params().listings_params.clear();
643 params().clearLayoutModules();
644 params().clearRemovedModules();
645 params().clearIncludedChildren();
646 params().pdfoptions().clear();
647 params().indiceslist().clear();
648 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
650 for (int i = 0; i < 4; ++i) {
651 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
652 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
655 ErrorList & errorList = d->errorLists["Parse"];
664 if (token == "\\end_header")
668 if (token == "\\begin_header") {
669 begin_header_line = line;
673 LYXERR(Debug::PARSER, "Handling document header token: `"
676 string unknown = params().readToken(lex, token, d->filename.onlyPath());
677 if (!unknown.empty()) {
678 if (unknown[0] != '\\' && token == "\\textclass") {
679 Alert::warning(_("Unknown document class"),
680 bformat(_("Using the default document class, because the "
681 "class %1$s is unknown."), from_utf8(unknown)));
684 docstring const s = bformat(_("Unknown token: "
688 errorList.push_back(ErrorItem(_("Document header error"),
693 if (begin_header_line) {
694 docstring const s = _("\\begin_header is missing");
695 errorList.push_back(ErrorItem(_("Document header error"),
699 params().makeDocumentClass();
701 return unknown_tokens;
706 // changed to be public and have one parameter
707 // Returns true if "\end_document" is not read (Asger)
708 bool Buffer::readDocument(Lexer & lex)
710 ErrorList & errorList = d->errorLists["Parse"];
713 if (!lex.checkFor("\\begin_document")) {
714 docstring const s = _("\\begin_document is missing");
715 errorList.push_back(ErrorItem(_("Document header error"),
719 // we are reading in a brand new document
720 LASSERT(paragraphs().empty(), /**/);
724 if (params().outputChanges) {
725 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
726 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
727 LaTeXFeatures::isAvailable("xcolor");
729 if (!dvipost && !xcolorulem) {
730 Alert::warning(_("Changes not shown in LaTeX output"),
731 _("Changes will not be highlighted in LaTeX output, "
732 "because neither dvipost nor xcolor/ulem are installed.\n"
733 "Please install these packages or redefine "
734 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
735 } else if (!xcolorulem) {
736 Alert::warning(_("Changes not shown in LaTeX output"),
737 _("Changes will not be highlighted in LaTeX output "
738 "when using pdflatex, because xcolor and ulem are not installed.\n"
739 "Please install both packages or redefine "
740 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
744 if (!params().master.empty()) {
745 FileName const master_file = makeAbsPath(params().master,
746 onlyPath(absFileName()));
747 if (isLyXFilename(master_file.absFilename())) {
749 checkAndLoadLyXFile(master_file, true);
751 // necessary e.g. after a reload
752 // to re-register the child (bug 5873)
753 // FIXME: clean up updateMacros (here, only
754 // child registering is needed).
755 master->updateMacros();
756 // set master as master buffer, but only
757 // if we are a real child
758 if (master->isChild(this))
760 // if the master is not fully loaded
761 // it is probably just loading this
762 // child. No warning needed then.
763 else if (master->isFullyLoaded())
764 LYXERR0("The master '"
766 << "' assigned to this document ("
768 << ") does not include "
769 "this document. Ignoring the master assignment.");
774 // assure we have a default index
775 params().indiceslist().addDefault(B_("Index"));
778 bool const res = text().read(lex, errorList, d->inset);
782 updateMacroInstances();
787 bool Buffer::readString(string const & s)
789 params().compressed = false;
791 // remove dummy empty par
792 paragraphs().clear();
796 FileName const name = FileName::tempName("Buffer_readString");
797 switch (readFile(lex, name, true)) {
801 // We need to call lyx2lyx, so write the input to a file
802 ofstream os(name.toFilesystemEncoding().c_str());
805 return readFile(name);
815 bool Buffer::readFile(FileName const & filename)
817 FileName fname(filename);
819 params().compressed = fname.isZippedFile();
821 // remove dummy empty par
822 paragraphs().clear();
825 if (readFile(lex, fname) != success)
832 bool Buffer::isFullyLoaded() const
834 return d->file_fully_loaded;
838 void Buffer::setFullyLoaded(bool value)
840 d->file_fully_loaded = value;
844 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
847 LASSERT(!filename.empty(), /**/);
849 // the first (non-comment) token _must_ be...
850 if (!lex.checkFor("\\lyxformat")) {
851 Alert::error(_("Document format failure"),
852 bformat(_("%1$s is not a readable LyX document."),
853 from_utf8(filename.absFilename())));
859 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
860 // if present remove ".," from string.
861 size_t dot = tmp_format.find_first_of(".,");
862 //lyxerr << " dot found at " << dot << endl;
863 if (dot != string::npos)
864 tmp_format.erase(dot, 1);
865 int const file_format = convert<int>(tmp_format);
866 //lyxerr << "format: " << file_format << endl;
868 // save timestamp and checksum of the original disk file, making sure
869 // to not overwrite them with those of the file created in the tempdir
870 // when it has to be converted to the current format.
872 // Save the timestamp and checksum of disk file. If filename is an
873 // emergency file, save the timestamp and checksum of the original lyx file
874 // because isExternallyModified will check for this file. (BUG4193)
875 string diskfile = filename.absFilename();
876 if (suffixIs(diskfile, ".emergency"))
877 diskfile = diskfile.substr(0, diskfile.size() - 10);
878 saveCheckSum(FileName(diskfile));
881 if (file_format != LYX_FORMAT) {
884 // lyx2lyx would fail
887 FileName const tmpfile = FileName::tempName("Buffer_readFile");
888 if (tmpfile.empty()) {
889 Alert::error(_("Conversion failed"),
890 bformat(_("%1$s is from a different"
891 " version of LyX, but a temporary"
892 " file for converting it could"
894 from_utf8(filename.absFilename())));
897 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
898 if (lyx2lyx.empty()) {
899 Alert::error(_("Conversion script not found"),
900 bformat(_("%1$s is from a different"
901 " version of LyX, but the"
902 " conversion script lyx2lyx"
903 " could not be found."),
904 from_utf8(filename.absFilename())));
907 ostringstream command;
908 command << os::python()
909 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
910 << " -t " << convert<string>(LYX_FORMAT)
911 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
912 << ' ' << quoteName(filename.toFilesystemEncoding());
913 string const command_str = command.str();
915 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
917 cmd_ret const ret = runCommand(command_str);
918 if (ret.first != 0) {
919 if (file_format < LYX_FORMAT)
920 Alert::error(_("Conversion script failed"),
921 bformat(_("%1$s is from an older version"
922 " of LyX, but the lyx2lyx script"
923 " failed to convert it."),
924 from_utf8(filename.absFilename())));
926 Alert::error(_("Conversion script failed"),
927 bformat(_("%1$s is from a newer version"
928 " of LyX and cannot be converted by the"
930 from_utf8(filename.absFilename())));
933 bool const ret = readFile(tmpfile);
934 // Do stuff with tmpfile name and buffer name here.
935 return ret ? success : failure;
940 if (readDocument(lex)) {
941 Alert::error(_("Document format failure"),
942 bformat(_("%1$s ended unexpectedly, which means"
943 " that it is probably corrupted."),
944 from_utf8(filename.absFilename())));
947 d->file_fully_loaded = true;
952 // Should probably be moved to somewhere else: BufferView? LyXView?
953 bool Buffer::save() const
955 // We don't need autosaves in the immediate future. (Asger)
956 resetAutosaveTimers();
958 string const encodedFilename = d->filename.toFilesystemEncoding();
961 bool madeBackup = false;
963 // make a backup if the file already exists
964 if (lyxrc.make_backup && fileName().exists()) {
965 backupName = FileName(absFileName() + '~');
966 if (!lyxrc.backupdir_path.empty()) {
967 string const mangledName =
968 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
969 backupName = FileName(addName(lyxrc.backupdir_path,
972 if (fileName().copyTo(backupName)) {
975 Alert::error(_("Backup failure"),
976 bformat(_("Cannot create backup file %1$s.\n"
977 "Please check whether the directory exists and is writeable."),
978 from_utf8(backupName.absFilename())));
979 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
983 // ask if the disk file has been externally modified (use checksum method)
984 if (fileName().exists() && isExternallyModified(checksum_method)) {
985 docstring const file = makeDisplayPath(absFileName(), 20);
986 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
987 "you want to overwrite this file?"), file);
988 int const ret = Alert::prompt(_("Overwrite modified file?"),
989 text, 1, 1, _("&Overwrite"), _("&Cancel"));
994 if (writeFile(d->filename)) {
998 // Saving failed, so backup is not backup
1000 backupName.moveTo(d->filename);
1006 bool Buffer::writeFile(FileName const & fname) const
1008 if (d->read_only && fname == d->filename)
1011 bool retval = false;
1013 docstring const str = bformat(_("Saving document %1$s..."),
1014 makeDisplayPath(fname.absFilename()));
1017 if (params().compressed) {
1018 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1019 retval = ofs && write(ofs);
1021 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1022 retval = ofs && write(ofs);
1026 message(str + _(" could not write file!"));
1030 removeAutosaveFile();
1032 saveCheckSum(d->filename);
1033 message(str + _(" done."));
1039 docstring Buffer::emergencyWrite()
1041 // No need to save if the buffer has not changed.
1045 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1047 docstring user_message = bformat(
1048 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1050 // We try to save three places:
1051 // 1) Same place as document. Unless it is an unnamed doc.
1053 string s = absFileName();
1056 if (writeFile(FileName(s))) {
1058 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1059 return user_message;
1061 user_message += _(" Save failed! Trying again...\n");
1065 // 2) In HOME directory.
1066 string s = addName(package().home_dir().absFilename(), absFileName());
1068 lyxerr << ' ' << s << endl;
1069 if (writeFile(FileName(s))) {
1071 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1072 return user_message;
1075 user_message += _(" Save failed! Trying yet again...\n");
1077 // 3) In "/tmp" directory.
1078 // MakeAbsPath to prepend the current
1079 // drive letter on OS/2
1080 s = addName(package().temp_dir().absFilename(), absFileName());
1082 lyxerr << ' ' << s << endl;
1083 if (writeFile(FileName(s))) {
1085 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1086 return user_message;
1089 user_message += _(" Save failed! Bummer. Document is lost.");
1092 return user_message;
1096 bool Buffer::write(ostream & ofs) const
1099 // Use the standard "C" locale for file output.
1100 ofs.imbue(locale::classic());
1103 // The top of the file should not be written by params().
1105 // write out a comment in the top of the file
1106 ofs << "#LyX " << lyx_version
1107 << " created this file. For more info see http://www.lyx.org/\n"
1108 << "\\lyxformat " << LYX_FORMAT << "\n"
1109 << "\\begin_document\n";
1111 /// For each author, set 'used' to true if there is a change
1112 /// by this author in the document; otherwise set it to 'false'.
1113 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1114 AuthorList::Authors::const_iterator a_end = params().authors().end();
1115 for (; a_it != a_end; ++a_it)
1116 a_it->setUsed(false);
1118 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1119 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1120 for ( ; it != end; ++it)
1121 it->checkAuthors(params().authors());
1123 // now write out the buffer parameters.
1124 ofs << "\\begin_header\n";
1125 params().writeFile(ofs);
1126 ofs << "\\end_header\n";
1129 ofs << "\n\\begin_body\n";
1131 ofs << "\n\\end_body\n";
1133 // Write marker that shows file is complete
1134 ofs << "\\end_document" << endl;
1136 // Shouldn't really be needed....
1139 // how to check if close went ok?
1140 // Following is an attempt... (BE 20001011)
1142 // good() returns false if any error occured, including some
1143 // formatting error.
1144 // bad() returns true if something bad happened in the buffer,
1145 // which should include file system full errors.
1150 lyxerr << "File was not closed properly." << endl;
1157 bool Buffer::makeLaTeXFile(FileName const & fname,
1158 string const & original_path,
1159 OutputParams const & runparams_in,
1160 bool output_preamble, bool output_body) const
1162 OutputParams runparams = runparams_in;
1163 if (params().useXetex)
1164 runparams.flavor = OutputParams::XETEX;
1166 string const encoding = runparams.encoding->iconvName();
1167 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1170 try { ofs.reset(encoding); }
1171 catch (iconv_codecvt_facet_exception & e) {
1172 lyxerr << "Caught iconv exception: " << e.what() << endl;
1173 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1174 "verify that the support software for your encoding (%1$s) is "
1175 "properly installed"), from_ascii(encoding)));
1178 if (!openFileWrite(ofs, fname))
1181 //TexStream ts(ofs.rdbuf(), &texrow());
1182 ErrorList & errorList = d->errorLists["Export"];
1184 bool failed_export = false;
1187 writeLaTeXSource(ofs, original_path,
1188 runparams, output_preamble, output_body);
1190 catch (EncodingException & e) {
1191 odocstringstream ods;
1192 ods.put(e.failed_char);
1194 oss << "0x" << hex << e.failed_char << dec;
1195 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1196 " (code point %2$s)"),
1197 ods.str(), from_utf8(oss.str()));
1198 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1199 "representable in the chosen encoding.\n"
1200 "Changing the document encoding to utf8 could help."),
1201 e.par_id, e.pos, e.pos + 1));
1202 failed_export = true;
1204 catch (iconv_codecvt_facet_exception & e) {
1205 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1206 _(e.what()), -1, 0, 0));
1207 failed_export = true;
1209 catch (exception const & e) {
1210 errorList.push_back(ErrorItem(_("conversion failed"),
1211 _(e.what()), -1, 0, 0));
1212 failed_export = true;
1215 lyxerr << "Caught some really weird exception..." << endl;
1221 failed_export = true;
1222 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1226 return !failed_export;
1230 void Buffer::writeLaTeXSource(odocstream & os,
1231 string const & original_path,
1232 OutputParams const & runparams_in,
1233 bool const output_preamble, bool const output_body) const
1235 // The child documents, if any, shall be already loaded at this point.
1237 OutputParams runparams = runparams_in;
1239 // Classify the unicode characters appearing in math insets
1240 Encodings::initUnicodeMath(*this);
1242 // validate the buffer.
1243 LYXERR(Debug::LATEX, " Validating buffer...");
1244 LaTeXFeatures features(*this, params(), runparams);
1246 LYXERR(Debug::LATEX, " Buffer validation done.");
1248 // The starting paragraph of the coming rows is the
1249 // first paragraph of the document. (Asger)
1250 if (output_preamble && runparams.nice) {
1251 os << "%% LyX " << lyx_version << " created this file. "
1252 "For more info, see http://www.lyx.org/.\n"
1253 "%% Do not edit unless you really know what "
1255 d->texrow.newline();
1256 d->texrow.newline();
1258 LYXERR(Debug::INFO, "lyx document header finished");
1260 // Don't move this behind the parent_buffer=0 code below,
1261 // because then the macros will not get the right "redefinition"
1262 // flag as they don't see the parent macros which are output before.
1265 // fold macros if possible, still with parent buffer as the
1266 // macros will be put in the prefix anyway.
1267 updateMacroInstances();
1269 // There are a few differences between nice LaTeX and usual files:
1270 // usual is \batchmode and has a
1271 // special input@path to allow the including of figures
1272 // with either \input or \includegraphics (what figinsets do).
1273 // input@path is set when the actual parameter
1274 // original_path is set. This is done for usual tex-file, but not
1275 // for nice-latex-file. (Matthias 250696)
1276 // Note that input@path is only needed for something the user does
1277 // in the preamble, included .tex files or ERT, files included by
1278 // LyX work without it.
1279 if (output_preamble) {
1280 if (!runparams.nice) {
1281 // code for usual, NOT nice-latex-file
1282 os << "\\batchmode\n"; // changed
1283 // from \nonstopmode
1284 d->texrow.newline();
1286 if (!original_path.empty()) {
1288 // We don't know the encoding of inputpath
1289 docstring const inputpath = from_utf8(latex_path(original_path));
1290 os << "\\makeatletter\n"
1291 << "\\def\\input@path{{"
1292 << inputpath << "/}}\n"
1293 << "\\makeatother\n";
1294 d->texrow.newline();
1295 d->texrow.newline();
1296 d->texrow.newline();
1299 // get parent macros (if this buffer has a parent) which will be
1300 // written at the document begin further down.
1301 MacroSet parentMacros;
1302 listParentMacros(parentMacros, features);
1304 // Write the preamble
1305 runparams.use_babel = params().writeLaTeX(os, features,
1307 d->filename.onlyPath());
1309 runparams.use_japanese = features.isRequired("japanese");
1315 os << "\\begin{document}\n";
1316 d->texrow.newline();
1318 // output the parent macros
1319 MacroSet::iterator it = parentMacros.begin();
1320 MacroSet::iterator end = parentMacros.end();
1321 for (; it != end; ++it)
1322 (*it)->write(os, true);
1323 } // output_preamble
1325 d->texrow.start(paragraphs().begin()->id(), 0);
1327 LYXERR(Debug::INFO, "preamble finished, now the body.");
1329 // if we are doing a real file with body, even if this is the
1330 // child of some other buffer, let's cut the link here.
1331 // This happens for example if only a child document is printed.
1332 Buffer const * save_parent = 0;
1333 if (output_preamble) {
1334 save_parent = d->parent();
1339 latexParagraphs(*this, text(), os, d->texrow, runparams);
1341 // Restore the parenthood if needed
1342 if (output_preamble)
1343 d->setParent(save_parent);
1345 // add this just in case after all the paragraphs
1347 d->texrow.newline();
1349 if (output_preamble) {
1350 os << "\\end{document}\n";
1351 d->texrow.newline();
1352 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1354 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1356 runparams_in.encoding = runparams.encoding;
1358 // Just to be sure. (Asger)
1359 d->texrow.newline();
1361 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1362 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1366 bool Buffer::isLatex() const
1368 return params().documentClass().outputType() == LATEX;
1372 bool Buffer::isLiterate() const
1374 return params().documentClass().outputType() == LITERATE;
1378 bool Buffer::isDocBook() const
1380 return params().documentClass().outputType() == DOCBOOK;
1384 void Buffer::makeDocBookFile(FileName const & fname,
1385 OutputParams const & runparams,
1386 bool const body_only) const
1388 LYXERR(Debug::LATEX, "makeDocBookFile...");
1391 if (!openFileWrite(ofs, fname))
1394 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1398 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1402 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1403 OutputParams const & runparams,
1404 bool const only_body) const
1406 LaTeXFeatures features(*this, params(), runparams);
1411 DocumentClass const & tclass = params().documentClass();
1412 string const top_element = tclass.latexname();
1415 if (runparams.flavor == OutputParams::XML)
1416 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1419 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1422 if (! tclass.class_header().empty())
1423 os << from_ascii(tclass.class_header());
1424 else if (runparams.flavor == OutputParams::XML)
1425 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1426 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1428 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1430 docstring preamble = from_utf8(params().preamble);
1431 if (runparams.flavor != OutputParams::XML ) {
1432 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1433 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1434 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1435 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1438 string const name = runparams.nice
1439 ? changeExtension(absFileName(), ".sgml") : fname;
1440 preamble += features.getIncludedFiles(name);
1441 preamble += features.getLyXSGMLEntities();
1443 if (!preamble.empty()) {
1444 os << "\n [ " << preamble << " ]";
1449 string top = top_element;
1451 if (runparams.flavor == OutputParams::XML)
1452 top += params().language->code();
1454 top += params().language->code().substr(0, 2);
1457 if (!params().options.empty()) {
1459 top += params().options;
1462 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1463 << " file was created by LyX " << lyx_version
1464 << "\n See http://www.lyx.org/ for more information -->\n";
1466 params().documentClass().counters().reset();
1470 sgml::openTag(os, top);
1472 docbookParagraphs(text(), *this, os, runparams);
1473 sgml::closeTag(os, top_element);
1477 void Buffer::makeLyXHTMLFile(FileName const & fname,
1478 OutputParams const & runparams,
1479 bool const body_only) const
1481 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1484 if (!openFileWrite(ofs, fname))
1487 writeLyXHTMLSource(ofs, runparams, body_only);
1491 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1495 void Buffer::writeLyXHTMLSource(odocstream & os,
1496 OutputParams const & runparams,
1497 bool const only_body) const
1499 LaTeXFeatures features(*this, params(), runparams);
1501 updateLabels(UpdateMaster, OutputUpdate);
1502 checkBibInfoCache();
1503 d->bibinfo_.makeCitationLabels(*this);
1505 updateMacroInstances();
1508 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1509 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";
1510 // FIXME Language should be set properly.
1511 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1513 // FIXME Presumably need to set this right
1514 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1515 os << "<title>" << features.htmlTitle() << "</title>\n";
1517 os << "\n<!-- Text Class Preamble -->\n"
1518 << features.getTClassHTMLPreamble()
1519 << "\n<!-- Premable Snippets -->\n"
1520 << from_utf8(features.getPreambleSnippets());
1522 os << "\n<!-- Layout-provided Styles -->\n";
1523 docstring const styleinfo = features.getTClassHTMLStyles();
1524 if (!styleinfo.empty()) {
1525 os << "<style type='text/css'>\n"
1529 os << "</head>\n<body>\n";
1533 params().documentClass().counters().reset();
1534 xhtmlParagraphs(text(), *this, xs, runparams);
1536 os << "</body>\n</html>\n";
1540 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1541 // Other flags: -wall -v0 -x
1542 int Buffer::runChktex()
1546 // get LaTeX-Filename
1547 FileName const path(temppath());
1548 string const name = addName(path.absFilename(), latexName());
1549 string const org_path = filePath();
1551 PathChanger p(path); // path to LaTeX file
1552 message(_("Running chktex..."));
1554 // Generate the LaTeX file if neccessary
1555 OutputParams runparams(¶ms().encoding());
1556 runparams.flavor = OutputParams::LATEX;
1557 runparams.nice = false;
1558 makeLaTeXFile(FileName(name), org_path, runparams);
1561 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1562 int const res = chktex.run(terr); // run chktex
1565 Alert::error(_("chktex failure"),
1566 _("Could not run chktex successfully."));
1567 } else if (res > 0) {
1568 ErrorList & errlist = d->errorLists["ChkTeX"];
1570 bufferErrors(terr, errlist);
1581 void Buffer::validate(LaTeXFeatures & features) const
1583 params().validate(features);
1587 for_each(paragraphs().begin(), paragraphs().end(),
1588 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1590 if (lyxerr.debugging(Debug::LATEX)) {
1591 features.showStruct();
1596 void Buffer::getLabelList(vector<docstring> & list) const
1598 // If this is a child document, use the parent's list instead.
1599 Buffer const * const pbuf = d->parent();
1601 pbuf->getLabelList(list);
1606 Toc & toc = d->toc_backend.toc("label");
1607 TocIterator toc_it = toc.begin();
1608 TocIterator end = toc.end();
1609 for (; toc_it != end; ++toc_it) {
1610 if (toc_it->depth() == 0)
1611 list.push_back(toc_it->str());
1616 void Buffer::updateBibfilesCache(UpdateScope scope) const
1618 // If this is a child document, use the parent's cache instead.
1619 Buffer const * const pbuf = d->parent();
1620 if (pbuf && scope != UpdateChildOnly) {
1621 pbuf->updateBibfilesCache();
1625 d->bibfiles_cache_.clear();
1626 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1627 if (it->lyxCode() == BIBTEX_CODE) {
1628 InsetBibtex const & inset =
1629 static_cast<InsetBibtex const &>(*it);
1630 support::FileNameList const bibfiles = inset.getBibFiles();
1631 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1634 } else if (it->lyxCode() == INCLUDE_CODE) {
1635 InsetInclude & inset =
1636 static_cast<InsetInclude &>(*it);
1637 inset.updateBibfilesCache();
1638 support::FileNameList const & bibfiles =
1639 inset.getBibfilesCache();
1640 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1645 // the bibinfo cache is now invalid
1646 d->bibinfo_cache_valid_ = false;
1650 void Buffer::invalidateBibinfoCache()
1652 d->bibinfo_cache_valid_ = false;
1656 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1658 // If this is a child document, use the parent's cache instead.
1659 Buffer const * const pbuf = d->parent();
1660 if (pbuf && scope != UpdateChildOnly)
1661 return pbuf->getBibfilesCache();
1663 // We update the cache when first used instead of at loading time.
1664 if (d->bibfiles_cache_.empty())
1665 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1667 return d->bibfiles_cache_;
1671 BiblioInfo const & Buffer::masterBibInfo() const
1673 // if this is a child document and the parent is already loaded
1674 // use the parent's list instead [ale990412]
1675 Buffer const * const tmp = masterBuffer();
1678 return tmp->masterBibInfo();
1679 return localBibInfo();
1683 BiblioInfo const & Buffer::localBibInfo() const
1689 void Buffer::checkBibInfoCache() const
1691 support::FileNameList const & bibfilesCache = getBibfilesCache();
1692 // compare the cached timestamps with the actual ones.
1693 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1694 support::FileNameList::const_iterator en = bibfilesCache.end();
1695 for (; ei != en; ++ ei) {
1696 time_t lastw = ei->lastModified();
1697 time_t prevw = d->bibfile_status_[*ei];
1698 if (lastw != prevw) {
1699 d->bibinfo_cache_valid_ = false;
1700 d->bibfile_status_[*ei] = lastw;
1704 if (!d->bibinfo_cache_valid_) {
1705 d->bibinfo_.clear();
1706 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1707 it->fillWithBibKeys(d->bibinfo_, it);
1708 d->bibinfo_cache_valid_ = true;
1713 bool Buffer::isDepClean(string const & name) const
1715 DepClean::const_iterator const it = d->dep_clean.find(name);
1716 if (it == d->dep_clean.end())
1722 void Buffer::markDepClean(string const & name)
1724 d->dep_clean[name] = true;
1728 bool Buffer::isExportableFormat(string const & format) const
1730 typedef vector<Format const *> Formats;
1732 formats = exportableFormats(true);
1733 Formats::const_iterator fit = formats.begin();
1734 Formats::const_iterator end = formats.end();
1735 for (; fit != end ; ++fit) {
1736 if ((*fit)->name() == format)
1743 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1746 // FIXME? if there is an Buffer LFUN that can be dispatched even
1747 // if internal, put a switch '(cmd.action)' here.
1753 switch (cmd.action) {
1755 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1756 flag.setOnOff(isReadonly());
1759 // FIXME: There is need for a command-line import.
1760 //case LFUN_BUFFER_IMPORT:
1762 case LFUN_BUFFER_AUTO_SAVE:
1765 case LFUN_BUFFER_EXPORT_CUSTOM:
1766 // FIXME: Nothing to check here?
1769 case LFUN_BUFFER_EXPORT: {
1770 docstring const arg = cmd.argument();
1771 enable = arg == "custom" || isExportable(to_utf8(arg));
1773 flag.message(bformat(
1774 _("Don't know how to export to format: %1$s"), arg));
1778 case LFUN_BUFFER_CHKTEX:
1779 enable = isLatex() && !lyxrc.chktex_command.empty();
1782 case LFUN_BUILD_PROGRAM:
1783 enable = isExportable("program");
1786 case LFUN_BRANCH_ACTIVATE:
1787 case LFUN_BRANCH_DEACTIVATE: {
1788 BranchList const & branchList = params().branchlist();
1789 docstring const branchName = cmd.argument();
1790 enable = !branchName.empty() && branchList.find(branchName);
1794 case LFUN_BRANCH_ADD:
1795 case LFUN_BRANCHES_RENAME:
1796 case LFUN_BUFFER_PRINT:
1797 // if no Buffer is present, then of course we won't be called!
1800 case LFUN_BUFFER_LANGUAGE:
1801 enable = !isReadonly();
1807 flag.setEnabled(enable);
1812 void Buffer::dispatch(string const & command, DispatchResult & result)
1814 return dispatch(lyxaction.lookupFunc(command), result);
1818 // NOTE We can end up here even if we have no GUI, because we are called
1819 // by LyX::exec to handled command-line requests. So we may need to check
1820 // whether we have a GUI or not. The boolean use_gui holds this information.
1821 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1824 // FIXME? if there is an Buffer LFUN that can be dispatched even
1825 // if internal, put a switch '(cmd.action)' here.
1826 dr.dispatched(false);
1829 string const argument = to_utf8(func.argument());
1830 // We'll set this back to false if need be.
1831 bool dispatched = true;
1832 undo().beginUndoGroup();
1834 switch (func.action) {
1835 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1836 if (lyxvc().inUse())
1837 lyxvc().toggleReadOnly();
1839 setReadonly(!isReadonly());
1842 case LFUN_BUFFER_EXPORT: {
1843 bool success = doExport(argument, false, false);
1844 dr.setError(success);
1846 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1851 case LFUN_BUILD_PROGRAM:
1852 doExport("program", true, false);
1855 case LFUN_BUFFER_CHKTEX:
1859 case LFUN_BUFFER_EXPORT_CUSTOM: {
1861 string command = split(argument, format_name, ' ');
1862 Format const * format = formats.getFormat(format_name);
1864 lyxerr << "Format \"" << format_name
1865 << "\" not recognized!"
1870 // The name of the file created by the conversion process
1873 // Output to filename
1874 if (format->name() == "lyx") {
1875 string const latexname = latexName(false);
1876 filename = changeExtension(latexname,
1877 format->extension());
1878 filename = addName(temppath(), filename);
1880 if (!writeFile(FileName(filename)))
1884 doExport(format_name, true, false, filename);
1887 // Substitute $$FName for filename
1888 if (!contains(command, "$$FName"))
1889 command = "( " + command + " ) < $$FName";
1890 command = subst(command, "$$FName", filename);
1892 // Execute the command in the background
1894 call.startscript(Systemcall::DontWait, command);
1898 // FIXME: There is need for a command-line import.
1900 case LFUN_BUFFER_IMPORT:
1905 case LFUN_BUFFER_AUTO_SAVE:
1909 case LFUN_BRANCH_ADD: {
1910 docstring const branch_name = func.argument();
1911 if (branch_name.empty()) {
1915 BranchList & branch_list = params().branchlist();
1916 Branch * branch = branch_list.find(branch_name);
1918 LYXERR0("Branch " << branch_name << " already exists.");
1920 docstring const msg =
1921 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1924 branch_list.add(branch_name);
1925 branch = branch_list.find(branch_name);
1926 string const x11hexname = X11hexname(branch->color());
1927 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1928 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1930 dr.update(Update::Force);
1935 case LFUN_BRANCH_ACTIVATE:
1936 case LFUN_BRANCH_DEACTIVATE: {
1937 BranchList & branchList = params().branchlist();
1938 docstring const branchName = func.argument();
1939 // the case without a branch name is handled elsewhere
1940 if (branchName.empty()) {
1944 Branch * branch = branchList.find(branchName);
1946 LYXERR0("Branch " << branchName << " does not exist.");
1948 docstring const msg =
1949 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1952 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1954 dr.update(Update::Force);
1959 case LFUN_BRANCHES_RENAME: {
1960 if (func.argument().empty())
1963 docstring const oldname = from_utf8(func.getArg(0));
1964 docstring const newname = from_utf8(func.getArg(1));
1965 InsetIterator it = inset_iterator_begin(inset());
1966 InsetIterator const end = inset_iterator_end(inset());
1967 bool success = false;
1968 for (; it != end; ++it) {
1969 if (it->lyxCode() == BRANCH_CODE) {
1970 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1971 if (ins.branch() == oldname) {
1972 undo().recordUndo(it);
1973 ins.rename(newname);
1978 if (it->lyxCode() == INCLUDE_CODE) {
1979 // get buffer of external file
1980 InsetInclude const & ins =
1981 static_cast<InsetInclude const &>(*it);
1982 Buffer * child = ins.getChildBuffer();
1985 child->dispatch(func, dr);
1990 dr.update(Update::Force);
1994 case LFUN_BUFFER_PRINT: {
1995 // we'll assume there's a problem until we succeed
1997 string target = func.getArg(0);
1998 string target_name = func.getArg(1);
1999 string command = func.getArg(2);
2002 || target_name.empty()
2003 || command.empty()) {
2004 LYXERR0("Unable to parse " << func.argument());
2005 docstring const msg =
2006 bformat(_("Unable to parse \"%1$s\""), func.argument());
2010 if (target != "printer" && target != "file") {
2011 LYXERR0("Unrecognized target \"" << target << '"');
2012 docstring const msg =
2013 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2018 bool const update_unincluded =
2019 params().maintain_unincluded_children
2020 && !params().getIncludedChildren().empty();
2021 if (!doExport("dvi", true, update_unincluded)) {
2022 showPrintError(absFileName());
2023 dr.setMessage(_("Error exporting to DVI."));
2027 // Push directory path.
2028 string const path = temppath();
2029 // Prevent the compiler from optimizing away p
2033 // there are three cases here:
2034 // 1. we print to a file
2035 // 2. we print directly to a printer
2036 // 3. we print using a spool command (print to file first)
2039 string const dviname = changeExtension(latexName(true), "dvi");
2041 if (target == "printer") {
2042 if (!lyxrc.print_spool_command.empty()) {
2043 // case 3: print using a spool
2044 string const psname = changeExtension(dviname,".ps");
2045 command += ' ' + lyxrc.print_to_file
2048 + quoteName(dviname);
2050 string command2 = lyxrc.print_spool_command + ' ';
2051 if (target_name != "default") {
2052 command2 += lyxrc.print_spool_printerprefix
2056 command2 += quoteName(psname);
2058 // If successful, then spool command
2059 res = one.startscript(Systemcall::Wait, command);
2062 // If there's no GUI, we have to wait on this command. Otherwise,
2063 // LyX deletes the temporary directory, and with it the spooled
2064 // file, before it can be printed!!
2065 Systemcall::Starttype stype = use_gui ?
2066 Systemcall::DontWait : Systemcall::Wait;
2067 res = one.startscript(stype, command2);
2070 // case 2: print directly to a printer
2071 if (target_name != "default")
2072 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2074 Systemcall::Starttype stype = use_gui ?
2075 Systemcall::DontWait : Systemcall::Wait;
2076 res = one.startscript(stype, command + quoteName(dviname));
2080 // case 1: print to a file
2081 FileName const filename(makeAbsPath(target_name, filePath()));
2082 FileName const dvifile(makeAbsPath(dviname, path));
2083 if (filename.exists()) {
2084 docstring text = bformat(
2085 _("The file %1$s already exists.\n\n"
2086 "Do you want to overwrite that file?"),
2087 makeDisplayPath(filename.absFilename()));
2088 if (Alert::prompt(_("Overwrite file?"),
2089 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2092 command += ' ' + lyxrc.print_to_file
2093 + quoteName(filename.toFilesystemEncoding())
2095 + quoteName(dvifile.toFilesystemEncoding());
2097 Systemcall::Starttype stype = use_gui ?
2098 Systemcall::DontWait : Systemcall::Wait;
2099 res = one.startscript(stype, command);
2105 dr.setMessage(_("Error running external commands."));
2106 showPrintError(absFileName());
2111 case LFUN_BUFFER_LANGUAGE: {
2112 Language const * oldL = params().language;
2113 Language const * newL = languages.getLanguage(argument);
2114 if (!newL || oldL == newL)
2116 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2117 changeLanguage(oldL, newL);
2125 dr.dispatched(dispatched);
2126 undo().endUndoGroup();
2130 void Buffer::changeLanguage(Language const * from, Language const * to)
2132 LASSERT(from, /**/);
2135 for_each(par_iterator_begin(),
2137 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2141 bool Buffer::isMultiLingual() const
2143 ParConstIterator end = par_iterator_end();
2144 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2145 if (it->isMultiLingual(params()))
2152 DocIterator Buffer::getParFromID(int const id) const
2154 Buffer * buf = const_cast<Buffer *>(this);
2156 // John says this is called with id == -1 from undo
2157 lyxerr << "getParFromID(), id: " << id << endl;
2158 return doc_iterator_end(buf);
2161 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2162 if (it.paragraph().id() == id)
2165 return doc_iterator_end(buf);
2169 bool Buffer::hasParWithID(int const id) const
2171 return !getParFromID(id).atEnd();
2175 ParIterator Buffer::par_iterator_begin()
2177 return ParIterator(doc_iterator_begin(this));
2181 ParIterator Buffer::par_iterator_end()
2183 return ParIterator(doc_iterator_end(this));
2187 ParConstIterator Buffer::par_iterator_begin() const
2189 return ParConstIterator(doc_iterator_begin(this));
2193 ParConstIterator Buffer::par_iterator_end() const
2195 return ParConstIterator(doc_iterator_end(this));
2199 Language const * Buffer::language() const
2201 return params().language;
2205 docstring const Buffer::B_(string const & l10n) const
2207 return params().B_(l10n);
2211 bool Buffer::isClean() const
2213 return d->lyx_clean;
2217 bool Buffer::isBakClean() const
2219 return d->bak_clean;
2223 bool Buffer::isExternallyModified(CheckMethod method) const
2225 LASSERT(d->filename.exists(), /**/);
2226 // if method == timestamp, check timestamp before checksum
2227 return (method == checksum_method
2228 || d->timestamp_ != d->filename.lastModified())
2229 && d->checksum_ != d->filename.checksum();
2233 void Buffer::saveCheckSum(FileName const & file) const
2235 if (file.exists()) {
2236 d->timestamp_ = file.lastModified();
2237 d->checksum_ = file.checksum();
2239 // in the case of save to a new file.
2246 void Buffer::markClean() const
2248 if (!d->lyx_clean) {
2249 d->lyx_clean = true;
2252 // if the .lyx file has been saved, we don't need an
2254 d->bak_clean = true;
2258 void Buffer::markBakClean() const
2260 d->bak_clean = true;
2264 void Buffer::setUnnamed(bool flag)
2270 bool Buffer::isUnnamed() const
2277 /// Don't check unnamed, here: isInternal() is used in
2278 /// newBuffer(), where the unnamed flag has not been set by anyone
2279 /// yet. Also, for an internal buffer, there should be no need for
2280 /// retrieving fileName() nor for checking if it is unnamed or not.
2281 bool Buffer::isInternal() const
2283 return fileName().extension() == "internal";
2287 void Buffer::markDirty()
2290 d->lyx_clean = false;
2293 d->bak_clean = false;
2295 DepClean::iterator it = d->dep_clean.begin();
2296 DepClean::const_iterator const end = d->dep_clean.end();
2298 for (; it != end; ++it)
2303 FileName Buffer::fileName() const
2309 string Buffer::absFileName() const
2311 return d->filename.absFilename();
2315 string Buffer::filePath() const
2317 return d->filename.onlyPath().absFilename() + "/";
2321 bool Buffer::isReadonly() const
2323 return d->read_only;
2327 void Buffer::setParent(Buffer const * buffer)
2329 // Avoids recursive include.
2330 d->setParent(buffer == this ? 0 : buffer);
2335 Buffer const * Buffer::parent() const
2341 void Buffer::collectRelatives(BufferSet & bufs) const
2345 parent()->collectRelatives(bufs);
2347 // loop over children
2348 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2349 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2350 for (; it != end; ++it)
2351 bufs.insert(const_cast<Buffer *>(it->first));
2355 std::vector<Buffer const *> Buffer::allRelatives() const
2358 collectRelatives(bufs);
2359 BufferSet::iterator it = bufs.begin();
2360 std::vector<Buffer const *> ret;
2361 for (; it != bufs.end(); ++it)
2367 Buffer const * Buffer::masterBuffer() const
2369 Buffer const * const pbuf = d->parent();
2373 return pbuf->masterBuffer();
2377 bool Buffer::isChild(Buffer * child) const
2379 return d->children_positions.find(child) != d->children_positions.end();
2383 DocIterator Buffer::firstChildPosition(Buffer const * child)
2385 Impl::BufferPositionMap::iterator it;
2386 it = d->children_positions.find(child);
2387 if (it == d->children_positions.end())
2388 return DocIterator(this);
2393 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2395 // loop over children
2396 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2397 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2398 for (; it != end; ++it) {
2399 Buffer * child = const_cast<Buffer *>(it->first);
2400 clist.push_back(child);
2401 if (grand_children) {
2402 // there might be grandchildren
2403 std::vector<Buffer *> glist = child->getChildren();
2404 for (vector<Buffer *>::const_iterator git = glist.begin();
2405 git != glist.end(); ++git)
2406 clist.push_back(*git);
2412 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2414 std::vector<Buffer *> v;
2415 getChildren(v, grand_children);
2420 template<typename M>
2421 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2426 typename M::iterator it = m.lower_bound(x);
2427 if (it == m.begin())
2435 MacroData const * Buffer::getBufferMacro(docstring const & name,
2436 DocIterator const & pos) const
2438 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2440 // if paragraphs have no macro context set, pos will be empty
2444 // we haven't found anything yet
2445 DocIterator bestPos = par_iterator_begin();
2446 MacroData const * bestData = 0;
2448 // find macro definitions for name
2449 Impl::NamePositionScopeMacroMap::iterator nameIt
2450 = d->macros.find(name);
2451 if (nameIt != d->macros.end()) {
2452 // find last definition in front of pos or at pos itself
2453 Impl::PositionScopeMacroMap::const_iterator it
2454 = greatest_below(nameIt->second, pos);
2455 if (it != nameIt->second.end()) {
2457 // scope ends behind pos?
2458 if (pos < it->second.first) {
2459 // Looks good, remember this. If there
2460 // is no external macro behind this,
2461 // we found the right one already.
2462 bestPos = it->first;
2463 bestData = &it->second.second;
2467 // try previous macro if there is one
2468 if (it == nameIt->second.begin())
2475 // find macros in included files
2476 Impl::PositionScopeBufferMap::const_iterator it
2477 = greatest_below(d->position_to_children, pos);
2478 if (it == d->position_to_children.end())
2479 // no children before
2483 // do we know something better (i.e. later) already?
2484 if (it->first < bestPos )
2487 // scope ends behind pos?
2488 if (pos < it->second.first) {
2489 // look for macro in external file
2490 d->macro_lock = true;
2491 MacroData const * data
2492 = it->second.second->getMacro(name, false);
2493 d->macro_lock = false;
2495 bestPos = it->first;
2501 // try previous file if there is one
2502 if (it == d->position_to_children.begin())
2507 // return the best macro we have found
2512 MacroData const * Buffer::getMacro(docstring const & name,
2513 DocIterator const & pos, bool global) const
2518 // query buffer macros
2519 MacroData const * data = getBufferMacro(name, pos);
2523 // If there is a master buffer, query that
2524 Buffer const * const pbuf = d->parent();
2526 d->macro_lock = true;
2527 MacroData const * macro = pbuf->getMacro(
2528 name, *this, false);
2529 d->macro_lock = false;
2535 data = MacroTable::globalMacros().get(name);
2544 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2546 // set scope end behind the last paragraph
2547 DocIterator scope = par_iterator_begin();
2548 scope.pit() = scope.lastpit() + 1;
2550 return getMacro(name, scope, global);
2554 MacroData const * Buffer::getMacro(docstring const & name,
2555 Buffer const & child, bool global) const
2557 // look where the child buffer is included first
2558 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2559 if (it == d->children_positions.end())
2562 // check for macros at the inclusion position
2563 return getMacro(name, it->second, global);
2567 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2569 pit_type const lastpit = it.lastpit();
2571 // look for macros in each paragraph
2572 while (it.pit() <= lastpit) {
2573 Paragraph & par = it.paragraph();
2575 // iterate over the insets of the current paragraph
2576 InsetList const & insets = par.insetList();
2577 InsetList::const_iterator iit = insets.begin();
2578 InsetList::const_iterator end = insets.end();
2579 for (; iit != end; ++iit) {
2580 it.pos() = iit->pos;
2582 // is it a nested text inset?
2583 if (iit->inset->asInsetText()) {
2584 // Inset needs its own scope?
2585 InsetText const * itext = iit->inset->asInsetText();
2586 bool newScope = itext->isMacroScope();
2588 // scope which ends just behind the inset
2589 DocIterator insetScope = it;
2592 // collect macros in inset
2593 it.push_back(CursorSlice(*iit->inset));
2594 updateMacros(it, newScope ? insetScope : scope);
2599 // is it an external file?
2600 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2601 // get buffer of external file
2602 InsetInclude const & inset =
2603 static_cast<InsetInclude const &>(*iit->inset);
2604 d->macro_lock = true;
2605 Buffer * child = inset.getChildBuffer();
2606 d->macro_lock = false;
2610 // register its position, but only when it is
2611 // included first in the buffer
2612 if (d->children_positions.find(child) ==
2613 d->children_positions.end())
2614 d->children_positions[child] = it;
2616 // register child with its scope
2617 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2621 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2625 MathMacroTemplate & macroTemplate =
2626 static_cast<MathMacroTemplate &>(*iit->inset);
2627 MacroContext mc(this, it);
2628 macroTemplate.updateToContext(mc);
2631 bool valid = macroTemplate.validMacro();
2632 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2633 // then the BufferView's cursor will be invalid in
2634 // some cases which leads to crashes.
2639 // FIXME (Abdel), I don't understandt why we pass 'it' here
2640 // instead of 'macroTemplate' defined above... is this correct?
2641 d->macros[macroTemplate.name()][it] =
2642 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2652 void Buffer::updateMacros() const
2657 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2659 // start with empty table
2661 d->children_positions.clear();
2662 d->position_to_children.clear();
2664 // Iterate over buffer, starting with first paragraph
2665 // The scope must be bigger than any lookup DocIterator
2666 // later. For the global lookup, lastpit+1 is used, hence
2667 // we use lastpit+2 here.
2668 DocIterator it = par_iterator_begin();
2669 DocIterator outerScope = it;
2670 outerScope.pit() = outerScope.lastpit() + 2;
2671 updateMacros(it, outerScope);
2675 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2677 InsetIterator it = inset_iterator_begin(inset());
2678 InsetIterator const end = inset_iterator_end(inset());
2679 for (; it != end; ++it) {
2680 if (it->lyxCode() == BRANCH_CODE) {
2681 InsetBranch & br = static_cast<InsetBranch &>(*it);
2682 docstring const name = br.branch();
2683 if (!from_master && !params().branchlist().find(name))
2684 result.push_back(name);
2685 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2686 result.push_back(name);
2689 if (it->lyxCode() == INCLUDE_CODE) {
2690 // get buffer of external file
2691 InsetInclude const & ins =
2692 static_cast<InsetInclude const &>(*it);
2693 Buffer * child = ins.getChildBuffer();
2696 child->getUsedBranches(result, true);
2699 // remove duplicates
2704 void Buffer::updateMacroInstances() const
2706 LYXERR(Debug::MACROS, "updateMacroInstances for "
2707 << d->filename.onlyFileName());
2708 DocIterator it = doc_iterator_begin(this);
2710 DocIterator const end = doc_iterator_end(this);
2711 for (; it != end; it.forwardInset()) {
2712 // look for MathData cells in InsetMathNest insets
2713 InsetMath * minset = it.nextInset()->asInsetMath();
2717 // update macro in all cells of the InsetMathNest
2718 DocIterator::idx_type n = minset->nargs();
2719 MacroContext mc = MacroContext(this, it);
2720 for (DocIterator::idx_type i = 0; i < n; ++i) {
2721 MathData & data = minset->cell(i);
2722 data.updateMacros(0, mc);
2728 void Buffer::listMacroNames(MacroNameSet & macros) const
2733 d->macro_lock = true;
2735 // loop over macro names
2736 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2737 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2738 for (; nameIt != nameEnd; ++nameIt)
2739 macros.insert(nameIt->first);
2741 // loop over children
2742 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2743 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2744 for (; it != end; ++it)
2745 it->first->listMacroNames(macros);
2748 Buffer const * const pbuf = d->parent();
2750 pbuf->listMacroNames(macros);
2752 d->macro_lock = false;
2756 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2758 Buffer const * const pbuf = d->parent();
2763 pbuf->listMacroNames(names);
2766 MacroNameSet::iterator it = names.begin();
2767 MacroNameSet::iterator end = names.end();
2768 for (; it != end; ++it) {
2770 MacroData const * data =
2771 pbuf->getMacro(*it, *this, false);
2773 macros.insert(data);
2775 // we cannot access the original MathMacroTemplate anymore
2776 // here to calls validate method. So we do its work here manually.
2777 // FIXME: somehow make the template accessible here.
2778 if (data->optionals() > 0)
2779 features.require("xargs");
2785 Buffer::References & Buffer::references(docstring const & label)
2788 return const_cast<Buffer *>(masterBuffer())->references(label);
2790 RefCache::iterator it = d->ref_cache_.find(label);
2791 if (it != d->ref_cache_.end())
2792 return it->second.second;
2794 static InsetLabel const * dummy_il = 0;
2795 static References const dummy_refs;
2796 it = d->ref_cache_.insert(
2797 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2798 return it->second.second;
2802 Buffer::References const & Buffer::references(docstring const & label) const
2804 return const_cast<Buffer *>(this)->references(label);
2808 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2810 masterBuffer()->d->ref_cache_[label].first = il;
2814 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2816 return masterBuffer()->d->ref_cache_[label].first;
2820 void Buffer::clearReferenceCache() const
2823 d->ref_cache_.clear();
2827 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2830 //FIXME: This does not work for child documents yet.
2831 LASSERT(code == CITE_CODE, /**/);
2832 // Check if the label 'from' appears more than once
2833 vector<docstring> labels;
2835 checkBibInfoCache();
2836 BiblioInfo const & keys = masterBibInfo();
2837 BiblioInfo::const_iterator bit = keys.begin();
2838 BiblioInfo::const_iterator bend = keys.end();
2840 for (; bit != bend; ++bit)
2842 labels.push_back(bit->first);
2845 if (count(labels.begin(), labels.end(), from) > 1)
2848 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2849 if (it->lyxCode() == code) {
2850 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2851 docstring const oldValue = inset.getParam(paramName);
2852 if (oldValue == from)
2853 inset.setParam(paramName, to);
2859 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2860 pit_type par_end, bool full_source) const
2862 OutputParams runparams(¶ms().encoding());
2863 runparams.nice = true;
2864 runparams.flavor = params().useXetex ?
2865 OutputParams::XETEX : OutputParams::LATEX;
2866 runparams.linelen = lyxrc.plaintext_linelen;
2867 // No side effect of file copying and image conversion
2868 runparams.dryrun = true;
2871 os << "% " << _("Preview source code") << "\n\n";
2873 d->texrow.newline();
2874 d->texrow.newline();
2876 writeDocBookSource(os, absFileName(), runparams, false);
2878 // latex or literate
2879 writeLaTeXSource(os, string(), runparams, true, true);
2881 runparams.par_begin = par_begin;
2882 runparams.par_end = par_end;
2883 if (par_begin + 1 == par_end) {
2885 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2889 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2890 convert<docstring>(par_begin),
2891 convert<docstring>(par_end - 1))
2898 // output paragraphs
2900 docbookParagraphs(text(), *this, os, runparams);
2902 // latex or literate
2903 latexParagraphs(*this, text(), os, texrow, runparams);
2908 ErrorList & Buffer::errorList(string const & type) const
2910 static ErrorList emptyErrorList;
2911 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2912 if (I == d->errorLists.end())
2913 return emptyErrorList;
2919 void Buffer::updateTocItem(std::string const & type,
2920 DocIterator const & dit) const
2923 gui_->updateTocItem(type, dit);
2927 void Buffer::structureChanged() const
2930 gui_->structureChanged();
2934 void Buffer::errors(string const & err, bool from_master) const
2937 gui_->errors(err, from_master);
2941 void Buffer::message(docstring const & msg) const
2948 void Buffer::setBusy(bool on) const
2955 void Buffer::setReadOnly(bool on) const
2958 d->wa_->setReadOnly(on);
2962 void Buffer::updateTitles() const
2965 d->wa_->updateTitles();
2969 void Buffer::resetAutosaveTimers() const
2972 gui_->resetAutosaveTimers();
2976 bool Buffer::hasGuiDelegate() const
2982 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2991 class AutoSaveBuffer : public ForkedProcess {
2994 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2995 : buffer_(buffer), fname_(fname) {}
2997 virtual boost::shared_ptr<ForkedProcess> clone() const
2999 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3004 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3005 from_utf8(fname_.absFilename())));
3006 return run(DontWait);
3010 virtual int generateChild();
3012 Buffer const & buffer_;
3017 int AutoSaveBuffer::generateChild()
3019 #if defined(__APPLE__)
3020 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3021 * We should use something else like threads.
3023 * Since I do not know how to determine at run time what is the OS X
3024 * version, I just disable forking altogether for now (JMarc)
3026 pid_t const pid = -1;
3028 // tmp_ret will be located (usually) in /tmp
3029 // will that be a problem?
3030 // Note that this calls ForkedCalls::fork(), so it's
3031 // ok cross-platform.
3032 pid_t const pid = fork();
3033 // If you want to debug the autosave
3034 // you should set pid to -1, and comment out the fork.
3035 if (pid != 0 && pid != -1)
3039 // pid = -1 signifies that lyx was unable
3040 // to fork. But we will do the save
3042 bool failed = false;
3043 FileName const tmp_ret = FileName::tempName("lyxauto");
3044 if (!tmp_ret.empty()) {
3045 buffer_.writeFile(tmp_ret);
3046 // assume successful write of tmp_ret
3047 if (!tmp_ret.moveTo(fname_))
3053 // failed to write/rename tmp_ret so try writing direct
3054 if (!buffer_.writeFile(fname_)) {
3055 // It is dangerous to do this in the child,
3056 // but safe in the parent, so...
3057 if (pid == -1) // emit message signal.
3058 buffer_.message(_("Autosave failed!"));
3062 if (pid == 0) // we are the child so...
3071 FileName Buffer::getAutosaveFilename() const
3073 // if the document is unnamed try to save in the backup dir, else
3074 // in the default document path, and as a last try in the filePath,
3075 // which will most often be the temporary directory
3078 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3079 : lyxrc.backupdir_path;
3080 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3083 string const fname = "#" + d->filename.onlyFileName() + "#";
3084 return makeAbsPath(fname, fpath);
3088 void Buffer::removeAutosaveFile() const
3090 FileName const f = getAutosaveFilename();
3096 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3098 FileName const newauto = getAutosaveFilename();
3099 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3100 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3104 // Perfect target for a thread...
3105 void Buffer::autoSave() const
3107 if (isBakClean() || isReadonly()) {
3108 // We don't save now, but we'll try again later
3109 resetAutosaveTimers();
3113 // emit message signal.
3114 message(_("Autosaving current document..."));
3115 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3119 resetAutosaveTimers();
3123 string Buffer::bufferFormat() const
3125 string format = params().documentClass().outputFormat();
3126 if (format == "latex") {
3127 if (params().useXetex)
3129 if (params().encoding().package() == Encoding::japanese)
3136 string Buffer::getDefaultOutputFormat() const
3138 if (!params().defaultOutputFormat.empty()
3139 && params().defaultOutputFormat != "default")
3140 return params().defaultOutputFormat;
3141 typedef vector<Format const *> Formats;
3142 Formats formats = exportableFormats(true);
3145 || params().useXetex
3146 || params().encoding().package() == Encoding::japanese) {
3147 if (formats.empty())
3149 // return the first we find
3150 return formats.front()->name();
3152 return lyxrc.default_view_format;
3157 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3158 bool includeall, string & result_file) const
3160 string backend_format;
3161 OutputParams runparams(¶ms().encoding());
3162 runparams.flavor = OutputParams::LATEX;
3163 runparams.linelen = lyxrc.plaintext_linelen;
3164 runparams.includeall = includeall;
3165 vector<string> backs = backends();
3166 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3167 // Get shortest path to format
3168 Graph::EdgePath path;
3169 for (vector<string>::const_iterator it = backs.begin();
3170 it != backs.end(); ++it) {
3171 Graph::EdgePath p = theConverters().getPath(*it, format);
3172 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3173 backend_format = *it;
3178 if (!put_in_tempdir) {
3179 // Only show this alert if this is an export to a non-temporary
3180 // file (not for previewing).
3181 Alert::error(_("Couldn't export file"), bformat(
3182 _("No information for exporting the format %1$s."),
3183 formats.prettyName(format)));
3187 runparams.flavor = theConverters().getFlavor(path);
3190 backend_format = format;
3191 // FIXME: Don't hardcode format names here, but use a flag
3192 if (backend_format == "pdflatex")
3193 runparams.flavor = OutputParams::PDFLATEX;
3196 string filename = latexName(false);
3197 filename = addName(temppath(), filename);
3198 filename = changeExtension(filename,
3199 formats.extension(backend_format));
3202 updateMacroInstances();
3204 // Plain text backend
3205 if (backend_format == "text") {
3206 runparams.flavor = OutputParams::TEXT;
3207 writePlaintextFile(*this, FileName(filename), runparams);
3210 else if (backend_format == "xhtml") {
3211 runparams.flavor = OutputParams::HTML;
3212 makeLyXHTMLFile(FileName(filename), runparams);
3213 } else if (backend_format == "lyx")
3214 writeFile(FileName(filename));
3216 else if (isDocBook()) {
3217 runparams.nice = !put_in_tempdir;
3218 makeDocBookFile(FileName(filename), runparams);
3221 else if (backend_format == format) {
3222 runparams.nice = true;
3223 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3225 } else if (!lyxrc.tex_allows_spaces
3226 && contains(filePath(), ' ')) {
3227 Alert::error(_("File name error"),
3228 _("The directory path to the document cannot contain spaces."));
3231 runparams.nice = false;
3232 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3236 string const error_type = (format == "program")
3237 ? "Build" : bufferFormat();
3238 ErrorList & error_list = d->errorLists[error_type];
3239 string const ext = formats.extension(format);
3240 FileName const tmp_result_file(changeExtension(filename, ext));
3241 bool const success = theConverters().convert(this, FileName(filename),
3242 tmp_result_file, FileName(absFileName()), backend_format, format,
3244 // Emit the signal to show the error list.
3245 if (format != backend_format) {
3247 // also to the children, in case of master-buffer-view
3248 std::vector<Buffer *> clist = getChildren();
3249 for (vector<Buffer *>::const_iterator cit = clist.begin();
3250 cit != clist.end(); ++cit)
3251 (*cit)->errors(error_type, true);
3256 if (d->cloned_buffer_) {
3257 // Enable reverse dvi or pdf to work by copying back the texrow
3258 // object to the cloned buffer.
3259 // FIXME: There is a possibility of concurrent access to texrow
3260 // here from the main GUI thread that should be securized.
3261 d->cloned_buffer_->d->texrow = d->texrow;
3264 if (put_in_tempdir) {
3265 result_file = tmp_result_file.absFilename();
3269 result_file = changeExtension(exportFileName().absFilename(), ext);
3270 // We need to copy referenced files (e. g. included graphics
3271 // if format == "dvi") to the result dir.
3272 vector<ExportedFile> const files =
3273 runparams.exportdata->externalFiles(format);
3274 string const dest = onlyPath(result_file);
3275 CopyStatus status = SUCCESS;
3276 for (vector<ExportedFile>::const_iterator it = files.begin();
3277 it != files.end() && status != CANCEL; ++it) {
3278 string const fmt = formats.getFormatFromFile(it->sourceName);
3279 status = copyFile(fmt, it->sourceName,
3280 makeAbsPath(it->exportName, dest),
3281 it->exportName, status == FORCE);
3283 if (status == CANCEL) {
3284 message(_("Document export cancelled."));
3285 } else if (tmp_result_file.exists()) {
3286 // Finally copy the main file
3287 status = copyFile(format, tmp_result_file,
3288 FileName(result_file), result_file,
3290 message(bformat(_("Document exported as %1$s "
3292 formats.prettyName(format),
3293 makeDisplayPath(result_file)));
3295 // This must be a dummy converter like fax (bug 1888)
3296 message(bformat(_("Document exported as %1$s"),
3297 formats.prettyName(format)));
3304 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3305 bool includeall) const
3308 // (1) export with all included children (omit \includeonly)
3309 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3311 // (2) export with included children only
3312 return doExport(format, put_in_tempdir, false, result_file);
3316 bool Buffer::preview(string const & format, bool includeall) const
3319 // (1) export with all included children (omit \includeonly)
3320 if (includeall && !doExport(format, true, true))
3322 // (2) export with included children only
3323 if (!doExport(format, true, false, result_file))
3325 return formats.view(*this, FileName(result_file), format);
3329 bool Buffer::isExportable(string const & format) const
3331 vector<string> backs = backends();
3332 for (vector<string>::const_iterator it = backs.begin();
3333 it != backs.end(); ++it)
3334 if (theConverters().isReachable(*it, format))
3340 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3342 vector<string> const backs = backends();
3343 vector<Format const *> result =
3344 theConverters().getReachable(backs[0], only_viewable, true);
3345 for (vector<string>::const_iterator it = backs.begin() + 1;
3346 it != backs.end(); ++it) {
3347 vector<Format const *> r =
3348 theConverters().getReachable(*it, only_viewable, false);
3349 result.insert(result.end(), r.begin(), r.end());
3355 vector<string> Buffer::backends() const
3358 v.push_back(bufferFormat());
3359 // FIXME: Don't hardcode format names here, but use a flag
3360 if (v.back() == "latex")
3361 v.push_back("pdflatex");
3362 v.push_back("xhtml");
3363 v.push_back("text");
3369 bool Buffer::readFileHelper(FileName const & s)
3371 // File information about normal file
3373 docstring const file = makeDisplayPath(s.absFilename(), 50);
3374 docstring text = bformat(_("The specified document\n%1$s"
3375 "\ncould not be read."), file);
3376 Alert::error(_("Could not read document"), text);
3380 // Check if emergency save file exists and is newer.
3381 FileName const e(s.absFilename() + ".emergency");
3383 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3384 docstring const file = makeDisplayPath(s.absFilename(), 20);
3385 docstring const text =
3386 bformat(_("An emergency save of the document "
3388 "Recover emergency save?"), file);
3389 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3390 _("&Recover"), _("&Load Original"),
3394 // the file is not saved if we load the emergency file.
3399 if ((res = readFile(e)) == success)
3400 str = _("Document was successfully recovered.");
3402 str = _("Document was NOT successfully recovered.");
3403 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3404 from_utf8(e.absFilename()));
3406 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3407 _("&Remove"), _("&Keep it"))) {
3410 Alert::warning(_("Emergency file deleted"),
3411 _("Do not forget to save your file now!"), true);
3416 if (!Alert::prompt(_("Delete emergency file?"),
3417 _("Remove emergency file now?"), 1, 1,
3418 _("&Remove"), _("&Keep it")))
3426 // Now check if autosave file is newer.
3427 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3429 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3430 docstring const file = makeDisplayPath(s.absFilename(), 20);
3431 docstring const text =
3432 bformat(_("The backup of the document "
3433 "%1$s is newer.\n\nLoad the "
3434 "backup instead?"), file);
3435 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3436 _("&Load backup"), _("Load &original"),
3440 // the file is not saved if we load the autosave file.
3444 // Here we delete the autosave
3455 bool Buffer::loadLyXFile(FileName const & s)
3457 // If the file is not readable, we try to
3458 // retrieve the file from version control.
3459 if (!s.isReadableFile()
3460 && !LyXVC::file_not_found_hook(s))
3463 if (s.isReadableFile()
3464 && readFileHelper(s)) {
3465 lyxvc().file_found_hook(s);
3466 setReadonly(!s.isWritable());
3473 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3475 TeXErrors::Errors::const_iterator cit = terr.begin();
3476 TeXErrors::Errors::const_iterator end = terr.end();
3478 for (; cit != end; ++cit) {
3481 int errorRow = cit->error_in_line;
3482 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3488 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3489 } while (found && id_start == id_end && pos_start == pos_end);
3491 errorList.push_back(ErrorItem(cit->error_desc,
3492 cit->error_text, id_start, pos_start, pos_end));
3497 void Buffer::setBuffersForInsets() const
3499 inset().setBuffer(const_cast<Buffer &>(*this));
3503 void Buffer::updateLabels(UpdateScope scope, UpdateType utype) const
3505 // Use the master text class also for child documents
3506 Buffer const * const master = masterBuffer();
3507 DocumentClass const & textclass = master->params().documentClass();
3509 // do this only if we are the top-level Buffer
3510 if (scope != UpdateMaster || master == this)
3511 checkBibInfoCache();
3513 // keep the buffers to be children in this set. If the call from the
3514 // master comes back we can see which of them were actually seen (i.e.
3515 // via an InsetInclude). The remaining ones in the set need still be updated.
3516 static std::set<Buffer const *> bufToUpdate;
3517 if (scope == UpdateMaster) {
3518 // If this is a child document start with the master
3519 if (master != this) {
3520 bufToUpdate.insert(this);
3521 master->updateLabels(UpdateMaster, utype);
3522 // Do this here in case the master has no gui associated with it. Then,
3523 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3527 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3528 if (bufToUpdate.find(this) == bufToUpdate.end())
3532 // start over the counters in the master
3533 textclass.counters().reset();
3536 // update will be done below for this buffer
3537 bufToUpdate.erase(this);
3539 // update all caches
3540 clearReferenceCache();
3543 Buffer & cbuf = const_cast<Buffer &>(*this);
3545 LASSERT(!text().paragraphs().empty(), /**/);
3548 ParIterator parit = cbuf.par_iterator_begin();
3549 updateLabels(parit, utype);
3552 // TocBackend update will be done later.
3555 cbuf.tocBackend().update();
3556 if (scope == UpdateMaster)
3557 cbuf.structureChanged();
3561 static depth_type getDepth(DocIterator const & it)
3563 depth_type depth = 0;
3564 for (size_t i = 0 ; i < it.depth() ; ++i)
3565 if (!it[i].inset().inMathed())
3566 depth += it[i].paragraph().getDepth() + 1;
3567 // remove 1 since the outer inset does not count
3571 static depth_type getItemDepth(ParIterator const & it)
3573 Paragraph const & par = *it;
3574 LabelType const labeltype = par.layout().labeltype;
3576 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3579 // this will hold the lowest depth encountered up to now.
3580 depth_type min_depth = getDepth(it);
3581 ParIterator prev_it = it;
3584 --prev_it.top().pit();
3586 // start of nested inset: go to outer par
3588 if (prev_it.empty()) {
3589 // start of document: nothing to do
3594 // We search for the first paragraph with same label
3595 // that is not more deeply nested.
3596 Paragraph & prev_par = *prev_it;
3597 depth_type const prev_depth = getDepth(prev_it);
3598 if (labeltype == prev_par.layout().labeltype) {
3599 if (prev_depth < min_depth)
3600 return prev_par.itemdepth + 1;
3601 if (prev_depth == min_depth)
3602 return prev_par.itemdepth;
3604 min_depth = min(min_depth, prev_depth);
3605 // small optimization: if we are at depth 0, we won't
3606 // find anything else
3607 if (prev_depth == 0)
3613 static bool needEnumCounterReset(ParIterator const & it)
3615 Paragraph const & par = *it;
3616 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3617 depth_type const cur_depth = par.getDepth();
3618 ParIterator prev_it = it;
3619 while (prev_it.pit()) {
3620 --prev_it.top().pit();
3621 Paragraph const & prev_par = *prev_it;
3622 if (prev_par.getDepth() <= cur_depth)
3623 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3625 // start of nested inset: reset
3630 // set the label of a paragraph. This includes the counters.
3631 void Buffer::setLabel(ParIterator & it, UpdateType utype) const
3633 BufferParams const & bp = this->masterBuffer()->params();
3634 DocumentClass const & textclass = bp.documentClass();
3635 Paragraph & par = it.paragraph();
3636 Layout const & layout = par.layout();
3637 Counters & counters = textclass.counters();
3639 if (par.params().startOfAppendix()) {
3640 // FIXME: only the counter corresponding to toplevel
3641 // sectioning should be reset
3643 counters.appendix(true);
3645 par.params().appendix(counters.appendix());
3647 // Compute the item depth of the paragraph
3648 par.itemdepth = getItemDepth(it);
3650 if (layout.margintype == MARGIN_MANUAL
3651 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3652 if (par.params().labelWidthString().empty())
3653 par.params().labelWidthString(par.expandLabel(layout, bp));
3655 par.params().labelWidthString(docstring());
3658 switch(layout.labeltype) {
3660 if (layout.toclevel <= bp.secnumdepth
3661 && (layout.latextype != LATEX_ENVIRONMENT
3662 || it.text()->isFirstInSequence(it.pit()))) {
3663 counters.step(layout.counter, utype);
3664 par.params().labelString(
3665 par.expandLabel(layout, bp));
3667 par.params().labelString(docstring());
3670 case LABEL_ITEMIZE: {
3671 // At some point of time we should do something more
3672 // clever here, like:
3673 // par.params().labelString(
3674 // bp.user_defined_bullet(par.itemdepth).getText());
3675 // for now, use a simple hardcoded label
3676 docstring itemlabel;
3677 switch (par.itemdepth) {
3679 itemlabel = char_type(0x2022);
3682 itemlabel = char_type(0x2013);
3685 itemlabel = char_type(0x2217);
3688 itemlabel = char_type(0x2219); // or 0x00b7
3691 par.params().labelString(itemlabel);
3695 case LABEL_ENUMERATE: {
3696 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3698 switch (par.itemdepth) {
3707 enumcounter += "iv";
3710 // not a valid enumdepth...
3714 // Maybe we have to reset the enumeration counter.
3715 if (needEnumCounterReset(it))
3716 counters.reset(enumcounter);
3717 counters.step(enumcounter, utype);
3719 string const & lang = par.getParLanguage(bp)->code();
3720 par.params().labelString(counters.theCounter(enumcounter, lang));
3725 case LABEL_SENSITIVE: {
3726 string const & type = counters.current_float();
3727 docstring full_label;
3729 full_label = this->B_("Senseless!!! ");
3731 docstring name = this->B_(textclass.floats().getType(type).name());
3732 if (counters.hasCounter(from_utf8(type))) {
3733 string const & lang = par.getParLanguage(bp)->code();
3734 counters.step(from_utf8(type), utype);
3735 full_label = bformat(from_ascii("%1$s %2$s:"),
3737 counters.theCounter(from_utf8(type), lang));
3739 full_label = bformat(from_ascii("%1$s #:"), name);
3741 par.params().labelString(full_label);
3745 case LABEL_NO_LABEL:
3746 par.params().labelString(docstring());
3750 case LABEL_TOP_ENVIRONMENT:
3751 case LABEL_CENTERED_TOP_ENVIRONMENT:
3754 par.params().labelString(par.expandLabel(layout, bp));
3760 void Buffer::updateLabels(ParIterator & parit, UpdateType utype) const
3762 LASSERT(parit.pit() == 0, /**/);
3764 // set the position of the text in the buffer to be able
3765 // to resolve macros in it. This has nothing to do with
3766 // labels, but by putting it here we avoid implementing
3767 // a whole bunch of traversal routines just for this call.
3768 parit.text()->setMacrocontextPosition(parit);
3770 depth_type maxdepth = 0;
3771 pit_type const lastpit = parit.lastpit();
3772 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3773 // reduce depth if necessary
3774 parit->params().depth(min(parit->params().depth(), maxdepth));
3775 maxdepth = parit->getMaxDepthAfter();
3777 if (utype == OutputUpdate) {
3778 // track the active counters
3779 // we have to do this for the master buffer, since the local
3780 // buffer isn't tracking anything.
3781 masterBuffer()->params().documentClass().counters().
3782 setActiveLayout(parit->layout());
3785 // set the counter for this paragraph
3786 setLabel(parit, utype);
3789 InsetList::const_iterator iit = parit->insetList().begin();
3790 InsetList::const_iterator end = parit->insetList().end();
3791 for (; iit != end; ++iit) {
3792 parit.pos() = iit->pos;
3793 iit->inset->updateLabels(parit, utype);
3799 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3800 WordLangTuple & word_lang, docstring_list & suggestions) const
3804 suggestions.clear();
3805 word_lang = WordLangTuple();
3806 // OK, we start from here.
3807 DocIterator const end = doc_iterator_end(this);
3808 for (; from != end; from.forwardPos()) {
3809 // We are only interested in text so remove the math CursorSlice.
3810 while (from.inMathed()) {
3814 // If from is at the end of the document (which is possible
3815 // when leaving the mathed) LyX will crash later.
3819 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3824 // Do not increase progress when from == to, otherwise the word
3825 // count will be wrong.
3835 bool Buffer::reload()
3838 // e.g., read-only status could have changed due to version control
3839 d->filename.refresh();
3840 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3842 bool const success = loadLyXFile(d->filename);
3847 message(bformat(_("Document %1$s reloaded."), disp_fn));
3849 message(bformat(_("Could not reload document %1$s."), disp_fn));