3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
48 #include "output_docbook.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 376; // jspitzm: support for unincluded file maintenance
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfiles_cache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfo_cache_valid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfile_status_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263 /// This one is useful for preview detached in a thread.
264 Buffer const * cloned_buffer_;
267 /// So we can force access via the accessors.
268 mutable Buffer const * parent_buffer;
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
277 // We are in our own directory. Why bother to mangle name?
278 // In fact I wrote this code to circumvent a problematic behaviour
279 // (bug?) of EMX mkstemp().
280 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281 convert<string>(count++));
283 if (!tmpfl.createDirectory(0777)) {
284 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286 from_utf8(tmpfl.absFilename())));
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293 Buffer const * cloned_buffer)
294 : lyx_clean(true), bak_clean(true), unnamed(false),
295 read_only(readonly_), filename(file), file_fully_loaded(false),
296 toc_backend(&parent), macro_lock(false), timestamp_(0),
297 checksum_(0), wa_(0), undo_(parent), bibinfo_cache_valid_(false),
298 cloned_buffer_(cloned_buffer), parent_buffer(0)
300 if (!cloned_buffer_) {
301 temppath = createBufferTmpDir();
302 lyxvc.setBuffer(&parent);
304 wa_ = new frontend::WorkAreaManager;
307 temppath = cloned_buffer_->d->temppath;
308 file_fully_loaded = true;
309 params = cloned_buffer_->d->params;
310 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
311 bibinfo_ = cloned_buffer_->d->bibinfo_;
312 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
313 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
317 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
318 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
320 LYXERR(Debug::INFO, "Buffer::Buffer()");
322 d->inset = new InsetText(*cloned_buffer->d->inset);
323 d->inset->setBuffer(*this);
324 // FIXME: optimize this loop somewhat, maybe by creating a new
325 // general recursive Inset::setId().
326 DocIterator it = doc_iterator_begin(this);
327 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
328 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
329 it.paragraph().setId(cloned_it.paragraph().id());
331 d->inset = new InsetText(this);
332 d->inset->setAutoBreakRows(true);
333 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
339 LYXERR(Debug::INFO, "Buffer::~Buffer()");
340 // here the buffer should take care that it is
341 // saved properly, before it goes into the void.
343 // GuiView already destroyed
347 // No need to do additional cleanups for internal buffer.
352 // loop over children
353 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
354 Impl::BufferPositionMap::iterator end = d->children_positions.end();
355 for (; it != end; ++it) {
356 Buffer * child = const_cast<Buffer *>(it->first);
357 if (d->cloned_buffer_)
359 // The child buffer might have been closed already.
360 else if (theBufferList().isLoaded(child))
361 theBufferList().releaseChild(this, child);
365 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
366 msg += emergencyWrite();
367 Alert::warning(_("Attempting to close changed document!"), msg);
370 // clear references to children in macro tables
371 d->children_positions.clear();
372 d->position_to_children.clear();
374 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
375 Alert::warning(_("Could not remove temporary directory"),
376 bformat(_("Could not remove the temporary directory %1$s"),
377 from_utf8(d->temppath.absFilename())));
380 // Remove any previewed LaTeX snippets associated with this buffer.
381 thePreviews().removeLoader(*this);
387 Buffer * Buffer::clone() const
389 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
390 buffer_clone->d->macro_lock = true;
391 buffer_clone->d->children_positions.clear();
392 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
393 // math macro caches need to be rethought and simplified.
394 // I am not sure wether we should handle Buffer cloning here or in BufferList.
395 // Right now BufferList knows nothing about buffer clones.
396 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
397 Impl::BufferPositionMap::iterator end = d->children_positions.end();
398 for (; it != end; ++it) {
399 DocIterator dit = it->second.clone(buffer_clone);
400 dit.setBuffer(buffer_clone);
401 Buffer * child = const_cast<Buffer *>(it->first);
402 Buffer * child_clone = child->clone();
403 Inset * inset = dit.nextInset();
404 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
405 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
406 inset_inc->setChildBuffer(child_clone);
407 child_clone->d->setParent(buffer_clone);
408 buffer_clone->setChild(dit, child_clone);
410 buffer_clone->d->macro_lock = false;
415 bool Buffer::isClone() const
417 return d->cloned_buffer_;
421 void Buffer::changed(bool update_metrics) const
424 d->wa_->redrawAll(update_metrics);
428 frontend::WorkAreaManager & Buffer::workAreaManager() const
430 LASSERT(d->wa_, /**/);
435 Text & Buffer::text() const
437 return d->inset->text();
441 Inset & Buffer::inset() const
447 BufferParams & Buffer::params()
453 BufferParams const & Buffer::params() const
459 ParagraphList & Buffer::paragraphs()
461 return text().paragraphs();
465 ParagraphList const & Buffer::paragraphs() const
467 return text().paragraphs();
471 LyXVC & Buffer::lyxvc()
477 LyXVC const & Buffer::lyxvc() const
483 string const Buffer::temppath() const
485 return d->temppath.absFilename();
489 TexRow & Buffer::texrow()
495 TexRow const & Buffer::texrow() const
501 TocBackend & Buffer::tocBackend() const
503 return d->toc_backend;
507 Undo & Buffer::undo()
513 void Buffer::setChild(DocIterator const & dit, Buffer * child)
515 d->children_positions[child] = dit;
519 string Buffer::latexName(bool const no_path) const
521 FileName latex_name =
522 makeLatexName(exportFileName());
523 return no_path ? latex_name.onlyFileName()
524 : latex_name.absFilename();
528 FileName Buffer::exportFileName() const
530 docstring const branch_suffix =
531 params().branchlist().getFilenameSuffix();
532 if (branch_suffix.empty())
535 string const name = fileName().onlyFileNameWithoutExt()
536 + to_utf8(branch_suffix);
537 FileName res(fileName().onlyPath().absFilename() + "/" + name);
538 res.changeExtension(fileName().extension());
544 string Buffer::logName(LogType * type) const
546 string const filename = latexName(false);
548 if (filename.empty()) {
554 string const path = temppath();
556 FileName const fname(addName(temppath(),
557 onlyFilename(changeExtension(filename,
560 // FIXME: how do we know this is the name of the build log?
561 FileName const bname(
562 addName(path, onlyFilename(
563 changeExtension(filename,
564 formats.extension(bufferFormat()) + ".out"))));
566 // Also consider the master buffer log file
567 FileName masterfname = fname;
569 if (masterBuffer() != this) {
570 string const mlogfile = masterBuffer()->logName(&mtype);
571 masterfname = FileName(mlogfile);
574 // If no Latex log or Build log is newer, show Build log
575 if (bname.exists() &&
576 ((!fname.exists() && !masterfname.exists())
577 || (fname.lastModified() < bname.lastModified()
578 && masterfname.lastModified() < bname.lastModified()))) {
579 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
582 return bname.absFilename();
583 // If we have a newer master file log or only a master log, show this
584 } else if (fname != masterfname
585 && (!fname.exists() && (masterfname.exists()
586 || fname.lastModified() < masterfname.lastModified()))) {
587 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
590 return masterfname.absFilename();
592 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
595 return fname.absFilename();
599 void Buffer::setReadonly(bool const flag)
601 if (d->read_only != flag) {
608 void Buffer::setFileName(string const & newfile)
610 d->filename = makeAbsPath(newfile);
611 setReadonly(d->filename.isReadOnly());
616 int Buffer::readHeader(Lexer & lex)
618 int unknown_tokens = 0;
620 int begin_header_line = -1;
622 // Initialize parameters that may be/go lacking in header:
623 params().branchlist().clear();
624 params().preamble.erase();
625 params().options.erase();
626 params().master.erase();
627 params().float_placement.erase();
628 params().paperwidth.erase();
629 params().paperheight.erase();
630 params().leftmargin.erase();
631 params().rightmargin.erase();
632 params().topmargin.erase();
633 params().bottommargin.erase();
634 params().headheight.erase();
635 params().headsep.erase();
636 params().footskip.erase();
637 params().columnsep.erase();
638 params().fontsCJK.erase();
639 params().listings_params.clear();
640 params().clearLayoutModules();
641 params().clearRemovedModules();
642 params().clearIncludedChildren();
643 params().pdfoptions().clear();
644 params().indiceslist().clear();
645 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
647 for (int i = 0; i < 4; ++i) {
648 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
649 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
652 ErrorList & errorList = d->errorLists["Parse"];
661 if (token == "\\end_header")
665 if (token == "\\begin_header") {
666 begin_header_line = line;
670 LYXERR(Debug::PARSER, "Handling document header token: `"
673 string unknown = params().readToken(lex, token, d->filename.onlyPath());
674 if (!unknown.empty()) {
675 if (unknown[0] != '\\' && token == "\\textclass") {
676 Alert::warning(_("Unknown document class"),
677 bformat(_("Using the default document class, because the "
678 "class %1$s is unknown."), from_utf8(unknown)));
681 docstring const s = bformat(_("Unknown token: "
685 errorList.push_back(ErrorItem(_("Document header error"),
690 if (begin_header_line) {
691 docstring const s = _("\\begin_header is missing");
692 errorList.push_back(ErrorItem(_("Document header error"),
696 params().makeDocumentClass();
698 return unknown_tokens;
703 // changed to be public and have one parameter
704 // Returns true if "\end_document" is not read (Asger)
705 bool Buffer::readDocument(Lexer & lex)
707 ErrorList & errorList = d->errorLists["Parse"];
710 if (!lex.checkFor("\\begin_document")) {
711 docstring const s = _("\\begin_document is missing");
712 errorList.push_back(ErrorItem(_("Document header error"),
716 // we are reading in a brand new document
717 LASSERT(paragraphs().empty(), /**/);
721 if (params().outputChanges) {
722 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
723 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
724 LaTeXFeatures::isAvailable("xcolor");
726 if (!dvipost && !xcolorulem) {
727 Alert::warning(_("Changes not shown in LaTeX output"),
728 _("Changes will not be highlighted in LaTeX output, "
729 "because neither dvipost nor xcolor/ulem are installed.\n"
730 "Please install these packages or redefine "
731 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
732 } else if (!xcolorulem) {
733 Alert::warning(_("Changes not shown in LaTeX output"),
734 _("Changes will not be highlighted in LaTeX output "
735 "when using pdflatex, because xcolor and ulem are not installed.\n"
736 "Please install both packages or redefine "
737 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
741 if (!params().master.empty()) {
742 FileName const master_file = makeAbsPath(params().master,
743 onlyPath(absFileName()));
744 if (isLyXFilename(master_file.absFilename())) {
746 checkAndLoadLyXFile(master_file, true);
748 // necessary e.g. after a reload
749 // to re-register the child (bug 5873)
750 // FIXME: clean up updateMacros (here, only
751 // child registering is needed).
752 master->updateMacros();
753 // set master as master buffer, but only
754 // if we are a real child
755 if (master->isChild(this))
757 // if the master is not fully loaded
758 // it is probably just loading this
759 // child. No warning needed then.
760 else if (master->isFullyLoaded())
761 LYXERR0("The master '"
763 << "' assigned to this document ("
765 << ") does not include "
766 "this document. Ignoring the master assignment.");
771 // assure we have a default index
772 params().indiceslist().addDefault(B_("Index"));
775 bool const res = text().read(lex, errorList, d->inset);
779 updateMacroInstances();
784 bool Buffer::readString(string const & s)
786 params().compressed = false;
788 // remove dummy empty par
789 paragraphs().clear();
793 FileName const name = FileName::tempName("Buffer_readString");
794 switch (readFile(lex, name, true)) {
798 // We need to call lyx2lyx, so write the input to a file
799 ofstream os(name.toFilesystemEncoding().c_str());
802 return readFile(name);
812 bool Buffer::readFile(FileName const & filename)
814 FileName fname(filename);
816 params().compressed = fname.isZippedFile();
818 // remove dummy empty par
819 paragraphs().clear();
822 if (readFile(lex, fname) != success)
829 bool Buffer::isFullyLoaded() const
831 return d->file_fully_loaded;
835 void Buffer::setFullyLoaded(bool value)
837 d->file_fully_loaded = value;
841 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
844 LASSERT(!filename.empty(), /**/);
846 // the first (non-comment) token _must_ be...
847 if (!lex.checkFor("\\lyxformat")) {
848 Alert::error(_("Document format failure"),
849 bformat(_("%1$s is not a readable LyX document."),
850 from_utf8(filename.absFilename())));
856 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
857 // if present remove ".," from string.
858 size_t dot = tmp_format.find_first_of(".,");
859 //lyxerr << " dot found at " << dot << endl;
860 if (dot != string::npos)
861 tmp_format.erase(dot, 1);
862 int const file_format = convert<int>(tmp_format);
863 //lyxerr << "format: " << file_format << endl;
865 // save timestamp and checksum of the original disk file, making sure
866 // to not overwrite them with those of the file created in the tempdir
867 // when it has to be converted to the current format.
869 // Save the timestamp and checksum of disk file. If filename is an
870 // emergency file, save the timestamp and checksum of the original lyx file
871 // because isExternallyModified will check for this file. (BUG4193)
872 string diskfile = filename.absFilename();
873 if (suffixIs(diskfile, ".emergency"))
874 diskfile = diskfile.substr(0, diskfile.size() - 10);
875 saveCheckSum(FileName(diskfile));
878 if (file_format != LYX_FORMAT) {
881 // lyx2lyx would fail
884 FileName const tmpfile = FileName::tempName("Buffer_readFile");
885 if (tmpfile.empty()) {
886 Alert::error(_("Conversion failed"),
887 bformat(_("%1$s is from a different"
888 " version of LyX, but a temporary"
889 " file for converting it could"
891 from_utf8(filename.absFilename())));
894 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
895 if (lyx2lyx.empty()) {
896 Alert::error(_("Conversion script not found"),
897 bformat(_("%1$s is from a different"
898 " version of LyX, but the"
899 " conversion script lyx2lyx"
900 " could not be found."),
901 from_utf8(filename.absFilename())));
904 ostringstream command;
905 command << os::python()
906 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
907 << " -t " << convert<string>(LYX_FORMAT)
908 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
909 << ' ' << quoteName(filename.toFilesystemEncoding());
910 string const command_str = command.str();
912 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
914 cmd_ret const ret = runCommand(command_str);
915 if (ret.first != 0) {
916 Alert::error(_("Conversion script failed"),
917 bformat(_("%1$s is from a different version"
918 " of LyX, but the lyx2lyx script"
919 " failed to convert it."),
920 from_utf8(filename.absFilename())));
923 bool const ret = readFile(tmpfile);
924 // Do stuff with tmpfile name and buffer name here.
925 return ret ? success : failure;
930 if (readDocument(lex)) {
931 Alert::error(_("Document format failure"),
932 bformat(_("%1$s ended unexpectedly, which means"
933 " that it is probably corrupted."),
934 from_utf8(filename.absFilename())));
937 d->file_fully_loaded = true;
942 // Should probably be moved to somewhere else: BufferView? LyXView?
943 bool Buffer::save() const
945 // We don't need autosaves in the immediate future. (Asger)
946 resetAutosaveTimers();
948 string const encodedFilename = d->filename.toFilesystemEncoding();
951 bool madeBackup = false;
953 // make a backup if the file already exists
954 if (lyxrc.make_backup && fileName().exists()) {
955 backupName = FileName(absFileName() + '~');
956 if (!lyxrc.backupdir_path.empty()) {
957 string const mangledName =
958 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
959 backupName = FileName(addName(lyxrc.backupdir_path,
962 if (fileName().copyTo(backupName)) {
965 Alert::error(_("Backup failure"),
966 bformat(_("Cannot create backup file %1$s.\n"
967 "Please check whether the directory exists and is writeable."),
968 from_utf8(backupName.absFilename())));
969 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
973 // ask if the disk file has been externally modified (use checksum method)
974 if (fileName().exists() && isExternallyModified(checksum_method)) {
975 docstring const file = makeDisplayPath(absFileName(), 20);
976 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
977 "you want to overwrite this file?"), file);
978 int const ret = Alert::prompt(_("Overwrite modified file?"),
979 text, 1, 1, _("&Overwrite"), _("&Cancel"));
984 if (writeFile(d->filename)) {
988 // Saving failed, so backup is not backup
990 backupName.moveTo(d->filename);
996 bool Buffer::writeFile(FileName const & fname) const
998 if (d->read_only && fname == d->filename)
1001 bool retval = false;
1003 docstring const str = bformat(_("Saving document %1$s..."),
1004 makeDisplayPath(fname.absFilename()));
1007 if (params().compressed) {
1008 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1009 retval = ofs && write(ofs);
1011 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1012 retval = ofs && write(ofs);
1016 message(str + _(" could not write file!"));
1020 removeAutosaveFile();
1022 saveCheckSum(d->filename);
1023 message(str + _(" done."));
1029 docstring Buffer::emergencyWrite()
1031 // No need to save if the buffer has not changed.
1035 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1037 docstring user_message = bformat(
1038 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1040 // We try to save three places:
1041 // 1) Same place as document. Unless it is an unnamed doc.
1043 string s = absFileName();
1046 if (writeFile(FileName(s))) {
1048 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1049 return user_message;
1051 user_message += _(" Save failed! Trying again...\n");
1055 // 2) In HOME directory.
1056 string s = addName(package().home_dir().absFilename(), absFileName());
1058 lyxerr << ' ' << s << endl;
1059 if (writeFile(FileName(s))) {
1061 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1062 return user_message;
1065 user_message += _(" Save failed! Trying yet again...\n");
1067 // 3) In "/tmp" directory.
1068 // MakeAbsPath to prepend the current
1069 // drive letter on OS/2
1070 s = addName(package().temp_dir().absFilename(), absFileName());
1072 lyxerr << ' ' << s << endl;
1073 if (writeFile(FileName(s))) {
1075 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1076 return user_message;
1079 user_message += _(" Save failed! Bummer. Document is lost.");
1082 return user_message;
1086 bool Buffer::write(ostream & ofs) const
1089 // Use the standard "C" locale for file output.
1090 ofs.imbue(locale::classic());
1093 // The top of the file should not be written by params().
1095 // write out a comment in the top of the file
1096 ofs << "#LyX " << lyx_version
1097 << " created this file. For more info see http://www.lyx.org/\n"
1098 << "\\lyxformat " << LYX_FORMAT << "\n"
1099 << "\\begin_document\n";
1101 /// For each author, set 'used' to true if there is a change
1102 /// by this author in the document; otherwise set it to 'false'.
1103 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1104 AuthorList::Authors::const_iterator a_end = params().authors().end();
1105 for (; a_it != a_end; ++a_it)
1106 a_it->setUsed(false);
1108 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1109 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1110 for ( ; it != end; ++it)
1111 it->checkAuthors(params().authors());
1113 // now write out the buffer parameters.
1114 ofs << "\\begin_header\n";
1115 params().writeFile(ofs);
1116 ofs << "\\end_header\n";
1119 ofs << "\n\\begin_body\n";
1121 ofs << "\n\\end_body\n";
1123 // Write marker that shows file is complete
1124 ofs << "\\end_document" << endl;
1126 // Shouldn't really be needed....
1129 // how to check if close went ok?
1130 // Following is an attempt... (BE 20001011)
1132 // good() returns false if any error occured, including some
1133 // formatting error.
1134 // bad() returns true if something bad happened in the buffer,
1135 // which should include file system full errors.
1140 lyxerr << "File was not closed properly." << endl;
1147 bool Buffer::makeLaTeXFile(FileName const & fname,
1148 string const & original_path,
1149 OutputParams const & runparams_in,
1150 bool output_preamble, bool output_body) const
1152 OutputParams runparams = runparams_in;
1153 if (params().useXetex)
1154 runparams.flavor = OutputParams::XETEX;
1156 string const encoding = runparams.encoding->iconvName();
1157 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1160 try { ofs.reset(encoding); }
1161 catch (iconv_codecvt_facet_exception & e) {
1162 lyxerr << "Caught iconv exception: " << e.what() << endl;
1163 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1164 "verify that the support software for your encoding (%1$s) is "
1165 "properly installed"), from_ascii(encoding)));
1168 if (!openFileWrite(ofs, fname))
1171 //TexStream ts(ofs.rdbuf(), &texrow());
1172 ErrorList & errorList = d->errorLists["Export"];
1174 bool failed_export = false;
1177 writeLaTeXSource(ofs, original_path,
1178 runparams, output_preamble, output_body);
1180 catch (EncodingException & e) {
1181 odocstringstream ods;
1182 ods.put(e.failed_char);
1184 oss << "0x" << hex << e.failed_char << dec;
1185 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1186 " (code point %2$s)"),
1187 ods.str(), from_utf8(oss.str()));
1188 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1189 "representable in the chosen encoding.\n"
1190 "Changing the document encoding to utf8 could help."),
1191 e.par_id, e.pos, e.pos + 1));
1192 failed_export = true;
1194 catch (iconv_codecvt_facet_exception & e) {
1195 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1196 _(e.what()), -1, 0, 0));
1197 failed_export = true;
1199 catch (exception const & e) {
1200 errorList.push_back(ErrorItem(_("conversion failed"),
1201 _(e.what()), -1, 0, 0));
1202 failed_export = true;
1205 lyxerr << "Caught some really weird exception..." << endl;
1211 failed_export = true;
1212 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1216 return !failed_export;
1220 void Buffer::writeLaTeXSource(odocstream & os,
1221 string const & original_path,
1222 OutputParams const & runparams_in,
1223 bool const output_preamble, bool const output_body) const
1225 // The child documents, if any, shall be already loaded at this point.
1227 OutputParams runparams = runparams_in;
1229 // Classify the unicode characters appearing in math insets
1230 Encodings::initUnicodeMath(*this);
1232 // validate the buffer.
1233 LYXERR(Debug::LATEX, " Validating buffer...");
1234 LaTeXFeatures features(*this, params(), runparams);
1236 LYXERR(Debug::LATEX, " Buffer validation done.");
1238 // The starting paragraph of the coming rows is the
1239 // first paragraph of the document. (Asger)
1240 if (output_preamble && runparams.nice) {
1241 os << "%% LyX " << lyx_version << " created this file. "
1242 "For more info, see http://www.lyx.org/.\n"
1243 "%% Do not edit unless you really know what "
1245 d->texrow.newline();
1246 d->texrow.newline();
1248 LYXERR(Debug::INFO, "lyx document header finished");
1250 // Don't move this behind the parent_buffer=0 code below,
1251 // because then the macros will not get the right "redefinition"
1252 // flag as they don't see the parent macros which are output before.
1255 // fold macros if possible, still with parent buffer as the
1256 // macros will be put in the prefix anyway.
1257 updateMacroInstances();
1259 // There are a few differences between nice LaTeX and usual files:
1260 // usual is \batchmode and has a
1261 // special input@path to allow the including of figures
1262 // with either \input or \includegraphics (what figinsets do).
1263 // input@path is set when the actual parameter
1264 // original_path is set. This is done for usual tex-file, but not
1265 // for nice-latex-file. (Matthias 250696)
1266 // Note that input@path is only needed for something the user does
1267 // in the preamble, included .tex files or ERT, files included by
1268 // LyX work without it.
1269 if (output_preamble) {
1270 if (!runparams.nice) {
1271 // code for usual, NOT nice-latex-file
1272 os << "\\batchmode\n"; // changed
1273 // from \nonstopmode
1274 d->texrow.newline();
1276 if (!original_path.empty()) {
1278 // We don't know the encoding of inputpath
1279 docstring const inputpath = from_utf8(latex_path(original_path));
1280 os << "\\makeatletter\n"
1281 << "\\def\\input@path{{"
1282 << inputpath << "/}}\n"
1283 << "\\makeatother\n";
1284 d->texrow.newline();
1285 d->texrow.newline();
1286 d->texrow.newline();
1289 // get parent macros (if this buffer has a parent) which will be
1290 // written at the document begin further down.
1291 MacroSet parentMacros;
1292 listParentMacros(parentMacros, features);
1294 // Write the preamble
1295 runparams.use_babel = params().writeLaTeX(os, features,
1297 d->filename.onlyPath());
1299 runparams.use_japanese = features.isRequired("japanese");
1305 os << "\\begin{document}\n";
1306 d->texrow.newline();
1308 // output the parent macros
1309 MacroSet::iterator it = parentMacros.begin();
1310 MacroSet::iterator end = parentMacros.end();
1311 for (; it != end; ++it)
1312 (*it)->write(os, true);
1313 } // output_preamble
1315 d->texrow.start(paragraphs().begin()->id(), 0);
1317 LYXERR(Debug::INFO, "preamble finished, now the body.");
1319 // if we are doing a real file with body, even if this is the
1320 // child of some other buffer, let's cut the link here.
1321 // This happens for example if only a child document is printed.
1322 Buffer const * save_parent = 0;
1323 if (output_preamble) {
1324 save_parent = d->parent();
1329 latexParagraphs(*this, text(), os, d->texrow, runparams);
1331 // Restore the parenthood if needed
1332 if (output_preamble)
1333 d->setParent(save_parent);
1335 // add this just in case after all the paragraphs
1337 d->texrow.newline();
1339 if (output_preamble) {
1340 os << "\\end{document}\n";
1341 d->texrow.newline();
1342 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1344 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1346 runparams_in.encoding = runparams.encoding;
1348 // Just to be sure. (Asger)
1349 d->texrow.newline();
1351 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1352 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1356 bool Buffer::isLatex() const
1358 return params().documentClass().outputType() == LATEX;
1362 bool Buffer::isLiterate() const
1364 return params().documentClass().outputType() == LITERATE;
1368 bool Buffer::isDocBook() const
1370 return params().documentClass().outputType() == DOCBOOK;
1374 void Buffer::makeDocBookFile(FileName const & fname,
1375 OutputParams const & runparams,
1376 bool const body_only) const
1378 LYXERR(Debug::LATEX, "makeDocBookFile...");
1381 if (!openFileWrite(ofs, fname))
1384 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1388 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1392 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1393 OutputParams const & runparams,
1394 bool const only_body) const
1396 LaTeXFeatures features(*this, params(), runparams);
1401 DocumentClass const & tclass = params().documentClass();
1402 string const top_element = tclass.latexname();
1405 if (runparams.flavor == OutputParams::XML)
1406 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1409 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1412 if (! tclass.class_header().empty())
1413 os << from_ascii(tclass.class_header());
1414 else if (runparams.flavor == OutputParams::XML)
1415 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1416 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1418 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1420 docstring preamble = from_utf8(params().preamble);
1421 if (runparams.flavor != OutputParams::XML ) {
1422 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1423 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1424 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1425 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1428 string const name = runparams.nice
1429 ? changeExtension(absFileName(), ".sgml") : fname;
1430 preamble += features.getIncludedFiles(name);
1431 preamble += features.getLyXSGMLEntities();
1433 if (!preamble.empty()) {
1434 os << "\n [ " << preamble << " ]";
1439 string top = top_element;
1441 if (runparams.flavor == OutputParams::XML)
1442 top += params().language->code();
1444 top += params().language->code().substr(0, 2);
1447 if (!params().options.empty()) {
1449 top += params().options;
1452 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1453 << " file was created by LyX " << lyx_version
1454 << "\n See http://www.lyx.org/ for more information -->\n";
1456 params().documentClass().counters().reset();
1460 sgml::openTag(os, top);
1462 docbookParagraphs(text(), *this, os, runparams);
1463 sgml::closeTag(os, top_element);
1467 void Buffer::makeLyXHTMLFile(FileName const & fname,
1468 OutputParams const & runparams,
1469 bool const body_only) const
1471 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1474 if (!openFileWrite(ofs, fname))
1477 writeLyXHTMLSource(ofs, runparams, body_only);
1481 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1485 void Buffer::writeLyXHTMLSource(odocstream & os,
1486 OutputParams const & runparams,
1487 bool const only_body) const
1489 LaTeXFeatures features(*this, params(), runparams);
1491 updateLabels(UpdateMaster, true);
1492 checkBibInfoCache();
1493 d->bibinfo_.makeCitationLabels(*this);
1495 updateMacroInstances();
1498 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1499 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";
1500 // FIXME Language should be set properly.
1501 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1504 // FIXME Presumably need to set this right
1505 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1506 // FIXME Get this during validation? What about other meta-data?
1507 os << "<title>TBA</title>\n";
1509 os << "\n<!-- Text Class Preamble -->\n"
1510 << features.getTClassHTMLPreamble()
1511 << "\n<!-- Premable Snippets -->\n"
1512 << from_utf8(features.getPreambleSnippets());
1514 os << "\n<!-- Layout-provided Styles -->\n";
1515 docstring const styleinfo = features.getTClassHTMLStyles();
1516 if (!styleinfo.empty()) {
1517 os << "<style type='text/css'>\n"
1521 os << "</head>\n<body>\n";
1525 params().documentClass().counters().reset();
1526 xhtmlParagraphs(text(), *this, xs, runparams);
1528 os << "</body>\n</html>\n";
1532 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1533 // Other flags: -wall -v0 -x
1534 int Buffer::runChktex()
1538 // get LaTeX-Filename
1539 FileName const path(temppath());
1540 string const name = addName(path.absFilename(), latexName());
1541 string const org_path = filePath();
1543 PathChanger p(path); // path to LaTeX file
1544 message(_("Running chktex..."));
1546 // Generate the LaTeX file if neccessary
1547 OutputParams runparams(¶ms().encoding());
1548 runparams.flavor = OutputParams::LATEX;
1549 runparams.nice = false;
1550 makeLaTeXFile(FileName(name), org_path, runparams);
1553 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1554 int const res = chktex.run(terr); // run chktex
1557 Alert::error(_("chktex failure"),
1558 _("Could not run chktex successfully."));
1559 } else if (res > 0) {
1560 ErrorList & errlist = d->errorLists["ChkTeX"];
1562 bufferErrors(terr, errlist);
1573 void Buffer::validate(LaTeXFeatures & features) const
1575 params().validate(features);
1579 for_each(paragraphs().begin(), paragraphs().end(),
1580 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1582 if (lyxerr.debugging(Debug::LATEX)) {
1583 features.showStruct();
1588 void Buffer::getLabelList(vector<docstring> & list) const
1590 // If this is a child document, use the parent's list instead.
1591 Buffer const * const pbuf = d->parent();
1593 pbuf->getLabelList(list);
1598 Toc & toc = d->toc_backend.toc("label");
1599 TocIterator toc_it = toc.begin();
1600 TocIterator end = toc.end();
1601 for (; toc_it != end; ++toc_it) {
1602 if (toc_it->depth() == 0)
1603 list.push_back(toc_it->str());
1608 void Buffer::updateBibfilesCache(UpdateScope scope) const
1610 // If this is a child document, use the parent's cache instead.
1611 Buffer const * const pbuf = d->parent();
1612 if (pbuf && scope != UpdateChildOnly) {
1613 pbuf->updateBibfilesCache();
1617 d->bibfiles_cache_.clear();
1618 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1619 if (it->lyxCode() == BIBTEX_CODE) {
1620 InsetBibtex const & inset =
1621 static_cast<InsetBibtex const &>(*it);
1622 support::FileNameList const bibfiles = inset.getBibFiles();
1623 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1626 } else if (it->lyxCode() == INCLUDE_CODE) {
1627 InsetInclude & inset =
1628 static_cast<InsetInclude &>(*it);
1629 inset.updateBibfilesCache();
1630 support::FileNameList const & bibfiles =
1631 inset.getBibfilesCache();
1632 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1637 // the bibinfo cache is now invalid
1638 d->bibinfo_cache_valid_ = false;
1642 void Buffer::invalidateBibinfoCache()
1644 d->bibinfo_cache_valid_ = false;
1648 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1650 // If this is a child document, use the parent's cache instead.
1651 Buffer const * const pbuf = d->parent();
1652 if (pbuf && scope != UpdateChildOnly)
1653 return pbuf->getBibfilesCache();
1655 // We update the cache when first used instead of at loading time.
1656 if (d->bibfiles_cache_.empty())
1657 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1659 return d->bibfiles_cache_;
1663 BiblioInfo const & Buffer::masterBibInfo() const
1665 // if this is a child document and the parent is already loaded
1666 // use the parent's list instead [ale990412]
1667 Buffer const * const tmp = masterBuffer();
1670 return tmp->masterBibInfo();
1671 return localBibInfo();
1675 BiblioInfo const & Buffer::localBibInfo() const
1681 void Buffer::checkBibInfoCache() const
1683 support::FileNameList const & bibfilesCache = getBibfilesCache();
1684 // compare the cached timestamps with the actual ones.
1685 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1686 support::FileNameList::const_iterator en = bibfilesCache.end();
1687 for (; ei != en; ++ ei) {
1688 time_t lastw = ei->lastModified();
1689 time_t prevw = d->bibfile_status_[*ei];
1690 if (lastw != prevw) {
1691 d->bibinfo_cache_valid_ = false;
1692 d->bibfile_status_[*ei] = lastw;
1696 if (!d->bibinfo_cache_valid_) {
1697 d->bibinfo_.clear();
1698 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1699 it->fillWithBibKeys(d->bibinfo_, it);
1700 d->bibinfo_cache_valid_ = true;
1705 bool Buffer::isDepClean(string const & name) const
1707 DepClean::const_iterator const it = d->dep_clean.find(name);
1708 if (it == d->dep_clean.end())
1714 void Buffer::markDepClean(string const & name)
1716 d->dep_clean[name] = true;
1720 bool Buffer::isExportableFormat(string const & format) const
1722 typedef vector<Format const *> Formats;
1724 formats = exportableFormats(true);
1725 Formats::const_iterator fit = formats.begin();
1726 Formats::const_iterator end = formats.end();
1727 for (; fit != end ; ++fit) {
1728 if ((*fit)->name() == format)
1735 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1738 // FIXME? if there is an Buffer LFUN that can be dispatched even
1739 // if internal, put a switch '(cmd.action)' here.
1745 switch (cmd.action) {
1747 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1748 flag.setOnOff(isReadonly());
1751 // FIXME: There is need for a command-line import.
1752 //case LFUN_BUFFER_IMPORT:
1754 case LFUN_BUFFER_AUTO_SAVE:
1757 case LFUN_BUFFER_EXPORT_CUSTOM:
1758 // FIXME: Nothing to check here?
1761 case LFUN_BUFFER_EXPORT: {
1762 docstring const arg = cmd.argument();
1763 enable = arg == "custom" || isExportable(to_utf8(arg));
1765 flag.message(bformat(
1766 _("Don't know how to export to format: %1$s"), arg));
1770 case LFUN_BUFFER_CHKTEX:
1771 enable = isLatex() && !lyxrc.chktex_command.empty();
1774 case LFUN_BUILD_PROGRAM:
1775 enable = isExportable("program");
1778 case LFUN_BRANCH_ACTIVATE:
1779 case LFUN_BRANCH_DEACTIVATE: {
1780 BranchList const & branchList = params().branchlist();
1781 docstring const branchName = cmd.argument();
1782 enable = !branchName.empty() && branchList.find(branchName);
1786 case LFUN_BRANCH_ADD:
1787 case LFUN_BRANCHES_RENAME:
1788 case LFUN_BUFFER_PRINT:
1789 // if no Buffer is present, then of course we won't be called!
1792 case LFUN_BUFFER_LANGUAGE:
1793 enable = !isReadonly();
1799 flag.setEnabled(enable);
1804 void Buffer::dispatch(string const & command, DispatchResult & result)
1806 return dispatch(lyxaction.lookupFunc(command), result);
1810 // NOTE We can end up here even if we have no GUI, because we are called
1811 // by LyX::exec to handled command-line requests. So we may need to check
1812 // whether we have a GUI or not. The boolean use_gui holds this information.
1813 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1816 // FIXME? if there is an Buffer LFUN that can be dispatched even
1817 // if internal, put a switch '(cmd.action)' here.
1818 dr.dispatched(false);
1821 string const argument = to_utf8(func.argument());
1822 // We'll set this back to false if need be.
1823 bool dispatched = true;
1824 undo().beginUndoGroup();
1826 switch (func.action) {
1827 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1828 if (lyxvc().inUse())
1829 lyxvc().toggleReadOnly();
1831 setReadonly(!isReadonly());
1834 case LFUN_BUFFER_EXPORT: {
1835 bool success = doExport(argument, false, false);
1836 dr.setError(success);
1838 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1843 case LFUN_BUILD_PROGRAM:
1844 doExport("program", true, false);
1847 case LFUN_BUFFER_CHKTEX:
1851 case LFUN_BUFFER_EXPORT_CUSTOM: {
1853 string command = split(argument, format_name, ' ');
1854 Format const * format = formats.getFormat(format_name);
1856 lyxerr << "Format \"" << format_name
1857 << "\" not recognized!"
1862 // The name of the file created by the conversion process
1865 // Output to filename
1866 if (format->name() == "lyx") {
1867 string const latexname = latexName(false);
1868 filename = changeExtension(latexname,
1869 format->extension());
1870 filename = addName(temppath(), filename);
1872 if (!writeFile(FileName(filename)))
1876 doExport(format_name, true, false, filename);
1879 // Substitute $$FName for filename
1880 if (!contains(command, "$$FName"))
1881 command = "( " + command + " ) < $$FName";
1882 command = subst(command, "$$FName", filename);
1884 // Execute the command in the background
1886 call.startscript(Systemcall::DontWait, command);
1890 // FIXME: There is need for a command-line import.
1892 case LFUN_BUFFER_IMPORT:
1897 case LFUN_BUFFER_AUTO_SAVE:
1901 case LFUN_BRANCH_ADD: {
1902 docstring const branch_name = func.argument();
1903 if (branch_name.empty()) {
1907 BranchList & branch_list = params().branchlist();
1908 Branch * branch = branch_list.find(branch_name);
1910 LYXERR0("Branch " << branch_name << " already exists.");
1912 docstring const msg =
1913 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1916 branch_list.add(branch_name);
1917 branch = branch_list.find(branch_name);
1918 string const x11hexname = X11hexname(branch->color());
1919 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1920 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1922 dr.update(Update::Force);
1927 case LFUN_BRANCH_ACTIVATE:
1928 case LFUN_BRANCH_DEACTIVATE: {
1929 BranchList & branchList = params().branchlist();
1930 docstring const branchName = func.argument();
1931 // the case without a branch name is handled elsewhere
1932 if (branchName.empty()) {
1936 Branch * branch = branchList.find(branchName);
1938 LYXERR0("Branch " << branchName << " does not exist.");
1940 docstring const msg =
1941 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1944 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1946 dr.update(Update::Force);
1951 case LFUN_BRANCHES_RENAME: {
1952 if (func.argument().empty())
1955 docstring const oldname = from_utf8(func.getArg(0));
1956 docstring const newname = from_utf8(func.getArg(1));
1957 InsetIterator it = inset_iterator_begin(inset());
1958 InsetIterator const end = inset_iterator_end(inset());
1959 bool success = false;
1960 for (; it != end; ++it) {
1961 if (it->lyxCode() == BRANCH_CODE) {
1962 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1963 if (ins.branch() == oldname) {
1964 undo().recordUndo(it);
1965 ins.rename(newname);
1970 if (it->lyxCode() == INCLUDE_CODE) {
1971 // get buffer of external file
1972 InsetInclude const & ins =
1973 static_cast<InsetInclude const &>(*it);
1974 Buffer * child = ins.getChildBuffer();
1977 child->dispatch(func, dr);
1982 dr.update(Update::Force);
1986 case LFUN_BUFFER_PRINT: {
1987 // we'll assume there's a problem until we succeed
1989 string target = func.getArg(0);
1990 string target_name = func.getArg(1);
1991 string command = func.getArg(2);
1994 || target_name.empty()
1995 || command.empty()) {
1996 LYXERR0("Unable to parse " << func.argument());
1997 docstring const msg =
1998 bformat(_("Unable to parse \"%1$s\""), func.argument());
2002 if (target != "printer" && target != "file") {
2003 LYXERR0("Unrecognized target \"" << target << '"');
2004 docstring const msg =
2005 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2010 bool const update_unincluded =
2011 params().maintain_unincluded_children
2012 && !params().getIncludedChildren().empty();
2013 if (!doExport("dvi", true, update_unincluded)) {
2014 showPrintError(absFileName());
2015 dr.setMessage(_("Error exporting to DVI."));
2019 // Push directory path.
2020 string const path = temppath();
2021 // Prevent the compiler from optimizing away p
2025 // there are three cases here:
2026 // 1. we print to a file
2027 // 2. we print directly to a printer
2028 // 3. we print using a spool command (print to file first)
2031 string const dviname = changeExtension(latexName(true), "dvi");
2033 if (target == "printer") {
2034 if (!lyxrc.print_spool_command.empty()) {
2035 // case 3: print using a spool
2036 string const psname = changeExtension(dviname,".ps");
2037 command += ' ' + lyxrc.print_to_file
2040 + quoteName(dviname);
2042 string command2 = lyxrc.print_spool_command + ' ';
2043 if (target_name != "default") {
2044 command2 += lyxrc.print_spool_printerprefix
2048 command2 += quoteName(psname);
2050 // If successful, then spool command
2051 res = one.startscript(Systemcall::Wait, command);
2054 // If there's no GUI, we have to wait on this command. Otherwise,
2055 // LyX deletes the temporary directory, and with it the spooled
2056 // file, before it can be printed!!
2057 Systemcall::Starttype stype = use_gui ?
2058 Systemcall::DontWait : Systemcall::Wait;
2059 res = one.startscript(stype, command2);
2062 // case 2: print directly to a printer
2063 if (target_name != "default")
2064 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2066 Systemcall::Starttype stype = use_gui ?
2067 Systemcall::DontWait : Systemcall::Wait;
2068 res = one.startscript(stype, command + quoteName(dviname));
2072 // case 1: print to a file
2073 FileName const filename(makeAbsPath(target_name, filePath()));
2074 FileName const dvifile(makeAbsPath(dviname, path));
2075 if (filename.exists()) {
2076 docstring text = bformat(
2077 _("The file %1$s already exists.\n\n"
2078 "Do you want to overwrite that file?"),
2079 makeDisplayPath(filename.absFilename()));
2080 if (Alert::prompt(_("Overwrite file?"),
2081 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2084 command += ' ' + lyxrc.print_to_file
2085 + quoteName(filename.toFilesystemEncoding())
2087 + quoteName(dvifile.toFilesystemEncoding());
2089 Systemcall::Starttype stype = use_gui ?
2090 Systemcall::DontWait : Systemcall::Wait;
2091 res = one.startscript(stype, command);
2097 dr.setMessage(_("Error running external commands."));
2098 showPrintError(absFileName());
2103 case LFUN_BUFFER_LANGUAGE: {
2104 Language const * oldL = params().language;
2105 Language const * newL = languages.getLanguage(argument);
2106 if (!newL || oldL == newL)
2108 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2109 changeLanguage(oldL, newL);
2117 dr.dispatched(dispatched);
2118 undo().endUndoGroup();
2122 void Buffer::changeLanguage(Language const * from, Language const * to)
2124 LASSERT(from, /**/);
2127 for_each(par_iterator_begin(),
2129 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2133 bool Buffer::isMultiLingual() const
2135 ParConstIterator end = par_iterator_end();
2136 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2137 if (it->isMultiLingual(params()))
2144 DocIterator Buffer::getParFromID(int const id) const
2146 Buffer * buf = const_cast<Buffer *>(this);
2148 // John says this is called with id == -1 from undo
2149 lyxerr << "getParFromID(), id: " << id << endl;
2150 return doc_iterator_end(buf);
2153 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2154 if (it.paragraph().id() == id)
2157 return doc_iterator_end(buf);
2161 bool Buffer::hasParWithID(int const id) const
2163 return !getParFromID(id).atEnd();
2167 ParIterator Buffer::par_iterator_begin()
2169 return ParIterator(doc_iterator_begin(this));
2173 ParIterator Buffer::par_iterator_end()
2175 return ParIterator(doc_iterator_end(this));
2179 ParConstIterator Buffer::par_iterator_begin() const
2181 return ParConstIterator(doc_iterator_begin(this));
2185 ParConstIterator Buffer::par_iterator_end() const
2187 return ParConstIterator(doc_iterator_end(this));
2191 Language const * Buffer::language() const
2193 return params().language;
2197 docstring const Buffer::B_(string const & l10n) const
2199 return params().B_(l10n);
2203 bool Buffer::isClean() const
2205 return d->lyx_clean;
2209 bool Buffer::isBakClean() const
2211 return d->bak_clean;
2215 bool Buffer::isExternallyModified(CheckMethod method) const
2217 LASSERT(d->filename.exists(), /**/);
2218 // if method == timestamp, check timestamp before checksum
2219 return (method == checksum_method
2220 || d->timestamp_ != d->filename.lastModified())
2221 && d->checksum_ != d->filename.checksum();
2225 void Buffer::saveCheckSum(FileName const & file) const
2227 if (file.exists()) {
2228 d->timestamp_ = file.lastModified();
2229 d->checksum_ = file.checksum();
2231 // in the case of save to a new file.
2238 void Buffer::markClean() const
2240 if (!d->lyx_clean) {
2241 d->lyx_clean = true;
2244 // if the .lyx file has been saved, we don't need an
2246 d->bak_clean = true;
2250 void Buffer::markBakClean() const
2252 d->bak_clean = true;
2256 void Buffer::setUnnamed(bool flag)
2262 bool Buffer::isUnnamed() const
2269 /// Don't check unnamed, here: isInternal() is used in
2270 /// newBuffer(), where the unnamed flag has not been set by anyone
2271 /// yet. Also, for an internal buffer, there should be no need for
2272 /// retrieving fileName() nor for checking if it is unnamed or not.
2273 bool Buffer::isInternal() const
2275 return fileName().extension() == "internal";
2279 void Buffer::markDirty()
2282 d->lyx_clean = false;
2285 d->bak_clean = false;
2287 DepClean::iterator it = d->dep_clean.begin();
2288 DepClean::const_iterator const end = d->dep_clean.end();
2290 for (; it != end; ++it)
2295 FileName Buffer::fileName() const
2301 string Buffer::absFileName() const
2303 return d->filename.absFilename();
2307 string Buffer::filePath() const
2309 return d->filename.onlyPath().absFilename() + "/";
2313 bool Buffer::isReadonly() const
2315 return d->read_only;
2319 void Buffer::setParent(Buffer const * buffer)
2321 // Avoids recursive include.
2322 d->setParent(buffer == this ? 0 : buffer);
2327 Buffer const * Buffer::parent() const
2333 void Buffer::collectRelatives(BufferSet & bufs) const
2337 parent()->collectRelatives(bufs);
2339 // loop over children
2340 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2341 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2342 for (; it != end; ++it)
2343 bufs.insert(const_cast<Buffer *>(it->first));
2347 std::vector<Buffer const *> Buffer::allRelatives() const
2350 collectRelatives(bufs);
2351 BufferSet::iterator it = bufs.begin();
2352 std::vector<Buffer const *> ret;
2353 for (; it != bufs.end(); ++it)
2359 Buffer const * Buffer::masterBuffer() const
2361 Buffer const * const pbuf = d->parent();
2365 return pbuf->masterBuffer();
2369 bool Buffer::isChild(Buffer * child) const
2371 return d->children_positions.find(child) != d->children_positions.end();
2375 DocIterator Buffer::firstChildPosition(Buffer const * child)
2377 Impl::BufferPositionMap::iterator it;
2378 it = d->children_positions.find(child);
2379 if (it == d->children_positions.end())
2380 return DocIterator(this);
2385 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2387 // loop over children
2388 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2389 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2390 for (; it != end; ++it) {
2391 Buffer * child = const_cast<Buffer *>(it->first);
2392 clist.push_back(child);
2393 if (grand_children) {
2394 // there might be grandchildren
2395 std::vector<Buffer *> glist = child->getChildren();
2396 for (vector<Buffer *>::const_iterator git = glist.begin();
2397 git != glist.end(); ++git)
2398 clist.push_back(*git);
2404 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2406 std::vector<Buffer *> v;
2407 getChildren(v, grand_children);
2412 template<typename M>
2413 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2418 typename M::iterator it = m.lower_bound(x);
2419 if (it == m.begin())
2427 MacroData const * Buffer::getBufferMacro(docstring const & name,
2428 DocIterator const & pos) const
2430 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2432 // if paragraphs have no macro context set, pos will be empty
2436 // we haven't found anything yet
2437 DocIterator bestPos = par_iterator_begin();
2438 MacroData const * bestData = 0;
2440 // find macro definitions for name
2441 Impl::NamePositionScopeMacroMap::iterator nameIt
2442 = d->macros.find(name);
2443 if (nameIt != d->macros.end()) {
2444 // find last definition in front of pos or at pos itself
2445 Impl::PositionScopeMacroMap::const_iterator it
2446 = greatest_below(nameIt->second, pos);
2447 if (it != nameIt->second.end()) {
2449 // scope ends behind pos?
2450 if (pos < it->second.first) {
2451 // Looks good, remember this. If there
2452 // is no external macro behind this,
2453 // we found the right one already.
2454 bestPos = it->first;
2455 bestData = &it->second.second;
2459 // try previous macro if there is one
2460 if (it == nameIt->second.begin())
2467 // find macros in included files
2468 Impl::PositionScopeBufferMap::const_iterator it
2469 = greatest_below(d->position_to_children, pos);
2470 if (it == d->position_to_children.end())
2471 // no children before
2475 // do we know something better (i.e. later) already?
2476 if (it->first < bestPos )
2479 // scope ends behind pos?
2480 if (pos < it->second.first) {
2481 // look for macro in external file
2482 d->macro_lock = true;
2483 MacroData const * data
2484 = it->second.second->getMacro(name, false);
2485 d->macro_lock = false;
2487 bestPos = it->first;
2493 // try previous file if there is one
2494 if (it == d->position_to_children.begin())
2499 // return the best macro we have found
2504 MacroData const * Buffer::getMacro(docstring const & name,
2505 DocIterator const & pos, bool global) const
2510 // query buffer macros
2511 MacroData const * data = getBufferMacro(name, pos);
2515 // If there is a master buffer, query that
2516 Buffer const * const pbuf = d->parent();
2518 d->macro_lock = true;
2519 MacroData const * macro = pbuf->getMacro(
2520 name, *this, false);
2521 d->macro_lock = false;
2527 data = MacroTable::globalMacros().get(name);
2536 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2538 // set scope end behind the last paragraph
2539 DocIterator scope = par_iterator_begin();
2540 scope.pit() = scope.lastpit() + 1;
2542 return getMacro(name, scope, global);
2546 MacroData const * Buffer::getMacro(docstring const & name,
2547 Buffer const & child, bool global) const
2549 // look where the child buffer is included first
2550 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2551 if (it == d->children_positions.end())
2554 // check for macros at the inclusion position
2555 return getMacro(name, it->second, global);
2559 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2561 pit_type const lastpit = it.lastpit();
2563 // look for macros in each paragraph
2564 while (it.pit() <= lastpit) {
2565 Paragraph & par = it.paragraph();
2567 // iterate over the insets of the current paragraph
2568 InsetList const & insets = par.insetList();
2569 InsetList::const_iterator iit = insets.begin();
2570 InsetList::const_iterator end = insets.end();
2571 for (; iit != end; ++iit) {
2572 it.pos() = iit->pos;
2574 // is it a nested text inset?
2575 if (iit->inset->asInsetText()) {
2576 // Inset needs its own scope?
2577 InsetText const * itext = iit->inset->asInsetText();
2578 bool newScope = itext->isMacroScope();
2580 // scope which ends just behind the inset
2581 DocIterator insetScope = it;
2584 // collect macros in inset
2585 it.push_back(CursorSlice(*iit->inset));
2586 updateMacros(it, newScope ? insetScope : scope);
2591 // is it an external file?
2592 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2593 // get buffer of external file
2594 InsetInclude const & inset =
2595 static_cast<InsetInclude const &>(*iit->inset);
2596 d->macro_lock = true;
2597 Buffer * child = inset.getChildBuffer();
2598 d->macro_lock = false;
2602 // register its position, but only when it is
2603 // included first in the buffer
2604 if (d->children_positions.find(child) ==
2605 d->children_positions.end())
2606 d->children_positions[child] = it;
2608 // register child with its scope
2609 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2613 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2617 MathMacroTemplate & macroTemplate =
2618 static_cast<MathMacroTemplate &>(*iit->inset);
2619 MacroContext mc(this, it);
2620 macroTemplate.updateToContext(mc);
2623 bool valid = macroTemplate.validMacro();
2624 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2625 // then the BufferView's cursor will be invalid in
2626 // some cases which leads to crashes.
2631 // FIXME (Abdel), I don't understandt why we pass 'it' here
2632 // instead of 'macroTemplate' defined above... is this correct?
2633 d->macros[macroTemplate.name()][it] =
2634 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2644 void Buffer::updateMacros() const
2649 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2651 // start with empty table
2653 d->children_positions.clear();
2654 d->position_to_children.clear();
2656 // Iterate over buffer, starting with first paragraph
2657 // The scope must be bigger than any lookup DocIterator
2658 // later. For the global lookup, lastpit+1 is used, hence
2659 // we use lastpit+2 here.
2660 DocIterator it = par_iterator_begin();
2661 DocIterator outerScope = it;
2662 outerScope.pit() = outerScope.lastpit() + 2;
2663 updateMacros(it, outerScope);
2667 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2669 InsetIterator it = inset_iterator_begin(inset());
2670 InsetIterator const end = inset_iterator_end(inset());
2671 for (; it != end; ++it) {
2672 if (it->lyxCode() == BRANCH_CODE) {
2673 InsetBranch & br = static_cast<InsetBranch &>(*it);
2674 docstring const name = br.branch();
2675 if (!from_master && !params().branchlist().find(name))
2676 result.push_back(name);
2677 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2678 result.push_back(name);
2681 if (it->lyxCode() == INCLUDE_CODE) {
2682 // get buffer of external file
2683 InsetInclude const & ins =
2684 static_cast<InsetInclude const &>(*it);
2685 Buffer * child = ins.getChildBuffer();
2688 child->getUsedBranches(result, true);
2691 // remove duplicates
2696 void Buffer::updateMacroInstances() const
2698 LYXERR(Debug::MACROS, "updateMacroInstances for "
2699 << d->filename.onlyFileName());
2700 DocIterator it = doc_iterator_begin(this);
2702 DocIterator const end = doc_iterator_end(this);
2703 for (; it != end; it.forwardInset()) {
2704 // look for MathData cells in InsetMathNest insets
2705 InsetMath * minset = it.nextInset()->asInsetMath();
2709 // update macro in all cells of the InsetMathNest
2710 DocIterator::idx_type n = minset->nargs();
2711 MacroContext mc = MacroContext(this, it);
2712 for (DocIterator::idx_type i = 0; i < n; ++i) {
2713 MathData & data = minset->cell(i);
2714 data.updateMacros(0, mc);
2720 void Buffer::listMacroNames(MacroNameSet & macros) const
2725 d->macro_lock = true;
2727 // loop over macro names
2728 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2729 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2730 for (; nameIt != nameEnd; ++nameIt)
2731 macros.insert(nameIt->first);
2733 // loop over children
2734 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2735 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2736 for (; it != end; ++it)
2737 it->first->listMacroNames(macros);
2740 Buffer const * const pbuf = d->parent();
2742 pbuf->listMacroNames(macros);
2744 d->macro_lock = false;
2748 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2750 Buffer const * const pbuf = d->parent();
2755 pbuf->listMacroNames(names);
2758 MacroNameSet::iterator it = names.begin();
2759 MacroNameSet::iterator end = names.end();
2760 for (; it != end; ++it) {
2762 MacroData const * data =
2763 pbuf->getMacro(*it, *this, false);
2765 macros.insert(data);
2767 // we cannot access the original MathMacroTemplate anymore
2768 // here to calls validate method. So we do its work here manually.
2769 // FIXME: somehow make the template accessible here.
2770 if (data->optionals() > 0)
2771 features.require("xargs");
2777 Buffer::References & Buffer::references(docstring const & label)
2780 return const_cast<Buffer *>(masterBuffer())->references(label);
2782 RefCache::iterator it = d->ref_cache_.find(label);
2783 if (it != d->ref_cache_.end())
2784 return it->second.second;
2786 static InsetLabel const * dummy_il = 0;
2787 static References const dummy_refs;
2788 it = d->ref_cache_.insert(
2789 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2790 return it->second.second;
2794 Buffer::References const & Buffer::references(docstring const & label) const
2796 return const_cast<Buffer *>(this)->references(label);
2800 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2802 masterBuffer()->d->ref_cache_[label].first = il;
2806 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2808 return masterBuffer()->d->ref_cache_[label].first;
2812 void Buffer::clearReferenceCache() const
2815 d->ref_cache_.clear();
2819 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2822 //FIXME: This does not work for child documents yet.
2823 LASSERT(code == CITE_CODE, /**/);
2824 // Check if the label 'from' appears more than once
2825 vector<docstring> labels;
2827 checkBibInfoCache();
2828 BiblioInfo const & keys = masterBibInfo();
2829 BiblioInfo::const_iterator bit = keys.begin();
2830 BiblioInfo::const_iterator bend = keys.end();
2832 for (; bit != bend; ++bit)
2834 labels.push_back(bit->first);
2837 if (count(labels.begin(), labels.end(), from) > 1)
2840 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2841 if (it->lyxCode() == code) {
2842 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2843 docstring const oldValue = inset.getParam(paramName);
2844 if (oldValue == from)
2845 inset.setParam(paramName, to);
2851 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2852 pit_type par_end, bool full_source) const
2854 OutputParams runparams(¶ms().encoding());
2855 runparams.nice = true;
2856 runparams.flavor = params().useXetex ?
2857 OutputParams::XETEX : OutputParams::LATEX;
2858 runparams.linelen = lyxrc.plaintext_linelen;
2859 // No side effect of file copying and image conversion
2860 runparams.dryrun = true;
2863 os << "% " << _("Preview source code") << "\n\n";
2865 d->texrow.newline();
2866 d->texrow.newline();
2868 writeDocBookSource(os, absFileName(), runparams, false);
2870 // latex or literate
2871 writeLaTeXSource(os, string(), runparams, true, true);
2873 runparams.par_begin = par_begin;
2874 runparams.par_end = par_end;
2875 if (par_begin + 1 == par_end) {
2877 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2881 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2882 convert<docstring>(par_begin),
2883 convert<docstring>(par_end - 1))
2890 // output paragraphs
2892 docbookParagraphs(text(), *this, os, runparams);
2894 // latex or literate
2895 latexParagraphs(*this, text(), os, texrow, runparams);
2900 ErrorList & Buffer::errorList(string const & type) const
2902 static ErrorList emptyErrorList;
2903 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2904 if (I == d->errorLists.end())
2905 return emptyErrorList;
2911 void Buffer::updateTocItem(std::string const & type,
2912 DocIterator const & dit) const
2915 gui_->updateTocItem(type, dit);
2919 void Buffer::structureChanged() const
2922 gui_->structureChanged();
2926 void Buffer::errors(string const & err, bool from_master) const
2929 gui_->errors(err, from_master);
2933 void Buffer::message(docstring const & msg) const
2940 void Buffer::setBusy(bool on) const
2947 void Buffer::setReadOnly(bool on) const
2950 d->wa_->setReadOnly(on);
2954 void Buffer::updateTitles() const
2957 d->wa_->updateTitles();
2961 void Buffer::resetAutosaveTimers() const
2964 gui_->resetAutosaveTimers();
2968 bool Buffer::hasGuiDelegate() const
2974 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2983 class AutoSaveBuffer : public ForkedProcess {
2986 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2987 : buffer_(buffer), fname_(fname) {}
2989 virtual boost::shared_ptr<ForkedProcess> clone() const
2991 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2996 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2997 from_utf8(fname_.absFilename())));
2998 return run(DontWait);
3002 virtual int generateChild();
3004 Buffer const & buffer_;
3009 int AutoSaveBuffer::generateChild()
3011 #if defined(__APPLE__)
3012 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3013 * We should use something else like threads.
3015 * Since I do not know how to determine at run time what is the OS X
3016 * version, I just disable forking altogether for now (JMarc)
3018 pid_t const pid = -1;
3020 // tmp_ret will be located (usually) in /tmp
3021 // will that be a problem?
3022 // Note that this calls ForkedCalls::fork(), so it's
3023 // ok cross-platform.
3024 pid_t const pid = fork();
3025 // If you want to debug the autosave
3026 // you should set pid to -1, and comment out the fork.
3027 if (pid != 0 && pid != -1)
3031 // pid = -1 signifies that lyx was unable
3032 // to fork. But we will do the save
3034 bool failed = false;
3035 FileName const tmp_ret = FileName::tempName("lyxauto");
3036 if (!tmp_ret.empty()) {
3037 buffer_.writeFile(tmp_ret);
3038 // assume successful write of tmp_ret
3039 if (!tmp_ret.moveTo(fname_))
3045 // failed to write/rename tmp_ret so try writing direct
3046 if (!buffer_.writeFile(fname_)) {
3047 // It is dangerous to do this in the child,
3048 // but safe in the parent, so...
3049 if (pid == -1) // emit message signal.
3050 buffer_.message(_("Autosave failed!"));
3054 if (pid == 0) // we are the child so...
3063 FileName Buffer::getAutosaveFilename() const
3065 // if the document is unnamed try to save in the backup dir, else
3066 // in the default document path, and as a last try in the filePath,
3067 // which will most often be the temporary directory
3070 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3071 : lyxrc.backupdir_path;
3072 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3075 string const fname = "#" + d->filename.onlyFileName() + "#";
3076 return makeAbsPath(fname, fpath);
3080 void Buffer::removeAutosaveFile() const
3082 FileName const f = getAutosaveFilename();
3088 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3090 FileName const newauto = getAutosaveFilename();
3091 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3092 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3096 // Perfect target for a thread...
3097 void Buffer::autoSave() const
3099 if (isBakClean() || isReadonly()) {
3100 // We don't save now, but we'll try again later
3101 resetAutosaveTimers();
3105 // emit message signal.
3106 message(_("Autosaving current document..."));
3107 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3111 resetAutosaveTimers();
3115 string Buffer::bufferFormat() const
3117 string format = params().documentClass().outputFormat();
3118 if (format == "latex") {
3119 if (params().useXetex)
3121 if (params().encoding().package() == Encoding::japanese)
3128 string Buffer::getDefaultOutputFormat() const
3130 if (!params().defaultOutputFormat.empty()
3131 && params().defaultOutputFormat != "default")
3132 return params().defaultOutputFormat;
3133 typedef vector<Format const *> Formats;
3134 Formats formats = exportableFormats(true);
3137 || params().useXetex
3138 || params().encoding().package() == Encoding::japanese) {
3139 if (formats.empty())
3141 // return the first we find
3142 return formats.front()->name();
3144 return lyxrc.default_view_format;
3149 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3150 bool includeall, string & result_file) const
3152 string backend_format;
3153 OutputParams runparams(¶ms().encoding());
3154 runparams.flavor = OutputParams::LATEX;
3155 runparams.linelen = lyxrc.plaintext_linelen;
3156 runparams.includeall = includeall;
3157 vector<string> backs = backends();
3158 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3159 // Get shortest path to format
3160 Graph::EdgePath path;
3161 for (vector<string>::const_iterator it = backs.begin();
3162 it != backs.end(); ++it) {
3163 Graph::EdgePath p = theConverters().getPath(*it, format);
3164 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3165 backend_format = *it;
3170 if (!put_in_tempdir) {
3171 // Only show this alert if this is an export to a non-temporary
3172 // file (not for previewing).
3173 Alert::error(_("Couldn't export file"), bformat(
3174 _("No information for exporting the format %1$s."),
3175 formats.prettyName(format)));
3179 runparams.flavor = theConverters().getFlavor(path);
3182 backend_format = format;
3183 // FIXME: Don't hardcode format names here, but use a flag
3184 if (backend_format == "pdflatex")
3185 runparams.flavor = OutputParams::PDFLATEX;
3188 string filename = latexName(false);
3189 filename = addName(temppath(), filename);
3190 filename = changeExtension(filename,
3191 formats.extension(backend_format));
3194 updateMacroInstances();
3196 // Plain text backend
3197 if (backend_format == "text") {
3198 runparams.flavor = OutputParams::TEXT;
3199 writePlaintextFile(*this, FileName(filename), runparams);
3202 else if (backend_format == "xhtml") {
3203 runparams.flavor = OutputParams::HTML;
3204 makeLyXHTMLFile(FileName(filename), runparams);
3205 } else if (backend_format == "lyx")
3206 writeFile(FileName(filename));
3208 else if (isDocBook()) {
3209 runparams.nice = !put_in_tempdir;
3210 makeDocBookFile(FileName(filename), runparams);
3213 else if (backend_format == format) {
3214 runparams.nice = true;
3215 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3217 } else if (!lyxrc.tex_allows_spaces
3218 && contains(filePath(), ' ')) {
3219 Alert::error(_("File name error"),
3220 _("The directory path to the document cannot contain spaces."));
3223 runparams.nice = false;
3224 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3228 string const error_type = (format == "program")
3229 ? "Build" : bufferFormat();
3230 ErrorList & error_list = d->errorLists[error_type];
3231 string const ext = formats.extension(format);
3232 FileName const tmp_result_file(changeExtension(filename, ext));
3233 bool const success = theConverters().convert(this, FileName(filename),
3234 tmp_result_file, FileName(absFileName()), backend_format, format,
3236 // Emit the signal to show the error list.
3237 if (format != backend_format) {
3239 // also to the children, in case of master-buffer-view
3240 std::vector<Buffer *> clist = getChildren();
3241 for (vector<Buffer *>::const_iterator cit = clist.begin();
3242 cit != clist.end(); ++cit)
3243 (*cit)->errors(error_type, true);
3248 if (d->cloned_buffer_) {
3249 // Enable reverse dvi or pdf to work by copying back the texrow
3250 // object to the cloned buffer.
3251 // FIXME: There is a possibility of concurrent access to texrow
3252 // here from the main GUI thread that should be securized.
3253 d->cloned_buffer_->d->texrow = d->texrow;
3256 if (put_in_tempdir) {
3257 result_file = tmp_result_file.absFilename();
3261 result_file = changeExtension(exportFileName().absFilename(), ext);
3262 // We need to copy referenced files (e. g. included graphics
3263 // if format == "dvi") to the result dir.
3264 vector<ExportedFile> const files =
3265 runparams.exportdata->externalFiles(format);
3266 string const dest = onlyPath(result_file);
3267 CopyStatus status = SUCCESS;
3268 for (vector<ExportedFile>::const_iterator it = files.begin();
3269 it != files.end() && status != CANCEL; ++it) {
3270 string const fmt = formats.getFormatFromFile(it->sourceName);
3271 status = copyFile(fmt, it->sourceName,
3272 makeAbsPath(it->exportName, dest),
3273 it->exportName, status == FORCE);
3275 if (status == CANCEL) {
3276 message(_("Document export cancelled."));
3277 } else if (tmp_result_file.exists()) {
3278 // Finally copy the main file
3279 status = copyFile(format, tmp_result_file,
3280 FileName(result_file), result_file,
3282 message(bformat(_("Document exported as %1$s "
3284 formats.prettyName(format),
3285 makeDisplayPath(result_file)));
3287 // This must be a dummy converter like fax (bug 1888)
3288 message(bformat(_("Document exported as %1$s"),
3289 formats.prettyName(format)));
3296 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3297 bool includeall) const
3300 // (1) export with all included children (omit \includeonly)
3301 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3303 // (2) export with included children only
3304 return doExport(format, put_in_tempdir, false, result_file);
3308 bool Buffer::preview(string const & format, bool includeall) const
3311 // (1) export with all included children (omit \includeonly)
3312 if (includeall && !doExport(format, true, true))
3314 // (2) export with included children only
3315 if (!doExport(format, true, false, result_file))
3317 return formats.view(*this, FileName(result_file), format);
3321 bool Buffer::isExportable(string const & format) const
3323 vector<string> backs = backends();
3324 for (vector<string>::const_iterator it = backs.begin();
3325 it != backs.end(); ++it)
3326 if (theConverters().isReachable(*it, format))
3332 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3334 vector<string> const backs = backends();
3335 vector<Format const *> result =
3336 theConverters().getReachable(backs[0], only_viewable, true);
3337 for (vector<string>::const_iterator it = backs.begin() + 1;
3338 it != backs.end(); ++it) {
3339 vector<Format const *> r =
3340 theConverters().getReachable(*it, only_viewable, false);
3341 result.insert(result.end(), r.begin(), r.end());
3347 vector<string> Buffer::backends() const
3350 v.push_back(bufferFormat());
3351 // FIXME: Don't hardcode format names here, but use a flag
3352 if (v.back() == "latex")
3353 v.push_back("pdflatex");
3354 v.push_back("xhtml");
3355 v.push_back("text");
3361 bool Buffer::readFileHelper(FileName const & s)
3363 // File information about normal file
3365 docstring const file = makeDisplayPath(s.absFilename(), 50);
3366 docstring text = bformat(_("The specified document\n%1$s"
3367 "\ncould not be read."), file);
3368 Alert::error(_("Could not read document"), text);
3372 // Check if emergency save file exists and is newer.
3373 FileName const e(s.absFilename() + ".emergency");
3375 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3376 docstring const file = makeDisplayPath(s.absFilename(), 20);
3377 docstring const text =
3378 bformat(_("An emergency save of the document "
3380 "Recover emergency save?"), file);
3381 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3382 _("&Recover"), _("&Load Original"),
3386 // the file is not saved if we load the emergency file.
3391 if ((res = readFile(e)) == success)
3392 str = _("Document was successfully recovered.");
3394 str = _("Document was NOT successfully recovered.");
3395 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3396 from_utf8(e.absFilename()));
3398 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3399 _("&Remove"), _("&Keep it"))) {
3402 Alert::warning(_("Emergency file deleted"),
3403 _("Do not forget to save your file now!"), true);
3408 if (!Alert::prompt(_("Delete emergency file?"),
3409 _("Remove emergency file now?"), 1, 1,
3410 _("&Remove"), _("&Keep it")))
3418 // Now check if autosave file is newer.
3419 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3421 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3422 docstring const file = makeDisplayPath(s.absFilename(), 20);
3423 docstring const text =
3424 bformat(_("The backup of the document "
3425 "%1$s is newer.\n\nLoad the "
3426 "backup instead?"), file);
3427 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3428 _("&Load backup"), _("Load &original"),
3432 // the file is not saved if we load the autosave file.
3436 // Here we delete the autosave
3447 bool Buffer::loadLyXFile(FileName const & s)
3449 // If the file is not readable, we try to
3450 // retrieve the file from version control.
3451 if (!s.isReadableFile()
3452 && !LyXVC::file_not_found_hook(s))
3455 if (s.isReadableFile()
3456 && readFileHelper(s)) {
3457 lyxvc().file_found_hook(s);
3458 setReadonly(!s.isWritable());
3465 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3467 TeXErrors::Errors::const_iterator cit = terr.begin();
3468 TeXErrors::Errors::const_iterator end = terr.end();
3470 for (; cit != end; ++cit) {
3473 int errorRow = cit->error_in_line;
3474 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3480 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3481 } while (found && id_start == id_end && pos_start == pos_end);
3483 errorList.push_back(ErrorItem(cit->error_desc,
3484 cit->error_text, id_start, pos_start, pos_end));
3489 void Buffer::setBuffersForInsets() const
3491 inset().setBuffer(const_cast<Buffer &>(*this));
3495 void Buffer::updateLabels(UpdateScope scope, bool out) const
3497 // Use the master text class also for child documents
3498 Buffer const * const master = masterBuffer();
3499 DocumentClass const & textclass = master->params().documentClass();
3501 // do this only if we are the top-level Buffer
3502 if (scope != UpdateMaster || master == this)
3503 checkBibInfoCache();
3505 // keep the buffers to be children in this set. If the call from the
3506 // master comes back we can see which of them were actually seen (i.e.
3507 // via an InsetInclude). The remaining ones in the set need still be updated.
3508 static std::set<Buffer const *> bufToUpdate;
3509 if (scope == UpdateMaster) {
3510 // If this is a child document start with the master
3511 if (master != this) {
3512 bufToUpdate.insert(this);
3513 master->updateLabels(UpdateMaster, out);
3514 // Do this here in case the master has no gui associated with it. Then,
3515 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3519 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3520 if (bufToUpdate.find(this) == bufToUpdate.end())
3524 // start over the counters in the master
3525 textclass.counters().reset();
3528 // update will be done below for this buffer
3529 bufToUpdate.erase(this);
3531 // update all caches
3532 clearReferenceCache();
3535 Buffer & cbuf = const_cast<Buffer &>(*this);
3537 LASSERT(!text().paragraphs().empty(), /**/);
3540 ParIterator parit = cbuf.par_iterator_begin();
3541 updateLabels(parit, out);
3544 // TocBackend update will be done later.
3547 cbuf.tocBackend().update();
3548 if (scope == UpdateMaster)
3549 cbuf.structureChanged();
3553 static depth_type getDepth(DocIterator const & it)
3555 depth_type depth = 0;
3556 for (size_t i = 0 ; i < it.depth() ; ++i)
3557 if (!it[i].inset().inMathed())
3558 depth += it[i].paragraph().getDepth() + 1;
3559 // remove 1 since the outer inset does not count
3563 static depth_type getItemDepth(ParIterator const & it)
3565 Paragraph const & par = *it;
3566 LabelType const labeltype = par.layout().labeltype;
3568 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3571 // this will hold the lowest depth encountered up to now.
3572 depth_type min_depth = getDepth(it);
3573 ParIterator prev_it = it;
3576 --prev_it.top().pit();
3578 // start of nested inset: go to outer par
3580 if (prev_it.empty()) {
3581 // start of document: nothing to do
3586 // We search for the first paragraph with same label
3587 // that is not more deeply nested.
3588 Paragraph & prev_par = *prev_it;
3589 depth_type const prev_depth = getDepth(prev_it);
3590 if (labeltype == prev_par.layout().labeltype) {
3591 if (prev_depth < min_depth)
3592 return prev_par.itemdepth + 1;
3593 if (prev_depth == min_depth)
3594 return prev_par.itemdepth;
3596 min_depth = min(min_depth, prev_depth);
3597 // small optimization: if we are at depth 0, we won't
3598 // find anything else
3599 if (prev_depth == 0)
3605 static bool needEnumCounterReset(ParIterator const & it)
3607 Paragraph const & par = *it;
3608 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3609 depth_type const cur_depth = par.getDepth();
3610 ParIterator prev_it = it;
3611 while (prev_it.pit()) {
3612 --prev_it.top().pit();
3613 Paragraph const & prev_par = *prev_it;
3614 if (prev_par.getDepth() <= cur_depth)
3615 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3617 // start of nested inset: reset
3622 // set the label of a paragraph. This includes the counters.
3623 void Buffer::setLabel(ParIterator & it) const
3625 BufferParams const & bp = this->masterBuffer()->params();
3626 DocumentClass const & textclass = bp.documentClass();
3627 Paragraph & par = it.paragraph();
3628 Layout const & layout = par.layout();
3629 Counters & counters = textclass.counters();
3631 if (par.params().startOfAppendix()) {
3632 // FIXME: only the counter corresponding to toplevel
3633 // sectioning should be reset
3635 counters.appendix(true);
3637 par.params().appendix(counters.appendix());
3639 // Compute the item depth of the paragraph
3640 par.itemdepth = getItemDepth(it);
3642 if (layout.margintype == MARGIN_MANUAL
3643 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3644 if (par.params().labelWidthString().empty())
3645 par.params().labelWidthString(par.expandLabel(layout, bp));
3647 par.params().labelWidthString(docstring());
3650 switch(layout.labeltype) {
3652 if (layout.toclevel <= bp.secnumdepth
3653 && (layout.latextype != LATEX_ENVIRONMENT
3654 || it.text()->isFirstInSequence(it.pit()))) {
3655 counters.step(layout.counter);
3656 par.params().labelString(
3657 par.expandLabel(layout, bp));
3659 par.params().labelString(docstring());
3662 case LABEL_ITEMIZE: {
3663 // At some point of time we should do something more
3664 // clever here, like:
3665 // par.params().labelString(
3666 // bp.user_defined_bullet(par.itemdepth).getText());
3667 // for now, use a simple hardcoded label
3668 docstring itemlabel;
3669 switch (par.itemdepth) {
3671 itemlabel = char_type(0x2022);
3674 itemlabel = char_type(0x2013);
3677 itemlabel = char_type(0x2217);
3680 itemlabel = char_type(0x2219); // or 0x00b7
3683 par.params().labelString(itemlabel);
3687 case LABEL_ENUMERATE: {
3688 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3690 switch (par.itemdepth) {
3699 enumcounter += "iv";
3702 // not a valid enumdepth...
3706 // Maybe we have to reset the enumeration counter.
3707 if (needEnumCounterReset(it))
3708 counters.reset(enumcounter);
3709 counters.step(enumcounter);
3711 string const & lang = par.getParLanguage(bp)->code();
3712 par.params().labelString(counters.theCounter(enumcounter, lang));
3717 case LABEL_SENSITIVE: {
3718 string const & type = counters.current_float();
3719 docstring full_label;
3721 full_label = this->B_("Senseless!!! ");
3723 docstring name = this->B_(textclass.floats().getType(type).name());
3724 if (counters.hasCounter(from_utf8(type))) {
3725 string const & lang = par.getParLanguage(bp)->code();
3726 counters.step(from_utf8(type));
3727 full_label = bformat(from_ascii("%1$s %2$s:"),
3729 counters.theCounter(from_utf8(type), lang));
3731 full_label = bformat(from_ascii("%1$s #:"), name);
3733 par.params().labelString(full_label);
3737 case LABEL_NO_LABEL:
3738 par.params().labelString(docstring());
3742 case LABEL_TOP_ENVIRONMENT:
3743 case LABEL_CENTERED_TOP_ENVIRONMENT:
3746 par.params().labelString(par.expandLabel(layout, bp));
3752 void Buffer::updateLabels(ParIterator & parit, bool out) const
3754 LASSERT(parit.pit() == 0, /**/);
3756 // set the position of the text in the buffer to be able
3757 // to resolve macros in it. This has nothing to do with
3758 // labels, but by putting it here we avoid implementing
3759 // a whole bunch of traversal routines just for this call.
3760 parit.text()->setMacrocontextPosition(parit);
3762 depth_type maxdepth = 0;
3763 pit_type const lastpit = parit.lastpit();
3764 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3765 // reduce depth if necessary
3766 parit->params().depth(min(parit->params().depth(), maxdepth));
3767 maxdepth = parit->getMaxDepthAfter();
3769 // set the counter for this paragraph
3773 InsetList::const_iterator iit = parit->insetList().begin();
3774 InsetList::const_iterator end = parit->insetList().end();
3775 for (; iit != end; ++iit) {
3776 parit.pos() = iit->pos;
3777 iit->inset->updateLabels(parit, out);
3783 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3784 WordLangTuple & word_lang, docstring_list & suggestions) const
3788 suggestions.clear();
3789 word_lang = WordLangTuple();
3790 // OK, we start from here.
3791 DocIterator const end = doc_iterator_end(this);
3792 for (; from != end; from.forwardPos()) {
3793 // We are only interested in text so remove the math CursorSlice.
3794 while (from.inMathed()) {
3798 // If from is at the end of the document (which is possible
3799 // when leaving the mathed) LyX will crash later.
3803 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3808 // Do not increase progress when from == to, otherwise the word
3809 // count will be wrong.
3819 bool Buffer::reload()
3822 // e.g., read-only status could have changed due to version control
3823 d->filename.refresh();
3824 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3826 bool const success = loadLyXFile(d->filename);
3831 message(bformat(_("Document %1$s reloaded."), disp_fn));
3833 message(bformat(_("Could not reload document %1$s."), disp_fn));