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_;
222 frontend::GuiBufferDelegate * gui_;
227 /// A cache for the bibfiles (including bibfiles of loaded child
228 /// documents), needed for appropriate update of natbib labels.
229 mutable support::FileNameList bibfiles_cache_;
231 // FIXME The caching mechanism could be improved. At present, we have a
232 // cache for each Buffer, that caches all the bibliography info for that
233 // Buffer. A more efficient solution would be to have a global cache per
234 // file, and then to construct the Buffer's bibinfo from that.
235 /// A cache for bibliography info
236 mutable BiblioInfo bibinfo_;
237 /// whether the bibinfo cache is valid
238 bool bibinfo_cache_valid_;
239 /// Cache of timestamps of .bib files
240 map<FileName, time_t> bibfile_status_;
242 mutable RefCache ref_cache_;
244 /// our Text that should be wrapped in an InsetText
247 /// This is here to force the test to be done whenever parent_buffer
249 Buffer const * parent() const {
250 // if parent_buffer is not loaded, then it has been unloaded,
251 // which means that parent_buffer is an invalid pointer. So we
252 // set it to null in that case.
253 // however, the BufferList doesn't know about cloned buffers, so
254 // they will always be regarded as unloaded. in that case, we hope
256 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
258 return parent_buffer;
261 void setParent(Buffer const * pb) {
262 if (parent_buffer && pb && parent_buffer != pb)
263 LYXERR0("Warning: a buffer should not have two parents!");
267 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
268 /// This one is useful for preview detached in a thread.
269 Buffer const * cloned_buffer_;
272 /// So we can force access via the accessors.
273 mutable Buffer const * parent_buffer;
278 /// Creates the per buffer temporary directory
279 static FileName createBufferTmpDir()
282 // We are in our own directory. Why bother to mangle name?
283 // In fact I wrote this code to circumvent a problematic behaviour
284 // (bug?) of EMX mkstemp().
285 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
286 convert<string>(count++));
288 if (!tmpfl.createDirectory(0777)) {
289 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
290 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
291 from_utf8(tmpfl.absFilename())));
297 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
298 Buffer const * cloned_buffer)
299 : lyx_clean(true), bak_clean(true), unnamed(false),
300 read_only(readonly_), filename(file), file_fully_loaded(false),
301 toc_backend(&parent), macro_lock(false), timestamp_(0),
302 checksum_(0), wa_(0), gui_(0), undo_(parent), bibinfo_cache_valid_(false),
303 cloned_buffer_(cloned_buffer), parent_buffer(0)
305 if (!cloned_buffer_) {
306 temppath = createBufferTmpDir();
307 lyxvc.setBuffer(&parent);
309 wa_ = new frontend::WorkAreaManager;
312 temppath = cloned_buffer_->d->temppath;
313 file_fully_loaded = true;
314 params = cloned_buffer_->d->params;
315 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
316 bibinfo_ = cloned_buffer_->d->bibinfo_;
317 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
318 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
322 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
323 : d(new Impl(*this, FileName(file), readonly, cloned_buffer))
325 LYXERR(Debug::INFO, "Buffer::Buffer()");
327 d->inset = new InsetText(*cloned_buffer->d->inset);
328 d->inset->setBuffer(*this);
329 // FIXME: optimize this loop somewhat, maybe by creating a new
330 // general recursive Inset::setId().
331 DocIterator it = doc_iterator_begin(this);
332 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
333 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
334 it.paragraph().setId(cloned_it.paragraph().id());
336 d->inset = new InsetText(this);
337 d->inset->setAutoBreakRows(true);
338 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
344 LYXERR(Debug::INFO, "Buffer::~Buffer()");
345 // here the buffer should take care that it is
346 // saved properly, before it goes into the void.
348 // GuiView already destroyed
352 // No need to do additional cleanups for internal buffer.
357 // loop over children
358 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
359 Impl::BufferPositionMap::iterator end = d->children_positions.end();
360 for (; it != end; ++it) {
361 Buffer * child = const_cast<Buffer *>(it->first);
362 if (d->cloned_buffer_)
364 // The child buffer might have been closed already.
365 else if (theBufferList().isLoaded(child))
366 theBufferList().releaseChild(this, child);
370 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
371 msg += emergencyWrite();
372 Alert::warning(_("Attempting to close changed document!"), msg);
375 // clear references to children in macro tables
376 d->children_positions.clear();
377 d->position_to_children.clear();
379 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
380 Alert::warning(_("Could not remove temporary directory"),
381 bformat(_("Could not remove the temporary directory %1$s"),
382 from_utf8(d->temppath.absFilename())));
385 // Remove any previewed LaTeX snippets associated with this buffer.
386 thePreviews().removeLoader(*this);
392 Buffer * Buffer::clone() const
394 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
395 buffer_clone->d->macro_lock = true;
396 buffer_clone->d->children_positions.clear();
397 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
398 // math macro caches need to be rethought and simplified.
399 // I am not sure wether we should handle Buffer cloning here or in BufferList.
400 // Right now BufferList knows nothing about buffer clones.
401 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
402 Impl::BufferPositionMap::iterator end = d->children_positions.end();
403 for (; it != end; ++it) {
404 DocIterator dit = it->second.clone(buffer_clone);
405 dit.setBuffer(buffer_clone);
406 Buffer * child = const_cast<Buffer *>(it->first);
407 Buffer * child_clone = child->clone();
408 Inset * inset = dit.nextInset();
409 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
410 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
411 inset_inc->setChildBuffer(child_clone);
412 child_clone->d->setParent(buffer_clone);
413 buffer_clone->setChild(dit, child_clone);
415 buffer_clone->d->macro_lock = false;
420 bool Buffer::isClone() const
422 return d->cloned_buffer_;
426 void Buffer::changed(bool update_metrics) const
429 d->wa_->redrawAll(update_metrics);
433 frontend::WorkAreaManager & Buffer::workAreaManager() const
435 LASSERT(d->wa_, /**/);
440 Text & Buffer::text() const
442 return d->inset->text();
446 Inset & Buffer::inset() const
452 BufferParams & Buffer::params()
458 BufferParams const & Buffer::params() const
464 ParagraphList & Buffer::paragraphs()
466 return text().paragraphs();
470 ParagraphList const & Buffer::paragraphs() const
472 return text().paragraphs();
476 LyXVC & Buffer::lyxvc()
482 LyXVC const & Buffer::lyxvc() const
488 string const Buffer::temppath() const
490 return d->temppath.absFilename();
494 TexRow & Buffer::texrow()
500 TexRow const & Buffer::texrow() const
506 TocBackend & Buffer::tocBackend() const
508 return d->toc_backend;
512 Undo & Buffer::undo()
518 void Buffer::setChild(DocIterator const & dit, Buffer * child)
520 d->children_positions[child] = dit;
524 string Buffer::latexName(bool const no_path) const
526 FileName latex_name =
527 makeLatexName(exportFileName());
528 return no_path ? latex_name.onlyFileName()
529 : latex_name.absFilename();
533 FileName Buffer::exportFileName() const
535 docstring const branch_suffix =
536 params().branchlist().getFilenameSuffix();
537 if (branch_suffix.empty())
540 string const name = fileName().onlyFileNameWithoutExt()
541 + to_utf8(branch_suffix);
542 FileName res(fileName().onlyPath().absFilename() + "/" + name);
543 res.changeExtension(fileName().extension());
549 string Buffer::logName(LogType * type) const
551 string const filename = latexName(false);
553 if (filename.empty()) {
559 string const path = temppath();
561 FileName const fname(addName(temppath(),
562 onlyFilename(changeExtension(filename,
565 // FIXME: how do we know this is the name of the build log?
566 FileName const bname(
567 addName(path, onlyFilename(
568 changeExtension(filename,
569 formats.extension(bufferFormat()) + ".out"))));
571 // Also consider the master buffer log file
572 FileName masterfname = fname;
574 if (masterBuffer() != this) {
575 string const mlogfile = masterBuffer()->logName(&mtype);
576 masterfname = FileName(mlogfile);
579 // If no Latex log or Build log is newer, show Build log
580 if (bname.exists() &&
581 ((!fname.exists() && !masterfname.exists())
582 || (fname.lastModified() < bname.lastModified()
583 && masterfname.lastModified() < bname.lastModified()))) {
584 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
587 return bname.absFilename();
588 // If we have a newer master file log or only a master log, show this
589 } else if (fname != masterfname
590 && (!fname.exists() && (masterfname.exists()
591 || fname.lastModified() < masterfname.lastModified()))) {
592 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
595 return masterfname.absFilename();
597 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
600 return fname.absFilename();
604 void Buffer::setReadonly(bool const flag)
606 if (d->read_only != flag) {
613 void Buffer::setFileName(string const & newfile)
615 d->filename = makeAbsPath(newfile);
616 setReadonly(d->filename.isReadOnly());
621 int Buffer::readHeader(Lexer & lex)
623 int unknown_tokens = 0;
625 int begin_header_line = -1;
627 // Initialize parameters that may be/go lacking in header:
628 params().branchlist().clear();
629 params().preamble.erase();
630 params().options.erase();
631 params().master.erase();
632 params().float_placement.erase();
633 params().paperwidth.erase();
634 params().paperheight.erase();
635 params().leftmargin.erase();
636 params().rightmargin.erase();
637 params().topmargin.erase();
638 params().bottommargin.erase();
639 params().headheight.erase();
640 params().headsep.erase();
641 params().footskip.erase();
642 params().columnsep.erase();
643 params().fontsCJK.erase();
644 params().listings_params.clear();
645 params().clearLayoutModules();
646 params().clearRemovedModules();
647 params().clearIncludedChildren();
648 params().pdfoptions().clear();
649 params().indiceslist().clear();
650 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
652 for (int i = 0; i < 4; ++i) {
653 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
654 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
657 ErrorList & errorList = d->errorLists["Parse"];
666 if (token == "\\end_header")
670 if (token == "\\begin_header") {
671 begin_header_line = line;
675 LYXERR(Debug::PARSER, "Handling document header token: `"
678 string unknown = params().readToken(lex, token, d->filename.onlyPath());
679 if (!unknown.empty()) {
680 if (unknown[0] != '\\' && token == "\\textclass") {
681 Alert::warning(_("Unknown document class"),
682 bformat(_("Using the default document class, because the "
683 "class %1$s is unknown."), from_utf8(unknown)));
686 docstring const s = bformat(_("Unknown token: "
690 errorList.push_back(ErrorItem(_("Document header error"),
695 if (begin_header_line) {
696 docstring const s = _("\\begin_header is missing");
697 errorList.push_back(ErrorItem(_("Document header error"),
701 params().makeDocumentClass();
703 return unknown_tokens;
708 // changed to be public and have one parameter
709 // Returns true if "\end_document" is not read (Asger)
710 bool Buffer::readDocument(Lexer & lex)
712 ErrorList & errorList = d->errorLists["Parse"];
715 if (!lex.checkFor("\\begin_document")) {
716 docstring const s = _("\\begin_document is missing");
717 errorList.push_back(ErrorItem(_("Document header error"),
721 // we are reading in a brand new document
722 LASSERT(paragraphs().empty(), /**/);
726 if (params().outputChanges) {
727 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
728 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
729 LaTeXFeatures::isAvailable("xcolor");
731 if (!dvipost && !xcolorulem) {
732 Alert::warning(_("Changes not shown in LaTeX output"),
733 _("Changes will not be highlighted in LaTeX output, "
734 "because neither dvipost nor xcolor/ulem are installed.\n"
735 "Please install these packages or redefine "
736 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
737 } else if (!xcolorulem) {
738 Alert::warning(_("Changes not shown in LaTeX output"),
739 _("Changes will not be highlighted in LaTeX output "
740 "when using pdflatex, because xcolor and ulem are not installed.\n"
741 "Please install both packages or redefine "
742 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
746 if (!params().master.empty()) {
747 FileName const master_file = makeAbsPath(params().master,
748 onlyPath(absFileName()));
749 if (isLyXFilename(master_file.absFilename())) {
751 checkAndLoadLyXFile(master_file, true);
753 // necessary e.g. after a reload
754 // to re-register the child (bug 5873)
755 // FIXME: clean up updateMacros (here, only
756 // child registering is needed).
757 master->updateMacros();
758 // set master as master buffer, but only
759 // if we are a real child
760 if (master->isChild(this))
762 // if the master is not fully loaded
763 // it is probably just loading this
764 // child. No warning needed then.
765 else if (master->isFullyLoaded())
766 LYXERR0("The master '"
768 << "' assigned to this document ("
770 << ") does not include "
771 "this document. Ignoring the master assignment.");
776 // assure we have a default index
777 params().indiceslist().addDefault(B_("Index"));
780 bool const res = text().read(lex, errorList, d->inset);
784 updateMacroInstances();
789 bool Buffer::readString(string const & s)
791 params().compressed = false;
793 // remove dummy empty par
794 paragraphs().clear();
798 FileName const name = FileName::tempName("Buffer_readString");
799 switch (readFile(lex, name, true)) {
803 // We need to call lyx2lyx, so write the input to a file
804 ofstream os(name.toFilesystemEncoding().c_str());
807 return readFile(name);
817 bool Buffer::readFile(FileName const & filename)
819 FileName fname(filename);
821 params().compressed = fname.isZippedFile();
823 // remove dummy empty par
824 paragraphs().clear();
827 if (readFile(lex, fname) != success)
834 bool Buffer::isFullyLoaded() const
836 return d->file_fully_loaded;
840 void Buffer::setFullyLoaded(bool value)
842 d->file_fully_loaded = value;
846 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
849 LASSERT(!filename.empty(), /**/);
851 // the first (non-comment) token _must_ be...
852 if (!lex.checkFor("\\lyxformat")) {
853 Alert::error(_("Document format failure"),
854 bformat(_("%1$s is not a readable LyX document."),
855 from_utf8(filename.absFilename())));
861 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
862 // if present remove ".," from string.
863 size_t dot = tmp_format.find_first_of(".,");
864 //lyxerr << " dot found at " << dot << endl;
865 if (dot != string::npos)
866 tmp_format.erase(dot, 1);
867 int const file_format = convert<int>(tmp_format);
868 //lyxerr << "format: " << file_format << endl;
870 // save timestamp and checksum of the original disk file, making sure
871 // to not overwrite them with those of the file created in the tempdir
872 // when it has to be converted to the current format.
874 // Save the timestamp and checksum of disk file. If filename is an
875 // emergency file, save the timestamp and checksum of the original lyx file
876 // because isExternallyModified will check for this file. (BUG4193)
877 string diskfile = filename.absFilename();
878 if (suffixIs(diskfile, ".emergency"))
879 diskfile = diskfile.substr(0, diskfile.size() - 10);
880 saveCheckSum(FileName(diskfile));
883 if (file_format != LYX_FORMAT) {
886 // lyx2lyx would fail
889 FileName const tmpfile = FileName::tempName("Buffer_readFile");
890 if (tmpfile.empty()) {
891 Alert::error(_("Conversion failed"),
892 bformat(_("%1$s is from a different"
893 " version of LyX, but a temporary"
894 " file for converting it could"
896 from_utf8(filename.absFilename())));
899 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
900 if (lyx2lyx.empty()) {
901 Alert::error(_("Conversion script not found"),
902 bformat(_("%1$s is from a different"
903 " version of LyX, but the"
904 " conversion script lyx2lyx"
905 " could not be found."),
906 from_utf8(filename.absFilename())));
909 ostringstream command;
910 command << os::python()
911 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
912 << " -t " << convert<string>(LYX_FORMAT)
913 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
914 << ' ' << quoteName(filename.toFilesystemEncoding());
915 string const command_str = command.str();
917 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
919 cmd_ret const ret = runCommand(command_str);
920 if (ret.first != 0) {
921 if (file_format < LYX_FORMAT)
922 Alert::error(_("Conversion script failed"),
923 bformat(_("%1$s is from an older version"
924 " of LyX, but the lyx2lyx script"
925 " failed to convert it."),
926 from_utf8(filename.absFilename())));
928 Alert::error(_("Conversion script failed"),
929 bformat(_("%1$s is from a newer version"
930 " of LyX and cannot be converted by the"
932 from_utf8(filename.absFilename())));
935 bool const ret = readFile(tmpfile);
936 // Do stuff with tmpfile name and buffer name here.
937 return ret ? success : failure;
942 if (readDocument(lex)) {
943 Alert::error(_("Document format failure"),
944 bformat(_("%1$s ended unexpectedly, which means"
945 " that it is probably corrupted."),
946 from_utf8(filename.absFilename())));
949 d->file_fully_loaded = true;
954 // Should probably be moved to somewhere else: BufferView? LyXView?
955 bool Buffer::save() const
957 // We don't need autosaves in the immediate future. (Asger)
958 resetAutosaveTimers();
960 string const encodedFilename = d->filename.toFilesystemEncoding();
963 bool madeBackup = false;
965 // make a backup if the file already exists
966 if (lyxrc.make_backup && fileName().exists()) {
967 backupName = FileName(absFileName() + '~');
968 if (!lyxrc.backupdir_path.empty()) {
969 string const mangledName =
970 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
971 backupName = FileName(addName(lyxrc.backupdir_path,
974 if (fileName().copyTo(backupName)) {
977 Alert::error(_("Backup failure"),
978 bformat(_("Cannot create backup file %1$s.\n"
979 "Please check whether the directory exists and is writeable."),
980 from_utf8(backupName.absFilename())));
981 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
985 // ask if the disk file has been externally modified (use checksum method)
986 if (fileName().exists() && isExternallyModified(checksum_method)) {
987 docstring const file = makeDisplayPath(absFileName(), 20);
988 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
989 "you want to overwrite this file?"), file);
990 int const ret = Alert::prompt(_("Overwrite modified file?"),
991 text, 1, 1, _("&Overwrite"), _("&Cancel"));
996 if (writeFile(d->filename)) {
1000 // Saving failed, so backup is not backup
1002 backupName.moveTo(d->filename);
1008 bool Buffer::writeFile(FileName const & fname) const
1010 if (d->read_only && fname == d->filename)
1013 bool retval = false;
1015 docstring const str = bformat(_("Saving document %1$s..."),
1016 makeDisplayPath(fname.absFilename()));
1019 if (params().compressed) {
1020 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1021 retval = ofs && write(ofs);
1023 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1024 retval = ofs && write(ofs);
1028 message(str + _(" could not write file!"));
1032 removeAutosaveFile();
1034 saveCheckSum(d->filename);
1035 message(str + _(" done."));
1041 docstring Buffer::emergencyWrite()
1043 // No need to save if the buffer has not changed.
1047 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1049 docstring user_message = bformat(
1050 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1052 // We try to save three places:
1053 // 1) Same place as document. Unless it is an unnamed doc.
1055 string s = absFileName();
1058 if (writeFile(FileName(s))) {
1060 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1061 return user_message;
1063 user_message += _(" Save failed! Trying again...\n");
1067 // 2) In HOME directory.
1068 string s = addName(package().home_dir().absFilename(), absFileName());
1070 lyxerr << ' ' << s << endl;
1071 if (writeFile(FileName(s))) {
1073 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1074 return user_message;
1077 user_message += _(" Save failed! Trying yet again...\n");
1079 // 3) In "/tmp" directory.
1080 // MakeAbsPath to prepend the current
1081 // drive letter on OS/2
1082 s = addName(package().temp_dir().absFilename(), absFileName());
1084 lyxerr << ' ' << s << endl;
1085 if (writeFile(FileName(s))) {
1087 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1088 return user_message;
1091 user_message += _(" Save failed! Bummer. Document is lost.");
1094 return user_message;
1098 bool Buffer::write(ostream & ofs) const
1101 // Use the standard "C" locale for file output.
1102 ofs.imbue(locale::classic());
1105 // The top of the file should not be written by params().
1107 // write out a comment in the top of the file
1108 ofs << "#LyX " << lyx_version
1109 << " created this file. For more info see http://www.lyx.org/\n"
1110 << "\\lyxformat " << LYX_FORMAT << "\n"
1111 << "\\begin_document\n";
1113 /// For each author, set 'used' to true if there is a change
1114 /// by this author in the document; otherwise set it to 'false'.
1115 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1116 AuthorList::Authors::const_iterator a_end = params().authors().end();
1117 for (; a_it != a_end; ++a_it)
1118 a_it->setUsed(false);
1120 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1121 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1122 for ( ; it != end; ++it)
1123 it->checkAuthors(params().authors());
1125 // now write out the buffer parameters.
1126 ofs << "\\begin_header\n";
1127 params().writeFile(ofs);
1128 ofs << "\\end_header\n";
1131 ofs << "\n\\begin_body\n";
1133 ofs << "\n\\end_body\n";
1135 // Write marker that shows file is complete
1136 ofs << "\\end_document" << endl;
1138 // Shouldn't really be needed....
1141 // how to check if close went ok?
1142 // Following is an attempt... (BE 20001011)
1144 // good() returns false if any error occured, including some
1145 // formatting error.
1146 // bad() returns true if something bad happened in the buffer,
1147 // which should include file system full errors.
1152 lyxerr << "File was not closed properly." << endl;
1159 bool Buffer::makeLaTeXFile(FileName const & fname,
1160 string const & original_path,
1161 OutputParams const & runparams_in,
1162 bool output_preamble, bool output_body) const
1164 OutputParams runparams = runparams_in;
1165 if (params().useXetex)
1166 runparams.flavor = OutputParams::XETEX;
1168 string const encoding = runparams.encoding->iconvName();
1169 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1172 try { ofs.reset(encoding); }
1173 catch (iconv_codecvt_facet_exception & e) {
1174 lyxerr << "Caught iconv exception: " << e.what() << endl;
1175 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1176 "verify that the support software for your encoding (%1$s) is "
1177 "properly installed"), from_ascii(encoding)));
1180 if (!openFileWrite(ofs, fname))
1183 //TexStream ts(ofs.rdbuf(), &texrow());
1184 ErrorList & errorList = d->errorLists["Export"];
1186 bool failed_export = false;
1189 writeLaTeXSource(ofs, original_path,
1190 runparams, output_preamble, output_body);
1192 catch (EncodingException & e) {
1193 odocstringstream ods;
1194 ods.put(e.failed_char);
1196 oss << "0x" << hex << e.failed_char << dec;
1197 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1198 " (code point %2$s)"),
1199 ods.str(), from_utf8(oss.str()));
1200 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1201 "representable in the chosen encoding.\n"
1202 "Changing the document encoding to utf8 could help."),
1203 e.par_id, e.pos, e.pos + 1));
1204 failed_export = true;
1206 catch (iconv_codecvt_facet_exception & e) {
1207 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1208 _(e.what()), -1, 0, 0));
1209 failed_export = true;
1211 catch (exception const & e) {
1212 errorList.push_back(ErrorItem(_("conversion failed"),
1213 _(e.what()), -1, 0, 0));
1214 failed_export = true;
1217 lyxerr << "Caught some really weird exception..." << endl;
1223 failed_export = true;
1224 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1228 return !failed_export;
1232 void Buffer::writeLaTeXSource(odocstream & os,
1233 string const & original_path,
1234 OutputParams const & runparams_in,
1235 bool const output_preamble, bool const output_body) const
1237 // The child documents, if any, shall be already loaded at this point.
1239 OutputParams runparams = runparams_in;
1241 // Classify the unicode characters appearing in math insets
1242 Encodings::initUnicodeMath(*this);
1244 // validate the buffer.
1245 LYXERR(Debug::LATEX, " Validating buffer...");
1246 LaTeXFeatures features(*this, params(), runparams);
1248 LYXERR(Debug::LATEX, " Buffer validation done.");
1250 // The starting paragraph of the coming rows is the
1251 // first paragraph of the document. (Asger)
1252 if (output_preamble && runparams.nice) {
1253 os << "%% LyX " << lyx_version << " created this file. "
1254 "For more info, see http://www.lyx.org/.\n"
1255 "%% Do not edit unless you really know what "
1257 d->texrow.newline();
1258 d->texrow.newline();
1260 LYXERR(Debug::INFO, "lyx document header finished");
1262 // Don't move this behind the parent_buffer=0 code below,
1263 // because then the macros will not get the right "redefinition"
1264 // flag as they don't see the parent macros which are output before.
1267 // fold macros if possible, still with parent buffer as the
1268 // macros will be put in the prefix anyway.
1269 updateMacroInstances();
1271 // There are a few differences between nice LaTeX and usual files:
1272 // usual is \batchmode and has a
1273 // special input@path to allow the including of figures
1274 // with either \input or \includegraphics (what figinsets do).
1275 // input@path is set when the actual parameter
1276 // original_path is set. This is done for usual tex-file, but not
1277 // for nice-latex-file. (Matthias 250696)
1278 // Note that input@path is only needed for something the user does
1279 // in the preamble, included .tex files or ERT, files included by
1280 // LyX work without it.
1281 if (output_preamble) {
1282 if (!runparams.nice) {
1283 // code for usual, NOT nice-latex-file
1284 os << "\\batchmode\n"; // changed
1285 // from \nonstopmode
1286 d->texrow.newline();
1288 if (!original_path.empty()) {
1290 // We don't know the encoding of inputpath
1291 docstring const inputpath = from_utf8(latex_path(original_path));
1292 os << "\\makeatletter\n"
1293 << "\\def\\input@path{{"
1294 << inputpath << "/}}\n"
1295 << "\\makeatother\n";
1296 d->texrow.newline();
1297 d->texrow.newline();
1298 d->texrow.newline();
1301 // get parent macros (if this buffer has a parent) which will be
1302 // written at the document begin further down.
1303 MacroSet parentMacros;
1304 listParentMacros(parentMacros, features);
1306 // Write the preamble
1307 runparams.use_babel = params().writeLaTeX(os, features,
1309 d->filename.onlyPath());
1311 runparams.use_japanese = features.isRequired("japanese");
1317 os << "\\begin{document}\n";
1318 d->texrow.newline();
1320 // output the parent macros
1321 MacroSet::iterator it = parentMacros.begin();
1322 MacroSet::iterator end = parentMacros.end();
1323 for (; it != end; ++it)
1324 (*it)->write(os, true);
1325 } // output_preamble
1327 d->texrow.start(paragraphs().begin()->id(), 0);
1329 LYXERR(Debug::INFO, "preamble finished, now the body.");
1331 // if we are doing a real file with body, even if this is the
1332 // child of some other buffer, let's cut the link here.
1333 // This happens for example if only a child document is printed.
1334 Buffer const * save_parent = 0;
1335 if (output_preamble) {
1336 save_parent = d->parent();
1341 latexParagraphs(*this, text(), os, d->texrow, runparams);
1343 // Restore the parenthood if needed
1344 if (output_preamble)
1345 d->setParent(save_parent);
1347 // add this just in case after all the paragraphs
1349 d->texrow.newline();
1351 if (output_preamble) {
1352 os << "\\end{document}\n";
1353 d->texrow.newline();
1354 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1356 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1358 runparams_in.encoding = runparams.encoding;
1360 // Just to be sure. (Asger)
1361 d->texrow.newline();
1363 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1364 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1368 bool Buffer::isLatex() const
1370 return params().documentClass().outputType() == LATEX;
1374 bool Buffer::isLiterate() const
1376 return params().documentClass().outputType() == LITERATE;
1380 bool Buffer::isDocBook() const
1382 return params().documentClass().outputType() == DOCBOOK;
1386 void Buffer::makeDocBookFile(FileName const & fname,
1387 OutputParams const & runparams,
1388 bool const body_only) const
1390 LYXERR(Debug::LATEX, "makeDocBookFile...");
1393 if (!openFileWrite(ofs, fname))
1396 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1400 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1404 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1405 OutputParams const & runparams,
1406 bool const only_body) const
1408 LaTeXFeatures features(*this, params(), runparams);
1413 DocumentClass const & tclass = params().documentClass();
1414 string const top_element = tclass.latexname();
1417 if (runparams.flavor == OutputParams::XML)
1418 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1421 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1424 if (! tclass.class_header().empty())
1425 os << from_ascii(tclass.class_header());
1426 else if (runparams.flavor == OutputParams::XML)
1427 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1428 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1430 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1432 docstring preamble = from_utf8(params().preamble);
1433 if (runparams.flavor != OutputParams::XML ) {
1434 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1435 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1436 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1437 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1440 string const name = runparams.nice
1441 ? changeExtension(absFileName(), ".sgml") : fname;
1442 preamble += features.getIncludedFiles(name);
1443 preamble += features.getLyXSGMLEntities();
1445 if (!preamble.empty()) {
1446 os << "\n [ " << preamble << " ]";
1451 string top = top_element;
1453 if (runparams.flavor == OutputParams::XML)
1454 top += params().language->code();
1456 top += params().language->code().substr(0, 2);
1459 if (!params().options.empty()) {
1461 top += params().options;
1464 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1465 << " file was created by LyX " << lyx_version
1466 << "\n See http://www.lyx.org/ for more information -->\n";
1468 params().documentClass().counters().reset();
1472 sgml::openTag(os, top);
1474 docbookParagraphs(text(), *this, os, runparams);
1475 sgml::closeTag(os, top_element);
1479 void Buffer::makeLyXHTMLFile(FileName const & fname,
1480 OutputParams const & runparams,
1481 bool const body_only) const
1483 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1486 if (!openFileWrite(ofs, fname))
1489 writeLyXHTMLSource(ofs, runparams, body_only);
1493 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1497 void Buffer::writeLyXHTMLSource(odocstream & os,
1498 OutputParams const & runparams,
1499 bool const only_body) const
1501 LaTeXFeatures features(*this, params(), runparams);
1503 updateLabels(UpdateMaster, OutputUpdate);
1504 checkBibInfoCache();
1505 d->bibinfo_.makeCitationLabels(*this);
1507 updateMacroInstances();
1510 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1511 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";
1512 // FIXME Language should be set properly.
1513 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1515 // FIXME Presumably need to set this right
1516 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1517 os << "<title>" << features.htmlTitle() << "</title>\n";
1519 os << "\n<!-- Text Class Preamble -->\n"
1520 << features.getTClassHTMLPreamble()
1521 << "\n<!-- Premable Snippets -->\n"
1522 << from_utf8(features.getPreambleSnippets());
1524 os << "\n<!-- Layout-provided Styles -->\n";
1525 docstring const styleinfo = features.getTClassHTMLStyles();
1526 if (!styleinfo.empty()) {
1527 os << "<style type='text/css'>\n"
1531 os << "</head>\n<body>\n";
1535 params().documentClass().counters().reset();
1536 xhtmlParagraphs(text(), *this, xs, runparams);
1538 os << "</body>\n</html>\n";
1542 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1543 // Other flags: -wall -v0 -x
1544 int Buffer::runChktex()
1548 // get LaTeX-Filename
1549 FileName const path(temppath());
1550 string const name = addName(path.absFilename(), latexName());
1551 string const org_path = filePath();
1553 PathChanger p(path); // path to LaTeX file
1554 message(_("Running chktex..."));
1556 // Generate the LaTeX file if neccessary
1557 OutputParams runparams(¶ms().encoding());
1558 runparams.flavor = OutputParams::LATEX;
1559 runparams.nice = false;
1560 makeLaTeXFile(FileName(name), org_path, runparams);
1563 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1564 int const res = chktex.run(terr); // run chktex
1567 Alert::error(_("chktex failure"),
1568 _("Could not run chktex successfully."));
1569 } else if (res > 0) {
1570 ErrorList & errlist = d->errorLists["ChkTeX"];
1572 bufferErrors(terr, errlist);
1583 void Buffer::validate(LaTeXFeatures & features) const
1585 params().validate(features);
1589 for_each(paragraphs().begin(), paragraphs().end(),
1590 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1592 if (lyxerr.debugging(Debug::LATEX)) {
1593 features.showStruct();
1598 void Buffer::getLabelList(vector<docstring> & list) const
1600 // If this is a child document, use the parent's list instead.
1601 Buffer const * const pbuf = d->parent();
1603 pbuf->getLabelList(list);
1608 Toc & toc = d->toc_backend.toc("label");
1609 TocIterator toc_it = toc.begin();
1610 TocIterator end = toc.end();
1611 for (; toc_it != end; ++toc_it) {
1612 if (toc_it->depth() == 0)
1613 list.push_back(toc_it->str());
1618 void Buffer::updateBibfilesCache(UpdateScope scope) const
1620 // If this is a child document, use the parent's cache instead.
1621 Buffer const * const pbuf = d->parent();
1622 if (pbuf && scope != UpdateChildOnly) {
1623 pbuf->updateBibfilesCache();
1627 d->bibfiles_cache_.clear();
1628 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1629 if (it->lyxCode() == BIBTEX_CODE) {
1630 InsetBibtex const & inset =
1631 static_cast<InsetBibtex const &>(*it);
1632 support::FileNameList const bibfiles = inset.getBibFiles();
1633 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1636 } else if (it->lyxCode() == INCLUDE_CODE) {
1637 InsetInclude & inset =
1638 static_cast<InsetInclude &>(*it);
1639 inset.updateBibfilesCache();
1640 support::FileNameList const & bibfiles =
1641 inset.getBibfilesCache();
1642 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1647 // the bibinfo cache is now invalid
1648 d->bibinfo_cache_valid_ = false;
1652 void Buffer::invalidateBibinfoCache()
1654 d->bibinfo_cache_valid_ = false;
1658 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1660 // If this is a child document, use the parent's cache instead.
1661 Buffer const * const pbuf = d->parent();
1662 if (pbuf && scope != UpdateChildOnly)
1663 return pbuf->getBibfilesCache();
1665 // We update the cache when first used instead of at loading time.
1666 if (d->bibfiles_cache_.empty())
1667 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1669 return d->bibfiles_cache_;
1673 BiblioInfo const & Buffer::masterBibInfo() const
1675 // if this is a child document and the parent is already loaded
1676 // use the parent's list instead [ale990412]
1677 Buffer const * const tmp = masterBuffer();
1680 return tmp->masterBibInfo();
1681 return localBibInfo();
1685 BiblioInfo const & Buffer::localBibInfo() const
1691 void Buffer::checkBibInfoCache() const
1693 support::FileNameList const & bibfilesCache = getBibfilesCache();
1694 // compare the cached timestamps with the actual ones.
1695 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1696 support::FileNameList::const_iterator en = bibfilesCache.end();
1697 for (; ei != en; ++ ei) {
1698 time_t lastw = ei->lastModified();
1699 time_t prevw = d->bibfile_status_[*ei];
1700 if (lastw != prevw) {
1701 d->bibinfo_cache_valid_ = false;
1702 d->bibfile_status_[*ei] = lastw;
1706 if (!d->bibinfo_cache_valid_) {
1707 d->bibinfo_.clear();
1708 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1709 it->fillWithBibKeys(d->bibinfo_, it);
1710 d->bibinfo_cache_valid_ = true;
1715 bool Buffer::isDepClean(string const & name) const
1717 DepClean::const_iterator const it = d->dep_clean.find(name);
1718 if (it == d->dep_clean.end())
1724 void Buffer::markDepClean(string const & name)
1726 d->dep_clean[name] = true;
1730 bool Buffer::isExportableFormat(string const & format) const
1732 typedef vector<Format const *> Formats;
1734 formats = exportableFormats(true);
1735 Formats::const_iterator fit = formats.begin();
1736 Formats::const_iterator end = formats.end();
1737 for (; fit != end ; ++fit) {
1738 if ((*fit)->name() == format)
1745 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1748 // FIXME? if there is an Buffer LFUN that can be dispatched even
1749 // if internal, put a switch '(cmd.action)' here.
1755 switch (cmd.action) {
1757 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1758 flag.setOnOff(isReadonly());
1761 // FIXME: There is need for a command-line import.
1762 //case LFUN_BUFFER_IMPORT:
1764 case LFUN_BUFFER_AUTO_SAVE:
1767 case LFUN_BUFFER_EXPORT_CUSTOM:
1768 // FIXME: Nothing to check here?
1771 case LFUN_BUFFER_EXPORT: {
1772 docstring const arg = cmd.argument();
1773 enable = arg == "custom" || isExportable(to_utf8(arg));
1775 flag.message(bformat(
1776 _("Don't know how to export to format: %1$s"), arg));
1780 case LFUN_BUFFER_CHKTEX:
1781 enable = isLatex() && !lyxrc.chktex_command.empty();
1784 case LFUN_BUILD_PROGRAM:
1785 enable = isExportable("program");
1788 case LFUN_BRANCH_ACTIVATE:
1789 case LFUN_BRANCH_DEACTIVATE: {
1790 BranchList const & branchList = params().branchlist();
1791 docstring const branchName = cmd.argument();
1792 enable = !branchName.empty() && branchList.find(branchName);
1796 case LFUN_BRANCH_ADD:
1797 case LFUN_BRANCHES_RENAME:
1798 case LFUN_BUFFER_PRINT:
1799 // if no Buffer is present, then of course we won't be called!
1802 case LFUN_BUFFER_LANGUAGE:
1803 enable = !isReadonly();
1809 flag.setEnabled(enable);
1814 void Buffer::dispatch(string const & command, DispatchResult & result)
1816 return dispatch(lyxaction.lookupFunc(command), result);
1820 // NOTE We can end up here even if we have no GUI, because we are called
1821 // by LyX::exec to handled command-line requests. So we may need to check
1822 // whether we have a GUI or not. The boolean use_gui holds this information.
1823 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1826 // FIXME? if there is an Buffer LFUN that can be dispatched even
1827 // if internal, put a switch '(cmd.action)' here.
1828 dr.dispatched(false);
1831 string const argument = to_utf8(func.argument());
1832 // We'll set this back to false if need be.
1833 bool dispatched = true;
1834 undo().beginUndoGroup();
1836 switch (func.action) {
1837 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1838 if (lyxvc().inUse())
1839 lyxvc().toggleReadOnly();
1841 setReadonly(!isReadonly());
1844 case LFUN_BUFFER_EXPORT: {
1845 bool success = doExport(argument, false, false);
1846 dr.setError(success);
1848 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1853 case LFUN_BUILD_PROGRAM:
1854 doExport("program", true, false);
1857 case LFUN_BUFFER_CHKTEX:
1861 case LFUN_BUFFER_EXPORT_CUSTOM: {
1863 string command = split(argument, format_name, ' ');
1864 Format const * format = formats.getFormat(format_name);
1866 lyxerr << "Format \"" << format_name
1867 << "\" not recognized!"
1872 // The name of the file created by the conversion process
1875 // Output to filename
1876 if (format->name() == "lyx") {
1877 string const latexname = latexName(false);
1878 filename = changeExtension(latexname,
1879 format->extension());
1880 filename = addName(temppath(), filename);
1882 if (!writeFile(FileName(filename)))
1886 doExport(format_name, true, false, filename);
1889 // Substitute $$FName for filename
1890 if (!contains(command, "$$FName"))
1891 command = "( " + command + " ) < $$FName";
1892 command = subst(command, "$$FName", filename);
1894 // Execute the command in the background
1896 call.startscript(Systemcall::DontWait, command);
1900 // FIXME: There is need for a command-line import.
1902 case LFUN_BUFFER_IMPORT:
1907 case LFUN_BUFFER_AUTO_SAVE:
1911 case LFUN_BRANCH_ADD: {
1912 docstring const branch_name = func.argument();
1913 if (branch_name.empty()) {
1917 BranchList & branch_list = params().branchlist();
1918 Branch * branch = branch_list.find(branch_name);
1920 LYXERR0("Branch " << branch_name << " already exists.");
1922 docstring const msg =
1923 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1926 branch_list.add(branch_name);
1927 branch = branch_list.find(branch_name);
1928 string const x11hexname = X11hexname(branch->color());
1929 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1930 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1932 dr.update(Update::Force);
1937 case LFUN_BRANCH_ACTIVATE:
1938 case LFUN_BRANCH_DEACTIVATE: {
1939 BranchList & branchList = params().branchlist();
1940 docstring const branchName = func.argument();
1941 // the case without a branch name is handled elsewhere
1942 if (branchName.empty()) {
1946 Branch * branch = branchList.find(branchName);
1948 LYXERR0("Branch " << branchName << " does not exist.");
1950 docstring const msg =
1951 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1954 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1956 dr.update(Update::Force);
1961 case LFUN_BRANCHES_RENAME: {
1962 if (func.argument().empty())
1965 docstring const oldname = from_utf8(func.getArg(0));
1966 docstring const newname = from_utf8(func.getArg(1));
1967 InsetIterator it = inset_iterator_begin(inset());
1968 InsetIterator const end = inset_iterator_end(inset());
1969 bool success = false;
1970 for (; it != end; ++it) {
1971 if (it->lyxCode() == BRANCH_CODE) {
1972 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1973 if (ins.branch() == oldname) {
1974 undo().recordUndo(it);
1975 ins.rename(newname);
1980 if (it->lyxCode() == INCLUDE_CODE) {
1981 // get buffer of external file
1982 InsetInclude const & ins =
1983 static_cast<InsetInclude const &>(*it);
1984 Buffer * child = ins.getChildBuffer();
1987 child->dispatch(func, dr);
1992 dr.update(Update::Force);
1996 case LFUN_BUFFER_PRINT: {
1997 // we'll assume there's a problem until we succeed
1999 string target = func.getArg(0);
2000 string target_name = func.getArg(1);
2001 string command = func.getArg(2);
2004 || target_name.empty()
2005 || command.empty()) {
2006 LYXERR0("Unable to parse " << func.argument());
2007 docstring const msg =
2008 bformat(_("Unable to parse \"%1$s\""), func.argument());
2012 if (target != "printer" && target != "file") {
2013 LYXERR0("Unrecognized target \"" << target << '"');
2014 docstring const msg =
2015 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2020 bool const update_unincluded =
2021 params().maintain_unincluded_children
2022 && !params().getIncludedChildren().empty();
2023 if (!doExport("dvi", true, update_unincluded)) {
2024 showPrintError(absFileName());
2025 dr.setMessage(_("Error exporting to DVI."));
2029 // Push directory path.
2030 string const path = temppath();
2031 // Prevent the compiler from optimizing away p
2035 // there are three cases here:
2036 // 1. we print to a file
2037 // 2. we print directly to a printer
2038 // 3. we print using a spool command (print to file first)
2041 string const dviname = changeExtension(latexName(true), "dvi");
2043 if (target == "printer") {
2044 if (!lyxrc.print_spool_command.empty()) {
2045 // case 3: print using a spool
2046 string const psname = changeExtension(dviname,".ps");
2047 command += ' ' + lyxrc.print_to_file
2050 + quoteName(dviname);
2052 string command2 = lyxrc.print_spool_command + ' ';
2053 if (target_name != "default") {
2054 command2 += lyxrc.print_spool_printerprefix
2058 command2 += quoteName(psname);
2060 // If successful, then spool command
2061 res = one.startscript(Systemcall::Wait, command);
2064 // If there's no GUI, we have to wait on this command. Otherwise,
2065 // LyX deletes the temporary directory, and with it the spooled
2066 // file, before it can be printed!!
2067 Systemcall::Starttype stype = use_gui ?
2068 Systemcall::DontWait : Systemcall::Wait;
2069 res = one.startscript(stype, command2);
2072 // case 2: print directly to a printer
2073 if (target_name != "default")
2074 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2076 Systemcall::Starttype stype = use_gui ?
2077 Systemcall::DontWait : Systemcall::Wait;
2078 res = one.startscript(stype, command + quoteName(dviname));
2082 // case 1: print to a file
2083 FileName const filename(makeAbsPath(target_name, filePath()));
2084 FileName const dvifile(makeAbsPath(dviname, path));
2085 if (filename.exists()) {
2086 docstring text = bformat(
2087 _("The file %1$s already exists.\n\n"
2088 "Do you want to overwrite that file?"),
2089 makeDisplayPath(filename.absFilename()));
2090 if (Alert::prompt(_("Overwrite file?"),
2091 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2094 command += ' ' + lyxrc.print_to_file
2095 + quoteName(filename.toFilesystemEncoding())
2097 + quoteName(dvifile.toFilesystemEncoding());
2099 Systemcall::Starttype stype = use_gui ?
2100 Systemcall::DontWait : Systemcall::Wait;
2101 res = one.startscript(stype, command);
2107 dr.setMessage(_("Error running external commands."));
2108 showPrintError(absFileName());
2113 case LFUN_BUFFER_LANGUAGE: {
2114 Language const * oldL = params().language;
2115 Language const * newL = languages.getLanguage(argument);
2116 if (!newL || oldL == newL)
2118 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2119 changeLanguage(oldL, newL);
2127 dr.dispatched(dispatched);
2128 undo().endUndoGroup();
2132 void Buffer::changeLanguage(Language const * from, Language const * to)
2134 LASSERT(from, /**/);
2137 for_each(par_iterator_begin(),
2139 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2143 bool Buffer::isMultiLingual() const
2145 ParConstIterator end = par_iterator_end();
2146 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2147 if (it->isMultiLingual(params()))
2154 DocIterator Buffer::getParFromID(int const id) const
2156 Buffer * buf = const_cast<Buffer *>(this);
2158 // John says this is called with id == -1 from undo
2159 lyxerr << "getParFromID(), id: " << id << endl;
2160 return doc_iterator_end(buf);
2163 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2164 if (it.paragraph().id() == id)
2167 return doc_iterator_end(buf);
2171 bool Buffer::hasParWithID(int const id) const
2173 return !getParFromID(id).atEnd();
2177 ParIterator Buffer::par_iterator_begin()
2179 return ParIterator(doc_iterator_begin(this));
2183 ParIterator Buffer::par_iterator_end()
2185 return ParIterator(doc_iterator_end(this));
2189 ParConstIterator Buffer::par_iterator_begin() const
2191 return ParConstIterator(doc_iterator_begin(this));
2195 ParConstIterator Buffer::par_iterator_end() const
2197 return ParConstIterator(doc_iterator_end(this));
2201 Language const * Buffer::language() const
2203 return params().language;
2207 docstring const Buffer::B_(string const & l10n) const
2209 return params().B_(l10n);
2213 bool Buffer::isClean() const
2215 return d->lyx_clean;
2219 bool Buffer::isExternallyModified(CheckMethod method) const
2221 LASSERT(d->filename.exists(), /**/);
2222 // if method == timestamp, check timestamp before checksum
2223 return (method == checksum_method
2224 || d->timestamp_ != d->filename.lastModified())
2225 && d->checksum_ != d->filename.checksum();
2229 void Buffer::saveCheckSum(FileName const & file) const
2231 if (file.exists()) {
2232 d->timestamp_ = file.lastModified();
2233 d->checksum_ = file.checksum();
2235 // in the case of save to a new file.
2242 void Buffer::markClean() const
2244 if (!d->lyx_clean) {
2245 d->lyx_clean = true;
2248 // if the .lyx file has been saved, we don't need an
2250 d->bak_clean = true;
2254 void Buffer::setUnnamed(bool flag)
2260 bool Buffer::isUnnamed() const
2267 /// Don't check unnamed, here: isInternal() is used in
2268 /// newBuffer(), where the unnamed flag has not been set by anyone
2269 /// yet. Also, for an internal buffer, there should be no need for
2270 /// retrieving fileName() nor for checking if it is unnamed or not.
2271 bool Buffer::isInternal() const
2273 return fileName().extension() == "internal";
2277 void Buffer::markDirty()
2280 d->lyx_clean = false;
2283 d->bak_clean = false;
2285 DepClean::iterator it = d->dep_clean.begin();
2286 DepClean::const_iterator const end = d->dep_clean.end();
2288 for (; it != end; ++it)
2293 FileName Buffer::fileName() const
2299 string Buffer::absFileName() const
2301 return d->filename.absFilename();
2305 string Buffer::filePath() const
2307 return d->filename.onlyPath().absFilename() + "/";
2311 bool Buffer::isReadonly() const
2313 return d->read_only;
2317 void Buffer::setParent(Buffer const * buffer)
2319 // Avoids recursive include.
2320 d->setParent(buffer == this ? 0 : buffer);
2325 Buffer const * Buffer::parent() const
2331 void Buffer::collectRelatives(BufferSet & bufs) const
2335 parent()->collectRelatives(bufs);
2337 // loop over children
2338 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2339 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2340 for (; it != end; ++it)
2341 bufs.insert(const_cast<Buffer *>(it->first));
2345 std::vector<Buffer const *> Buffer::allRelatives() const
2348 collectRelatives(bufs);
2349 BufferSet::iterator it = bufs.begin();
2350 std::vector<Buffer const *> ret;
2351 for (; it != bufs.end(); ++it)
2357 Buffer const * Buffer::masterBuffer() const
2359 Buffer const * const pbuf = d->parent();
2363 return pbuf->masterBuffer();
2367 bool Buffer::isChild(Buffer * child) const
2369 return d->children_positions.find(child) != d->children_positions.end();
2373 DocIterator Buffer::firstChildPosition(Buffer const * child)
2375 Impl::BufferPositionMap::iterator it;
2376 it = d->children_positions.find(child);
2377 if (it == d->children_positions.end())
2378 return DocIterator(this);
2383 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2385 // loop over children
2386 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2387 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2388 for (; it != end; ++it) {
2389 Buffer * child = const_cast<Buffer *>(it->first);
2390 clist.push_back(child);
2391 if (grand_children) {
2392 // there might be grandchildren
2393 std::vector<Buffer *> glist = child->getChildren();
2394 for (vector<Buffer *>::const_iterator git = glist.begin();
2395 git != glist.end(); ++git)
2396 clist.push_back(*git);
2402 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2404 std::vector<Buffer *> v;
2405 getChildren(v, grand_children);
2410 template<typename M>
2411 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2416 typename M::iterator it = m.lower_bound(x);
2417 if (it == m.begin())
2425 MacroData const * Buffer::getBufferMacro(docstring const & name,
2426 DocIterator const & pos) const
2428 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2430 // if paragraphs have no macro context set, pos will be empty
2434 // we haven't found anything yet
2435 DocIterator bestPos = par_iterator_begin();
2436 MacroData const * bestData = 0;
2438 // find macro definitions for name
2439 Impl::NamePositionScopeMacroMap::iterator nameIt
2440 = d->macros.find(name);
2441 if (nameIt != d->macros.end()) {
2442 // find last definition in front of pos or at pos itself
2443 Impl::PositionScopeMacroMap::const_iterator it
2444 = greatest_below(nameIt->second, pos);
2445 if (it != nameIt->second.end()) {
2447 // scope ends behind pos?
2448 if (pos < it->second.first) {
2449 // Looks good, remember this. If there
2450 // is no external macro behind this,
2451 // we found the right one already.
2452 bestPos = it->first;
2453 bestData = &it->second.second;
2457 // try previous macro if there is one
2458 if (it == nameIt->second.begin())
2465 // find macros in included files
2466 Impl::PositionScopeBufferMap::const_iterator it
2467 = greatest_below(d->position_to_children, pos);
2468 if (it == d->position_to_children.end())
2469 // no children before
2473 // do we know something better (i.e. later) already?
2474 if (it->first < bestPos )
2477 // scope ends behind pos?
2478 if (pos < it->second.first) {
2479 // look for macro in external file
2480 d->macro_lock = true;
2481 MacroData const * data
2482 = it->second.second->getMacro(name, false);
2483 d->macro_lock = false;
2485 bestPos = it->first;
2491 // try previous file if there is one
2492 if (it == d->position_to_children.begin())
2497 // return the best macro we have found
2502 MacroData const * Buffer::getMacro(docstring const & name,
2503 DocIterator const & pos, bool global) const
2508 // query buffer macros
2509 MacroData const * data = getBufferMacro(name, pos);
2513 // If there is a master buffer, query that
2514 Buffer const * const pbuf = d->parent();
2516 d->macro_lock = true;
2517 MacroData const * macro = pbuf->getMacro(
2518 name, *this, false);
2519 d->macro_lock = false;
2525 data = MacroTable::globalMacros().get(name);
2534 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2536 // set scope end behind the last paragraph
2537 DocIterator scope = par_iterator_begin();
2538 scope.pit() = scope.lastpit() + 1;
2540 return getMacro(name, scope, global);
2544 MacroData const * Buffer::getMacro(docstring const & name,
2545 Buffer const & child, bool global) const
2547 // look where the child buffer is included first
2548 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2549 if (it == d->children_positions.end())
2552 // check for macros at the inclusion position
2553 return getMacro(name, it->second, global);
2557 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2559 pit_type const lastpit = it.lastpit();
2561 // look for macros in each paragraph
2562 while (it.pit() <= lastpit) {
2563 Paragraph & par = it.paragraph();
2565 // iterate over the insets of the current paragraph
2566 InsetList const & insets = par.insetList();
2567 InsetList::const_iterator iit = insets.begin();
2568 InsetList::const_iterator end = insets.end();
2569 for (; iit != end; ++iit) {
2570 it.pos() = iit->pos;
2572 // is it a nested text inset?
2573 if (iit->inset->asInsetText()) {
2574 // Inset needs its own scope?
2575 InsetText const * itext = iit->inset->asInsetText();
2576 bool newScope = itext->isMacroScope();
2578 // scope which ends just behind the inset
2579 DocIterator insetScope = it;
2582 // collect macros in inset
2583 it.push_back(CursorSlice(*iit->inset));
2584 updateMacros(it, newScope ? insetScope : scope);
2589 // is it an external file?
2590 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2591 // get buffer of external file
2592 InsetInclude const & inset =
2593 static_cast<InsetInclude const &>(*iit->inset);
2594 d->macro_lock = true;
2595 Buffer * child = inset.getChildBuffer();
2596 d->macro_lock = false;
2600 // register its position, but only when it is
2601 // included first in the buffer
2602 if (d->children_positions.find(child) ==
2603 d->children_positions.end())
2604 d->children_positions[child] = it;
2606 // register child with its scope
2607 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2611 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2615 MathMacroTemplate & macroTemplate =
2616 static_cast<MathMacroTemplate &>(*iit->inset);
2617 MacroContext mc(this, it);
2618 macroTemplate.updateToContext(mc);
2621 bool valid = macroTemplate.validMacro();
2622 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2623 // then the BufferView's cursor will be invalid in
2624 // some cases which leads to crashes.
2629 // FIXME (Abdel), I don't understandt why we pass 'it' here
2630 // instead of 'macroTemplate' defined above... is this correct?
2631 d->macros[macroTemplate.name()][it] =
2632 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2642 void Buffer::updateMacros() const
2647 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2649 // start with empty table
2651 d->children_positions.clear();
2652 d->position_to_children.clear();
2654 // Iterate over buffer, starting with first paragraph
2655 // The scope must be bigger than any lookup DocIterator
2656 // later. For the global lookup, lastpit+1 is used, hence
2657 // we use lastpit+2 here.
2658 DocIterator it = par_iterator_begin();
2659 DocIterator outerScope = it;
2660 outerScope.pit() = outerScope.lastpit() + 2;
2661 updateMacros(it, outerScope);
2665 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2667 InsetIterator it = inset_iterator_begin(inset());
2668 InsetIterator const end = inset_iterator_end(inset());
2669 for (; it != end; ++it) {
2670 if (it->lyxCode() == BRANCH_CODE) {
2671 InsetBranch & br = static_cast<InsetBranch &>(*it);
2672 docstring const name = br.branch();
2673 if (!from_master && !params().branchlist().find(name))
2674 result.push_back(name);
2675 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2676 result.push_back(name);
2679 if (it->lyxCode() == INCLUDE_CODE) {
2680 // get buffer of external file
2681 InsetInclude const & ins =
2682 static_cast<InsetInclude const &>(*it);
2683 Buffer * child = ins.getChildBuffer();
2686 child->getUsedBranches(result, true);
2689 // remove duplicates
2694 void Buffer::updateMacroInstances() const
2696 LYXERR(Debug::MACROS, "updateMacroInstances for "
2697 << d->filename.onlyFileName());
2698 DocIterator it = doc_iterator_begin(this);
2700 DocIterator const end = doc_iterator_end(this);
2701 for (; it != end; it.forwardInset()) {
2702 // look for MathData cells in InsetMathNest insets
2703 InsetMath * minset = it.nextInset()->asInsetMath();
2707 // update macro in all cells of the InsetMathNest
2708 DocIterator::idx_type n = minset->nargs();
2709 MacroContext mc = MacroContext(this, it);
2710 for (DocIterator::idx_type i = 0; i < n; ++i) {
2711 MathData & data = minset->cell(i);
2712 data.updateMacros(0, mc);
2718 void Buffer::listMacroNames(MacroNameSet & macros) const
2723 d->macro_lock = true;
2725 // loop over macro names
2726 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2727 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2728 for (; nameIt != nameEnd; ++nameIt)
2729 macros.insert(nameIt->first);
2731 // loop over children
2732 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2733 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2734 for (; it != end; ++it)
2735 it->first->listMacroNames(macros);
2738 Buffer const * const pbuf = d->parent();
2740 pbuf->listMacroNames(macros);
2742 d->macro_lock = false;
2746 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2748 Buffer const * const pbuf = d->parent();
2753 pbuf->listMacroNames(names);
2756 MacroNameSet::iterator it = names.begin();
2757 MacroNameSet::iterator end = names.end();
2758 for (; it != end; ++it) {
2760 MacroData const * data =
2761 pbuf->getMacro(*it, *this, false);
2763 macros.insert(data);
2765 // we cannot access the original MathMacroTemplate anymore
2766 // here to calls validate method. So we do its work here manually.
2767 // FIXME: somehow make the template accessible here.
2768 if (data->optionals() > 0)
2769 features.require("xargs");
2775 Buffer::References & Buffer::references(docstring const & label)
2778 return const_cast<Buffer *>(masterBuffer())->references(label);
2780 RefCache::iterator it = d->ref_cache_.find(label);
2781 if (it != d->ref_cache_.end())
2782 return it->second.second;
2784 static InsetLabel const * dummy_il = 0;
2785 static References const dummy_refs;
2786 it = d->ref_cache_.insert(
2787 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2788 return it->second.second;
2792 Buffer::References const & Buffer::references(docstring const & label) const
2794 return const_cast<Buffer *>(this)->references(label);
2798 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2800 masterBuffer()->d->ref_cache_[label].first = il;
2804 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2806 return masterBuffer()->d->ref_cache_[label].first;
2810 void Buffer::clearReferenceCache() const
2813 d->ref_cache_.clear();
2817 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2820 //FIXME: This does not work for child documents yet.
2821 LASSERT(code == CITE_CODE, /**/);
2822 // Check if the label 'from' appears more than once
2823 vector<docstring> labels;
2825 checkBibInfoCache();
2826 BiblioInfo const & keys = masterBibInfo();
2827 BiblioInfo::const_iterator bit = keys.begin();
2828 BiblioInfo::const_iterator bend = keys.end();
2830 for (; bit != bend; ++bit)
2832 labels.push_back(bit->first);
2835 if (count(labels.begin(), labels.end(), from) > 1)
2838 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2839 if (it->lyxCode() == code) {
2840 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2841 docstring const oldValue = inset.getParam(paramName);
2842 if (oldValue == from)
2843 inset.setParam(paramName, to);
2849 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2850 pit_type par_end, bool full_source) const
2852 OutputParams runparams(¶ms().encoding());
2853 runparams.nice = true;
2854 runparams.flavor = params().useXetex ?
2855 OutputParams::XETEX : OutputParams::LATEX;
2856 runparams.linelen = lyxrc.plaintext_linelen;
2857 // No side effect of file copying and image conversion
2858 runparams.dryrun = true;
2861 os << "% " << _("Preview source code") << "\n\n";
2863 d->texrow.newline();
2864 d->texrow.newline();
2866 writeDocBookSource(os, absFileName(), runparams, false);
2868 // latex or literate
2869 writeLaTeXSource(os, string(), runparams, true, true);
2871 runparams.par_begin = par_begin;
2872 runparams.par_end = par_end;
2873 if (par_begin + 1 == par_end) {
2875 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2879 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2880 convert<docstring>(par_begin),
2881 convert<docstring>(par_end - 1))
2888 // output paragraphs
2890 docbookParagraphs(text(), *this, os, runparams);
2892 // latex or literate
2893 latexParagraphs(*this, text(), os, texrow, runparams);
2898 ErrorList & Buffer::errorList(string const & type) const
2900 static ErrorList emptyErrorList;
2901 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2902 if (I == d->errorLists.end())
2903 return emptyErrorList;
2909 void Buffer::updateTocItem(std::string const & type,
2910 DocIterator const & dit) const
2913 d->gui_->updateTocItem(type, dit);
2917 void Buffer::structureChanged() const
2920 d->gui_->structureChanged();
2924 void Buffer::errors(string const & err, bool from_master) const
2927 d->gui_->errors(err, from_master);
2931 void Buffer::message(docstring const & msg) const
2934 d->gui_->message(msg);
2938 void Buffer::setBusy(bool on) const
2941 d->gui_->setBusy(on);
2945 void Buffer::updateTitles() const
2948 d->wa_->updateTitles();
2952 void Buffer::resetAutosaveTimers() const
2955 d->gui_->resetAutosaveTimers();
2959 bool Buffer::hasGuiDelegate() const
2965 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2974 class AutoSaveBuffer : public ForkedProcess {
2977 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2978 : buffer_(buffer), fname_(fname) {}
2980 virtual boost::shared_ptr<ForkedProcess> clone() const
2982 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2987 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2988 from_utf8(fname_.absFilename())));
2989 return run(DontWait);
2993 virtual int generateChild();
2995 Buffer const & buffer_;
3000 int AutoSaveBuffer::generateChild()
3002 #if defined(__APPLE__)
3003 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3004 * We should use something else like threads.
3006 * Since I do not know how to determine at run time what is the OS X
3007 * version, I just disable forking altogether for now (JMarc)
3009 pid_t const pid = -1;
3011 // tmp_ret will be located (usually) in /tmp
3012 // will that be a problem?
3013 // Note that this calls ForkedCalls::fork(), so it's
3014 // ok cross-platform.
3015 pid_t const pid = fork();
3016 // If you want to debug the autosave
3017 // you should set pid to -1, and comment out the fork.
3018 if (pid != 0 && pid != -1)
3022 // pid = -1 signifies that lyx was unable
3023 // to fork. But we will do the save
3025 bool failed = false;
3026 FileName const tmp_ret = FileName::tempName("lyxauto");
3027 if (!tmp_ret.empty()) {
3028 buffer_.writeFile(tmp_ret);
3029 // assume successful write of tmp_ret
3030 if (!tmp_ret.moveTo(fname_))
3036 // failed to write/rename tmp_ret so try writing direct
3037 if (!buffer_.writeFile(fname_)) {
3038 // It is dangerous to do this in the child,
3039 // but safe in the parent, so...
3040 if (pid == -1) // emit message signal.
3041 buffer_.message(_("Autosave failed!"));
3045 if (pid == 0) // we are the child so...
3054 FileName Buffer::getAutosaveFilename() const
3056 // if the document is unnamed try to save in the backup dir, else
3057 // in the default document path, and as a last try in the filePath,
3058 // which will most often be the temporary directory
3061 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3062 : lyxrc.backupdir_path;
3063 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3066 string const fname = "#" + d->filename.onlyFileName() + "#";
3067 return makeAbsPath(fname, fpath);
3071 void Buffer::removeAutosaveFile() const
3073 FileName const f = getAutosaveFilename();
3079 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3081 FileName const newauto = getAutosaveFilename();
3082 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3083 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3087 // Perfect target for a thread...
3088 void Buffer::autoSave() const
3090 if (d->bak_clean || isReadonly()) {
3091 // We don't save now, but we'll try again later
3092 resetAutosaveTimers();
3096 // emit message signal.
3097 message(_("Autosaving current document..."));
3098 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3101 d->bak_clean = true;
3103 resetAutosaveTimers();
3107 string Buffer::bufferFormat() const
3109 string format = params().documentClass().outputFormat();
3110 if (format == "latex") {
3111 if (params().useXetex)
3113 if (params().encoding().package() == Encoding::japanese)
3120 string Buffer::getDefaultOutputFormat() const
3122 if (!params().defaultOutputFormat.empty()
3123 && params().defaultOutputFormat != "default")
3124 return params().defaultOutputFormat;
3125 typedef vector<Format const *> Formats;
3126 Formats formats = exportableFormats(true);
3129 || params().useXetex
3130 || params().encoding().package() == Encoding::japanese) {
3131 if (formats.empty())
3133 // return the first we find
3134 return formats.front()->name();
3136 return lyxrc.default_view_format;
3141 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3142 bool includeall, string & result_file) const
3144 string backend_format;
3145 OutputParams runparams(¶ms().encoding());
3146 runparams.flavor = OutputParams::LATEX;
3147 runparams.linelen = lyxrc.plaintext_linelen;
3148 runparams.includeall = includeall;
3149 vector<string> backs = backends();
3150 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3151 // Get shortest path to format
3152 Graph::EdgePath path;
3153 for (vector<string>::const_iterator it = backs.begin();
3154 it != backs.end(); ++it) {
3155 Graph::EdgePath p = theConverters().getPath(*it, format);
3156 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3157 backend_format = *it;
3162 if (!put_in_tempdir) {
3163 // Only show this alert if this is an export to a non-temporary
3164 // file (not for previewing).
3165 Alert::error(_("Couldn't export file"), bformat(
3166 _("No information for exporting the format %1$s."),
3167 formats.prettyName(format)));
3171 runparams.flavor = theConverters().getFlavor(path);
3174 backend_format = format;
3175 // FIXME: Don't hardcode format names here, but use a flag
3176 if (backend_format == "pdflatex")
3177 runparams.flavor = OutputParams::PDFLATEX;
3180 string filename = latexName(false);
3181 filename = addName(temppath(), filename);
3182 filename = changeExtension(filename,
3183 formats.extension(backend_format));
3186 updateMacroInstances();
3188 // Plain text backend
3189 if (backend_format == "text") {
3190 runparams.flavor = OutputParams::TEXT;
3191 writePlaintextFile(*this, FileName(filename), runparams);
3194 else if (backend_format == "xhtml") {
3195 runparams.flavor = OutputParams::HTML;
3196 makeLyXHTMLFile(FileName(filename), runparams);
3197 } else if (backend_format == "lyx")
3198 writeFile(FileName(filename));
3200 else if (isDocBook()) {
3201 runparams.nice = !put_in_tempdir;
3202 makeDocBookFile(FileName(filename), runparams);
3205 else if (backend_format == format) {
3206 runparams.nice = true;
3207 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3209 } else if (!lyxrc.tex_allows_spaces
3210 && contains(filePath(), ' ')) {
3211 Alert::error(_("File name error"),
3212 _("The directory path to the document cannot contain spaces."));
3215 runparams.nice = false;
3216 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3220 string const error_type = (format == "program")
3221 ? "Build" : bufferFormat();
3222 ErrorList & error_list = d->errorLists[error_type];
3223 string const ext = formats.extension(format);
3224 FileName const tmp_result_file(changeExtension(filename, ext));
3225 bool const success = theConverters().convert(this, FileName(filename),
3226 tmp_result_file, FileName(absFileName()), backend_format, format,
3228 // Emit the signal to show the error list.
3229 if (format != backend_format) {
3231 // also to the children, in case of master-buffer-view
3232 std::vector<Buffer *> clist = getChildren();
3233 for (vector<Buffer *>::const_iterator cit = clist.begin();
3234 cit != clist.end(); ++cit)
3235 (*cit)->errors(error_type, true);
3240 if (d->cloned_buffer_) {
3241 // Enable reverse dvi or pdf to work by copying back the texrow
3242 // object to the cloned buffer.
3243 // FIXME: There is a possibility of concurrent access to texrow
3244 // here from the main GUI thread that should be securized.
3245 d->cloned_buffer_->d->texrow = d->texrow;
3248 if (put_in_tempdir) {
3249 result_file = tmp_result_file.absFilename();
3253 result_file = changeExtension(exportFileName().absFilename(), ext);
3254 // We need to copy referenced files (e. g. included graphics
3255 // if format == "dvi") to the result dir.
3256 vector<ExportedFile> const files =
3257 runparams.exportdata->externalFiles(format);
3258 string const dest = onlyPath(result_file);
3259 CopyStatus status = SUCCESS;
3261 vector<ExportedFile>::const_iterator it = files.begin();
3262 vector<ExportedFile>::const_iterator const en = files.end();
3263 for (; it != en && status != CANCEL; ++it) {
3264 string const fmt = formats.getFormatFromFile(it->sourceName);
3265 status = copyFile(fmt, it->sourceName,
3266 makeAbsPath(it->exportName, dest),
3267 it->exportName, status == FORCE);
3270 if (status == CANCEL) {
3271 message(_("Document export cancelled."));
3272 } else if (tmp_result_file.exists()) {
3273 // Finally copy the main file
3274 status = copyFile(format, tmp_result_file,
3275 FileName(result_file), result_file,
3277 message(bformat(_("Document exported as %1$s "
3279 formats.prettyName(format),
3280 makeDisplayPath(result_file)));
3282 // This must be a dummy converter like fax (bug 1888)
3283 message(bformat(_("Document exported as %1$s"),
3284 formats.prettyName(format)));
3291 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3292 bool includeall) const
3295 // (1) export with all included children (omit \includeonly)
3296 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3298 // (2) export with included children only
3299 return doExport(format, put_in_tempdir, false, result_file);
3303 bool Buffer::preview(string const & format, bool includeall) const
3306 // (1) export with all included children (omit \includeonly)
3307 if (includeall && !doExport(format, true, true))
3309 // (2) export with included children only
3310 if (!doExport(format, true, false, result_file))
3312 return formats.view(*this, FileName(result_file), format);
3316 bool Buffer::isExportable(string const & format) const
3318 vector<string> backs = backends();
3319 for (vector<string>::const_iterator it = backs.begin();
3320 it != backs.end(); ++it)
3321 if (theConverters().isReachable(*it, format))
3327 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3329 vector<string> const backs = backends();
3330 vector<Format const *> result =
3331 theConverters().getReachable(backs[0], only_viewable, true);
3332 for (vector<string>::const_iterator it = backs.begin() + 1;
3333 it != backs.end(); ++it) {
3334 vector<Format const *> r =
3335 theConverters().getReachable(*it, only_viewable, false);
3336 result.insert(result.end(), r.begin(), r.end());
3342 vector<string> Buffer::backends() const
3345 v.push_back(bufferFormat());
3346 // FIXME: Don't hardcode format names here, but use a flag
3347 if (v.back() == "latex")
3348 v.push_back("pdflatex");
3349 v.push_back("xhtml");
3350 v.push_back("text");
3356 bool Buffer::readFileHelper(FileName const & s)
3358 // File information about normal file
3360 docstring const file = makeDisplayPath(s.absFilename(), 50);
3361 docstring text = bformat(_("The specified document\n%1$s"
3362 "\ncould not be read."), file);
3363 Alert::error(_("Could not read document"), text);
3367 // Check if emergency save file exists and is newer.
3368 FileName const e(s.absFilename() + ".emergency");
3370 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3371 docstring const file = makeDisplayPath(s.absFilename(), 20);
3372 docstring const text =
3373 bformat(_("An emergency save of the document "
3375 "Recover emergency save?"), file);
3376 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3377 _("&Recover"), _("&Load Original"),
3381 // the file is not saved if we load the emergency file.
3386 if ((res = readFile(e)) == success)
3387 str = _("Document was successfully recovered.");
3389 str = _("Document was NOT successfully recovered.");
3390 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3391 from_utf8(e.absFilename()));
3393 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3394 _("&Remove"), _("&Keep it"))) {
3397 Alert::warning(_("Emergency file deleted"),
3398 _("Do not forget to save your file now!"), true);
3403 if (!Alert::prompt(_("Delete emergency file?"),
3404 _("Remove emergency file now?"), 1, 1,
3405 _("&Remove"), _("&Keep it")))
3413 // Now check if autosave file is newer.
3414 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3416 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3417 docstring const file = makeDisplayPath(s.absFilename(), 20);
3418 docstring const text =
3419 bformat(_("The backup of the document "
3420 "%1$s is newer.\n\nLoad the "
3421 "backup instead?"), file);
3422 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3423 _("&Load backup"), _("Load &original"),
3427 // the file is not saved if we load the autosave file.
3431 // Here we delete the autosave
3442 bool Buffer::loadLyXFile(FileName const & s)
3444 // If the file is not readable, we try to
3445 // retrieve the file from version control.
3446 if (!s.isReadableFile()
3447 && !LyXVC::file_not_found_hook(s))
3450 if (s.isReadableFile()
3451 && readFileHelper(s)) {
3452 lyxvc().file_found_hook(s);
3453 setReadonly(!s.isWritable());
3460 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3462 TeXErrors::Errors::const_iterator cit = terr.begin();
3463 TeXErrors::Errors::const_iterator end = terr.end();
3465 for (; cit != end; ++cit) {
3468 int errorRow = cit->error_in_line;
3469 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3475 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3476 } while (found && id_start == id_end && pos_start == pos_end);
3478 errorList.push_back(ErrorItem(cit->error_desc,
3479 cit->error_text, id_start, pos_start, pos_end));
3484 void Buffer::setBuffersForInsets() const
3486 inset().setBuffer(const_cast<Buffer &>(*this));
3490 void Buffer::updateLabels(UpdateScope scope, UpdateType utype) const
3492 // Use the master text class also for child documents
3493 Buffer const * const master = masterBuffer();
3494 DocumentClass const & textclass = master->params().documentClass();
3496 // do this only if we are the top-level Buffer
3497 if (scope != UpdateMaster || master == this)
3498 checkBibInfoCache();
3500 // keep the buffers to be children in this set. If the call from the
3501 // master comes back we can see which of them were actually seen (i.e.
3502 // via an InsetInclude). The remaining ones in the set need still be updated.
3503 static std::set<Buffer const *> bufToUpdate;
3504 if (scope == UpdateMaster) {
3505 // If this is a child document start with the master
3506 if (master != this) {
3507 bufToUpdate.insert(this);
3508 master->updateLabels(UpdateMaster, utype);
3509 // Do this here in case the master has no gui associated with it. Then,
3510 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3511 if (!master->d->gui_)
3514 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3515 if (bufToUpdate.find(this) == bufToUpdate.end())
3519 // start over the counters in the master
3520 textclass.counters().reset();
3523 // update will be done below for this buffer
3524 bufToUpdate.erase(this);
3526 // update all caches
3527 clearReferenceCache();
3530 Buffer & cbuf = const_cast<Buffer &>(*this);
3532 LASSERT(!text().paragraphs().empty(), /**/);
3535 ParIterator parit = cbuf.par_iterator_begin();
3536 updateLabels(parit, utype);
3539 // TocBackend update will be done later.
3542 cbuf.tocBackend().update();
3543 if (scope == UpdateMaster)
3544 cbuf.structureChanged();
3548 static depth_type getDepth(DocIterator const & it)
3550 depth_type depth = 0;
3551 for (size_t i = 0 ; i < it.depth() ; ++i)
3552 if (!it[i].inset().inMathed())
3553 depth += it[i].paragraph().getDepth() + 1;
3554 // remove 1 since the outer inset does not count
3558 static depth_type getItemDepth(ParIterator const & it)
3560 Paragraph const & par = *it;
3561 LabelType const labeltype = par.layout().labeltype;
3563 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3566 // this will hold the lowest depth encountered up to now.
3567 depth_type min_depth = getDepth(it);
3568 ParIterator prev_it = it;
3571 --prev_it.top().pit();
3573 // start of nested inset: go to outer par
3575 if (prev_it.empty()) {
3576 // start of document: nothing to do
3581 // We search for the first paragraph with same label
3582 // that is not more deeply nested.
3583 Paragraph & prev_par = *prev_it;
3584 depth_type const prev_depth = getDepth(prev_it);
3585 if (labeltype == prev_par.layout().labeltype) {
3586 if (prev_depth < min_depth)
3587 return prev_par.itemdepth + 1;
3588 if (prev_depth == min_depth)
3589 return prev_par.itemdepth;
3591 min_depth = min(min_depth, prev_depth);
3592 // small optimization: if we are at depth 0, we won't
3593 // find anything else
3594 if (prev_depth == 0)
3600 static bool needEnumCounterReset(ParIterator const & it)
3602 Paragraph const & par = *it;
3603 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3604 depth_type const cur_depth = par.getDepth();
3605 ParIterator prev_it = it;
3606 while (prev_it.pit()) {
3607 --prev_it.top().pit();
3608 Paragraph const & prev_par = *prev_it;
3609 if (prev_par.getDepth() <= cur_depth)
3610 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3612 // start of nested inset: reset
3617 // set the label of a paragraph. This includes the counters.
3618 void Buffer::setLabel(ParIterator & it, UpdateType utype) const
3620 BufferParams const & bp = this->masterBuffer()->params();
3621 DocumentClass const & textclass = bp.documentClass();
3622 Paragraph & par = it.paragraph();
3623 Layout const & layout = par.layout();
3624 Counters & counters = textclass.counters();
3626 if (par.params().startOfAppendix()) {
3627 // FIXME: only the counter corresponding to toplevel
3628 // sectioning should be reset
3630 counters.appendix(true);
3632 par.params().appendix(counters.appendix());
3634 // Compute the item depth of the paragraph
3635 par.itemdepth = getItemDepth(it);
3637 if (layout.margintype == MARGIN_MANUAL
3638 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3639 if (par.params().labelWidthString().empty())
3640 par.params().labelWidthString(par.expandLabel(layout, bp));
3642 par.params().labelWidthString(docstring());
3645 switch(layout.labeltype) {
3647 if (layout.toclevel <= bp.secnumdepth
3648 && (layout.latextype != LATEX_ENVIRONMENT
3649 || it.text()->isFirstInSequence(it.pit()))) {
3650 counters.step(layout.counter, utype);
3651 par.params().labelString(
3652 par.expandLabel(layout, bp));
3654 par.params().labelString(docstring());
3657 case LABEL_ITEMIZE: {
3658 // At some point of time we should do something more
3659 // clever here, like:
3660 // par.params().labelString(
3661 // bp.user_defined_bullet(par.itemdepth).getText());
3662 // for now, use a simple hardcoded label
3663 docstring itemlabel;
3664 switch (par.itemdepth) {
3666 itemlabel = char_type(0x2022);
3669 itemlabel = char_type(0x2013);
3672 itemlabel = char_type(0x2217);
3675 itemlabel = char_type(0x2219); // or 0x00b7
3678 par.params().labelString(itemlabel);
3682 case LABEL_ENUMERATE: {
3683 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3685 switch (par.itemdepth) {
3694 enumcounter += "iv";
3697 // not a valid enumdepth...
3701 // Maybe we have to reset the enumeration counter.
3702 if (needEnumCounterReset(it))
3703 counters.reset(enumcounter);
3704 counters.step(enumcounter, utype);
3706 string const & lang = par.getParLanguage(bp)->code();
3707 par.params().labelString(counters.theCounter(enumcounter, lang));
3712 case LABEL_SENSITIVE: {
3713 string const & type = counters.current_float();
3714 docstring full_label;
3716 full_label = this->B_("Senseless!!! ");
3718 docstring name = this->B_(textclass.floats().getType(type).name());
3719 if (counters.hasCounter(from_utf8(type))) {
3720 string const & lang = par.getParLanguage(bp)->code();
3721 counters.step(from_utf8(type), utype);
3722 full_label = bformat(from_ascii("%1$s %2$s:"),
3724 counters.theCounter(from_utf8(type), lang));
3726 full_label = bformat(from_ascii("%1$s #:"), name);
3728 par.params().labelString(full_label);
3732 case LABEL_NO_LABEL:
3733 par.params().labelString(docstring());
3737 case LABEL_TOP_ENVIRONMENT:
3738 case LABEL_CENTERED_TOP_ENVIRONMENT:
3741 par.params().labelString(par.expandLabel(layout, bp));
3747 void Buffer::updateLabels(ParIterator & parit, UpdateType utype) const
3749 LASSERT(parit.pit() == 0, /**/);
3751 // set the position of the text in the buffer to be able
3752 // to resolve macros in it. This has nothing to do with
3753 // labels, but by putting it here we avoid implementing
3754 // a whole bunch of traversal routines just for this call.
3755 parit.text()->setMacrocontextPosition(parit);
3757 depth_type maxdepth = 0;
3758 pit_type const lastpit = parit.lastpit();
3759 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3760 // reduce depth if necessary
3761 parit->params().depth(min(parit->params().depth(), maxdepth));
3762 maxdepth = parit->getMaxDepthAfter();
3764 if (utype == OutputUpdate) {
3765 // track the active counters
3766 // we have to do this for the master buffer, since the local
3767 // buffer isn't tracking anything.
3768 masterBuffer()->params().documentClass().counters().
3769 setActiveLayout(parit->layout());
3772 // set the counter for this paragraph
3773 setLabel(parit, utype);
3776 InsetList::const_iterator iit = parit->insetList().begin();
3777 InsetList::const_iterator end = parit->insetList().end();
3778 for (; iit != end; ++iit) {
3779 parit.pos() = iit->pos;
3780 iit->inset->updateLabels(parit, utype);
3786 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3787 WordLangTuple & word_lang, docstring_list & suggestions) const
3791 suggestions.clear();
3792 word_lang = WordLangTuple();
3793 // OK, we start from here.
3794 DocIterator const end = doc_iterator_end(this);
3795 for (; from != end; from.forwardPos()) {
3796 // We are only interested in text so remove the math CursorSlice.
3797 while (from.inMathed()) {
3801 // If from is at the end of the document (which is possible
3802 // when leaving the mathed) LyX will crash later.
3806 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3811 // Do not increase progress when from == to, otherwise the word
3812 // count will be wrong.
3822 bool Buffer::reload()
3825 // e.g., read-only status could have changed due to version control
3826 d->filename.refresh();
3827 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3829 bool const success = loadLyXFile(d->filename);
3834 message(bformat(_("Document %1$s reloaded."), disp_fn));
3836 message(bformat(_("Could not reload document %1$s."), disp_fn));