3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 376; // jspitzm: support for unincluded file maintenance
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfiles_cache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfo_cache_valid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfile_status_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 // however, the BufferList doesn't know about cloned buffers, so
252 // they will always be regarded as unloaded. in that case, we hope
254 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
256 return parent_buffer;
259 void setParent(Buffer const * pb) {
260 if (parent_buffer && pb && parent_buffer != pb)
261 LYXERR0("Warning: a buffer should not have two parents!");
265 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
266 /// This one is useful for preview detached in a thread.
267 Buffer const * cloned_buffer_;
270 /// So we can force access via the accessors.
271 mutable Buffer const * parent_buffer;
276 /// Creates the per buffer temporary directory
277 static FileName createBufferTmpDir()
280 // We are in our own directory. Why bother to mangle name?
281 // In fact I wrote this code to circumvent a problematic behaviour
282 // (bug?) of EMX mkstemp().
283 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
284 convert<string>(count++));
286 if (!tmpfl.createDirectory(0777)) {
287 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
288 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
289 from_utf8(tmpfl.absFilename())));
295 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
296 Buffer const * cloned_buffer)
297 : lyx_clean(true), bak_clean(true), unnamed(false),
298 read_only(readonly_), filename(file), file_fully_loaded(false),
299 toc_backend(&parent), macro_lock(false), timestamp_(0),
300 checksum_(0), wa_(0), undo_(parent), bibinfo_cache_valid_(false),
301 cloned_buffer_(cloned_buffer), parent_buffer(0)
303 if (!cloned_buffer_) {
304 temppath = createBufferTmpDir();
305 lyxvc.setBuffer(&parent);
307 wa_ = new frontend::WorkAreaManager;
310 temppath = cloned_buffer_->d->temppath;
311 file_fully_loaded = true;
312 params = cloned_buffer_->d->params;
313 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
314 bibinfo_ = cloned_buffer_->d->bibinfo_;
315 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
316 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
320 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
321 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
323 LYXERR(Debug::INFO, "Buffer::Buffer()");
325 d->inset = new InsetText(*cloned_buffer->d->inset);
326 d->inset->setBuffer(*this);
327 // FIXME: optimize this loop somewhat, maybe by creating a new
328 // general recursive Inset::setId().
329 DocIterator it = doc_iterator_begin(this);
330 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
331 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
332 it.paragraph().setId(cloned_it.paragraph().id());
334 d->inset = new InsetText(this);
335 d->inset->setAutoBreakRows(true);
336 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
342 LYXERR(Debug::INFO, "Buffer::~Buffer()");
343 // here the buffer should take care that it is
344 // saved properly, before it goes into the void.
346 // GuiView already destroyed
350 // No need to do additional cleanups for internal buffer.
355 // loop over children
356 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
357 Impl::BufferPositionMap::iterator end = d->children_positions.end();
358 for (; it != end; ++it) {
359 Buffer * child = const_cast<Buffer *>(it->first);
360 if (d->cloned_buffer_)
362 // The child buffer might have been closed already.
363 else if (theBufferList().isLoaded(child))
364 theBufferList().releaseChild(this, child);
368 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
369 msg += emergencyWrite();
370 Alert::warning(_("Attempting to close changed document!"), msg);
373 // clear references to children in macro tables
374 d->children_positions.clear();
375 d->position_to_children.clear();
377 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
378 Alert::warning(_("Could not remove temporary directory"),
379 bformat(_("Could not remove the temporary directory %1$s"),
380 from_utf8(d->temppath.absFilename())));
383 // Remove any previewed LaTeX snippets associated with this buffer.
384 thePreviews().removeLoader(*this);
390 Buffer * Buffer::clone() const
392 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
393 buffer_clone->d->macro_lock = true;
394 buffer_clone->d->children_positions.clear();
395 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
396 // math macro caches need to be rethought and simplified.
397 // I am not sure wether we should handle Buffer cloning here or in BufferList.
398 // Right now BufferList knows nothing about buffer clones.
399 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
400 Impl::BufferPositionMap::iterator end = d->children_positions.end();
401 for (; it != end; ++it) {
402 DocIterator dit = it->second.clone(buffer_clone);
403 dit.setBuffer(buffer_clone);
404 Buffer * child = const_cast<Buffer *>(it->first);
405 Buffer * child_clone = child->clone();
406 Inset * inset = dit.nextInset();
407 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
408 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
409 inset_inc->setChildBuffer(child_clone);
410 child_clone->d->setParent(buffer_clone);
411 buffer_clone->setChild(dit, child_clone);
413 buffer_clone->d->macro_lock = false;
418 bool Buffer::isClone() const
420 return d->cloned_buffer_;
424 void Buffer::changed(bool update_metrics) const
427 d->wa_->redrawAll(update_metrics);
431 frontend::WorkAreaManager & Buffer::workAreaManager() const
433 LASSERT(d->wa_, /**/);
438 Text & Buffer::text() const
440 return d->inset->text();
444 Inset & Buffer::inset() const
450 BufferParams & Buffer::params()
456 BufferParams const & Buffer::params() const
462 ParagraphList & Buffer::paragraphs()
464 return text().paragraphs();
468 ParagraphList const & Buffer::paragraphs() const
470 return text().paragraphs();
474 LyXVC & Buffer::lyxvc()
480 LyXVC const & Buffer::lyxvc() const
486 string const Buffer::temppath() const
488 return d->temppath.absFilename();
492 TexRow & Buffer::texrow()
498 TexRow const & Buffer::texrow() const
504 TocBackend & Buffer::tocBackend() const
506 return d->toc_backend;
510 Undo & Buffer::undo()
516 void Buffer::setChild(DocIterator const & dit, Buffer * child)
518 d->children_positions[child] = dit;
522 string Buffer::latexName(bool const no_path) const
524 FileName latex_name =
525 makeLatexName(exportFileName());
526 return no_path ? latex_name.onlyFileName()
527 : latex_name.absFilename();
531 FileName Buffer::exportFileName() const
533 docstring const branch_suffix =
534 params().branchlist().getFilenameSuffix();
535 if (branch_suffix.empty())
538 string const name = fileName().onlyFileNameWithoutExt()
539 + to_utf8(branch_suffix);
540 FileName res(fileName().onlyPath().absFilename() + "/" + name);
541 res.changeExtension(fileName().extension());
547 string Buffer::logName(LogType * type) const
549 string const filename = latexName(false);
551 if (filename.empty()) {
557 string const path = temppath();
559 FileName const fname(addName(temppath(),
560 onlyFilename(changeExtension(filename,
563 // FIXME: how do we know this is the name of the build log?
564 FileName const bname(
565 addName(path, onlyFilename(
566 changeExtension(filename,
567 formats.extension(bufferFormat()) + ".out"))));
569 // Also consider the master buffer log file
570 FileName masterfname = fname;
572 if (masterBuffer() != this) {
573 string const mlogfile = masterBuffer()->logName(&mtype);
574 masterfname = FileName(mlogfile);
577 // If no Latex log or Build log is newer, show Build log
578 if (bname.exists() &&
579 ((!fname.exists() && !masterfname.exists())
580 || (fname.lastModified() < bname.lastModified()
581 && masterfname.lastModified() < bname.lastModified()))) {
582 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
585 return bname.absFilename();
586 // If we have a newer master file log or only a master log, show this
587 } else if (fname != masterfname
588 && (!fname.exists() && (masterfname.exists()
589 || fname.lastModified() < masterfname.lastModified()))) {
590 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
593 return masterfname.absFilename();
595 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
598 return fname.absFilename();
602 void Buffer::setReadonly(bool const flag)
604 if (d->read_only != flag) {
611 void Buffer::setFileName(string const & newfile)
613 d->filename = makeAbsPath(newfile);
614 setReadonly(d->filename.isReadOnly());
619 int Buffer::readHeader(Lexer & lex)
621 int unknown_tokens = 0;
623 int begin_header_line = -1;
625 // Initialize parameters that may be/go lacking in header:
626 params().branchlist().clear();
627 params().preamble.erase();
628 params().options.erase();
629 params().master.erase();
630 params().float_placement.erase();
631 params().paperwidth.erase();
632 params().paperheight.erase();
633 params().leftmargin.erase();
634 params().rightmargin.erase();
635 params().topmargin.erase();
636 params().bottommargin.erase();
637 params().headheight.erase();
638 params().headsep.erase();
639 params().footskip.erase();
640 params().columnsep.erase();
641 params().fontsCJK.erase();
642 params().listings_params.clear();
643 params().clearLayoutModules();
644 params().clearRemovedModules();
645 params().clearIncludedChildren();
646 params().pdfoptions().clear();
647 params().indiceslist().clear();
648 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
650 for (int i = 0; i < 4; ++i) {
651 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
652 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
655 ErrorList & errorList = d->errorLists["Parse"];
664 if (token == "\\end_header")
668 if (token == "\\begin_header") {
669 begin_header_line = line;
673 LYXERR(Debug::PARSER, "Handling document header token: `"
676 string unknown = params().readToken(lex, token, d->filename.onlyPath());
677 if (!unknown.empty()) {
678 if (unknown[0] != '\\' && token == "\\textclass") {
679 Alert::warning(_("Unknown document class"),
680 bformat(_("Using the default document class, because the "
681 "class %1$s is unknown."), from_utf8(unknown)));
684 docstring const s = bformat(_("Unknown token: "
688 errorList.push_back(ErrorItem(_("Document header error"),
693 if (begin_header_line) {
694 docstring const s = _("\\begin_header is missing");
695 errorList.push_back(ErrorItem(_("Document header error"),
699 params().makeDocumentClass();
701 return unknown_tokens;
706 // changed to be public and have one parameter
707 // Returns true if "\end_document" is not read (Asger)
708 bool Buffer::readDocument(Lexer & lex)
710 ErrorList & errorList = d->errorLists["Parse"];
713 if (!lex.checkFor("\\begin_document")) {
714 docstring const s = _("\\begin_document is missing");
715 errorList.push_back(ErrorItem(_("Document header error"),
719 // we are reading in a brand new document
720 LASSERT(paragraphs().empty(), /**/);
724 if (params().outputChanges) {
725 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
726 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
727 LaTeXFeatures::isAvailable("xcolor");
729 if (!dvipost && !xcolorulem) {
730 Alert::warning(_("Changes not shown in LaTeX output"),
731 _("Changes will not be highlighted in LaTeX output, "
732 "because neither dvipost nor xcolor/ulem are installed.\n"
733 "Please install these packages or redefine "
734 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
735 } else if (!xcolorulem) {
736 Alert::warning(_("Changes not shown in LaTeX output"),
737 _("Changes will not be highlighted in LaTeX output "
738 "when using pdflatex, because xcolor and ulem are not installed.\n"
739 "Please install both packages or redefine "
740 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
744 if (!params().master.empty()) {
745 FileName const master_file = makeAbsPath(params().master,
746 onlyPath(absFileName()));
747 if (isLyXFilename(master_file.absFilename())) {
749 checkAndLoadLyXFile(master_file, true);
751 // necessary e.g. after a reload
752 // to re-register the child (bug 5873)
753 // FIXME: clean up updateMacros (here, only
754 // child registering is needed).
755 master->updateMacros();
756 // set master as master buffer, but only
757 // if we are a real child
758 if (master->isChild(this))
760 // if the master is not fully loaded
761 // it is probably just loading this
762 // child. No warning needed then.
763 else if (master->isFullyLoaded())
764 LYXERR0("The master '"
766 << "' assigned to this document ("
768 << ") does not include "
769 "this document. Ignoring the master assignment.");
774 // assure we have a default index
775 params().indiceslist().addDefault(B_("Index"));
778 bool const res = text().read(lex, errorList, d->inset);
782 updateMacroInstances();
787 bool Buffer::readString(string const & s)
789 params().compressed = false;
791 // remove dummy empty par
792 paragraphs().clear();
796 FileName const name = FileName::tempName("Buffer_readString");
797 switch (readFile(lex, name, true)) {
801 // We need to call lyx2lyx, so write the input to a file
802 ofstream os(name.toFilesystemEncoding().c_str());
805 return readFile(name);
815 bool Buffer::readFile(FileName const & filename)
817 FileName fname(filename);
819 params().compressed = fname.isZippedFile();
821 // remove dummy empty par
822 paragraphs().clear();
825 if (readFile(lex, fname) != success)
832 bool Buffer::isFullyLoaded() const
834 return d->file_fully_loaded;
838 void Buffer::setFullyLoaded(bool value)
840 d->file_fully_loaded = value;
844 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
847 LASSERT(!filename.empty(), /**/);
849 // the first (non-comment) token _must_ be...
850 if (!lex.checkFor("\\lyxformat")) {
851 Alert::error(_("Document format failure"),
852 bformat(_("%1$s is not a readable LyX document."),
853 from_utf8(filename.absFilename())));
859 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
860 // if present remove ".," from string.
861 size_t dot = tmp_format.find_first_of(".,");
862 //lyxerr << " dot found at " << dot << endl;
863 if (dot != string::npos)
864 tmp_format.erase(dot, 1);
865 int const file_format = convert<int>(tmp_format);
866 //lyxerr << "format: " << file_format << endl;
868 // save timestamp and checksum of the original disk file, making sure
869 // to not overwrite them with those of the file created in the tempdir
870 // when it has to be converted to the current format.
872 // Save the timestamp and checksum of disk file. If filename is an
873 // emergency file, save the timestamp and checksum of the original lyx file
874 // because isExternallyModified will check for this file. (BUG4193)
875 string diskfile = filename.absFilename();
876 if (suffixIs(diskfile, ".emergency"))
877 diskfile = diskfile.substr(0, diskfile.size() - 10);
878 saveCheckSum(FileName(diskfile));
881 if (file_format != LYX_FORMAT) {
884 // lyx2lyx would fail
887 FileName const tmpfile = FileName::tempName("Buffer_readFile");
888 if (tmpfile.empty()) {
889 Alert::error(_("Conversion failed"),
890 bformat(_("%1$s is from a different"
891 " version of LyX, but a temporary"
892 " file for converting it could"
894 from_utf8(filename.absFilename())));
897 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
898 if (lyx2lyx.empty()) {
899 Alert::error(_("Conversion script not found"),
900 bformat(_("%1$s is from a different"
901 " version of LyX, but the"
902 " conversion script lyx2lyx"
903 " could not be found."),
904 from_utf8(filename.absFilename())));
907 ostringstream command;
908 command << os::python()
909 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
910 << " -t " << convert<string>(LYX_FORMAT)
911 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
912 << ' ' << quoteName(filename.toFilesystemEncoding());
913 string const command_str = command.str();
915 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
917 cmd_ret const ret = runCommand(command_str);
918 if (ret.first != 0) {
919 if (file_format < LYX_FORMAT)
920 Alert::error(_("Conversion script failed"),
921 bformat(_("%1$s is from an older version"
922 " of LyX, but the lyx2lyx script"
923 " failed to convert it."),
924 from_utf8(filename.absFilename())));
926 Alert::error(_("Conversion script failed"),
927 bformat(_("%1$s is from a newer version"
928 " of LyX and cannot be converted by the"
930 from_utf8(filename.absFilename())));
933 bool const ret = readFile(tmpfile);
934 // Do stuff with tmpfile name and buffer name here.
935 return ret ? success : failure;
940 if (readDocument(lex)) {
941 Alert::error(_("Document format failure"),
942 bformat(_("%1$s ended unexpectedly, which means"
943 " that it is probably corrupted."),
944 from_utf8(filename.absFilename())));
947 d->file_fully_loaded = true;
952 // Should probably be moved to somewhere else: BufferView? LyXView?
953 bool Buffer::save() const
955 // We don't need autosaves in the immediate future. (Asger)
956 resetAutosaveTimers();
958 string const encodedFilename = d->filename.toFilesystemEncoding();
961 bool madeBackup = false;
963 // make a backup if the file already exists
964 if (lyxrc.make_backup && fileName().exists()) {
965 backupName = FileName(absFileName() + '~');
966 if (!lyxrc.backupdir_path.empty()) {
967 string const mangledName =
968 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
969 backupName = FileName(addName(lyxrc.backupdir_path,
972 if (fileName().copyTo(backupName)) {
975 Alert::error(_("Backup failure"),
976 bformat(_("Cannot create backup file %1$s.\n"
977 "Please check whether the directory exists and is writeable."),
978 from_utf8(backupName.absFilename())));
979 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
983 // ask if the disk file has been externally modified (use checksum method)
984 if (fileName().exists() && isExternallyModified(checksum_method)) {
985 docstring const file = makeDisplayPath(absFileName(), 20);
986 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
987 "you want to overwrite this file?"), file);
988 int const ret = Alert::prompt(_("Overwrite modified file?"),
989 text, 1, 1, _("&Overwrite"), _("&Cancel"));
994 if (writeFile(d->filename)) {
998 // Saving failed, so backup is not backup
1000 backupName.moveTo(d->filename);
1006 bool Buffer::writeFile(FileName const & fname) const
1008 if (d->read_only && fname == d->filename)
1011 bool retval = false;
1013 docstring const str = bformat(_("Saving document %1$s..."),
1014 makeDisplayPath(fname.absFilename()));
1017 if (params().compressed) {
1018 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1019 retval = ofs && write(ofs);
1021 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1022 retval = ofs && write(ofs);
1026 message(str + _(" could not write file!"));
1030 removeAutosaveFile();
1032 saveCheckSum(d->filename);
1033 message(str + _(" done."));
1039 docstring Buffer::emergencyWrite()
1041 // No need to save if the buffer has not changed.
1045 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1047 docstring user_message = bformat(
1048 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1050 // We try to save three places:
1051 // 1) Same place as document. Unless it is an unnamed doc.
1053 string s = absFileName();
1056 if (writeFile(FileName(s))) {
1058 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1059 return user_message;
1061 user_message += _(" Save failed! Trying again...\n");
1065 // 2) In HOME directory.
1066 string s = addName(package().home_dir().absFilename(), absFileName());
1068 lyxerr << ' ' << s << endl;
1069 if (writeFile(FileName(s))) {
1071 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1072 return user_message;
1075 user_message += _(" Save failed! Trying yet again...\n");
1077 // 3) In "/tmp" directory.
1078 // MakeAbsPath to prepend the current
1079 // drive letter on OS/2
1080 s = addName(package().temp_dir().absFilename(), absFileName());
1082 lyxerr << ' ' << s << endl;
1083 if (writeFile(FileName(s))) {
1085 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1086 return user_message;
1089 user_message += _(" Save failed! Bummer. Document is lost.");
1092 return user_message;
1096 bool Buffer::write(ostream & ofs) const
1099 // Use the standard "C" locale for file output.
1100 ofs.imbue(locale::classic());
1103 // The top of the file should not be written by params().
1105 // write out a comment in the top of the file
1106 ofs << "#LyX " << lyx_version
1107 << " created this file. For more info see http://www.lyx.org/\n"
1108 << "\\lyxformat " << LYX_FORMAT << "\n"
1109 << "\\begin_document\n";
1111 /// For each author, set 'used' to true if there is a change
1112 /// by this author in the document; otherwise set it to 'false'.
1113 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1114 AuthorList::Authors::const_iterator a_end = params().authors().end();
1115 for (; a_it != a_end; ++a_it)
1116 a_it->setUsed(false);
1118 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1119 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1120 for ( ; it != end; ++it)
1121 it->checkAuthors(params().authors());
1123 // now write out the buffer parameters.
1124 ofs << "\\begin_header\n";
1125 params().writeFile(ofs);
1126 ofs << "\\end_header\n";
1129 ofs << "\n\\begin_body\n";
1131 ofs << "\n\\end_body\n";
1133 // Write marker that shows file is complete
1134 ofs << "\\end_document" << endl;
1136 // Shouldn't really be needed....
1139 // how to check if close went ok?
1140 // Following is an attempt... (BE 20001011)
1142 // good() returns false if any error occured, including some
1143 // formatting error.
1144 // bad() returns true if something bad happened in the buffer,
1145 // which should include file system full errors.
1150 lyxerr << "File was not closed properly." << endl;
1157 bool Buffer::makeLaTeXFile(FileName const & fname,
1158 string const & original_path,
1159 OutputParams const & runparams_in,
1160 bool output_preamble, bool output_body) const
1162 OutputParams runparams = runparams_in;
1163 if (params().useXetex)
1164 runparams.flavor = OutputParams::XETEX;
1166 string const encoding = runparams.encoding->iconvName();
1167 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1170 try { ofs.reset(encoding); }
1171 catch (iconv_codecvt_facet_exception & e) {
1172 lyxerr << "Caught iconv exception: " << e.what() << endl;
1173 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1174 "verify that the support software for your encoding (%1$s) is "
1175 "properly installed"), from_ascii(encoding)));
1178 if (!openFileWrite(ofs, fname))
1181 //TexStream ts(ofs.rdbuf(), &texrow());
1182 ErrorList & errorList = d->errorLists["Export"];
1184 bool failed_export = false;
1187 writeLaTeXSource(ofs, original_path,
1188 runparams, output_preamble, output_body);
1190 catch (EncodingException & e) {
1191 odocstringstream ods;
1192 ods.put(e.failed_char);
1194 oss << "0x" << hex << e.failed_char << dec;
1195 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1196 " (code point %2$s)"),
1197 ods.str(), from_utf8(oss.str()));
1198 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1199 "representable in the chosen encoding.\n"
1200 "Changing the document encoding to utf8 could help."),
1201 e.par_id, e.pos, e.pos + 1));
1202 failed_export = true;
1204 catch (iconv_codecvt_facet_exception & e) {
1205 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1206 _(e.what()), -1, 0, 0));
1207 failed_export = true;
1209 catch (exception const & e) {
1210 errorList.push_back(ErrorItem(_("conversion failed"),
1211 _(e.what()), -1, 0, 0));
1212 failed_export = true;
1215 lyxerr << "Caught some really weird exception..." << endl;
1221 failed_export = true;
1222 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1226 return !failed_export;
1230 void Buffer::writeLaTeXSource(odocstream & os,
1231 string const & original_path,
1232 OutputParams const & runparams_in,
1233 bool const output_preamble, bool const output_body) const
1235 // The child documents, if any, shall be already loaded at this point.
1237 OutputParams runparams = runparams_in;
1239 // Classify the unicode characters appearing in math insets
1240 Encodings::initUnicodeMath(*this);
1242 // validate the buffer.
1243 LYXERR(Debug::LATEX, " Validating buffer...");
1244 LaTeXFeatures features(*this, params(), runparams);
1246 LYXERR(Debug::LATEX, " Buffer validation done.");
1248 // The starting paragraph of the coming rows is the
1249 // first paragraph of the document. (Asger)
1250 if (output_preamble && runparams.nice) {
1251 os << "%% LyX " << lyx_version << " created this file. "
1252 "For more info, see http://www.lyx.org/.\n"
1253 "%% Do not edit unless you really know what "
1255 d->texrow.newline();
1256 d->texrow.newline();
1258 LYXERR(Debug::INFO, "lyx document header finished");
1260 // Don't move this behind the parent_buffer=0 code below,
1261 // because then the macros will not get the right "redefinition"
1262 // flag as they don't see the parent macros which are output before.
1265 // fold macros if possible, still with parent buffer as the
1266 // macros will be put in the prefix anyway.
1267 updateMacroInstances();
1269 // There are a few differences between nice LaTeX and usual files:
1270 // usual is \batchmode and has a
1271 // special input@path to allow the including of figures
1272 // with either \input or \includegraphics (what figinsets do).
1273 // input@path is set when the actual parameter
1274 // original_path is set. This is done for usual tex-file, but not
1275 // for nice-latex-file. (Matthias 250696)
1276 // Note that input@path is only needed for something the user does
1277 // in the preamble, included .tex files or ERT, files included by
1278 // LyX work without it.
1279 if (output_preamble) {
1280 if (!runparams.nice) {
1281 // code for usual, NOT nice-latex-file
1282 os << "\\batchmode\n"; // changed
1283 // from \nonstopmode
1284 d->texrow.newline();
1286 if (!original_path.empty()) {
1288 // We don't know the encoding of inputpath
1289 docstring const inputpath = from_utf8(latex_path(original_path));
1290 os << "\\makeatletter\n"
1291 << "\\def\\input@path{{"
1292 << inputpath << "/}}\n"
1293 << "\\makeatother\n";
1294 d->texrow.newline();
1295 d->texrow.newline();
1296 d->texrow.newline();
1299 // get parent macros (if this buffer has a parent) which will be
1300 // written at the document begin further down.
1301 MacroSet parentMacros;
1302 listParentMacros(parentMacros, features);
1304 // Write the preamble
1305 runparams.use_babel = params().writeLaTeX(os, features,
1307 d->filename.onlyPath());
1309 runparams.use_japanese = features.isRequired("japanese");
1315 os << "\\begin{document}\n";
1316 d->texrow.newline();
1318 // output the parent macros
1319 MacroSet::iterator it = parentMacros.begin();
1320 MacroSet::iterator end = parentMacros.end();
1321 for (; it != end; ++it)
1322 (*it)->write(os, true);
1323 } // output_preamble
1325 d->texrow.start(paragraphs().begin()->id(), 0);
1327 LYXERR(Debug::INFO, "preamble finished, now the body.");
1329 // if we are doing a real file with body, even if this is the
1330 // child of some other buffer, let's cut the link here.
1331 // This happens for example if only a child document is printed.
1332 Buffer const * save_parent = 0;
1333 if (output_preamble) {
1334 save_parent = d->parent();
1339 latexParagraphs(*this, text(), os, d->texrow, runparams);
1341 // Restore the parenthood if needed
1342 if (output_preamble)
1343 d->setParent(save_parent);
1345 // add this just in case after all the paragraphs
1347 d->texrow.newline();
1349 if (output_preamble) {
1350 os << "\\end{document}\n";
1351 d->texrow.newline();
1352 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1354 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1356 runparams_in.encoding = runparams.encoding;
1358 // Just to be sure. (Asger)
1359 d->texrow.newline();
1361 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1362 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1366 bool Buffer::isLatex() const
1368 return params().documentClass().outputType() == LATEX;
1372 bool Buffer::isLiterate() const
1374 return params().documentClass().outputType() == LITERATE;
1378 bool Buffer::isDocBook() const
1380 return params().documentClass().outputType() == DOCBOOK;
1384 void Buffer::makeDocBookFile(FileName const & fname,
1385 OutputParams const & runparams,
1386 bool const body_only) const
1388 LYXERR(Debug::LATEX, "makeDocBookFile...");
1391 if (!openFileWrite(ofs, fname))
1394 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1398 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1402 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1403 OutputParams const & runparams,
1404 bool const only_body) const
1406 LaTeXFeatures features(*this, params(), runparams);
1411 DocumentClass const & tclass = params().documentClass();
1412 string const top_element = tclass.latexname();
1415 if (runparams.flavor == OutputParams::XML)
1416 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1419 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1422 if (! tclass.class_header().empty())
1423 os << from_ascii(tclass.class_header());
1424 else if (runparams.flavor == OutputParams::XML)
1425 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1426 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1428 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1430 docstring preamble = from_utf8(params().preamble);
1431 if (runparams.flavor != OutputParams::XML ) {
1432 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1433 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1434 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1435 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1438 string const name = runparams.nice
1439 ? changeExtension(absFileName(), ".sgml") : fname;
1440 preamble += features.getIncludedFiles(name);
1441 preamble += features.getLyXSGMLEntities();
1443 if (!preamble.empty()) {
1444 os << "\n [ " << preamble << " ]";
1449 string top = top_element;
1451 if (runparams.flavor == OutputParams::XML)
1452 top += params().language->code();
1454 top += params().language->code().substr(0, 2);
1457 if (!params().options.empty()) {
1459 top += params().options;
1462 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1463 << " file was created by LyX " << lyx_version
1464 << "\n See http://www.lyx.org/ for more information -->\n";
1466 params().documentClass().counters().reset();
1470 sgml::openTag(os, top);
1472 docbookParagraphs(text(), *this, os, runparams);
1473 sgml::closeTag(os, top_element);
1477 void Buffer::makeLyXHTMLFile(FileName const & fname,
1478 OutputParams const & runparams,
1479 bool const body_only) const
1481 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1484 if (!openFileWrite(ofs, fname))
1487 writeLyXHTMLSource(ofs, runparams, body_only);
1491 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1495 void Buffer::writeLyXHTMLSource(odocstream & os,
1496 OutputParams const & runparams,
1497 bool const only_body) const
1499 LaTeXFeatures features(*this, params(), runparams);
1501 updateLabels(UpdateMaster, OutputUpdate);
1502 checkBibInfoCache();
1503 d->bibinfo_.makeCitationLabels(*this);
1505 updateMacroInstances();
1508 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1509 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
1510 // FIXME Language should be set properly.
1511 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1513 // FIXME Presumably need to set this right
1514 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1515 os << "<title>" << features.htmlTitle() << "</title>\n";
1517 os << "\n<!-- Text Class Preamble -->\n"
1518 << features.getTClassHTMLPreamble()
1519 << "\n<!-- Premable Snippets -->\n"
1520 << from_utf8(features.getPreambleSnippets());
1522 os << "\n<!-- Layout-provided Styles -->\n";
1523 docstring const styleinfo = features.getTClassHTMLStyles();
1524 if (!styleinfo.empty()) {
1525 os << "<style type='text/css'>\n"
1529 os << "</head>\n<body>\n";
1533 params().documentClass().counters().reset();
1534 xhtmlParagraphs(text(), *this, xs, runparams);
1536 os << "</body>\n</html>\n";
1540 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1541 // Other flags: -wall -v0 -x
1542 int Buffer::runChktex()
1546 // get LaTeX-Filename
1547 FileName const path(temppath());
1548 string const name = addName(path.absFilename(), latexName());
1549 string const org_path = filePath();
1551 PathChanger p(path); // path to LaTeX file
1552 message(_("Running chktex..."));
1554 // Generate the LaTeX file if neccessary
1555 OutputParams runparams(¶ms().encoding());
1556 runparams.flavor = OutputParams::LATEX;
1557 runparams.nice = false;
1558 makeLaTeXFile(FileName(name), org_path, runparams);
1561 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1562 int const res = chktex.run(terr); // run chktex
1565 Alert::error(_("chktex failure"),
1566 _("Could not run chktex successfully."));
1567 } else if (res > 0) {
1568 ErrorList & errlist = d->errorLists["ChkTeX"];
1570 bufferErrors(terr, errlist);
1581 void Buffer::validate(LaTeXFeatures & features) const
1583 params().validate(features);
1587 for_each(paragraphs().begin(), paragraphs().end(),
1588 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1590 if (lyxerr.debugging(Debug::LATEX)) {
1591 features.showStruct();
1596 void Buffer::getLabelList(vector<docstring> & list) const
1598 // If this is a child document, use the parent's list instead.
1599 Buffer const * const pbuf = d->parent();
1601 pbuf->getLabelList(list);
1606 Toc & toc = d->toc_backend.toc("label");
1607 TocIterator toc_it = toc.begin();
1608 TocIterator end = toc.end();
1609 for (; toc_it != end; ++toc_it) {
1610 if (toc_it->depth() == 0)
1611 list.push_back(toc_it->str());
1616 void Buffer::updateBibfilesCache(UpdateScope scope) const
1618 // If this is a child document, use the parent's cache instead.
1619 Buffer const * const pbuf = d->parent();
1620 if (pbuf && scope != UpdateChildOnly) {
1621 pbuf->updateBibfilesCache();
1625 d->bibfiles_cache_.clear();
1626 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1627 if (it->lyxCode() == BIBTEX_CODE) {
1628 InsetBibtex const & inset =
1629 static_cast<InsetBibtex const &>(*it);
1630 support::FileNameList const bibfiles = inset.getBibFiles();
1631 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1634 } else if (it->lyxCode() == INCLUDE_CODE) {
1635 InsetInclude & inset =
1636 static_cast<InsetInclude &>(*it);
1637 inset.updateBibfilesCache();
1638 support::FileNameList const & bibfiles =
1639 inset.getBibfilesCache();
1640 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1645 // the bibinfo cache is now invalid
1646 d->bibinfo_cache_valid_ = false;
1650 void Buffer::invalidateBibinfoCache()
1652 d->bibinfo_cache_valid_ = false;
1656 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1658 // If this is a child document, use the parent's cache instead.
1659 Buffer const * const pbuf = d->parent();
1660 if (pbuf && scope != UpdateChildOnly)
1661 return pbuf->getBibfilesCache();
1663 // We update the cache when first used instead of at loading time.
1664 if (d->bibfiles_cache_.empty())
1665 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1667 return d->bibfiles_cache_;
1671 BiblioInfo const & Buffer::masterBibInfo() const
1673 // if this is a child document and the parent is already loaded
1674 // use the parent's list instead [ale990412]
1675 Buffer const * const tmp = masterBuffer();
1678 return tmp->masterBibInfo();
1679 return localBibInfo();
1683 BiblioInfo const & Buffer::localBibInfo() const
1689 void Buffer::checkBibInfoCache() const
1691 support::FileNameList const & bibfilesCache = getBibfilesCache();
1692 // compare the cached timestamps with the actual ones.
1693 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1694 support::FileNameList::const_iterator en = bibfilesCache.end();
1695 for (; ei != en; ++ ei) {
1696 time_t lastw = ei->lastModified();
1697 time_t prevw = d->bibfile_status_[*ei];
1698 if (lastw != prevw) {
1699 d->bibinfo_cache_valid_ = false;
1700 d->bibfile_status_[*ei] = lastw;
1704 if (!d->bibinfo_cache_valid_) {
1705 d->bibinfo_.clear();
1706 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1707 it->fillWithBibKeys(d->bibinfo_, it);
1708 d->bibinfo_cache_valid_ = true;
1713 bool Buffer::isDepClean(string const & name) const
1715 DepClean::const_iterator const it = d->dep_clean.find(name);
1716 if (it == d->dep_clean.end())
1722 void Buffer::markDepClean(string const & name)
1724 d->dep_clean[name] = true;
1728 bool Buffer::isExportableFormat(string const & format) const
1730 typedef vector<Format const *> Formats;
1732 formats = exportableFormats(true);
1733 Formats::const_iterator fit = formats.begin();
1734 Formats::const_iterator end = formats.end();
1735 for (; fit != end ; ++fit) {
1736 if ((*fit)->name() == format)
1743 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1746 // FIXME? if there is an Buffer LFUN that can be dispatched even
1747 // if internal, put a switch '(cmd.action)' here.
1753 switch (cmd.action) {
1755 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1756 flag.setOnOff(isReadonly());
1759 // FIXME: There is need for a command-line import.
1760 //case LFUN_BUFFER_IMPORT:
1762 case LFUN_BUFFER_AUTO_SAVE:
1765 case LFUN_BUFFER_EXPORT_CUSTOM:
1766 // FIXME: Nothing to check here?
1769 case LFUN_BUFFER_EXPORT: {
1770 docstring const arg = cmd.argument();
1771 enable = arg == "custom" || isExportable(to_utf8(arg));
1773 flag.message(bformat(
1774 _("Don't know how to export to format: %1$s"), arg));
1778 case LFUN_BUFFER_CHKTEX:
1779 enable = isLatex() && !lyxrc.chktex_command.empty();
1782 case LFUN_BUILD_PROGRAM:
1783 enable = isExportable("program");
1786 case LFUN_BRANCH_ACTIVATE:
1787 case LFUN_BRANCH_DEACTIVATE: {
1788 BranchList const & branchList = params().branchlist();
1789 docstring const branchName = cmd.argument();
1790 enable = !branchName.empty() && branchList.find(branchName);
1794 case LFUN_BRANCH_ADD:
1795 case LFUN_BRANCHES_RENAME:
1796 case LFUN_BUFFER_PRINT:
1797 // if no Buffer is present, then of course we won't be called!
1800 case LFUN_BUFFER_LANGUAGE:
1801 enable = !isReadonly();
1807 flag.setEnabled(enable);
1812 void Buffer::dispatch(string const & command, DispatchResult & result)
1814 return dispatch(lyxaction.lookupFunc(command), result);
1818 // NOTE We can end up here even if we have no GUI, because we are called
1819 // by LyX::exec to handled command-line requests. So we may need to check
1820 // whether we have a GUI or not. The boolean use_gui holds this information.
1821 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1824 // FIXME? if there is an Buffer LFUN that can be dispatched even
1825 // if internal, put a switch '(cmd.action)' here.
1826 dr.dispatched(false);
1829 string const argument = to_utf8(func.argument());
1830 // We'll set this back to false if need be.
1831 bool dispatched = true;
1832 undo().beginUndoGroup();
1834 switch (func.action) {
1835 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1836 if (lyxvc().inUse())
1837 lyxvc().toggleReadOnly();
1839 setReadonly(!isReadonly());
1842 case LFUN_BUFFER_EXPORT: {
1843 bool success = doExport(argument, false, false);
1844 dr.setError(success);
1846 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1851 case LFUN_BUILD_PROGRAM:
1852 doExport("program", true, false);
1855 case LFUN_BUFFER_CHKTEX:
1859 case LFUN_BUFFER_EXPORT_CUSTOM: {
1861 string command = split(argument, format_name, ' ');
1862 Format const * format = formats.getFormat(format_name);
1864 lyxerr << "Format \"" << format_name
1865 << "\" not recognized!"
1870 // The name of the file created by the conversion process
1873 // Output to filename
1874 if (format->name() == "lyx") {
1875 string const latexname = latexName(false);
1876 filename = changeExtension(latexname,
1877 format->extension());
1878 filename = addName(temppath(), filename);
1880 if (!writeFile(FileName(filename)))
1884 doExport(format_name, true, false, filename);
1887 // Substitute $$FName for filename
1888 if (!contains(command, "$$FName"))
1889 command = "( " + command + " ) < $$FName";
1890 command = subst(command, "$$FName", filename);
1892 // Execute the command in the background
1894 call.startscript(Systemcall::DontWait, command);
1898 // FIXME: There is need for a command-line import.
1900 case LFUN_BUFFER_IMPORT:
1905 case LFUN_BUFFER_AUTO_SAVE:
1909 case LFUN_BRANCH_ADD: {
1910 docstring const branch_name = func.argument();
1911 if (branch_name.empty()) {
1915 BranchList & branch_list = params().branchlist();
1916 Branch * branch = branch_list.find(branch_name);
1918 LYXERR0("Branch " << branch_name << " already exists.");
1920 docstring const msg =
1921 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1924 branch_list.add(branch_name);
1925 branch = branch_list.find(branch_name);
1926 string const x11hexname = X11hexname(branch->color());
1927 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1928 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1930 dr.update(Update::Force);
1935 case LFUN_BRANCH_ACTIVATE:
1936 case LFUN_BRANCH_DEACTIVATE: {
1937 BranchList & branchList = params().branchlist();
1938 docstring const branchName = func.argument();
1939 // the case without a branch name is handled elsewhere
1940 if (branchName.empty()) {
1944 Branch * branch = branchList.find(branchName);
1946 LYXERR0("Branch " << branchName << " does not exist.");
1948 docstring const msg =
1949 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1952 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1954 dr.update(Update::Force);
1959 case LFUN_BRANCHES_RENAME: {
1960 if (func.argument().empty())
1963 docstring const oldname = from_utf8(func.getArg(0));
1964 docstring const newname = from_utf8(func.getArg(1));
1965 InsetIterator it = inset_iterator_begin(inset());
1966 InsetIterator const end = inset_iterator_end(inset());
1967 bool success = false;
1968 for (; it != end; ++it) {
1969 if (it->lyxCode() == BRANCH_CODE) {
1970 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1971 if (ins.branch() == oldname) {
1972 undo().recordUndo(it);
1973 ins.rename(newname);
1978 if (it->lyxCode() == INCLUDE_CODE) {
1979 // get buffer of external file
1980 InsetInclude const & ins =
1981 static_cast<InsetInclude const &>(*it);
1982 Buffer * child = ins.getChildBuffer();
1985 child->dispatch(func, dr);
1990 dr.update(Update::Force);
1994 case LFUN_BUFFER_PRINT: {
1995 // we'll assume there's a problem until we succeed
1997 string target = func.getArg(0);
1998 string target_name = func.getArg(1);
1999 string command = func.getArg(2);
2002 || target_name.empty()
2003 || command.empty()) {
2004 LYXERR0("Unable to parse " << func.argument());
2005 docstring const msg =
2006 bformat(_("Unable to parse \"%1$s\""), func.argument());
2010 if (target != "printer" && target != "file") {
2011 LYXERR0("Unrecognized target \"" << target << '"');
2012 docstring const msg =
2013 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2018 bool const update_unincluded =
2019 params().maintain_unincluded_children
2020 && !params().getIncludedChildren().empty();
2021 if (!doExport("dvi", true, update_unincluded)) {
2022 showPrintError(absFileName());
2023 dr.setMessage(_("Error exporting to DVI."));
2027 // Push directory path.
2028 string const path = temppath();
2029 // Prevent the compiler from optimizing away p
2033 // there are three cases here:
2034 // 1. we print to a file
2035 // 2. we print directly to a printer
2036 // 3. we print using a spool command (print to file first)
2039 string const dviname = changeExtension(latexName(true), "dvi");
2041 if (target == "printer") {
2042 if (!lyxrc.print_spool_command.empty()) {
2043 // case 3: print using a spool
2044 string const psname = changeExtension(dviname,".ps");
2045 command += ' ' + lyxrc.print_to_file
2048 + quoteName(dviname);
2050 string command2 = lyxrc.print_spool_command + ' ';
2051 if (target_name != "default") {
2052 command2 += lyxrc.print_spool_printerprefix
2056 command2 += quoteName(psname);
2058 // If successful, then spool command
2059 res = one.startscript(Systemcall::Wait, command);
2062 // If there's no GUI, we have to wait on this command. Otherwise,
2063 // LyX deletes the temporary directory, and with it the spooled
2064 // file, before it can be printed!!
2065 Systemcall::Starttype stype = use_gui ?
2066 Systemcall::DontWait : Systemcall::Wait;
2067 res = one.startscript(stype, command2);
2070 // case 2: print directly to a printer
2071 if (target_name != "default")
2072 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2074 Systemcall::Starttype stype = use_gui ?
2075 Systemcall::DontWait : Systemcall::Wait;
2076 res = one.startscript(stype, command + quoteName(dviname));
2080 // case 1: print to a file
2081 FileName const filename(makeAbsPath(target_name, filePath()));
2082 FileName const dvifile(makeAbsPath(dviname, path));
2083 if (filename.exists()) {
2084 docstring text = bformat(
2085 _("The file %1$s already exists.\n\n"
2086 "Do you want to overwrite that file?"),
2087 makeDisplayPath(filename.absFilename()));
2088 if (Alert::prompt(_("Overwrite file?"),
2089 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2092 command += ' ' + lyxrc.print_to_file
2093 + quoteName(filename.toFilesystemEncoding())
2095 + quoteName(dvifile.toFilesystemEncoding());
2097 Systemcall::Starttype stype = use_gui ?
2098 Systemcall::DontWait : Systemcall::Wait;
2099 res = one.startscript(stype, command);
2105 dr.setMessage(_("Error running external commands."));
2106 showPrintError(absFileName());
2111 case LFUN_BUFFER_LANGUAGE: {
2112 Language const * oldL = params().language;
2113 Language const * newL = languages.getLanguage(argument);
2114 if (!newL || oldL == newL)
2116 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2117 changeLanguage(oldL, newL);
2125 dr.dispatched(dispatched);
2126 undo().endUndoGroup();
2130 void Buffer::changeLanguage(Language const * from, Language const * to)
2132 LASSERT(from, /**/);
2135 for_each(par_iterator_begin(),
2137 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2141 bool Buffer::isMultiLingual() const
2143 ParConstIterator end = par_iterator_end();
2144 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2145 if (it->isMultiLingual(params()))
2152 DocIterator Buffer::getParFromID(int const id) const
2154 Buffer * buf = const_cast<Buffer *>(this);
2156 // John says this is called with id == -1 from undo
2157 lyxerr << "getParFromID(), id: " << id << endl;
2158 return doc_iterator_end(buf);
2161 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2162 if (it.paragraph().id() == id)
2165 return doc_iterator_end(buf);
2169 bool Buffer::hasParWithID(int const id) const
2171 return !getParFromID(id).atEnd();
2175 ParIterator Buffer::par_iterator_begin()
2177 return ParIterator(doc_iterator_begin(this));
2181 ParIterator Buffer::par_iterator_end()
2183 return ParIterator(doc_iterator_end(this));
2187 ParConstIterator Buffer::par_iterator_begin() const
2189 return ParConstIterator(doc_iterator_begin(this));
2193 ParConstIterator Buffer::par_iterator_end() const
2195 return ParConstIterator(doc_iterator_end(this));
2199 Language const * Buffer::language() const
2201 return params().language;
2205 docstring const Buffer::B_(string const & l10n) const
2207 return params().B_(l10n);
2211 bool Buffer::isClean() const
2213 return d->lyx_clean;
2217 bool Buffer::isExternallyModified(CheckMethod method) const
2219 LASSERT(d->filename.exists(), /**/);
2220 // if method == timestamp, check timestamp before checksum
2221 return (method == checksum_method
2222 || d->timestamp_ != d->filename.lastModified())
2223 && d->checksum_ != d->filename.checksum();
2227 void Buffer::saveCheckSum(FileName const & file) const
2229 if (file.exists()) {
2230 d->timestamp_ = file.lastModified();
2231 d->checksum_ = file.checksum();
2233 // in the case of save to a new file.
2240 void Buffer::markClean() const
2242 if (!d->lyx_clean) {
2243 d->lyx_clean = true;
2246 // if the .lyx file has been saved, we don't need an
2248 d->bak_clean = true;
2252 void Buffer::setUnnamed(bool flag)
2258 bool Buffer::isUnnamed() const
2265 /// Don't check unnamed, here: isInternal() is used in
2266 /// newBuffer(), where the unnamed flag has not been set by anyone
2267 /// yet. Also, for an internal buffer, there should be no need for
2268 /// retrieving fileName() nor for checking if it is unnamed or not.
2269 bool Buffer::isInternal() const
2271 return fileName().extension() == "internal";
2275 void Buffer::markDirty()
2278 d->lyx_clean = false;
2281 d->bak_clean = false;
2283 DepClean::iterator it = d->dep_clean.begin();
2284 DepClean::const_iterator const end = d->dep_clean.end();
2286 for (; it != end; ++it)
2291 FileName Buffer::fileName() const
2297 string Buffer::absFileName() const
2299 return d->filename.absFilename();
2303 string Buffer::filePath() const
2305 return d->filename.onlyPath().absFilename() + "/";
2309 bool Buffer::isReadonly() const
2311 return d->read_only;
2315 void Buffer::setParent(Buffer const * buffer)
2317 // Avoids recursive include.
2318 d->setParent(buffer == this ? 0 : buffer);
2323 Buffer const * Buffer::parent() const
2329 void Buffer::collectRelatives(BufferSet & bufs) const
2333 parent()->collectRelatives(bufs);
2335 // loop over children
2336 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2337 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2338 for (; it != end; ++it)
2339 bufs.insert(const_cast<Buffer *>(it->first));
2343 std::vector<Buffer const *> Buffer::allRelatives() const
2346 collectRelatives(bufs);
2347 BufferSet::iterator it = bufs.begin();
2348 std::vector<Buffer const *> ret;
2349 for (; it != bufs.end(); ++it)
2355 Buffer const * Buffer::masterBuffer() const
2357 Buffer const * const pbuf = d->parent();
2361 return pbuf->masterBuffer();
2365 bool Buffer::isChild(Buffer * child) const
2367 return d->children_positions.find(child) != d->children_positions.end();
2371 DocIterator Buffer::firstChildPosition(Buffer const * child)
2373 Impl::BufferPositionMap::iterator it;
2374 it = d->children_positions.find(child);
2375 if (it == d->children_positions.end())
2376 return DocIterator(this);
2381 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2383 // loop over children
2384 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2385 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2386 for (; it != end; ++it) {
2387 Buffer * child = const_cast<Buffer *>(it->first);
2388 clist.push_back(child);
2389 if (grand_children) {
2390 // there might be grandchildren
2391 std::vector<Buffer *> glist = child->getChildren();
2392 for (vector<Buffer *>::const_iterator git = glist.begin();
2393 git != glist.end(); ++git)
2394 clist.push_back(*git);
2400 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2402 std::vector<Buffer *> v;
2403 getChildren(v, grand_children);
2408 template<typename M>
2409 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2414 typename M::iterator it = m.lower_bound(x);
2415 if (it == m.begin())
2423 MacroData const * Buffer::getBufferMacro(docstring const & name,
2424 DocIterator const & pos) const
2426 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2428 // if paragraphs have no macro context set, pos will be empty
2432 // we haven't found anything yet
2433 DocIterator bestPos = par_iterator_begin();
2434 MacroData const * bestData = 0;
2436 // find macro definitions for name
2437 Impl::NamePositionScopeMacroMap::iterator nameIt
2438 = d->macros.find(name);
2439 if (nameIt != d->macros.end()) {
2440 // find last definition in front of pos or at pos itself
2441 Impl::PositionScopeMacroMap::const_iterator it
2442 = greatest_below(nameIt->second, pos);
2443 if (it != nameIt->second.end()) {
2445 // scope ends behind pos?
2446 if (pos < it->second.first) {
2447 // Looks good, remember this. If there
2448 // is no external macro behind this,
2449 // we found the right one already.
2450 bestPos = it->first;
2451 bestData = &it->second.second;
2455 // try previous macro if there is one
2456 if (it == nameIt->second.begin())
2463 // find macros in included files
2464 Impl::PositionScopeBufferMap::const_iterator it
2465 = greatest_below(d->position_to_children, pos);
2466 if (it == d->position_to_children.end())
2467 // no children before
2471 // do we know something better (i.e. later) already?
2472 if (it->first < bestPos )
2475 // scope ends behind pos?
2476 if (pos < it->second.first) {
2477 // look for macro in external file
2478 d->macro_lock = true;
2479 MacroData const * data
2480 = it->second.second->getMacro(name, false);
2481 d->macro_lock = false;
2483 bestPos = it->first;
2489 // try previous file if there is one
2490 if (it == d->position_to_children.begin())
2495 // return the best macro we have found
2500 MacroData const * Buffer::getMacro(docstring const & name,
2501 DocIterator const & pos, bool global) const
2506 // query buffer macros
2507 MacroData const * data = getBufferMacro(name, pos);
2511 // If there is a master buffer, query that
2512 Buffer const * const pbuf = d->parent();
2514 d->macro_lock = true;
2515 MacroData const * macro = pbuf->getMacro(
2516 name, *this, false);
2517 d->macro_lock = false;
2523 data = MacroTable::globalMacros().get(name);
2532 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2534 // set scope end behind the last paragraph
2535 DocIterator scope = par_iterator_begin();
2536 scope.pit() = scope.lastpit() + 1;
2538 return getMacro(name, scope, global);
2542 MacroData const * Buffer::getMacro(docstring const & name,
2543 Buffer const & child, bool global) const
2545 // look where the child buffer is included first
2546 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2547 if (it == d->children_positions.end())
2550 // check for macros at the inclusion position
2551 return getMacro(name, it->second, global);
2555 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2557 pit_type const lastpit = it.lastpit();
2559 // look for macros in each paragraph
2560 while (it.pit() <= lastpit) {
2561 Paragraph & par = it.paragraph();
2563 // iterate over the insets of the current paragraph
2564 InsetList const & insets = par.insetList();
2565 InsetList::const_iterator iit = insets.begin();
2566 InsetList::const_iterator end = insets.end();
2567 for (; iit != end; ++iit) {
2568 it.pos() = iit->pos;
2570 // is it a nested text inset?
2571 if (iit->inset->asInsetText()) {
2572 // Inset needs its own scope?
2573 InsetText const * itext = iit->inset->asInsetText();
2574 bool newScope = itext->isMacroScope();
2576 // scope which ends just behind the inset
2577 DocIterator insetScope = it;
2580 // collect macros in inset
2581 it.push_back(CursorSlice(*iit->inset));
2582 updateMacros(it, newScope ? insetScope : scope);
2587 // is it an external file?
2588 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2589 // get buffer of external file
2590 InsetInclude const & inset =
2591 static_cast<InsetInclude const &>(*iit->inset);
2592 d->macro_lock = true;
2593 Buffer * child = inset.getChildBuffer();
2594 d->macro_lock = false;
2598 // register its position, but only when it is
2599 // included first in the buffer
2600 if (d->children_positions.find(child) ==
2601 d->children_positions.end())
2602 d->children_positions[child] = it;
2604 // register child with its scope
2605 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2609 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2613 MathMacroTemplate & macroTemplate =
2614 static_cast<MathMacroTemplate &>(*iit->inset);
2615 MacroContext mc(this, it);
2616 macroTemplate.updateToContext(mc);
2619 bool valid = macroTemplate.validMacro();
2620 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2621 // then the BufferView's cursor will be invalid in
2622 // some cases which leads to crashes.
2627 // FIXME (Abdel), I don't understandt why we pass 'it' here
2628 // instead of 'macroTemplate' defined above... is this correct?
2629 d->macros[macroTemplate.name()][it] =
2630 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2640 void Buffer::updateMacros() const
2645 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2647 // start with empty table
2649 d->children_positions.clear();
2650 d->position_to_children.clear();
2652 // Iterate over buffer, starting with first paragraph
2653 // The scope must be bigger than any lookup DocIterator
2654 // later. For the global lookup, lastpit+1 is used, hence
2655 // we use lastpit+2 here.
2656 DocIterator it = par_iterator_begin();
2657 DocIterator outerScope = it;
2658 outerScope.pit() = outerScope.lastpit() + 2;
2659 updateMacros(it, outerScope);
2663 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2665 InsetIterator it = inset_iterator_begin(inset());
2666 InsetIterator const end = inset_iterator_end(inset());
2667 for (; it != end; ++it) {
2668 if (it->lyxCode() == BRANCH_CODE) {
2669 InsetBranch & br = static_cast<InsetBranch &>(*it);
2670 docstring const name = br.branch();
2671 if (!from_master && !params().branchlist().find(name))
2672 result.push_back(name);
2673 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2674 result.push_back(name);
2677 if (it->lyxCode() == INCLUDE_CODE) {
2678 // get buffer of external file
2679 InsetInclude const & ins =
2680 static_cast<InsetInclude const &>(*it);
2681 Buffer * child = ins.getChildBuffer();
2684 child->getUsedBranches(result, true);
2687 // remove duplicates
2692 void Buffer::updateMacroInstances() const
2694 LYXERR(Debug::MACROS, "updateMacroInstances for "
2695 << d->filename.onlyFileName());
2696 DocIterator it = doc_iterator_begin(this);
2698 DocIterator const end = doc_iterator_end(this);
2699 for (; it != end; it.forwardInset()) {
2700 // look for MathData cells in InsetMathNest insets
2701 InsetMath * minset = it.nextInset()->asInsetMath();
2705 // update macro in all cells of the InsetMathNest
2706 DocIterator::idx_type n = minset->nargs();
2707 MacroContext mc = MacroContext(this, it);
2708 for (DocIterator::idx_type i = 0; i < n; ++i) {
2709 MathData & data = minset->cell(i);
2710 data.updateMacros(0, mc);
2716 void Buffer::listMacroNames(MacroNameSet & macros) const
2721 d->macro_lock = true;
2723 // loop over macro names
2724 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2725 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2726 for (; nameIt != nameEnd; ++nameIt)
2727 macros.insert(nameIt->first);
2729 // loop over children
2730 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2731 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2732 for (; it != end; ++it)
2733 it->first->listMacroNames(macros);
2736 Buffer const * const pbuf = d->parent();
2738 pbuf->listMacroNames(macros);
2740 d->macro_lock = false;
2744 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2746 Buffer const * const pbuf = d->parent();
2751 pbuf->listMacroNames(names);
2754 MacroNameSet::iterator it = names.begin();
2755 MacroNameSet::iterator end = names.end();
2756 for (; it != end; ++it) {
2758 MacroData const * data =
2759 pbuf->getMacro(*it, *this, false);
2761 macros.insert(data);
2763 // we cannot access the original MathMacroTemplate anymore
2764 // here to calls validate method. So we do its work here manually.
2765 // FIXME: somehow make the template accessible here.
2766 if (data->optionals() > 0)
2767 features.require("xargs");
2773 Buffer::References & Buffer::references(docstring const & label)
2776 return const_cast<Buffer *>(masterBuffer())->references(label);
2778 RefCache::iterator it = d->ref_cache_.find(label);
2779 if (it != d->ref_cache_.end())
2780 return it->second.second;
2782 static InsetLabel const * dummy_il = 0;
2783 static References const dummy_refs;
2784 it = d->ref_cache_.insert(
2785 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2786 return it->second.second;
2790 Buffer::References const & Buffer::references(docstring const & label) const
2792 return const_cast<Buffer *>(this)->references(label);
2796 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2798 masterBuffer()->d->ref_cache_[label].first = il;
2802 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2804 return masterBuffer()->d->ref_cache_[label].first;
2808 void Buffer::clearReferenceCache() const
2811 d->ref_cache_.clear();
2815 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2818 //FIXME: This does not work for child documents yet.
2819 LASSERT(code == CITE_CODE, /**/);
2820 // Check if the label 'from' appears more than once
2821 vector<docstring> labels;
2823 checkBibInfoCache();
2824 BiblioInfo const & keys = masterBibInfo();
2825 BiblioInfo::const_iterator bit = keys.begin();
2826 BiblioInfo::const_iterator bend = keys.end();
2828 for (; bit != bend; ++bit)
2830 labels.push_back(bit->first);
2833 if (count(labels.begin(), labels.end(), from) > 1)
2836 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2837 if (it->lyxCode() == code) {
2838 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2839 docstring const oldValue = inset.getParam(paramName);
2840 if (oldValue == from)
2841 inset.setParam(paramName, to);
2847 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2848 pit_type par_end, bool full_source) const
2850 OutputParams runparams(¶ms().encoding());
2851 runparams.nice = true;
2852 runparams.flavor = params().useXetex ?
2853 OutputParams::XETEX : OutputParams::LATEX;
2854 runparams.linelen = lyxrc.plaintext_linelen;
2855 // No side effect of file copying and image conversion
2856 runparams.dryrun = true;
2859 os << "% " << _("Preview source code") << "\n\n";
2861 d->texrow.newline();
2862 d->texrow.newline();
2864 writeDocBookSource(os, absFileName(), runparams, false);
2866 // latex or literate
2867 writeLaTeXSource(os, string(), runparams, true, true);
2869 runparams.par_begin = par_begin;
2870 runparams.par_end = par_end;
2871 if (par_begin + 1 == par_end) {
2873 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2877 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2878 convert<docstring>(par_begin),
2879 convert<docstring>(par_end - 1))
2886 // output paragraphs
2888 docbookParagraphs(text(), *this, os, runparams);
2890 // latex or literate
2891 latexParagraphs(*this, text(), os, texrow, runparams);
2896 ErrorList & Buffer::errorList(string const & type) const
2898 static ErrorList emptyErrorList;
2899 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2900 if (I == d->errorLists.end())
2901 return emptyErrorList;
2907 void Buffer::updateTocItem(std::string const & type,
2908 DocIterator const & dit) const
2911 gui_->updateTocItem(type, dit);
2915 void Buffer::structureChanged() const
2918 gui_->structureChanged();
2922 void Buffer::errors(string const & err, bool from_master) const
2925 gui_->errors(err, from_master);
2929 void Buffer::message(docstring const & msg) const
2936 void Buffer::setBusy(bool on) const
2943 void Buffer::updateTitles() const
2946 d->wa_->updateTitles();
2950 void Buffer::resetAutosaveTimers() const
2953 gui_->resetAutosaveTimers();
2957 bool Buffer::hasGuiDelegate() const
2963 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2972 class AutoSaveBuffer : public ForkedProcess {
2975 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2976 : buffer_(buffer), fname_(fname) {}
2978 virtual boost::shared_ptr<ForkedProcess> clone() const
2980 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2985 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2986 from_utf8(fname_.absFilename())));
2987 return run(DontWait);
2991 virtual int generateChild();
2993 Buffer const & buffer_;
2998 int AutoSaveBuffer::generateChild()
3000 #if defined(__APPLE__)
3001 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3002 * We should use something else like threads.
3004 * Since I do not know how to determine at run time what is the OS X
3005 * version, I just disable forking altogether for now (JMarc)
3007 pid_t const pid = -1;
3009 // tmp_ret will be located (usually) in /tmp
3010 // will that be a problem?
3011 // Note that this calls ForkedCalls::fork(), so it's
3012 // ok cross-platform.
3013 pid_t const pid = fork();
3014 // If you want to debug the autosave
3015 // you should set pid to -1, and comment out the fork.
3016 if (pid != 0 && pid != -1)
3020 // pid = -1 signifies that lyx was unable
3021 // to fork. But we will do the save
3023 bool failed = false;
3024 FileName const tmp_ret = FileName::tempName("lyxauto");
3025 if (!tmp_ret.empty()) {
3026 buffer_.writeFile(tmp_ret);
3027 // assume successful write of tmp_ret
3028 if (!tmp_ret.moveTo(fname_))
3034 // failed to write/rename tmp_ret so try writing direct
3035 if (!buffer_.writeFile(fname_)) {
3036 // It is dangerous to do this in the child,
3037 // but safe in the parent, so...
3038 if (pid == -1) // emit message signal.
3039 buffer_.message(_("Autosave failed!"));
3043 if (pid == 0) // we are the child so...
3052 FileName Buffer::getAutosaveFilename() const
3054 // if the document is unnamed try to save in the backup dir, else
3055 // in the default document path, and as a last try in the filePath,
3056 // which will most often be the temporary directory
3059 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3060 : lyxrc.backupdir_path;
3061 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3064 string const fname = "#" + d->filename.onlyFileName() + "#";
3065 return makeAbsPath(fname, fpath);
3069 void Buffer::removeAutosaveFile() const
3071 FileName const f = getAutosaveFilename();
3077 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3079 FileName const newauto = getAutosaveFilename();
3080 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3081 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3085 // Perfect target for a thread...
3086 void Buffer::autoSave() const
3088 if (d->bak_clean || isReadonly()) {
3089 // We don't save now, but we'll try again later
3090 resetAutosaveTimers();
3094 // emit message signal.
3095 message(_("Autosaving current document..."));
3096 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3099 d->bak_clean = true;
3101 resetAutosaveTimers();
3105 string Buffer::bufferFormat() const
3107 string format = params().documentClass().outputFormat();
3108 if (format == "latex") {
3109 if (params().useXetex)
3111 if (params().encoding().package() == Encoding::japanese)
3118 string Buffer::getDefaultOutputFormat() const
3120 if (!params().defaultOutputFormat.empty()
3121 && params().defaultOutputFormat != "default")
3122 return params().defaultOutputFormat;
3123 typedef vector<Format const *> Formats;
3124 Formats formats = exportableFormats(true);
3127 || params().useXetex
3128 || params().encoding().package() == Encoding::japanese) {
3129 if (formats.empty())
3131 // return the first we find
3132 return formats.front()->name();
3134 return lyxrc.default_view_format;
3139 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3140 bool includeall, string & result_file) const
3142 string backend_format;
3143 OutputParams runparams(¶ms().encoding());
3144 runparams.flavor = OutputParams::LATEX;
3145 runparams.linelen = lyxrc.plaintext_linelen;
3146 runparams.includeall = includeall;
3147 vector<string> backs = backends();
3148 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3149 // Get shortest path to format
3150 Graph::EdgePath path;
3151 for (vector<string>::const_iterator it = backs.begin();
3152 it != backs.end(); ++it) {
3153 Graph::EdgePath p = theConverters().getPath(*it, format);
3154 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3155 backend_format = *it;
3160 if (!put_in_tempdir) {
3161 // Only show this alert if this is an export to a non-temporary
3162 // file (not for previewing).
3163 Alert::error(_("Couldn't export file"), bformat(
3164 _("No information for exporting the format %1$s."),
3165 formats.prettyName(format)));
3169 runparams.flavor = theConverters().getFlavor(path);
3172 backend_format = format;
3173 // FIXME: Don't hardcode format names here, but use a flag
3174 if (backend_format == "pdflatex")
3175 runparams.flavor = OutputParams::PDFLATEX;
3178 string filename = latexName(false);
3179 filename = addName(temppath(), filename);
3180 filename = changeExtension(filename,
3181 formats.extension(backend_format));
3184 updateMacroInstances();
3186 // Plain text backend
3187 if (backend_format == "text") {
3188 runparams.flavor = OutputParams::TEXT;
3189 writePlaintextFile(*this, FileName(filename), runparams);
3192 else if (backend_format == "xhtml") {
3193 runparams.flavor = OutputParams::HTML;
3194 makeLyXHTMLFile(FileName(filename), runparams);
3195 } else if (backend_format == "lyx")
3196 writeFile(FileName(filename));
3198 else if (isDocBook()) {
3199 runparams.nice = !put_in_tempdir;
3200 makeDocBookFile(FileName(filename), runparams);
3203 else if (backend_format == format) {
3204 runparams.nice = true;
3205 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3207 } else if (!lyxrc.tex_allows_spaces
3208 && contains(filePath(), ' ')) {
3209 Alert::error(_("File name error"),
3210 _("The directory path to the document cannot contain spaces."));
3213 runparams.nice = false;
3214 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3218 string const error_type = (format == "program")
3219 ? "Build" : bufferFormat();
3220 ErrorList & error_list = d->errorLists[error_type];
3221 string const ext = formats.extension(format);
3222 FileName const tmp_result_file(changeExtension(filename, ext));
3223 bool const success = theConverters().convert(this, FileName(filename),
3224 tmp_result_file, FileName(absFileName()), backend_format, format,
3226 // Emit the signal to show the error list.
3227 if (format != backend_format) {
3229 // also to the children, in case of master-buffer-view
3230 std::vector<Buffer *> clist = getChildren();
3231 for (vector<Buffer *>::const_iterator cit = clist.begin();
3232 cit != clist.end(); ++cit)
3233 (*cit)->errors(error_type, true);
3238 if (d->cloned_buffer_) {
3239 // Enable reverse dvi or pdf to work by copying back the texrow
3240 // object to the cloned buffer.
3241 // FIXME: There is a possibility of concurrent access to texrow
3242 // here from the main GUI thread that should be securized.
3243 d->cloned_buffer_->d->texrow = d->texrow;
3246 if (put_in_tempdir) {
3247 result_file = tmp_result_file.absFilename();
3251 result_file = changeExtension(exportFileName().absFilename(), ext);
3252 // We need to copy referenced files (e. g. included graphics
3253 // if format == "dvi") to the result dir.
3254 vector<ExportedFile> const files =
3255 runparams.exportdata->externalFiles(format);
3256 string const dest = onlyPath(result_file);
3257 CopyStatus status = SUCCESS;
3259 vector<ExportedFile>::const_iterator it = files.begin();
3260 vector<ExportedFile>::const_iterator const en = files.end();
3261 for (; it != en && status != CANCEL; ++it) {
3262 string const fmt = formats.getFormatFromFile(it->sourceName);
3263 status = copyFile(fmt, it->sourceName,
3264 makeAbsPath(it->exportName, dest),
3265 it->exportName, status == FORCE);
3268 if (status == CANCEL) {
3269 message(_("Document export cancelled."));
3270 } else if (tmp_result_file.exists()) {
3271 // Finally copy the main file
3272 status = copyFile(format, tmp_result_file,
3273 FileName(result_file), result_file,
3275 message(bformat(_("Document exported as %1$s "
3277 formats.prettyName(format),
3278 makeDisplayPath(result_file)));
3280 // This must be a dummy converter like fax (bug 1888)
3281 message(bformat(_("Document exported as %1$s"),
3282 formats.prettyName(format)));
3289 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3290 bool includeall) const
3293 // (1) export with all included children (omit \includeonly)
3294 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3296 // (2) export with included children only
3297 return doExport(format, put_in_tempdir, false, result_file);
3301 bool Buffer::preview(string const & format, bool includeall) const
3304 // (1) export with all included children (omit \includeonly)
3305 if (includeall && !doExport(format, true, true))
3307 // (2) export with included children only
3308 if (!doExport(format, true, false, result_file))
3310 return formats.view(*this, FileName(result_file), format);
3314 bool Buffer::isExportable(string const & format) const
3316 vector<string> backs = backends();
3317 for (vector<string>::const_iterator it = backs.begin();
3318 it != backs.end(); ++it)
3319 if (theConverters().isReachable(*it, format))
3325 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3327 vector<string> const backs = backends();
3328 vector<Format const *> result =
3329 theConverters().getReachable(backs[0], only_viewable, true);
3330 for (vector<string>::const_iterator it = backs.begin() + 1;
3331 it != backs.end(); ++it) {
3332 vector<Format const *> r =
3333 theConverters().getReachable(*it, only_viewable, false);
3334 result.insert(result.end(), r.begin(), r.end());
3340 vector<string> Buffer::backends() const
3343 v.push_back(bufferFormat());
3344 // FIXME: Don't hardcode format names here, but use a flag
3345 if (v.back() == "latex")
3346 v.push_back("pdflatex");
3347 v.push_back("xhtml");
3348 v.push_back("text");
3354 bool Buffer::readFileHelper(FileName const & s)
3356 // File information about normal file
3358 docstring const file = makeDisplayPath(s.absFilename(), 50);
3359 docstring text = bformat(_("The specified document\n%1$s"
3360 "\ncould not be read."), file);
3361 Alert::error(_("Could not read document"), text);
3365 // Check if emergency save file exists and is newer.
3366 FileName const e(s.absFilename() + ".emergency");
3368 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3369 docstring const file = makeDisplayPath(s.absFilename(), 20);
3370 docstring const text =
3371 bformat(_("An emergency save of the document "
3373 "Recover emergency save?"), file);
3374 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3375 _("&Recover"), _("&Load Original"),
3379 // the file is not saved if we load the emergency file.
3384 if ((res = readFile(e)) == success)
3385 str = _("Document was successfully recovered.");
3387 str = _("Document was NOT successfully recovered.");
3388 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3389 from_utf8(e.absFilename()));
3391 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3392 _("&Remove"), _("&Keep it"))) {
3395 Alert::warning(_("Emergency file deleted"),
3396 _("Do not forget to save your file now!"), true);
3401 if (!Alert::prompt(_("Delete emergency file?"),
3402 _("Remove emergency file now?"), 1, 1,
3403 _("&Remove"), _("&Keep it")))
3411 // Now check if autosave file is newer.
3412 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3414 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3415 docstring const file = makeDisplayPath(s.absFilename(), 20);
3416 docstring const text =
3417 bformat(_("The backup of the document "
3418 "%1$s is newer.\n\nLoad the "
3419 "backup instead?"), file);
3420 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3421 _("&Load backup"), _("Load &original"),
3425 // the file is not saved if we load the autosave file.
3429 // Here we delete the autosave
3440 bool Buffer::loadLyXFile(FileName const & s)
3442 // If the file is not readable, we try to
3443 // retrieve the file from version control.
3444 if (!s.isReadableFile()
3445 && !LyXVC::file_not_found_hook(s))
3448 if (s.isReadableFile()
3449 && readFileHelper(s)) {
3450 lyxvc().file_found_hook(s);
3451 setReadonly(!s.isWritable());
3458 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3460 TeXErrors::Errors::const_iterator cit = terr.begin();
3461 TeXErrors::Errors::const_iterator end = terr.end();
3463 for (; cit != end; ++cit) {
3466 int errorRow = cit->error_in_line;
3467 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3473 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3474 } while (found && id_start == id_end && pos_start == pos_end);
3476 errorList.push_back(ErrorItem(cit->error_desc,
3477 cit->error_text, id_start, pos_start, pos_end));
3482 void Buffer::setBuffersForInsets() const
3484 inset().setBuffer(const_cast<Buffer &>(*this));
3488 void Buffer::updateLabels(UpdateScope scope, UpdateType utype) const
3490 // Use the master text class also for child documents
3491 Buffer const * const master = masterBuffer();
3492 DocumentClass const & textclass = master->params().documentClass();
3494 // do this only if we are the top-level Buffer
3495 if (scope != UpdateMaster || master == this)
3496 checkBibInfoCache();
3498 // keep the buffers to be children in this set. If the call from the
3499 // master comes back we can see which of them were actually seen (i.e.
3500 // via an InsetInclude). The remaining ones in the set need still be updated.
3501 static std::set<Buffer const *> bufToUpdate;
3502 if (scope == UpdateMaster) {
3503 // If this is a child document start with the master
3504 if (master != this) {
3505 bufToUpdate.insert(this);
3506 master->updateLabels(UpdateMaster, utype);
3507 // Do this here in case the master has no gui associated with it. Then,
3508 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3512 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3513 if (bufToUpdate.find(this) == bufToUpdate.end())
3517 // start over the counters in the master
3518 textclass.counters().reset();
3521 // update will be done below for this buffer
3522 bufToUpdate.erase(this);
3524 // update all caches
3525 clearReferenceCache();
3528 Buffer & cbuf = const_cast<Buffer &>(*this);
3530 LASSERT(!text().paragraphs().empty(), /**/);
3533 ParIterator parit = cbuf.par_iterator_begin();
3534 updateLabels(parit, utype);
3537 // TocBackend update will be done later.
3540 cbuf.tocBackend().update();
3541 if (scope == UpdateMaster)
3542 cbuf.structureChanged();
3546 static depth_type getDepth(DocIterator const & it)
3548 depth_type depth = 0;
3549 for (size_t i = 0 ; i < it.depth() ; ++i)
3550 if (!it[i].inset().inMathed())
3551 depth += it[i].paragraph().getDepth() + 1;
3552 // remove 1 since the outer inset does not count
3556 static depth_type getItemDepth(ParIterator const & it)
3558 Paragraph const & par = *it;
3559 LabelType const labeltype = par.layout().labeltype;
3561 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3564 // this will hold the lowest depth encountered up to now.
3565 depth_type min_depth = getDepth(it);
3566 ParIterator prev_it = it;
3569 --prev_it.top().pit();
3571 // start of nested inset: go to outer par
3573 if (prev_it.empty()) {
3574 // start of document: nothing to do
3579 // We search for the first paragraph with same label
3580 // that is not more deeply nested.
3581 Paragraph & prev_par = *prev_it;
3582 depth_type const prev_depth = getDepth(prev_it);
3583 if (labeltype == prev_par.layout().labeltype) {
3584 if (prev_depth < min_depth)
3585 return prev_par.itemdepth + 1;
3586 if (prev_depth == min_depth)
3587 return prev_par.itemdepth;
3589 min_depth = min(min_depth, prev_depth);
3590 // small optimization: if we are at depth 0, we won't
3591 // find anything else
3592 if (prev_depth == 0)
3598 static bool needEnumCounterReset(ParIterator const & it)
3600 Paragraph const & par = *it;
3601 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3602 depth_type const cur_depth = par.getDepth();
3603 ParIterator prev_it = it;
3604 while (prev_it.pit()) {
3605 --prev_it.top().pit();
3606 Paragraph const & prev_par = *prev_it;
3607 if (prev_par.getDepth() <= cur_depth)
3608 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3610 // start of nested inset: reset
3615 // set the label of a paragraph. This includes the counters.
3616 void Buffer::setLabel(ParIterator & it, UpdateType utype) const
3618 BufferParams const & bp = this->masterBuffer()->params();
3619 DocumentClass const & textclass = bp.documentClass();
3620 Paragraph & par = it.paragraph();
3621 Layout const & layout = par.layout();
3622 Counters & counters = textclass.counters();
3624 if (par.params().startOfAppendix()) {
3625 // FIXME: only the counter corresponding to toplevel
3626 // sectioning should be reset
3628 counters.appendix(true);
3630 par.params().appendix(counters.appendix());
3632 // Compute the item depth of the paragraph
3633 par.itemdepth = getItemDepth(it);
3635 if (layout.margintype == MARGIN_MANUAL
3636 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3637 if (par.params().labelWidthString().empty())
3638 par.params().labelWidthString(par.expandLabel(layout, bp));
3640 par.params().labelWidthString(docstring());
3643 switch(layout.labeltype) {
3645 if (layout.toclevel <= bp.secnumdepth
3646 && (layout.latextype != LATEX_ENVIRONMENT
3647 || it.text()->isFirstInSequence(it.pit()))) {
3648 counters.step(layout.counter, utype);
3649 par.params().labelString(
3650 par.expandLabel(layout, bp));
3652 par.params().labelString(docstring());
3655 case LABEL_ITEMIZE: {
3656 // At some point of time we should do something more
3657 // clever here, like:
3658 // par.params().labelString(
3659 // bp.user_defined_bullet(par.itemdepth).getText());
3660 // for now, use a simple hardcoded label
3661 docstring itemlabel;
3662 switch (par.itemdepth) {
3664 itemlabel = char_type(0x2022);
3667 itemlabel = char_type(0x2013);
3670 itemlabel = char_type(0x2217);
3673 itemlabel = char_type(0x2219); // or 0x00b7
3676 par.params().labelString(itemlabel);
3680 case LABEL_ENUMERATE: {
3681 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3683 switch (par.itemdepth) {
3692 enumcounter += "iv";
3695 // not a valid enumdepth...
3699 // Maybe we have to reset the enumeration counter.
3700 if (needEnumCounterReset(it))
3701 counters.reset(enumcounter);
3702 counters.step(enumcounter, utype);
3704 string const & lang = par.getParLanguage(bp)->code();
3705 par.params().labelString(counters.theCounter(enumcounter, lang));
3710 case LABEL_SENSITIVE: {
3711 string const & type = counters.current_float();
3712 docstring full_label;
3714 full_label = this->B_("Senseless!!! ");
3716 docstring name = this->B_(textclass.floats().getType(type).name());
3717 if (counters.hasCounter(from_utf8(type))) {
3718 string const & lang = par.getParLanguage(bp)->code();
3719 counters.step(from_utf8(type), utype);
3720 full_label = bformat(from_ascii("%1$s %2$s:"),
3722 counters.theCounter(from_utf8(type), lang));
3724 full_label = bformat(from_ascii("%1$s #:"), name);
3726 par.params().labelString(full_label);
3730 case LABEL_NO_LABEL:
3731 par.params().labelString(docstring());
3735 case LABEL_TOP_ENVIRONMENT:
3736 case LABEL_CENTERED_TOP_ENVIRONMENT:
3739 par.params().labelString(par.expandLabel(layout, bp));
3745 void Buffer::updateLabels(ParIterator & parit, UpdateType utype) const
3747 LASSERT(parit.pit() == 0, /**/);
3749 // set the position of the text in the buffer to be able
3750 // to resolve macros in it. This has nothing to do with
3751 // labels, but by putting it here we avoid implementing
3752 // a whole bunch of traversal routines just for this call.
3753 parit.text()->setMacrocontextPosition(parit);
3755 depth_type maxdepth = 0;
3756 pit_type const lastpit = parit.lastpit();
3757 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3758 // reduce depth if necessary
3759 parit->params().depth(min(parit->params().depth(), maxdepth));
3760 maxdepth = parit->getMaxDepthAfter();
3762 if (utype == OutputUpdate) {
3763 // track the active counters
3764 // we have to do this for the master buffer, since the local
3765 // buffer isn't tracking anything.
3766 masterBuffer()->params().documentClass().counters().
3767 setActiveLayout(parit->layout());
3770 // set the counter for this paragraph
3771 setLabel(parit, utype);
3774 InsetList::const_iterator iit = parit->insetList().begin();
3775 InsetList::const_iterator end = parit->insetList().end();
3776 for (; iit != end; ++iit) {
3777 parit.pos() = iit->pos;
3778 iit->inset->updateLabels(parit, utype);
3784 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3785 WordLangTuple & word_lang, docstring_list & suggestions) const
3789 suggestions.clear();
3790 word_lang = WordLangTuple();
3791 // OK, we start from here.
3792 DocIterator const end = doc_iterator_end(this);
3793 for (; from != end; from.forwardPos()) {
3794 // We are only interested in text so remove the math CursorSlice.
3795 while (from.inMathed()) {
3799 // If from is at the end of the document (which is possible
3800 // when leaving the mathed) LyX will crash later.
3804 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3809 // Do not increase progress when from == to, otherwise the word
3810 // count will be wrong.
3820 bool Buffer::reload()
3823 // e.g., read-only status could have changed due to version control
3824 d->filename.refresh();
3825 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3827 bool const success = loadLyXFile(d->filename);
3832 message(bformat(_("Document %1$s reloaded."), disp_fn));
3834 message(bformat(_("Could not reload document %1$s."), disp_fn));