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 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263 /// This one is useful for preview detached in a thread.
264 Buffer const * cloned_buffer_;
267 /// So we can force access via the accessors.
268 mutable Buffer const * parent_buffer;
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
277 // We are in our own directory. Why bother to mangle name?
278 // In fact I wrote this code to circumvent a problematic behaviour
279 // (bug?) of EMX mkstemp().
280 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281 convert<string>(count++));
283 if (!tmpfl.createDirectory(0777)) {
284 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286 from_utf8(tmpfl.absFilename())));
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293 Buffer const * cloned_buffer)
294 : lyx_clean(true), bak_clean(true), unnamed(false),
295 read_only(readonly_), filename(file), file_fully_loaded(false),
296 toc_backend(&parent), macro_lock(false), timestamp_(0),
297 checksum_(0), wa_(0), undo_(parent), bibinfo_cache_valid_(false),
298 cloned_buffer_(cloned_buffer), parent_buffer(0)
300 if (!cloned_buffer_) {
301 temppath = createBufferTmpDir();
302 lyxvc.setBuffer(&parent);
304 wa_ = new frontend::WorkAreaManager;
307 temppath = cloned_buffer_->d->temppath;
308 file_fully_loaded = true;
309 params = cloned_buffer_->d->params;
310 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
311 bibinfo_ = cloned_buffer_->d->bibinfo_;
312 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
313 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
317 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
318 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
320 LYXERR(Debug::INFO, "Buffer::Buffer()");
322 d->inset = new InsetText(*cloned_buffer->d->inset);
323 d->inset->setBuffer(*this);
324 // FIXME: optimize this loop somewhat, maybe by creating a new
325 // general recursive Inset::setId().
326 DocIterator it = doc_iterator_begin(this);
327 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
328 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
329 it.paragraph().setId(cloned_it.paragraph().id());
331 d->inset = new InsetText(this);
332 d->inset->setAutoBreakRows(true);
333 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
339 LYXERR(Debug::INFO, "Buffer::~Buffer()");
340 // here the buffer should take care that it is
341 // saved properly, before it goes into the void.
343 // GuiView already destroyed
347 // No need to do additional cleanups for internal buffer.
352 // loop over children
353 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
354 Impl::BufferPositionMap::iterator end = d->children_positions.end();
355 for (; it != end; ++it) {
356 Buffer * child = const_cast<Buffer *>(it->first);
357 if (d->cloned_buffer_)
359 // The child buffer might have been closed already.
360 else if (theBufferList().isLoaded(child))
361 theBufferList().releaseChild(this, child);
365 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
366 msg += emergencyWrite();
367 Alert::warning(_("Attempting to close changed document!"), msg);
370 // clear references to children in macro tables
371 d->children_positions.clear();
372 d->position_to_children.clear();
374 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
375 Alert::warning(_("Could not remove temporary directory"),
376 bformat(_("Could not remove the temporary directory %1$s"),
377 from_utf8(d->temppath.absFilename())));
380 // Remove any previewed LaTeX snippets associated with this buffer.
381 thePreviews().removeLoader(*this);
387 Buffer * Buffer::clone() const
389 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
390 buffer_clone->d->macro_lock = true;
391 buffer_clone->d->children_positions.clear();
392 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
393 // math macro caches need to be rethought and simplified.
394 // I am not sure wether we should handle Buffer cloning here or in BufferList.
395 // Right now BufferList knows nothing about buffer clones.
396 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
397 Impl::BufferPositionMap::iterator end = d->children_positions.end();
398 for (; it != end; ++it) {
399 DocIterator dit = it->second.clone(buffer_clone);
400 dit.setBuffer(buffer_clone);
401 Buffer * child = const_cast<Buffer *>(it->first);
402 Buffer * child_clone = child->clone();
403 Inset * inset = dit.nextInset();
404 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
405 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
406 inset_inc->setChildBuffer(child_clone);
407 child_clone->d->setParent(buffer_clone);
408 buffer_clone->setChild(dit, child_clone);
410 buffer_clone->d->macro_lock = false;
415 bool Buffer::isClone() const
417 return d->cloned_buffer_;
421 void Buffer::changed(bool update_metrics) const
424 d->wa_->redrawAll(update_metrics);
428 frontend::WorkAreaManager & Buffer::workAreaManager() const
430 LASSERT(d->wa_, /**/);
435 Text & Buffer::text() const
437 return d->inset->text();
441 Inset & Buffer::inset() const
447 BufferParams & Buffer::params()
453 BufferParams const & Buffer::params() const
459 ParagraphList & Buffer::paragraphs()
461 return text().paragraphs();
465 ParagraphList const & Buffer::paragraphs() const
467 return text().paragraphs();
471 LyXVC & Buffer::lyxvc()
477 LyXVC const & Buffer::lyxvc() const
483 string const Buffer::temppath() const
485 return d->temppath.absFilename();
489 TexRow & Buffer::texrow()
495 TexRow const & Buffer::texrow() const
501 TocBackend & Buffer::tocBackend() const
503 return d->toc_backend;
507 Undo & Buffer::undo()
513 void Buffer::setChild(DocIterator const & dit, Buffer * child)
515 d->children_positions[child] = dit;
519 string Buffer::latexName(bool const no_path) const
521 FileName latex_name =
522 makeLatexName(exportFileName());
523 return no_path ? latex_name.onlyFileName()
524 : latex_name.absFilename();
528 FileName Buffer::exportFileName() const
530 docstring const branch_suffix =
531 params().branchlist().getFilenameSuffix();
532 if (branch_suffix.empty())
535 string const name = fileName().onlyFileNameWithoutExt()
536 + to_utf8(branch_suffix);
537 FileName res(fileName().onlyPath().absFilename() + "/" + name);
538 res.changeExtension(fileName().extension());
544 string Buffer::logName(LogType * type) const
546 string const filename = latexName(false);
548 if (filename.empty()) {
554 string const path = temppath();
556 FileName const fname(addName(temppath(),
557 onlyFilename(changeExtension(filename,
560 // FIXME: how do we know this is the name of the build log?
561 FileName const bname(
562 addName(path, onlyFilename(
563 changeExtension(filename,
564 formats.extension(bufferFormat()) + ".out"))));
566 // Also consider the master buffer log file
567 FileName masterfname = fname;
569 if (masterBuffer() != this) {
570 string const mlogfile = masterBuffer()->logName(&mtype);
571 masterfname = FileName(mlogfile);
574 // If no Latex log or Build log is newer, show Build log
575 if (bname.exists() &&
576 ((!fname.exists() && !masterfname.exists())
577 || (fname.lastModified() < bname.lastModified()
578 && masterfname.lastModified() < bname.lastModified()))) {
579 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
582 return bname.absFilename();
583 // If we have a newer master file log or only a master log, show this
584 } else if (fname != masterfname
585 && (!fname.exists() && (masterfname.exists()
586 || fname.lastModified() < masterfname.lastModified()))) {
587 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
590 return masterfname.absFilename();
592 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
595 return fname.absFilename();
599 void Buffer::setReadonly(bool const flag)
601 if (d->read_only != flag) {
608 void Buffer::setFileName(string const & newfile)
610 d->filename = makeAbsPath(newfile);
611 setReadonly(d->filename.isReadOnly());
616 int Buffer::readHeader(Lexer & lex)
618 int unknown_tokens = 0;
620 int begin_header_line = -1;
622 // Initialize parameters that may be/go lacking in header:
623 params().branchlist().clear();
624 params().preamble.erase();
625 params().options.erase();
626 params().master.erase();
627 params().float_placement.erase();
628 params().paperwidth.erase();
629 params().paperheight.erase();
630 params().leftmargin.erase();
631 params().rightmargin.erase();
632 params().topmargin.erase();
633 params().bottommargin.erase();
634 params().headheight.erase();
635 params().headsep.erase();
636 params().footskip.erase();
637 params().columnsep.erase();
638 params().fontsCJK.erase();
639 params().listings_params.clear();
640 params().clearLayoutModules();
641 params().clearRemovedModules();
642 params().clearIncludedChildren();
643 params().pdfoptions().clear();
644 params().indiceslist().clear();
645 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
647 for (int i = 0; i < 4; ++i) {
648 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
649 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
652 ErrorList & errorList = d->errorLists["Parse"];
661 if (token == "\\end_header")
665 if (token == "\\begin_header") {
666 begin_header_line = line;
670 LYXERR(Debug::PARSER, "Handling document header token: `"
673 string unknown = params().readToken(lex, token, d->filename.onlyPath());
674 if (!unknown.empty()) {
675 if (unknown[0] != '\\' && token == "\\textclass") {
676 Alert::warning(_("Unknown document class"),
677 bformat(_("Using the default document class, because the "
678 "class %1$s is unknown."), from_utf8(unknown)));
681 docstring const s = bformat(_("Unknown token: "
685 errorList.push_back(ErrorItem(_("Document header error"),
690 if (begin_header_line) {
691 docstring const s = _("\\begin_header is missing");
692 errorList.push_back(ErrorItem(_("Document header error"),
696 params().makeDocumentClass();
698 return unknown_tokens;
703 // changed to be public and have one parameter
704 // Returns true if "\end_document" is not read (Asger)
705 bool Buffer::readDocument(Lexer & lex)
707 ErrorList & errorList = d->errorLists["Parse"];
710 if (!lex.checkFor("\\begin_document")) {
711 docstring const s = _("\\begin_document is missing");
712 errorList.push_back(ErrorItem(_("Document header error"),
716 // we are reading in a brand new document
717 LASSERT(paragraphs().empty(), /**/);
721 if (params().outputChanges) {
722 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
723 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
724 LaTeXFeatures::isAvailable("xcolor");
726 if (!dvipost && !xcolorulem) {
727 Alert::warning(_("Changes not shown in LaTeX output"),
728 _("Changes will not be highlighted in LaTeX output, "
729 "because neither dvipost nor xcolor/ulem are installed.\n"
730 "Please install these packages or redefine "
731 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
732 } else if (!xcolorulem) {
733 Alert::warning(_("Changes not shown in LaTeX output"),
734 _("Changes will not be highlighted in LaTeX output "
735 "when using pdflatex, because xcolor and ulem are not installed.\n"
736 "Please install both packages or redefine "
737 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
741 if (!params().master.empty()) {
742 FileName const master_file = makeAbsPath(params().master,
743 onlyPath(absFileName()));
744 if (isLyXFilename(master_file.absFilename())) {
746 checkAndLoadLyXFile(master_file, true);
748 // necessary e.g. after a reload
749 // to re-register the child (bug 5873)
750 // FIXME: clean up updateMacros (here, only
751 // child registering is needed).
752 master->updateMacros();
753 // set master as master buffer, but only
754 // if we are a real child
755 if (master->isChild(this))
757 // if the master is not fully loaded
758 // it is probably just loading this
759 // child. No warning needed then.
760 else if (master->isFullyLoaded())
761 LYXERR0("The master '"
763 << "' assigned to this document ("
765 << ") does not include "
766 "this document. Ignoring the master assignment.");
771 // assure we have a default index
772 params().indiceslist().addDefault(B_("Index"));
775 bool const res = text().read(lex, errorList, d->inset);
779 updateMacroInstances();
784 bool Buffer::readString(string const & s)
786 params().compressed = false;
788 // remove dummy empty par
789 paragraphs().clear();
793 FileName const name = FileName::tempName("Buffer_readString");
794 switch (readFile(lex, name, true)) {
798 // We need to call lyx2lyx, so write the input to a file
799 ofstream os(name.toFilesystemEncoding().c_str());
802 return readFile(name);
812 bool Buffer::readFile(FileName const & filename)
814 FileName fname(filename);
816 params().compressed = fname.isZippedFile();
818 // remove dummy empty par
819 paragraphs().clear();
822 if (readFile(lex, fname) != success)
829 bool Buffer::isFullyLoaded() const
831 return d->file_fully_loaded;
835 void Buffer::setFullyLoaded(bool value)
837 d->file_fully_loaded = value;
841 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
844 LASSERT(!filename.empty(), /**/);
846 // the first (non-comment) token _must_ be...
847 if (!lex.checkFor("\\lyxformat")) {
848 Alert::error(_("Document format failure"),
849 bformat(_("%1$s is not a readable LyX document."),
850 from_utf8(filename.absFilename())));
856 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
857 // if present remove ".," from string.
858 size_t dot = tmp_format.find_first_of(".,");
859 //lyxerr << " dot found at " << dot << endl;
860 if (dot != string::npos)
861 tmp_format.erase(dot, 1);
862 int const file_format = convert<int>(tmp_format);
863 //lyxerr << "format: " << file_format << endl;
865 // save timestamp and checksum of the original disk file, making sure
866 // to not overwrite them with those of the file created in the tempdir
867 // when it has to be converted to the current format.
869 // Save the timestamp and checksum of disk file. If filename is an
870 // emergency file, save the timestamp and checksum of the original lyx file
871 // because isExternallyModified will check for this file. (BUG4193)
872 string diskfile = filename.absFilename();
873 if (suffixIs(diskfile, ".emergency"))
874 diskfile = diskfile.substr(0, diskfile.size() - 10);
875 saveCheckSum(FileName(diskfile));
878 if (file_format != LYX_FORMAT) {
881 // lyx2lyx would fail
884 FileName const tmpfile = FileName::tempName("Buffer_readFile");
885 if (tmpfile.empty()) {
886 Alert::error(_("Conversion failed"),
887 bformat(_("%1$s is from a different"
888 " version of LyX, but a temporary"
889 " file for converting it could"
891 from_utf8(filename.absFilename())));
894 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
895 if (lyx2lyx.empty()) {
896 Alert::error(_("Conversion script not found"),
897 bformat(_("%1$s is from a different"
898 " version of LyX, but the"
899 " conversion script lyx2lyx"
900 " could not be found."),
901 from_utf8(filename.absFilename())));
904 ostringstream command;
905 command << os::python()
906 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
907 << " -t " << convert<string>(LYX_FORMAT)
908 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
909 << ' ' << quoteName(filename.toFilesystemEncoding());
910 string const command_str = command.str();
912 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
914 cmd_ret const ret = runCommand(command_str);
915 if (ret.first != 0) {
916 if (file_format < LYX_FORMAT)
917 Alert::error(_("Conversion script failed"),
918 bformat(_("%1$s is from an older version"
919 " of LyX, but the lyx2lyx script"
920 " failed to convert it."),
921 from_utf8(filename.absFilename())));
923 Alert::error(_("Conversion script failed"),
924 bformat(_("%1$s is from a newer version"
925 " of LyX and cannot be converted by the"
927 from_utf8(filename.absFilename())));
930 bool const ret = readFile(tmpfile);
931 // Do stuff with tmpfile name and buffer name here.
932 return ret ? success : failure;
937 if (readDocument(lex)) {
938 Alert::error(_("Document format failure"),
939 bformat(_("%1$s ended unexpectedly, which means"
940 " that it is probably corrupted."),
941 from_utf8(filename.absFilename())));
944 d->file_fully_loaded = true;
949 // Should probably be moved to somewhere else: BufferView? LyXView?
950 bool Buffer::save() const
952 // We don't need autosaves in the immediate future. (Asger)
953 resetAutosaveTimers();
955 string const encodedFilename = d->filename.toFilesystemEncoding();
958 bool madeBackup = false;
960 // make a backup if the file already exists
961 if (lyxrc.make_backup && fileName().exists()) {
962 backupName = FileName(absFileName() + '~');
963 if (!lyxrc.backupdir_path.empty()) {
964 string const mangledName =
965 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
966 backupName = FileName(addName(lyxrc.backupdir_path,
969 if (fileName().copyTo(backupName)) {
972 Alert::error(_("Backup failure"),
973 bformat(_("Cannot create backup file %1$s.\n"
974 "Please check whether the directory exists and is writeable."),
975 from_utf8(backupName.absFilename())));
976 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
980 // ask if the disk file has been externally modified (use checksum method)
981 if (fileName().exists() && isExternallyModified(checksum_method)) {
982 docstring const file = makeDisplayPath(absFileName(), 20);
983 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
984 "you want to overwrite this file?"), file);
985 int const ret = Alert::prompt(_("Overwrite modified file?"),
986 text, 1, 1, _("&Overwrite"), _("&Cancel"));
991 if (writeFile(d->filename)) {
995 // Saving failed, so backup is not backup
997 backupName.moveTo(d->filename);
1003 bool Buffer::writeFile(FileName const & fname) const
1005 if (d->read_only && fname == d->filename)
1008 bool retval = false;
1010 docstring const str = bformat(_("Saving document %1$s..."),
1011 makeDisplayPath(fname.absFilename()));
1014 if (params().compressed) {
1015 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1016 retval = ofs && write(ofs);
1018 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1019 retval = ofs && write(ofs);
1023 message(str + _(" could not write file!"));
1027 removeAutosaveFile();
1029 saveCheckSum(d->filename);
1030 message(str + _(" done."));
1036 docstring Buffer::emergencyWrite()
1038 // No need to save if the buffer has not changed.
1042 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1044 docstring user_message = bformat(
1045 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1047 // We try to save three places:
1048 // 1) Same place as document. Unless it is an unnamed doc.
1050 string s = absFileName();
1053 if (writeFile(FileName(s))) {
1055 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1056 return user_message;
1058 user_message += _(" Save failed! Trying again...\n");
1062 // 2) In HOME directory.
1063 string s = addName(package().home_dir().absFilename(), absFileName());
1065 lyxerr << ' ' << s << endl;
1066 if (writeFile(FileName(s))) {
1068 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1069 return user_message;
1072 user_message += _(" Save failed! Trying yet again...\n");
1074 // 3) In "/tmp" directory.
1075 // MakeAbsPath to prepend the current
1076 // drive letter on OS/2
1077 s = addName(package().temp_dir().absFilename(), absFileName());
1079 lyxerr << ' ' << s << endl;
1080 if (writeFile(FileName(s))) {
1082 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1083 return user_message;
1086 user_message += _(" Save failed! Bummer. Document is lost.");
1089 return user_message;
1093 bool Buffer::write(ostream & ofs) const
1096 // Use the standard "C" locale for file output.
1097 ofs.imbue(locale::classic());
1100 // The top of the file should not be written by params().
1102 // write out a comment in the top of the file
1103 ofs << "#LyX " << lyx_version
1104 << " created this file. For more info see http://www.lyx.org/\n"
1105 << "\\lyxformat " << LYX_FORMAT << "\n"
1106 << "\\begin_document\n";
1108 /// For each author, set 'used' to true if there is a change
1109 /// by this author in the document; otherwise set it to 'false'.
1110 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1111 AuthorList::Authors::const_iterator a_end = params().authors().end();
1112 for (; a_it != a_end; ++a_it)
1113 a_it->setUsed(false);
1115 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1116 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1117 for ( ; it != end; ++it)
1118 it->checkAuthors(params().authors());
1120 // now write out the buffer parameters.
1121 ofs << "\\begin_header\n";
1122 params().writeFile(ofs);
1123 ofs << "\\end_header\n";
1126 ofs << "\n\\begin_body\n";
1128 ofs << "\n\\end_body\n";
1130 // Write marker that shows file is complete
1131 ofs << "\\end_document" << endl;
1133 // Shouldn't really be needed....
1136 // how to check if close went ok?
1137 // Following is an attempt... (BE 20001011)
1139 // good() returns false if any error occured, including some
1140 // formatting error.
1141 // bad() returns true if something bad happened in the buffer,
1142 // which should include file system full errors.
1147 lyxerr << "File was not closed properly." << endl;
1154 bool Buffer::makeLaTeXFile(FileName const & fname,
1155 string const & original_path,
1156 OutputParams const & runparams_in,
1157 bool output_preamble, bool output_body) const
1159 OutputParams runparams = runparams_in;
1160 if (params().useXetex)
1161 runparams.flavor = OutputParams::XETEX;
1163 string const encoding = runparams.encoding->iconvName();
1164 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1167 try { ofs.reset(encoding); }
1168 catch (iconv_codecvt_facet_exception & e) {
1169 lyxerr << "Caught iconv exception: " << e.what() << endl;
1170 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1171 "verify that the support software for your encoding (%1$s) is "
1172 "properly installed"), from_ascii(encoding)));
1175 if (!openFileWrite(ofs, fname))
1178 //TexStream ts(ofs.rdbuf(), &texrow());
1179 ErrorList & errorList = d->errorLists["Export"];
1181 bool failed_export = false;
1184 writeLaTeXSource(ofs, original_path,
1185 runparams, output_preamble, output_body);
1187 catch (EncodingException & e) {
1188 odocstringstream ods;
1189 ods.put(e.failed_char);
1191 oss << "0x" << hex << e.failed_char << dec;
1192 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1193 " (code point %2$s)"),
1194 ods.str(), from_utf8(oss.str()));
1195 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1196 "representable in the chosen encoding.\n"
1197 "Changing the document encoding to utf8 could help."),
1198 e.par_id, e.pos, e.pos + 1));
1199 failed_export = true;
1201 catch (iconv_codecvt_facet_exception & e) {
1202 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1203 _(e.what()), -1, 0, 0));
1204 failed_export = true;
1206 catch (exception const & e) {
1207 errorList.push_back(ErrorItem(_("conversion failed"),
1208 _(e.what()), -1, 0, 0));
1209 failed_export = true;
1212 lyxerr << "Caught some really weird exception..." << endl;
1218 failed_export = true;
1219 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1223 return !failed_export;
1227 void Buffer::writeLaTeXSource(odocstream & os,
1228 string const & original_path,
1229 OutputParams const & runparams_in,
1230 bool const output_preamble, bool const output_body) const
1232 // The child documents, if any, shall be already loaded at this point.
1234 OutputParams runparams = runparams_in;
1236 // Classify the unicode characters appearing in math insets
1237 Encodings::initUnicodeMath(*this);
1239 // validate the buffer.
1240 LYXERR(Debug::LATEX, " Validating buffer...");
1241 LaTeXFeatures features(*this, params(), runparams);
1243 LYXERR(Debug::LATEX, " Buffer validation done.");
1245 // The starting paragraph of the coming rows is the
1246 // first paragraph of the document. (Asger)
1247 if (output_preamble && runparams.nice) {
1248 os << "%% LyX " << lyx_version << " created this file. "
1249 "For more info, see http://www.lyx.org/.\n"
1250 "%% Do not edit unless you really know what "
1252 d->texrow.newline();
1253 d->texrow.newline();
1255 LYXERR(Debug::INFO, "lyx document header finished");
1257 // Don't move this behind the parent_buffer=0 code below,
1258 // because then the macros will not get the right "redefinition"
1259 // flag as they don't see the parent macros which are output before.
1262 // fold macros if possible, still with parent buffer as the
1263 // macros will be put in the prefix anyway.
1264 updateMacroInstances();
1266 // There are a few differences between nice LaTeX and usual files:
1267 // usual is \batchmode and has a
1268 // special input@path to allow the including of figures
1269 // with either \input or \includegraphics (what figinsets do).
1270 // input@path is set when the actual parameter
1271 // original_path is set. This is done for usual tex-file, but not
1272 // for nice-latex-file. (Matthias 250696)
1273 // Note that input@path is only needed for something the user does
1274 // in the preamble, included .tex files or ERT, files included by
1275 // LyX work without it.
1276 if (output_preamble) {
1277 if (!runparams.nice) {
1278 // code for usual, NOT nice-latex-file
1279 os << "\\batchmode\n"; // changed
1280 // from \nonstopmode
1281 d->texrow.newline();
1283 if (!original_path.empty()) {
1285 // We don't know the encoding of inputpath
1286 docstring const inputpath = from_utf8(latex_path(original_path));
1287 os << "\\makeatletter\n"
1288 << "\\def\\input@path{{"
1289 << inputpath << "/}}\n"
1290 << "\\makeatother\n";
1291 d->texrow.newline();
1292 d->texrow.newline();
1293 d->texrow.newline();
1296 // get parent macros (if this buffer has a parent) which will be
1297 // written at the document begin further down.
1298 MacroSet parentMacros;
1299 listParentMacros(parentMacros, features);
1301 // Write the preamble
1302 runparams.use_babel = params().writeLaTeX(os, features,
1304 d->filename.onlyPath());
1306 runparams.use_japanese = features.isRequired("japanese");
1312 os << "\\begin{document}\n";
1313 d->texrow.newline();
1315 // output the parent macros
1316 MacroSet::iterator it = parentMacros.begin();
1317 MacroSet::iterator end = parentMacros.end();
1318 for (; it != end; ++it)
1319 (*it)->write(os, true);
1320 } // output_preamble
1322 d->texrow.start(paragraphs().begin()->id(), 0);
1324 LYXERR(Debug::INFO, "preamble finished, now the body.");
1326 // if we are doing a real file with body, even if this is the
1327 // child of some other buffer, let's cut the link here.
1328 // This happens for example if only a child document is printed.
1329 Buffer const * save_parent = 0;
1330 if (output_preamble) {
1331 save_parent = d->parent();
1336 latexParagraphs(*this, text(), os, d->texrow, runparams);
1338 // Restore the parenthood if needed
1339 if (output_preamble)
1340 d->setParent(save_parent);
1342 // add this just in case after all the paragraphs
1344 d->texrow.newline();
1346 if (output_preamble) {
1347 os << "\\end{document}\n";
1348 d->texrow.newline();
1349 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1351 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1353 runparams_in.encoding = runparams.encoding;
1355 // Just to be sure. (Asger)
1356 d->texrow.newline();
1358 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1359 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1363 bool Buffer::isLatex() const
1365 return params().documentClass().outputType() == LATEX;
1369 bool Buffer::isLiterate() const
1371 return params().documentClass().outputType() == LITERATE;
1375 bool Buffer::isDocBook() const
1377 return params().documentClass().outputType() == DOCBOOK;
1381 void Buffer::makeDocBookFile(FileName const & fname,
1382 OutputParams const & runparams,
1383 bool const body_only) const
1385 LYXERR(Debug::LATEX, "makeDocBookFile...");
1388 if (!openFileWrite(ofs, fname))
1391 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1395 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1399 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1400 OutputParams const & runparams,
1401 bool const only_body) const
1403 LaTeXFeatures features(*this, params(), runparams);
1408 DocumentClass const & tclass = params().documentClass();
1409 string const top_element = tclass.latexname();
1412 if (runparams.flavor == OutputParams::XML)
1413 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1416 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1419 if (! tclass.class_header().empty())
1420 os << from_ascii(tclass.class_header());
1421 else if (runparams.flavor == OutputParams::XML)
1422 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1423 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1425 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1427 docstring preamble = from_utf8(params().preamble);
1428 if (runparams.flavor != OutputParams::XML ) {
1429 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1430 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1431 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1432 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1435 string const name = runparams.nice
1436 ? changeExtension(absFileName(), ".sgml") : fname;
1437 preamble += features.getIncludedFiles(name);
1438 preamble += features.getLyXSGMLEntities();
1440 if (!preamble.empty()) {
1441 os << "\n [ " << preamble << " ]";
1446 string top = top_element;
1448 if (runparams.flavor == OutputParams::XML)
1449 top += params().language->code();
1451 top += params().language->code().substr(0, 2);
1454 if (!params().options.empty()) {
1456 top += params().options;
1459 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1460 << " file was created by LyX " << lyx_version
1461 << "\n See http://www.lyx.org/ for more information -->\n";
1463 params().documentClass().counters().reset();
1467 sgml::openTag(os, top);
1469 docbookParagraphs(text(), *this, os, runparams);
1470 sgml::closeTag(os, top_element);
1474 void Buffer::makeLyXHTMLFile(FileName const & fname,
1475 OutputParams const & runparams,
1476 bool const body_only) const
1478 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1481 if (!openFileWrite(ofs, fname))
1484 writeLyXHTMLSource(ofs, runparams, body_only);
1488 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1492 void Buffer::writeLyXHTMLSource(odocstream & os,
1493 OutputParams const & runparams,
1494 bool const only_body) const
1496 LaTeXFeatures features(*this, params(), runparams);
1498 updateLabels(UpdateMaster, true);
1499 checkBibInfoCache();
1500 d->bibinfo_.makeCitationLabels(*this);
1502 updateMacroInstances();
1505 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1506 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";
1507 // FIXME Language should be set properly.
1508 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1511 // FIXME Presumably need to set this right
1512 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1513 // FIXME Get this during validation? What about other meta-data?
1514 os << "<title>TBA</title>\n";
1516 os << "\n<!-- Text Class Preamble -->\n"
1517 << features.getTClassHTMLPreamble()
1518 << "\n<!-- Premable Snippets -->\n"
1519 << from_utf8(features.getPreambleSnippets());
1521 os << "\n<!-- Layout-provided Styles -->\n";
1522 docstring const styleinfo = features.getTClassHTMLStyles();
1523 if (!styleinfo.empty()) {
1524 os << "<style type='text/css'>\n"
1528 os << "</head>\n<body>\n";
1532 params().documentClass().counters().reset();
1533 xhtmlParagraphs(text(), *this, xs, runparams);
1535 os << "</body>\n</html>\n";
1539 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1540 // Other flags: -wall -v0 -x
1541 int Buffer::runChktex()
1545 // get LaTeX-Filename
1546 FileName const path(temppath());
1547 string const name = addName(path.absFilename(), latexName());
1548 string const org_path = filePath();
1550 PathChanger p(path); // path to LaTeX file
1551 message(_("Running chktex..."));
1553 // Generate the LaTeX file if neccessary
1554 OutputParams runparams(¶ms().encoding());
1555 runparams.flavor = OutputParams::LATEX;
1556 runparams.nice = false;
1557 makeLaTeXFile(FileName(name), org_path, runparams);
1560 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1561 int const res = chktex.run(terr); // run chktex
1564 Alert::error(_("chktex failure"),
1565 _("Could not run chktex successfully."));
1566 } else if (res > 0) {
1567 ErrorList & errlist = d->errorLists["ChkTeX"];
1569 bufferErrors(terr, errlist);
1580 void Buffer::validate(LaTeXFeatures & features) const
1582 params().validate(features);
1586 for_each(paragraphs().begin(), paragraphs().end(),
1587 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1589 if (lyxerr.debugging(Debug::LATEX)) {
1590 features.showStruct();
1595 void Buffer::getLabelList(vector<docstring> & list) const
1597 // If this is a child document, use the parent's list instead.
1598 Buffer const * const pbuf = d->parent();
1600 pbuf->getLabelList(list);
1605 Toc & toc = d->toc_backend.toc("label");
1606 TocIterator toc_it = toc.begin();
1607 TocIterator end = toc.end();
1608 for (; toc_it != end; ++toc_it) {
1609 if (toc_it->depth() == 0)
1610 list.push_back(toc_it->str());
1615 void Buffer::updateBibfilesCache(UpdateScope scope) const
1617 // If this is a child document, use the parent's cache instead.
1618 Buffer const * const pbuf = d->parent();
1619 if (pbuf && scope != UpdateChildOnly) {
1620 pbuf->updateBibfilesCache();
1624 d->bibfiles_cache_.clear();
1625 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1626 if (it->lyxCode() == BIBTEX_CODE) {
1627 InsetBibtex const & inset =
1628 static_cast<InsetBibtex const &>(*it);
1629 support::FileNameList const bibfiles = inset.getBibFiles();
1630 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1633 } else if (it->lyxCode() == INCLUDE_CODE) {
1634 InsetInclude & inset =
1635 static_cast<InsetInclude &>(*it);
1636 inset.updateBibfilesCache();
1637 support::FileNameList const & bibfiles =
1638 inset.getBibfilesCache();
1639 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1644 // the bibinfo cache is now invalid
1645 d->bibinfo_cache_valid_ = false;
1649 void Buffer::invalidateBibinfoCache()
1651 d->bibinfo_cache_valid_ = false;
1655 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1657 // If this is a child document, use the parent's cache instead.
1658 Buffer const * const pbuf = d->parent();
1659 if (pbuf && scope != UpdateChildOnly)
1660 return pbuf->getBibfilesCache();
1662 // We update the cache when first used instead of at loading time.
1663 if (d->bibfiles_cache_.empty())
1664 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1666 return d->bibfiles_cache_;
1670 BiblioInfo const & Buffer::masterBibInfo() const
1672 // if this is a child document and the parent is already loaded
1673 // use the parent's list instead [ale990412]
1674 Buffer const * const tmp = masterBuffer();
1677 return tmp->masterBibInfo();
1678 return localBibInfo();
1682 BiblioInfo const & Buffer::localBibInfo() const
1688 void Buffer::checkBibInfoCache() const
1690 support::FileNameList const & bibfilesCache = getBibfilesCache();
1691 // compare the cached timestamps with the actual ones.
1692 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1693 support::FileNameList::const_iterator en = bibfilesCache.end();
1694 for (; ei != en; ++ ei) {
1695 time_t lastw = ei->lastModified();
1696 time_t prevw = d->bibfile_status_[*ei];
1697 if (lastw != prevw) {
1698 d->bibinfo_cache_valid_ = false;
1699 d->bibfile_status_[*ei] = lastw;
1703 if (!d->bibinfo_cache_valid_) {
1704 d->bibinfo_.clear();
1705 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1706 it->fillWithBibKeys(d->bibinfo_, it);
1707 d->bibinfo_cache_valid_ = true;
1712 bool Buffer::isDepClean(string const & name) const
1714 DepClean::const_iterator const it = d->dep_clean.find(name);
1715 if (it == d->dep_clean.end())
1721 void Buffer::markDepClean(string const & name)
1723 d->dep_clean[name] = true;
1727 bool Buffer::isExportableFormat(string const & format) const
1729 typedef vector<Format const *> Formats;
1731 formats = exportableFormats(true);
1732 Formats::const_iterator fit = formats.begin();
1733 Formats::const_iterator end = formats.end();
1734 for (; fit != end ; ++fit) {
1735 if ((*fit)->name() == format)
1742 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1745 // FIXME? if there is an Buffer LFUN that can be dispatched even
1746 // if internal, put a switch '(cmd.action)' here.
1752 switch (cmd.action) {
1754 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1755 flag.setOnOff(isReadonly());
1758 // FIXME: There is need for a command-line import.
1759 //case LFUN_BUFFER_IMPORT:
1761 case LFUN_BUFFER_AUTO_SAVE:
1764 case LFUN_BUFFER_EXPORT_CUSTOM:
1765 // FIXME: Nothing to check here?
1768 case LFUN_BUFFER_EXPORT: {
1769 docstring const arg = cmd.argument();
1770 enable = arg == "custom" || isExportable(to_utf8(arg));
1772 flag.message(bformat(
1773 _("Don't know how to export to format: %1$s"), arg));
1777 case LFUN_BUFFER_CHKTEX:
1778 enable = isLatex() && !lyxrc.chktex_command.empty();
1781 case LFUN_BUILD_PROGRAM:
1782 enable = isExportable("program");
1785 case LFUN_BRANCH_ACTIVATE:
1786 case LFUN_BRANCH_DEACTIVATE: {
1787 BranchList const & branchList = params().branchlist();
1788 docstring const branchName = cmd.argument();
1789 enable = !branchName.empty() && branchList.find(branchName);
1793 case LFUN_BRANCH_ADD:
1794 case LFUN_BRANCHES_RENAME:
1795 case LFUN_BUFFER_PRINT:
1796 // if no Buffer is present, then of course we won't be called!
1799 case LFUN_BUFFER_LANGUAGE:
1800 enable = !isReadonly();
1806 flag.setEnabled(enable);
1811 void Buffer::dispatch(string const & command, DispatchResult & result)
1813 return dispatch(lyxaction.lookupFunc(command), result);
1817 // NOTE We can end up here even if we have no GUI, because we are called
1818 // by LyX::exec to handled command-line requests. So we may need to check
1819 // whether we have a GUI or not. The boolean use_gui holds this information.
1820 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1823 // FIXME? if there is an Buffer LFUN that can be dispatched even
1824 // if internal, put a switch '(cmd.action)' here.
1825 dr.dispatched(false);
1828 string const argument = to_utf8(func.argument());
1829 // We'll set this back to false if need be.
1830 bool dispatched = true;
1831 undo().beginUndoGroup();
1833 switch (func.action) {
1834 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1835 if (lyxvc().inUse())
1836 lyxvc().toggleReadOnly();
1838 setReadonly(!isReadonly());
1841 case LFUN_BUFFER_EXPORT: {
1842 bool success = doExport(argument, false, false);
1843 dr.setError(success);
1845 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1850 case LFUN_BUILD_PROGRAM:
1851 doExport("program", true, false);
1854 case LFUN_BUFFER_CHKTEX:
1858 case LFUN_BUFFER_EXPORT_CUSTOM: {
1860 string command = split(argument, format_name, ' ');
1861 Format const * format = formats.getFormat(format_name);
1863 lyxerr << "Format \"" << format_name
1864 << "\" not recognized!"
1869 // The name of the file created by the conversion process
1872 // Output to filename
1873 if (format->name() == "lyx") {
1874 string const latexname = latexName(false);
1875 filename = changeExtension(latexname,
1876 format->extension());
1877 filename = addName(temppath(), filename);
1879 if (!writeFile(FileName(filename)))
1883 doExport(format_name, true, false, filename);
1886 // Substitute $$FName for filename
1887 if (!contains(command, "$$FName"))
1888 command = "( " + command + " ) < $$FName";
1889 command = subst(command, "$$FName", filename);
1891 // Execute the command in the background
1893 call.startscript(Systemcall::DontWait, command);
1897 // FIXME: There is need for a command-line import.
1899 case LFUN_BUFFER_IMPORT:
1904 case LFUN_BUFFER_AUTO_SAVE:
1908 case LFUN_BRANCH_ADD: {
1909 docstring const branch_name = func.argument();
1910 if (branch_name.empty()) {
1914 BranchList & branch_list = params().branchlist();
1915 Branch * branch = branch_list.find(branch_name);
1917 LYXERR0("Branch " << branch_name << " already exists.");
1919 docstring const msg =
1920 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1923 branch_list.add(branch_name);
1924 branch = branch_list.find(branch_name);
1925 string const x11hexname = X11hexname(branch->color());
1926 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1927 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1929 dr.update(Update::Force);
1934 case LFUN_BRANCH_ACTIVATE:
1935 case LFUN_BRANCH_DEACTIVATE: {
1936 BranchList & branchList = params().branchlist();
1937 docstring const branchName = func.argument();
1938 // the case without a branch name is handled elsewhere
1939 if (branchName.empty()) {
1943 Branch * branch = branchList.find(branchName);
1945 LYXERR0("Branch " << branchName << " does not exist.");
1947 docstring const msg =
1948 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1951 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1953 dr.update(Update::Force);
1958 case LFUN_BRANCHES_RENAME: {
1959 if (func.argument().empty())
1962 docstring const oldname = from_utf8(func.getArg(0));
1963 docstring const newname = from_utf8(func.getArg(1));
1964 InsetIterator it = inset_iterator_begin(inset());
1965 InsetIterator const end = inset_iterator_end(inset());
1966 bool success = false;
1967 for (; it != end; ++it) {
1968 if (it->lyxCode() == BRANCH_CODE) {
1969 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1970 if (ins.branch() == oldname) {
1971 undo().recordUndo(it);
1972 ins.rename(newname);
1977 if (it->lyxCode() == INCLUDE_CODE) {
1978 // get buffer of external file
1979 InsetInclude const & ins =
1980 static_cast<InsetInclude const &>(*it);
1981 Buffer * child = ins.getChildBuffer();
1984 child->dispatch(func, dr);
1989 dr.update(Update::Force);
1993 case LFUN_BUFFER_PRINT: {
1994 // we'll assume there's a problem until we succeed
1996 string target = func.getArg(0);
1997 string target_name = func.getArg(1);
1998 string command = func.getArg(2);
2001 || target_name.empty()
2002 || command.empty()) {
2003 LYXERR0("Unable to parse " << func.argument());
2004 docstring const msg =
2005 bformat(_("Unable to parse \"%1$s\""), func.argument());
2009 if (target != "printer" && target != "file") {
2010 LYXERR0("Unrecognized target \"" << target << '"');
2011 docstring const msg =
2012 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2017 bool const update_unincluded =
2018 params().maintain_unincluded_children
2019 && !params().getIncludedChildren().empty();
2020 if (!doExport("dvi", true, update_unincluded)) {
2021 showPrintError(absFileName());
2022 dr.setMessage(_("Error exporting to DVI."));
2026 // Push directory path.
2027 string const path = temppath();
2028 // Prevent the compiler from optimizing away p
2032 // there are three cases here:
2033 // 1. we print to a file
2034 // 2. we print directly to a printer
2035 // 3. we print using a spool command (print to file first)
2038 string const dviname = changeExtension(latexName(true), "dvi");
2040 if (target == "printer") {
2041 if (!lyxrc.print_spool_command.empty()) {
2042 // case 3: print using a spool
2043 string const psname = changeExtension(dviname,".ps");
2044 command += ' ' + lyxrc.print_to_file
2047 + quoteName(dviname);
2049 string command2 = lyxrc.print_spool_command + ' ';
2050 if (target_name != "default") {
2051 command2 += lyxrc.print_spool_printerprefix
2055 command2 += quoteName(psname);
2057 // If successful, then spool command
2058 res = one.startscript(Systemcall::Wait, command);
2061 // If there's no GUI, we have to wait on this command. Otherwise,
2062 // LyX deletes the temporary directory, and with it the spooled
2063 // file, before it can be printed!!
2064 Systemcall::Starttype stype = use_gui ?
2065 Systemcall::DontWait : Systemcall::Wait;
2066 res = one.startscript(stype, command2);
2069 // case 2: print directly to a printer
2070 if (target_name != "default")
2071 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2073 Systemcall::Starttype stype = use_gui ?
2074 Systemcall::DontWait : Systemcall::Wait;
2075 res = one.startscript(stype, command + quoteName(dviname));
2079 // case 1: print to a file
2080 FileName const filename(makeAbsPath(target_name, filePath()));
2081 FileName const dvifile(makeAbsPath(dviname, path));
2082 if (filename.exists()) {
2083 docstring text = bformat(
2084 _("The file %1$s already exists.\n\n"
2085 "Do you want to overwrite that file?"),
2086 makeDisplayPath(filename.absFilename()));
2087 if (Alert::prompt(_("Overwrite file?"),
2088 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2091 command += ' ' + lyxrc.print_to_file
2092 + quoteName(filename.toFilesystemEncoding())
2094 + quoteName(dvifile.toFilesystemEncoding());
2096 Systemcall::Starttype stype = use_gui ?
2097 Systemcall::DontWait : Systemcall::Wait;
2098 res = one.startscript(stype, command);
2104 dr.setMessage(_("Error running external commands."));
2105 showPrintError(absFileName());
2110 case LFUN_BUFFER_LANGUAGE: {
2111 Language const * oldL = params().language;
2112 Language const * newL = languages.getLanguage(argument);
2113 if (!newL || oldL == newL)
2115 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2116 changeLanguage(oldL, newL);
2124 dr.dispatched(dispatched);
2125 undo().endUndoGroup();
2129 void Buffer::changeLanguage(Language const * from, Language const * to)
2131 LASSERT(from, /**/);
2134 for_each(par_iterator_begin(),
2136 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2140 bool Buffer::isMultiLingual() const
2142 ParConstIterator end = par_iterator_end();
2143 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2144 if (it->isMultiLingual(params()))
2151 DocIterator Buffer::getParFromID(int const id) const
2153 Buffer * buf = const_cast<Buffer *>(this);
2155 // John says this is called with id == -1 from undo
2156 lyxerr << "getParFromID(), id: " << id << endl;
2157 return doc_iterator_end(buf);
2160 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2161 if (it.paragraph().id() == id)
2164 return doc_iterator_end(buf);
2168 bool Buffer::hasParWithID(int const id) const
2170 return !getParFromID(id).atEnd();
2174 ParIterator Buffer::par_iterator_begin()
2176 return ParIterator(doc_iterator_begin(this));
2180 ParIterator Buffer::par_iterator_end()
2182 return ParIterator(doc_iterator_end(this));
2186 ParConstIterator Buffer::par_iterator_begin() const
2188 return ParConstIterator(doc_iterator_begin(this));
2192 ParConstIterator Buffer::par_iterator_end() const
2194 return ParConstIterator(doc_iterator_end(this));
2198 Language const * Buffer::language() const
2200 return params().language;
2204 docstring const Buffer::B_(string const & l10n) const
2206 return params().B_(l10n);
2210 bool Buffer::isClean() const
2212 return d->lyx_clean;
2216 bool Buffer::isBakClean() const
2218 return d->bak_clean;
2222 bool Buffer::isExternallyModified(CheckMethod method) const
2224 LASSERT(d->filename.exists(), /**/);
2225 // if method == timestamp, check timestamp before checksum
2226 return (method == checksum_method
2227 || d->timestamp_ != d->filename.lastModified())
2228 && d->checksum_ != d->filename.checksum();
2232 void Buffer::saveCheckSum(FileName const & file) const
2234 if (file.exists()) {
2235 d->timestamp_ = file.lastModified();
2236 d->checksum_ = file.checksum();
2238 // in the case of save to a new file.
2245 void Buffer::markClean() const
2247 if (!d->lyx_clean) {
2248 d->lyx_clean = true;
2251 // if the .lyx file has been saved, we don't need an
2253 d->bak_clean = true;
2257 void Buffer::markBakClean() const
2259 d->bak_clean = true;
2263 void Buffer::setUnnamed(bool flag)
2269 bool Buffer::isUnnamed() const
2276 /// Don't check unnamed, here: isInternal() is used in
2277 /// newBuffer(), where the unnamed flag has not been set by anyone
2278 /// yet. Also, for an internal buffer, there should be no need for
2279 /// retrieving fileName() nor for checking if it is unnamed or not.
2280 bool Buffer::isInternal() const
2282 return fileName().extension() == "internal";
2286 void Buffer::markDirty()
2289 d->lyx_clean = false;
2292 d->bak_clean = false;
2294 DepClean::iterator it = d->dep_clean.begin();
2295 DepClean::const_iterator const end = d->dep_clean.end();
2297 for (; it != end; ++it)
2302 FileName Buffer::fileName() const
2308 string Buffer::absFileName() const
2310 return d->filename.absFilename();
2314 string Buffer::filePath() const
2316 return d->filename.onlyPath().absFilename() + "/";
2320 bool Buffer::isReadonly() const
2322 return d->read_only;
2326 void Buffer::setParent(Buffer const * buffer)
2328 // Avoids recursive include.
2329 d->setParent(buffer == this ? 0 : buffer);
2334 Buffer const * Buffer::parent() const
2340 void Buffer::collectRelatives(BufferSet & bufs) const
2344 parent()->collectRelatives(bufs);
2346 // loop over children
2347 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2348 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2349 for (; it != end; ++it)
2350 bufs.insert(const_cast<Buffer *>(it->first));
2354 std::vector<Buffer const *> Buffer::allRelatives() const
2357 collectRelatives(bufs);
2358 BufferSet::iterator it = bufs.begin();
2359 std::vector<Buffer const *> ret;
2360 for (; it != bufs.end(); ++it)
2366 Buffer const * Buffer::masterBuffer() const
2368 Buffer const * const pbuf = d->parent();
2372 return pbuf->masterBuffer();
2376 bool Buffer::isChild(Buffer * child) const
2378 return d->children_positions.find(child) != d->children_positions.end();
2382 DocIterator Buffer::firstChildPosition(Buffer const * child)
2384 Impl::BufferPositionMap::iterator it;
2385 it = d->children_positions.find(child);
2386 if (it == d->children_positions.end())
2387 return DocIterator(this);
2392 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2394 // loop over children
2395 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2396 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2397 for (; it != end; ++it) {
2398 Buffer * child = const_cast<Buffer *>(it->first);
2399 clist.push_back(child);
2400 if (grand_children) {
2401 // there might be grandchildren
2402 std::vector<Buffer *> glist = child->getChildren();
2403 for (vector<Buffer *>::const_iterator git = glist.begin();
2404 git != glist.end(); ++git)
2405 clist.push_back(*git);
2411 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2413 std::vector<Buffer *> v;
2414 getChildren(v, grand_children);
2419 template<typename M>
2420 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2425 typename M::iterator it = m.lower_bound(x);
2426 if (it == m.begin())
2434 MacroData const * Buffer::getBufferMacro(docstring const & name,
2435 DocIterator const & pos) const
2437 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2439 // if paragraphs have no macro context set, pos will be empty
2443 // we haven't found anything yet
2444 DocIterator bestPos = par_iterator_begin();
2445 MacroData const * bestData = 0;
2447 // find macro definitions for name
2448 Impl::NamePositionScopeMacroMap::iterator nameIt
2449 = d->macros.find(name);
2450 if (nameIt != d->macros.end()) {
2451 // find last definition in front of pos or at pos itself
2452 Impl::PositionScopeMacroMap::const_iterator it
2453 = greatest_below(nameIt->second, pos);
2454 if (it != nameIt->second.end()) {
2456 // scope ends behind pos?
2457 if (pos < it->second.first) {
2458 // Looks good, remember this. If there
2459 // is no external macro behind this,
2460 // we found the right one already.
2461 bestPos = it->first;
2462 bestData = &it->second.second;
2466 // try previous macro if there is one
2467 if (it == nameIt->second.begin())
2474 // find macros in included files
2475 Impl::PositionScopeBufferMap::const_iterator it
2476 = greatest_below(d->position_to_children, pos);
2477 if (it == d->position_to_children.end())
2478 // no children before
2482 // do we know something better (i.e. later) already?
2483 if (it->first < bestPos )
2486 // scope ends behind pos?
2487 if (pos < it->second.first) {
2488 // look for macro in external file
2489 d->macro_lock = true;
2490 MacroData const * data
2491 = it->second.second->getMacro(name, false);
2492 d->macro_lock = false;
2494 bestPos = it->first;
2500 // try previous file if there is one
2501 if (it == d->position_to_children.begin())
2506 // return the best macro we have found
2511 MacroData const * Buffer::getMacro(docstring const & name,
2512 DocIterator const & pos, bool global) const
2517 // query buffer macros
2518 MacroData const * data = getBufferMacro(name, pos);
2522 // If there is a master buffer, query that
2523 Buffer const * const pbuf = d->parent();
2525 d->macro_lock = true;
2526 MacroData const * macro = pbuf->getMacro(
2527 name, *this, false);
2528 d->macro_lock = false;
2534 data = MacroTable::globalMacros().get(name);
2543 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2545 // set scope end behind the last paragraph
2546 DocIterator scope = par_iterator_begin();
2547 scope.pit() = scope.lastpit() + 1;
2549 return getMacro(name, scope, global);
2553 MacroData const * Buffer::getMacro(docstring const & name,
2554 Buffer const & child, bool global) const
2556 // look where the child buffer is included first
2557 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2558 if (it == d->children_positions.end())
2561 // check for macros at the inclusion position
2562 return getMacro(name, it->second, global);
2566 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2568 pit_type const lastpit = it.lastpit();
2570 // look for macros in each paragraph
2571 while (it.pit() <= lastpit) {
2572 Paragraph & par = it.paragraph();
2574 // iterate over the insets of the current paragraph
2575 InsetList const & insets = par.insetList();
2576 InsetList::const_iterator iit = insets.begin();
2577 InsetList::const_iterator end = insets.end();
2578 for (; iit != end; ++iit) {
2579 it.pos() = iit->pos;
2581 // is it a nested text inset?
2582 if (iit->inset->asInsetText()) {
2583 // Inset needs its own scope?
2584 InsetText const * itext = iit->inset->asInsetText();
2585 bool newScope = itext->isMacroScope();
2587 // scope which ends just behind the inset
2588 DocIterator insetScope = it;
2591 // collect macros in inset
2592 it.push_back(CursorSlice(*iit->inset));
2593 updateMacros(it, newScope ? insetScope : scope);
2598 // is it an external file?
2599 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2600 // get buffer of external file
2601 InsetInclude const & inset =
2602 static_cast<InsetInclude const &>(*iit->inset);
2603 d->macro_lock = true;
2604 Buffer * child = inset.getChildBuffer();
2605 d->macro_lock = false;
2609 // register its position, but only when it is
2610 // included first in the buffer
2611 if (d->children_positions.find(child) ==
2612 d->children_positions.end())
2613 d->children_positions[child] = it;
2615 // register child with its scope
2616 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2620 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2624 MathMacroTemplate & macroTemplate =
2625 static_cast<MathMacroTemplate &>(*iit->inset);
2626 MacroContext mc(this, it);
2627 macroTemplate.updateToContext(mc);
2630 bool valid = macroTemplate.validMacro();
2631 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2632 // then the BufferView's cursor will be invalid in
2633 // some cases which leads to crashes.
2638 // FIXME (Abdel), I don't understandt why we pass 'it' here
2639 // instead of 'macroTemplate' defined above... is this correct?
2640 d->macros[macroTemplate.name()][it] =
2641 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2651 void Buffer::updateMacros() const
2656 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2658 // start with empty table
2660 d->children_positions.clear();
2661 d->position_to_children.clear();
2663 // Iterate over buffer, starting with first paragraph
2664 // The scope must be bigger than any lookup DocIterator
2665 // later. For the global lookup, lastpit+1 is used, hence
2666 // we use lastpit+2 here.
2667 DocIterator it = par_iterator_begin();
2668 DocIterator outerScope = it;
2669 outerScope.pit() = outerScope.lastpit() + 2;
2670 updateMacros(it, outerScope);
2674 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2676 InsetIterator it = inset_iterator_begin(inset());
2677 InsetIterator const end = inset_iterator_end(inset());
2678 for (; it != end; ++it) {
2679 if (it->lyxCode() == BRANCH_CODE) {
2680 InsetBranch & br = static_cast<InsetBranch &>(*it);
2681 docstring const name = br.branch();
2682 if (!from_master && !params().branchlist().find(name))
2683 result.push_back(name);
2684 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2685 result.push_back(name);
2688 if (it->lyxCode() == INCLUDE_CODE) {
2689 // get buffer of external file
2690 InsetInclude const & ins =
2691 static_cast<InsetInclude const &>(*it);
2692 Buffer * child = ins.getChildBuffer();
2695 child->getUsedBranches(result, true);
2698 // remove duplicates
2703 void Buffer::updateMacroInstances() const
2705 LYXERR(Debug::MACROS, "updateMacroInstances for "
2706 << d->filename.onlyFileName());
2707 DocIterator it = doc_iterator_begin(this);
2709 DocIterator const end = doc_iterator_end(this);
2710 for (; it != end; it.forwardInset()) {
2711 // look for MathData cells in InsetMathNest insets
2712 InsetMath * minset = it.nextInset()->asInsetMath();
2716 // update macro in all cells of the InsetMathNest
2717 DocIterator::idx_type n = minset->nargs();
2718 MacroContext mc = MacroContext(this, it);
2719 for (DocIterator::idx_type i = 0; i < n; ++i) {
2720 MathData & data = minset->cell(i);
2721 data.updateMacros(0, mc);
2727 void Buffer::listMacroNames(MacroNameSet & macros) const
2732 d->macro_lock = true;
2734 // loop over macro names
2735 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2736 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2737 for (; nameIt != nameEnd; ++nameIt)
2738 macros.insert(nameIt->first);
2740 // loop over children
2741 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2742 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2743 for (; it != end; ++it)
2744 it->first->listMacroNames(macros);
2747 Buffer const * const pbuf = d->parent();
2749 pbuf->listMacroNames(macros);
2751 d->macro_lock = false;
2755 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2757 Buffer const * const pbuf = d->parent();
2762 pbuf->listMacroNames(names);
2765 MacroNameSet::iterator it = names.begin();
2766 MacroNameSet::iterator end = names.end();
2767 for (; it != end; ++it) {
2769 MacroData const * data =
2770 pbuf->getMacro(*it, *this, false);
2772 macros.insert(data);
2774 // we cannot access the original MathMacroTemplate anymore
2775 // here to calls validate method. So we do its work here manually.
2776 // FIXME: somehow make the template accessible here.
2777 if (data->optionals() > 0)
2778 features.require("xargs");
2784 Buffer::References & Buffer::references(docstring const & label)
2787 return const_cast<Buffer *>(masterBuffer())->references(label);
2789 RefCache::iterator it = d->ref_cache_.find(label);
2790 if (it != d->ref_cache_.end())
2791 return it->second.second;
2793 static InsetLabel const * dummy_il = 0;
2794 static References const dummy_refs;
2795 it = d->ref_cache_.insert(
2796 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2797 return it->second.second;
2801 Buffer::References const & Buffer::references(docstring const & label) const
2803 return const_cast<Buffer *>(this)->references(label);
2807 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2809 masterBuffer()->d->ref_cache_[label].first = il;
2813 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2815 return masterBuffer()->d->ref_cache_[label].first;
2819 void Buffer::clearReferenceCache() const
2822 d->ref_cache_.clear();
2826 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2829 //FIXME: This does not work for child documents yet.
2830 LASSERT(code == CITE_CODE, /**/);
2831 // Check if the label 'from' appears more than once
2832 vector<docstring> labels;
2834 checkBibInfoCache();
2835 BiblioInfo const & keys = masterBibInfo();
2836 BiblioInfo::const_iterator bit = keys.begin();
2837 BiblioInfo::const_iterator bend = keys.end();
2839 for (; bit != bend; ++bit)
2841 labels.push_back(bit->first);
2844 if (count(labels.begin(), labels.end(), from) > 1)
2847 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2848 if (it->lyxCode() == code) {
2849 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2850 docstring const oldValue = inset.getParam(paramName);
2851 if (oldValue == from)
2852 inset.setParam(paramName, to);
2858 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2859 pit_type par_end, bool full_source) const
2861 OutputParams runparams(¶ms().encoding());
2862 runparams.nice = true;
2863 runparams.flavor = params().useXetex ?
2864 OutputParams::XETEX : OutputParams::LATEX;
2865 runparams.linelen = lyxrc.plaintext_linelen;
2866 // No side effect of file copying and image conversion
2867 runparams.dryrun = true;
2870 os << "% " << _("Preview source code") << "\n\n";
2872 d->texrow.newline();
2873 d->texrow.newline();
2875 writeDocBookSource(os, absFileName(), runparams, false);
2877 // latex or literate
2878 writeLaTeXSource(os, string(), runparams, true, true);
2880 runparams.par_begin = par_begin;
2881 runparams.par_end = par_end;
2882 if (par_begin + 1 == par_end) {
2884 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2888 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2889 convert<docstring>(par_begin),
2890 convert<docstring>(par_end - 1))
2897 // output paragraphs
2899 docbookParagraphs(text(), *this, os, runparams);
2901 // latex or literate
2902 latexParagraphs(*this, text(), os, texrow, runparams);
2907 ErrorList & Buffer::errorList(string const & type) const
2909 static ErrorList emptyErrorList;
2910 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2911 if (I == d->errorLists.end())
2912 return emptyErrorList;
2918 void Buffer::updateTocItem(std::string const & type,
2919 DocIterator const & dit) const
2922 gui_->updateTocItem(type, dit);
2926 void Buffer::structureChanged() const
2929 gui_->structureChanged();
2933 void Buffer::errors(string const & err, bool from_master) const
2936 gui_->errors(err, from_master);
2940 void Buffer::message(docstring const & msg) const
2947 void Buffer::setBusy(bool on) const
2954 void Buffer::setReadOnly(bool on) const
2957 d->wa_->setReadOnly(on);
2961 void Buffer::updateTitles() const
2964 d->wa_->updateTitles();
2968 void Buffer::resetAutosaveTimers() const
2971 gui_->resetAutosaveTimers();
2975 bool Buffer::hasGuiDelegate() const
2981 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2990 class AutoSaveBuffer : public ForkedProcess {
2993 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2994 : buffer_(buffer), fname_(fname) {}
2996 virtual boost::shared_ptr<ForkedProcess> clone() const
2998 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3003 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3004 from_utf8(fname_.absFilename())));
3005 return run(DontWait);
3009 virtual int generateChild();
3011 Buffer const & buffer_;
3016 int AutoSaveBuffer::generateChild()
3018 #if defined(__APPLE__)
3019 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3020 * We should use something else like threads.
3022 * Since I do not know how to determine at run time what is the OS X
3023 * version, I just disable forking altogether for now (JMarc)
3025 pid_t const pid = -1;
3027 // tmp_ret will be located (usually) in /tmp
3028 // will that be a problem?
3029 // Note that this calls ForkedCalls::fork(), so it's
3030 // ok cross-platform.
3031 pid_t const pid = fork();
3032 // If you want to debug the autosave
3033 // you should set pid to -1, and comment out the fork.
3034 if (pid != 0 && pid != -1)
3038 // pid = -1 signifies that lyx was unable
3039 // to fork. But we will do the save
3041 bool failed = false;
3042 FileName const tmp_ret = FileName::tempName("lyxauto");
3043 if (!tmp_ret.empty()) {
3044 buffer_.writeFile(tmp_ret);
3045 // assume successful write of tmp_ret
3046 if (!tmp_ret.moveTo(fname_))
3052 // failed to write/rename tmp_ret so try writing direct
3053 if (!buffer_.writeFile(fname_)) {
3054 // It is dangerous to do this in the child,
3055 // but safe in the parent, so...
3056 if (pid == -1) // emit message signal.
3057 buffer_.message(_("Autosave failed!"));
3061 if (pid == 0) // we are the child so...
3070 FileName Buffer::getAutosaveFilename() const
3072 // if the document is unnamed try to save in the backup dir, else
3073 // in the default document path, and as a last try in the filePath,
3074 // which will most often be the temporary directory
3077 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3078 : lyxrc.backupdir_path;
3079 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3082 string const fname = "#" + d->filename.onlyFileName() + "#";
3083 return makeAbsPath(fname, fpath);
3087 void Buffer::removeAutosaveFile() const
3089 FileName const f = getAutosaveFilename();
3095 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3097 FileName const newauto = getAutosaveFilename();
3098 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3099 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3103 // Perfect target for a thread...
3104 void Buffer::autoSave() const
3106 if (isBakClean() || isReadonly()) {
3107 // We don't save now, but we'll try again later
3108 resetAutosaveTimers();
3112 // emit message signal.
3113 message(_("Autosaving current document..."));
3114 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3118 resetAutosaveTimers();
3122 string Buffer::bufferFormat() const
3124 string format = params().documentClass().outputFormat();
3125 if (format == "latex") {
3126 if (params().useXetex)
3128 if (params().encoding().package() == Encoding::japanese)
3135 string Buffer::getDefaultOutputFormat() const
3137 if (!params().defaultOutputFormat.empty()
3138 && params().defaultOutputFormat != "default")
3139 return params().defaultOutputFormat;
3140 typedef vector<Format const *> Formats;
3141 Formats formats = exportableFormats(true);
3144 || params().useXetex
3145 || params().encoding().package() == Encoding::japanese) {
3146 if (formats.empty())
3148 // return the first we find
3149 return formats.front()->name();
3151 return lyxrc.default_view_format;
3156 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3157 bool includeall, string & result_file) const
3159 string backend_format;
3160 OutputParams runparams(¶ms().encoding());
3161 runparams.flavor = OutputParams::LATEX;
3162 runparams.linelen = lyxrc.plaintext_linelen;
3163 runparams.includeall = includeall;
3164 vector<string> backs = backends();
3165 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3166 // Get shortest path to format
3167 Graph::EdgePath path;
3168 for (vector<string>::const_iterator it = backs.begin();
3169 it != backs.end(); ++it) {
3170 Graph::EdgePath p = theConverters().getPath(*it, format);
3171 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3172 backend_format = *it;
3177 if (!put_in_tempdir) {
3178 // Only show this alert if this is an export to a non-temporary
3179 // file (not for previewing).
3180 Alert::error(_("Couldn't export file"), bformat(
3181 _("No information for exporting the format %1$s."),
3182 formats.prettyName(format)));
3186 runparams.flavor = theConverters().getFlavor(path);
3189 backend_format = format;
3190 // FIXME: Don't hardcode format names here, but use a flag
3191 if (backend_format == "pdflatex")
3192 runparams.flavor = OutputParams::PDFLATEX;
3195 string filename = latexName(false);
3196 filename = addName(temppath(), filename);
3197 filename = changeExtension(filename,
3198 formats.extension(backend_format));
3201 updateMacroInstances();
3203 // Plain text backend
3204 if (backend_format == "text") {
3205 runparams.flavor = OutputParams::TEXT;
3206 writePlaintextFile(*this, FileName(filename), runparams);
3209 else if (backend_format == "xhtml") {
3210 runparams.flavor = OutputParams::HTML;
3211 makeLyXHTMLFile(FileName(filename), runparams);
3212 } else if (backend_format == "lyx")
3213 writeFile(FileName(filename));
3215 else if (isDocBook()) {
3216 runparams.nice = !put_in_tempdir;
3217 makeDocBookFile(FileName(filename), runparams);
3220 else if (backend_format == format) {
3221 runparams.nice = true;
3222 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3224 } else if (!lyxrc.tex_allows_spaces
3225 && contains(filePath(), ' ')) {
3226 Alert::error(_("File name error"),
3227 _("The directory path to the document cannot contain spaces."));
3230 runparams.nice = false;
3231 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3235 string const error_type = (format == "program")
3236 ? "Build" : bufferFormat();
3237 ErrorList & error_list = d->errorLists[error_type];
3238 string const ext = formats.extension(format);
3239 FileName const tmp_result_file(changeExtension(filename, ext));
3240 bool const success = theConverters().convert(this, FileName(filename),
3241 tmp_result_file, FileName(absFileName()), backend_format, format,
3243 // Emit the signal to show the error list.
3244 if (format != backend_format) {
3246 // also to the children, in case of master-buffer-view
3247 std::vector<Buffer *> clist = getChildren();
3248 for (vector<Buffer *>::const_iterator cit = clist.begin();
3249 cit != clist.end(); ++cit)
3250 (*cit)->errors(error_type, true);
3255 if (d->cloned_buffer_) {
3256 // Enable reverse dvi or pdf to work by copying back the texrow
3257 // object to the cloned buffer.
3258 // FIXME: There is a possibility of concurrent access to texrow
3259 // here from the main GUI thread that should be securized.
3260 d->cloned_buffer_->d->texrow = d->texrow;
3263 if (put_in_tempdir) {
3264 result_file = tmp_result_file.absFilename();
3268 result_file = changeExtension(exportFileName().absFilename(), ext);
3269 // We need to copy referenced files (e. g. included graphics
3270 // if format == "dvi") to the result dir.
3271 vector<ExportedFile> const files =
3272 runparams.exportdata->externalFiles(format);
3273 string const dest = onlyPath(result_file);
3274 CopyStatus status = SUCCESS;
3275 for (vector<ExportedFile>::const_iterator it = files.begin();
3276 it != files.end() && status != CANCEL; ++it) {
3277 string const fmt = formats.getFormatFromFile(it->sourceName);
3278 status = copyFile(fmt, it->sourceName,
3279 makeAbsPath(it->exportName, dest),
3280 it->exportName, status == FORCE);
3282 if (status == CANCEL) {
3283 message(_("Document export cancelled."));
3284 } else if (tmp_result_file.exists()) {
3285 // Finally copy the main file
3286 status = copyFile(format, tmp_result_file,
3287 FileName(result_file), result_file,
3289 message(bformat(_("Document exported as %1$s "
3291 formats.prettyName(format),
3292 makeDisplayPath(result_file)));
3294 // This must be a dummy converter like fax (bug 1888)
3295 message(bformat(_("Document exported as %1$s"),
3296 formats.prettyName(format)));
3303 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3304 bool includeall) const
3307 // (1) export with all included children (omit \includeonly)
3308 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3310 // (2) export with included children only
3311 return doExport(format, put_in_tempdir, false, result_file);
3315 bool Buffer::preview(string const & format, bool includeall) const
3318 // (1) export with all included children (omit \includeonly)
3319 if (includeall && !doExport(format, true, true))
3321 // (2) export with included children only
3322 if (!doExport(format, true, false, result_file))
3324 return formats.view(*this, FileName(result_file), format);
3328 bool Buffer::isExportable(string const & format) const
3330 vector<string> backs = backends();
3331 for (vector<string>::const_iterator it = backs.begin();
3332 it != backs.end(); ++it)
3333 if (theConverters().isReachable(*it, format))
3339 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3341 vector<string> const backs = backends();
3342 vector<Format const *> result =
3343 theConverters().getReachable(backs[0], only_viewable, true);
3344 for (vector<string>::const_iterator it = backs.begin() + 1;
3345 it != backs.end(); ++it) {
3346 vector<Format const *> r =
3347 theConverters().getReachable(*it, only_viewable, false);
3348 result.insert(result.end(), r.begin(), r.end());
3354 vector<string> Buffer::backends() const
3357 v.push_back(bufferFormat());
3358 // FIXME: Don't hardcode format names here, but use a flag
3359 if (v.back() == "latex")
3360 v.push_back("pdflatex");
3361 v.push_back("xhtml");
3362 v.push_back("text");
3368 bool Buffer::readFileHelper(FileName const & s)
3370 // File information about normal file
3372 docstring const file = makeDisplayPath(s.absFilename(), 50);
3373 docstring text = bformat(_("The specified document\n%1$s"
3374 "\ncould not be read."), file);
3375 Alert::error(_("Could not read document"), text);
3379 // Check if emergency save file exists and is newer.
3380 FileName const e(s.absFilename() + ".emergency");
3382 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3383 docstring const file = makeDisplayPath(s.absFilename(), 20);
3384 docstring const text =
3385 bformat(_("An emergency save of the document "
3387 "Recover emergency save?"), file);
3388 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3389 _("&Recover"), _("&Load Original"),
3393 // the file is not saved if we load the emergency file.
3398 if ((res = readFile(e)) == success)
3399 str = _("Document was successfully recovered.");
3401 str = _("Document was NOT successfully recovered.");
3402 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3403 from_utf8(e.absFilename()));
3405 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3406 _("&Remove"), _("&Keep it"))) {
3409 Alert::warning(_("Emergency file deleted"),
3410 _("Do not forget to save your file now!"), true);
3415 if (!Alert::prompt(_("Delete emergency file?"),
3416 _("Remove emergency file now?"), 1, 1,
3417 _("&Remove"), _("&Keep it")))
3425 // Now check if autosave file is newer.
3426 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3428 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3429 docstring const file = makeDisplayPath(s.absFilename(), 20);
3430 docstring const text =
3431 bformat(_("The backup of the document "
3432 "%1$s is newer.\n\nLoad the "
3433 "backup instead?"), file);
3434 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3435 _("&Load backup"), _("Load &original"),
3439 // the file is not saved if we load the autosave file.
3443 // Here we delete the autosave
3454 bool Buffer::loadLyXFile(FileName const & s)
3456 // If the file is not readable, we try to
3457 // retrieve the file from version control.
3458 if (!s.isReadableFile()
3459 && !LyXVC::file_not_found_hook(s))
3462 if (s.isReadableFile()
3463 && readFileHelper(s)) {
3464 lyxvc().file_found_hook(s);
3465 setReadonly(!s.isWritable());
3472 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3474 TeXErrors::Errors::const_iterator cit = terr.begin();
3475 TeXErrors::Errors::const_iterator end = terr.end();
3477 for (; cit != end; ++cit) {
3480 int errorRow = cit->error_in_line;
3481 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3487 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3488 } while (found && id_start == id_end && pos_start == pos_end);
3490 errorList.push_back(ErrorItem(cit->error_desc,
3491 cit->error_text, id_start, pos_start, pos_end));
3496 void Buffer::setBuffersForInsets() const
3498 inset().setBuffer(const_cast<Buffer &>(*this));
3502 void Buffer::updateLabels(UpdateScope scope, bool out) const
3504 // Use the master text class also for child documents
3505 Buffer const * const master = masterBuffer();
3506 DocumentClass const & textclass = master->params().documentClass();
3508 // do this only if we are the top-level Buffer
3509 if (scope != UpdateMaster || master == this)
3510 checkBibInfoCache();
3512 // keep the buffers to be children in this set. If the call from the
3513 // master comes back we can see which of them were actually seen (i.e.
3514 // via an InsetInclude). The remaining ones in the set need still be updated.
3515 static std::set<Buffer const *> bufToUpdate;
3516 if (scope == UpdateMaster) {
3517 // If this is a child document start with the master
3518 if (master != this) {
3519 bufToUpdate.insert(this);
3520 master->updateLabels(UpdateMaster, out);
3521 // Do this here in case the master has no gui associated with it. Then,
3522 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3526 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3527 if (bufToUpdate.find(this) == bufToUpdate.end())
3531 // start over the counters in the master
3532 textclass.counters().reset();
3535 // update will be done below for this buffer
3536 bufToUpdate.erase(this);
3538 // update all caches
3539 clearReferenceCache();
3542 Buffer & cbuf = const_cast<Buffer &>(*this);
3544 LASSERT(!text().paragraphs().empty(), /**/);
3547 ParIterator parit = cbuf.par_iterator_begin();
3548 updateLabels(parit, out);
3551 // TocBackend update will be done later.
3554 cbuf.tocBackend().update();
3555 if (scope == UpdateMaster)
3556 cbuf.structureChanged();
3560 static depth_type getDepth(DocIterator const & it)
3562 depth_type depth = 0;
3563 for (size_t i = 0 ; i < it.depth() ; ++i)
3564 if (!it[i].inset().inMathed())
3565 depth += it[i].paragraph().getDepth() + 1;
3566 // remove 1 since the outer inset does not count
3570 static depth_type getItemDepth(ParIterator const & it)
3572 Paragraph const & par = *it;
3573 LabelType const labeltype = par.layout().labeltype;
3575 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3578 // this will hold the lowest depth encountered up to now.
3579 depth_type min_depth = getDepth(it);
3580 ParIterator prev_it = it;
3583 --prev_it.top().pit();
3585 // start of nested inset: go to outer par
3587 if (prev_it.empty()) {
3588 // start of document: nothing to do
3593 // We search for the first paragraph with same label
3594 // that is not more deeply nested.
3595 Paragraph & prev_par = *prev_it;
3596 depth_type const prev_depth = getDepth(prev_it);
3597 if (labeltype == prev_par.layout().labeltype) {
3598 if (prev_depth < min_depth)
3599 return prev_par.itemdepth + 1;
3600 if (prev_depth == min_depth)
3601 return prev_par.itemdepth;
3603 min_depth = min(min_depth, prev_depth);
3604 // small optimization: if we are at depth 0, we won't
3605 // find anything else
3606 if (prev_depth == 0)
3612 static bool needEnumCounterReset(ParIterator const & it)
3614 Paragraph const & par = *it;
3615 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3616 depth_type const cur_depth = par.getDepth();
3617 ParIterator prev_it = it;
3618 while (prev_it.pit()) {
3619 --prev_it.top().pit();
3620 Paragraph const & prev_par = *prev_it;
3621 if (prev_par.getDepth() <= cur_depth)
3622 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3624 // start of nested inset: reset
3629 // set the label of a paragraph. This includes the counters.
3630 void Buffer::setLabel(ParIterator & it) const
3632 BufferParams const & bp = this->masterBuffer()->params();
3633 DocumentClass const & textclass = bp.documentClass();
3634 Paragraph & par = it.paragraph();
3635 Layout const & layout = par.layout();
3636 Counters & counters = textclass.counters();
3638 if (par.params().startOfAppendix()) {
3639 // FIXME: only the counter corresponding to toplevel
3640 // sectioning should be reset
3642 counters.appendix(true);
3644 par.params().appendix(counters.appendix());
3646 // Compute the item depth of the paragraph
3647 par.itemdepth = getItemDepth(it);
3649 if (layout.margintype == MARGIN_MANUAL
3650 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3651 if (par.params().labelWidthString().empty())
3652 par.params().labelWidthString(par.expandLabel(layout, bp));
3654 par.params().labelWidthString(docstring());
3657 switch(layout.labeltype) {
3659 if (layout.toclevel <= bp.secnumdepth
3660 && (layout.latextype != LATEX_ENVIRONMENT
3661 || it.text()->isFirstInSequence(it.pit()))) {
3662 counters.step(layout.counter);
3663 par.params().labelString(
3664 par.expandLabel(layout, bp));
3666 par.params().labelString(docstring());
3669 case LABEL_ITEMIZE: {
3670 // At some point of time we should do something more
3671 // clever here, like:
3672 // par.params().labelString(
3673 // bp.user_defined_bullet(par.itemdepth).getText());
3674 // for now, use a simple hardcoded label
3675 docstring itemlabel;
3676 switch (par.itemdepth) {
3678 itemlabel = char_type(0x2022);
3681 itemlabel = char_type(0x2013);
3684 itemlabel = char_type(0x2217);
3687 itemlabel = char_type(0x2219); // or 0x00b7
3690 par.params().labelString(itemlabel);
3694 case LABEL_ENUMERATE: {
3695 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3697 switch (par.itemdepth) {
3706 enumcounter += "iv";
3709 // not a valid enumdepth...
3713 // Maybe we have to reset the enumeration counter.
3714 if (needEnumCounterReset(it))
3715 counters.reset(enumcounter);
3716 counters.step(enumcounter);
3718 string const & lang = par.getParLanguage(bp)->code();
3719 par.params().labelString(counters.theCounter(enumcounter, lang));
3724 case LABEL_SENSITIVE: {
3725 string const & type = counters.current_float();
3726 docstring full_label;
3728 full_label = this->B_("Senseless!!! ");
3730 docstring name = this->B_(textclass.floats().getType(type).name());
3731 if (counters.hasCounter(from_utf8(type))) {
3732 string const & lang = par.getParLanguage(bp)->code();
3733 counters.step(from_utf8(type));
3734 full_label = bformat(from_ascii("%1$s %2$s:"),
3736 counters.theCounter(from_utf8(type), lang));
3738 full_label = bformat(from_ascii("%1$s #:"), name);
3740 par.params().labelString(full_label);
3744 case LABEL_NO_LABEL:
3745 par.params().labelString(docstring());
3749 case LABEL_TOP_ENVIRONMENT:
3750 case LABEL_CENTERED_TOP_ENVIRONMENT:
3753 par.params().labelString(par.expandLabel(layout, bp));
3759 void Buffer::updateLabels(ParIterator & parit, bool out) const
3761 LASSERT(parit.pit() == 0, /**/);
3763 // set the position of the text in the buffer to be able
3764 // to resolve macros in it. This has nothing to do with
3765 // labels, but by putting it here we avoid implementing
3766 // a whole bunch of traversal routines just for this call.
3767 parit.text()->setMacrocontextPosition(parit);
3769 depth_type maxdepth = 0;
3770 pit_type const lastpit = parit.lastpit();
3771 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3772 // reduce depth if necessary
3773 parit->params().depth(min(parit->params().depth(), maxdepth));
3774 maxdepth = parit->getMaxDepthAfter();
3776 // set the counter for this paragraph
3780 InsetList::const_iterator iit = parit->insetList().begin();
3781 InsetList::const_iterator end = parit->insetList().end();
3782 for (; iit != end; ++iit) {
3783 parit.pos() = iit->pos;
3784 iit->inset->updateLabels(parit, out);
3790 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3791 WordLangTuple & word_lang, docstring_list & suggestions) const
3795 suggestions.clear();
3796 word_lang = WordLangTuple();
3797 // OK, we start from here.
3798 DocIterator const end = doc_iterator_end(this);
3799 for (; from != end; from.forwardPos()) {
3800 // We are only interested in text so remove the math CursorSlice.
3801 while (from.inMathed()) {
3805 // If from is at the end of the document (which is possible
3806 // when leaving the mathed) LyX will crash later.
3810 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3815 // Do not increase progress when from == to, otherwise the word
3816 // count will be wrong.
3826 bool Buffer::reload()
3829 // e.g., read-only status could have changed due to version control
3830 d->filename.refresh();
3831 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3833 bool const success = loadLyXFile(d->filename);
3838 message(bformat(_("Document %1$s reloaded."), disp_fn));
3840 message(bformat(_("Could not reload document %1$s."), disp_fn));