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);
414 bool Buffer::isClone() const
416 return d->cloned_buffer_;
420 void Buffer::changed(bool update_metrics) const
423 d->wa_->redrawAll(update_metrics);
427 frontend::WorkAreaManager & Buffer::workAreaManager() const
429 LASSERT(d->wa_, /**/);
434 Text & Buffer::text() const
436 return d->inset->text();
440 Inset & Buffer::inset() const
446 BufferParams & Buffer::params()
452 BufferParams const & Buffer::params() const
458 ParagraphList & Buffer::paragraphs()
460 return text().paragraphs();
464 ParagraphList const & Buffer::paragraphs() const
466 return text().paragraphs();
470 LyXVC & Buffer::lyxvc()
476 LyXVC const & Buffer::lyxvc() const
482 string const Buffer::temppath() const
484 return d->temppath.absFilename();
488 TexRow & Buffer::texrow()
494 TexRow const & Buffer::texrow() const
500 TocBackend & Buffer::tocBackend() const
502 return d->toc_backend;
506 Undo & Buffer::undo()
512 void Buffer::setChild(DocIterator const & dit, Buffer * child)
514 d->children_positions[child] = dit;
518 string Buffer::latexName(bool const no_path) const
520 FileName latex_name =
521 makeLatexName(exportFileName());
522 return no_path ? latex_name.onlyFileName()
523 : latex_name.absFilename();
527 FileName Buffer::exportFileName() const
529 docstring const branch_suffix =
530 params().branchlist().getFilenameSuffix();
531 if (branch_suffix.empty())
534 string const name = fileName().onlyFileNameWithoutExt()
535 + to_utf8(branch_suffix);
536 FileName res(fileName().onlyPath().absFilename() + "/" + name);
537 res.changeExtension(fileName().extension());
543 string Buffer::logName(LogType * type) const
545 string const filename = latexName(false);
547 if (filename.empty()) {
553 string const path = temppath();
555 FileName const fname(addName(temppath(),
556 onlyFilename(changeExtension(filename,
559 // FIXME: how do we know this is the name of the build log?
560 FileName const bname(
561 addName(path, onlyFilename(
562 changeExtension(filename,
563 formats.extension(bufferFormat()) + ".out"))));
565 // Also consider the master buffer log file
566 FileName masterfname = fname;
568 if (masterBuffer() != this) {
569 string const mlogfile = masterBuffer()->logName(&mtype);
570 masterfname = FileName(mlogfile);
573 // If no Latex log or Build log is newer, show Build log
574 if (bname.exists() &&
575 ((!fname.exists() && !masterfname.exists())
576 || (fname.lastModified() < bname.lastModified()
577 && masterfname.lastModified() < bname.lastModified()))) {
578 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
581 return bname.absFilename();
582 // If we have a newer master file log or only a master log, show this
583 } else if (fname != masterfname
584 && (!fname.exists() && (masterfname.exists()
585 || fname.lastModified() < masterfname.lastModified()))) {
586 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
589 return masterfname.absFilename();
591 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
594 return fname.absFilename();
598 void Buffer::setReadonly(bool const flag)
600 if (d->read_only != flag) {
607 void Buffer::setFileName(string const & newfile)
609 d->filename = makeAbsPath(newfile);
610 setReadonly(d->filename.isReadOnly());
615 int Buffer::readHeader(Lexer & lex)
617 int unknown_tokens = 0;
619 int begin_header_line = -1;
621 // Initialize parameters that may be/go lacking in header:
622 params().branchlist().clear();
623 params().preamble.erase();
624 params().options.erase();
625 params().master.erase();
626 params().float_placement.erase();
627 params().paperwidth.erase();
628 params().paperheight.erase();
629 params().leftmargin.erase();
630 params().rightmargin.erase();
631 params().topmargin.erase();
632 params().bottommargin.erase();
633 params().headheight.erase();
634 params().headsep.erase();
635 params().footskip.erase();
636 params().columnsep.erase();
637 params().fontsCJK.erase();
638 params().listings_params.clear();
639 params().clearLayoutModules();
640 params().clearRemovedModules();
641 params().clearIncludedChildren();
642 params().pdfoptions().clear();
643 params().indiceslist().clear();
644 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
646 for (int i = 0; i < 4; ++i) {
647 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
648 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
651 ErrorList & errorList = d->errorLists["Parse"];
660 if (token == "\\end_header")
664 if (token == "\\begin_header") {
665 begin_header_line = line;
669 LYXERR(Debug::PARSER, "Handling document header token: `"
672 string unknown = params().readToken(lex, token, d->filename.onlyPath());
673 if (!unknown.empty()) {
674 if (unknown[0] != '\\' && token == "\\textclass") {
675 Alert::warning(_("Unknown document class"),
676 bformat(_("Using the default document class, because the "
677 "class %1$s is unknown."), from_utf8(unknown)));
680 docstring const s = bformat(_("Unknown token: "
684 errorList.push_back(ErrorItem(_("Document header error"),
689 if (begin_header_line) {
690 docstring const s = _("\\begin_header is missing");
691 errorList.push_back(ErrorItem(_("Document header error"),
695 params().makeDocumentClass();
697 return unknown_tokens;
702 // changed to be public and have one parameter
703 // Returns true if "\end_document" is not read (Asger)
704 bool Buffer::readDocument(Lexer & lex)
706 ErrorList & errorList = d->errorLists["Parse"];
709 if (!lex.checkFor("\\begin_document")) {
710 docstring const s = _("\\begin_document is missing");
711 errorList.push_back(ErrorItem(_("Document header error"),
715 // we are reading in a brand new document
716 LASSERT(paragraphs().empty(), /**/);
720 if (params().outputChanges) {
721 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
722 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
723 LaTeXFeatures::isAvailable("xcolor");
725 if (!dvipost && !xcolorulem) {
726 Alert::warning(_("Changes not shown in LaTeX output"),
727 _("Changes will not be highlighted in LaTeX output, "
728 "because neither dvipost nor xcolor/ulem are installed.\n"
729 "Please install these packages or redefine "
730 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
731 } else if (!xcolorulem) {
732 Alert::warning(_("Changes not shown in LaTeX output"),
733 _("Changes will not be highlighted in LaTeX output "
734 "when using pdflatex, because xcolor and ulem are not installed.\n"
735 "Please install both packages or redefine "
736 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
740 if (!params().master.empty()) {
741 FileName const master_file = makeAbsPath(params().master,
742 onlyPath(absFileName()));
743 if (isLyXFilename(master_file.absFilename())) {
745 checkAndLoadLyXFile(master_file, true);
747 // necessary e.g. after a reload
748 // to re-register the child (bug 5873)
749 // FIXME: clean up updateMacros (here, only
750 // child registering is needed).
751 master->updateMacros();
752 // set master as master buffer, but only
753 // if we are a real child
754 if (master->isChild(this))
756 // if the master is not fully loaded
757 // it is probably just loading this
758 // child. No warning needed then.
759 else if (master->isFullyLoaded())
760 LYXERR0("The master '"
762 << "' assigned to this document ("
764 << ") does not include "
765 "this document. Ignoring the master assignment.");
770 // assure we have a default index
771 params().indiceslist().addDefault(B_("Index"));
774 bool const res = text().read(lex, errorList, d->inset);
778 updateMacroInstances();
783 bool Buffer::readString(string const & s)
785 params().compressed = false;
787 // remove dummy empty par
788 paragraphs().clear();
792 FileName const name = FileName::tempName("Buffer_readString");
793 switch (readFile(lex, name, true)) {
797 // We need to call lyx2lyx, so write the input to a file
798 ofstream os(name.toFilesystemEncoding().c_str());
801 return readFile(name);
811 bool Buffer::readFile(FileName const & filename)
813 FileName fname(filename);
815 params().compressed = fname.isZippedFile();
817 // remove dummy empty par
818 paragraphs().clear();
821 if (readFile(lex, fname) != success)
828 bool Buffer::isFullyLoaded() const
830 return d->file_fully_loaded;
834 void Buffer::setFullyLoaded(bool value)
836 d->file_fully_loaded = value;
840 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
843 LASSERT(!filename.empty(), /**/);
845 // the first (non-comment) token _must_ be...
846 if (!lex.checkFor("\\lyxformat")) {
847 Alert::error(_("Document format failure"),
848 bformat(_("%1$s is not a readable LyX document."),
849 from_utf8(filename.absFilename())));
855 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
856 // if present remove ".," from string.
857 size_t dot = tmp_format.find_first_of(".,");
858 //lyxerr << " dot found at " << dot << endl;
859 if (dot != string::npos)
860 tmp_format.erase(dot, 1);
861 int const file_format = convert<int>(tmp_format);
862 //lyxerr << "format: " << file_format << endl;
864 // save timestamp and checksum of the original disk file, making sure
865 // to not overwrite them with those of the file created in the tempdir
866 // when it has to be converted to the current format.
868 // Save the timestamp and checksum of disk file. If filename is an
869 // emergency file, save the timestamp and checksum of the original lyx file
870 // because isExternallyModified will check for this file. (BUG4193)
871 string diskfile = filename.absFilename();
872 if (suffixIs(diskfile, ".emergency"))
873 diskfile = diskfile.substr(0, diskfile.size() - 10);
874 saveCheckSum(FileName(diskfile));
877 if (file_format != LYX_FORMAT) {
880 // lyx2lyx would fail
883 FileName const tmpfile = FileName::tempName("Buffer_readFile");
884 if (tmpfile.empty()) {
885 Alert::error(_("Conversion failed"),
886 bformat(_("%1$s is from a different"
887 " version of LyX, but a temporary"
888 " file for converting it could"
890 from_utf8(filename.absFilename())));
893 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
894 if (lyx2lyx.empty()) {
895 Alert::error(_("Conversion script not found"),
896 bformat(_("%1$s is from a different"
897 " version of LyX, but the"
898 " conversion script lyx2lyx"
899 " could not be found."),
900 from_utf8(filename.absFilename())));
903 ostringstream command;
904 command << os::python()
905 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
906 << " -t " << convert<string>(LYX_FORMAT)
907 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
908 << ' ' << quoteName(filename.toFilesystemEncoding());
909 string const command_str = command.str();
911 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
913 cmd_ret const ret = runCommand(command_str);
914 if (ret.first != 0) {
915 Alert::error(_("Conversion script failed"),
916 bformat(_("%1$s is from a different version"
917 " of LyX, but the lyx2lyx script"
918 " failed to convert it."),
919 from_utf8(filename.absFilename())));
922 bool const ret = readFile(tmpfile);
923 // Do stuff with tmpfile name and buffer name here.
924 return ret ? success : failure;
929 if (readDocument(lex)) {
930 Alert::error(_("Document format failure"),
931 bformat(_("%1$s ended unexpectedly, which means"
932 " that it is probably corrupted."),
933 from_utf8(filename.absFilename())));
936 d->file_fully_loaded = true;
941 // Should probably be moved to somewhere else: BufferView? LyXView?
942 bool Buffer::save() const
944 // We don't need autosaves in the immediate future. (Asger)
945 resetAutosaveTimers();
947 string const encodedFilename = d->filename.toFilesystemEncoding();
950 bool madeBackup = false;
952 // make a backup if the file already exists
953 if (lyxrc.make_backup && fileName().exists()) {
954 backupName = FileName(absFileName() + '~');
955 if (!lyxrc.backupdir_path.empty()) {
956 string const mangledName =
957 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
958 backupName = FileName(addName(lyxrc.backupdir_path,
961 if (fileName().copyTo(backupName)) {
964 Alert::error(_("Backup failure"),
965 bformat(_("Cannot create backup file %1$s.\n"
966 "Please check whether the directory exists and is writeable."),
967 from_utf8(backupName.absFilename())));
968 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
972 // ask if the disk file has been externally modified (use checksum method)
973 if (fileName().exists() && isExternallyModified(checksum_method)) {
974 docstring const file = makeDisplayPath(absFileName(), 20);
975 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
976 "you want to overwrite this file?"), file);
977 int const ret = Alert::prompt(_("Overwrite modified file?"),
978 text, 1, 1, _("&Overwrite"), _("&Cancel"));
983 if (writeFile(d->filename)) {
987 // Saving failed, so backup is not backup
989 backupName.moveTo(d->filename);
995 bool Buffer::writeFile(FileName const & fname) const
997 if (d->read_only && fname == d->filename)
1000 bool retval = false;
1002 docstring const str = bformat(_("Saving document %1$s..."),
1003 makeDisplayPath(fname.absFilename()));
1006 if (params().compressed) {
1007 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1008 retval = ofs && write(ofs);
1010 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1011 retval = ofs && write(ofs);
1015 message(str + _(" could not write file!"));
1019 removeAutosaveFile();
1021 saveCheckSum(d->filename);
1022 message(str + _(" done."));
1028 docstring Buffer::emergencyWrite()
1030 // No need to save if the buffer has not changed.
1034 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1036 docstring user_message = bformat(
1037 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1039 // We try to save three places:
1040 // 1) Same place as document. Unless it is an unnamed doc.
1042 string s = absFileName();
1045 if (writeFile(FileName(s))) {
1047 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1048 return user_message;
1050 user_message += _(" Save failed! Trying again...\n");
1054 // 2) In HOME directory.
1055 string s = addName(package().home_dir().absFilename(), absFileName());
1057 lyxerr << ' ' << s << endl;
1058 if (writeFile(FileName(s))) {
1060 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1061 return user_message;
1064 user_message += _(" Save failed! Trying yet again...\n");
1066 // 3) In "/tmp" directory.
1067 // MakeAbsPath to prepend the current
1068 // drive letter on OS/2
1069 s = addName(package().temp_dir().absFilename(), absFileName());
1071 lyxerr << ' ' << s << endl;
1072 if (writeFile(FileName(s))) {
1074 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1075 return user_message;
1078 user_message += _(" Save failed! Bummer. Document is lost.");
1081 return user_message;
1085 bool Buffer::write(ostream & ofs) const
1088 // Use the standard "C" locale for file output.
1089 ofs.imbue(locale::classic());
1092 // The top of the file should not be written by params().
1094 // write out a comment in the top of the file
1095 ofs << "#LyX " << lyx_version
1096 << " created this file. For more info see http://www.lyx.org/\n"
1097 << "\\lyxformat " << LYX_FORMAT << "\n"
1098 << "\\begin_document\n";
1100 /// For each author, set 'used' to true if there is a change
1101 /// by this author in the document; otherwise set it to 'false'.
1102 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1103 AuthorList::Authors::const_iterator a_end = params().authors().end();
1104 for (; a_it != a_end; ++a_it)
1105 a_it->setUsed(false);
1107 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1108 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1109 for ( ; it != end; ++it)
1110 it->checkAuthors(params().authors());
1112 // now write out the buffer parameters.
1113 ofs << "\\begin_header\n";
1114 params().writeFile(ofs);
1115 ofs << "\\end_header\n";
1118 ofs << "\n\\begin_body\n";
1120 ofs << "\n\\end_body\n";
1122 // Write marker that shows file is complete
1123 ofs << "\\end_document" << endl;
1125 // Shouldn't really be needed....
1128 // how to check if close went ok?
1129 // Following is an attempt... (BE 20001011)
1131 // good() returns false if any error occured, including some
1132 // formatting error.
1133 // bad() returns true if something bad happened in the buffer,
1134 // which should include file system full errors.
1139 lyxerr << "File was not closed properly." << endl;
1146 bool Buffer::makeLaTeXFile(FileName const & fname,
1147 string const & original_path,
1148 OutputParams const & runparams_in,
1149 bool output_preamble, bool output_body) const
1151 OutputParams runparams = runparams_in;
1152 if (params().useXetex)
1153 runparams.flavor = OutputParams::XETEX;
1155 string const encoding = runparams.encoding->iconvName();
1156 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1159 try { ofs.reset(encoding); }
1160 catch (iconv_codecvt_facet_exception & e) {
1161 lyxerr << "Caught iconv exception: " << e.what() << endl;
1162 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1163 "verify that the support software for your encoding (%1$s) is "
1164 "properly installed"), from_ascii(encoding)));
1167 if (!openFileWrite(ofs, fname))
1170 //TexStream ts(ofs.rdbuf(), &texrow());
1171 ErrorList & errorList = d->errorLists["Export"];
1173 bool failed_export = false;
1176 writeLaTeXSource(ofs, original_path,
1177 runparams, output_preamble, output_body);
1179 catch (EncodingException & e) {
1180 odocstringstream ods;
1181 ods.put(e.failed_char);
1183 oss << "0x" << hex << e.failed_char << dec;
1184 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1185 " (code point %2$s)"),
1186 ods.str(), from_utf8(oss.str()));
1187 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1188 "representable in the chosen encoding.\n"
1189 "Changing the document encoding to utf8 could help."),
1190 e.par_id, e.pos, e.pos + 1));
1191 failed_export = true;
1193 catch (iconv_codecvt_facet_exception & e) {
1194 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1195 _(e.what()), -1, 0, 0));
1196 failed_export = true;
1198 catch (exception const & e) {
1199 errorList.push_back(ErrorItem(_("conversion failed"),
1200 _(e.what()), -1, 0, 0));
1201 failed_export = true;
1204 lyxerr << "Caught some really weird exception..." << endl;
1210 failed_export = true;
1211 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1215 return !failed_export;
1219 void Buffer::writeLaTeXSource(odocstream & os,
1220 string const & original_path,
1221 OutputParams const & runparams_in,
1222 bool const output_preamble, bool const output_body) const
1224 // The child documents, if any, shall be already loaded at this point.
1226 OutputParams runparams = runparams_in;
1228 // Classify the unicode characters appearing in math insets
1229 Encodings::initUnicodeMath(*this);
1231 // validate the buffer.
1232 LYXERR(Debug::LATEX, " Validating buffer...");
1233 LaTeXFeatures features(*this, params(), runparams);
1235 LYXERR(Debug::LATEX, " Buffer validation done.");
1237 // The starting paragraph of the coming rows is the
1238 // first paragraph of the document. (Asger)
1239 if (output_preamble && runparams.nice) {
1240 os << "%% LyX " << lyx_version << " created this file. "
1241 "For more info, see http://www.lyx.org/.\n"
1242 "%% Do not edit unless you really know what "
1244 d->texrow.newline();
1245 d->texrow.newline();
1247 LYXERR(Debug::INFO, "lyx document header finished");
1249 // Don't move this behind the parent_buffer=0 code below,
1250 // because then the macros will not get the right "redefinition"
1251 // flag as they don't see the parent macros which are output before.
1254 // fold macros if possible, still with parent buffer as the
1255 // macros will be put in the prefix anyway.
1256 updateMacroInstances();
1258 // There are a few differences between nice LaTeX and usual files:
1259 // usual is \batchmode and has a
1260 // special input@path to allow the including of figures
1261 // with either \input or \includegraphics (what figinsets do).
1262 // input@path is set when the actual parameter
1263 // original_path is set. This is done for usual tex-file, but not
1264 // for nice-latex-file. (Matthias 250696)
1265 // Note that input@path is only needed for something the user does
1266 // in the preamble, included .tex files or ERT, files included by
1267 // LyX work without it.
1268 if (output_preamble) {
1269 if (!runparams.nice) {
1270 // code for usual, NOT nice-latex-file
1271 os << "\\batchmode\n"; // changed
1272 // from \nonstopmode
1273 d->texrow.newline();
1275 if (!original_path.empty()) {
1277 // We don't know the encoding of inputpath
1278 docstring const inputpath = from_utf8(latex_path(original_path));
1279 os << "\\makeatletter\n"
1280 << "\\def\\input@path{{"
1281 << inputpath << "/}}\n"
1282 << "\\makeatother\n";
1283 d->texrow.newline();
1284 d->texrow.newline();
1285 d->texrow.newline();
1288 // get parent macros (if this buffer has a parent) which will be
1289 // written at the document begin further down.
1290 MacroSet parentMacros;
1291 listParentMacros(parentMacros, features);
1293 // Write the preamble
1294 runparams.use_babel = params().writeLaTeX(os, features,
1296 d->filename.onlyPath());
1298 runparams.use_japanese = features.isRequired("japanese");
1304 os << "\\begin{document}\n";
1305 d->texrow.newline();
1307 // output the parent macros
1308 MacroSet::iterator it = parentMacros.begin();
1309 MacroSet::iterator end = parentMacros.end();
1310 for (; it != end; ++it)
1311 (*it)->write(os, true);
1312 } // output_preamble
1314 d->texrow.start(paragraphs().begin()->id(), 0);
1316 LYXERR(Debug::INFO, "preamble finished, now the body.");
1318 // if we are doing a real file with body, even if this is the
1319 // child of some other buffer, let's cut the link here.
1320 // This happens for example if only a child document is printed.
1321 Buffer const * save_parent = 0;
1322 if (output_preamble) {
1323 save_parent = d->parent();
1328 latexParagraphs(*this, text(), os, d->texrow, runparams);
1330 // Restore the parenthood if needed
1331 if (output_preamble)
1332 d->setParent(save_parent);
1334 // add this just in case after all the paragraphs
1336 d->texrow.newline();
1338 if (output_preamble) {
1339 os << "\\end{document}\n";
1340 d->texrow.newline();
1341 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1343 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1345 runparams_in.encoding = runparams.encoding;
1347 // Just to be sure. (Asger)
1348 d->texrow.newline();
1350 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1351 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1355 bool Buffer::isLatex() const
1357 return params().documentClass().outputType() == LATEX;
1361 bool Buffer::isLiterate() const
1363 return params().documentClass().outputType() == LITERATE;
1367 bool Buffer::isDocBook() const
1369 return params().documentClass().outputType() == DOCBOOK;
1373 void Buffer::makeDocBookFile(FileName const & fname,
1374 OutputParams const & runparams,
1375 bool const body_only) const
1377 LYXERR(Debug::LATEX, "makeDocBookFile...");
1380 if (!openFileWrite(ofs, fname))
1383 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1387 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1391 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1392 OutputParams const & runparams,
1393 bool const only_body) const
1395 LaTeXFeatures features(*this, params(), runparams);
1400 DocumentClass const & tclass = params().documentClass();
1401 string const top_element = tclass.latexname();
1404 if (runparams.flavor == OutputParams::XML)
1405 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1408 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1411 if (! tclass.class_header().empty())
1412 os << from_ascii(tclass.class_header());
1413 else if (runparams.flavor == OutputParams::XML)
1414 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1415 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1417 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1419 docstring preamble = from_utf8(params().preamble);
1420 if (runparams.flavor != OutputParams::XML ) {
1421 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1422 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1423 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1424 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1427 string const name = runparams.nice
1428 ? changeExtension(absFileName(), ".sgml") : fname;
1429 preamble += features.getIncludedFiles(name);
1430 preamble += features.getLyXSGMLEntities();
1432 if (!preamble.empty()) {
1433 os << "\n [ " << preamble << " ]";
1438 string top = top_element;
1440 if (runparams.flavor == OutputParams::XML)
1441 top += params().language->code();
1443 top += params().language->code().substr(0, 2);
1446 if (!params().options.empty()) {
1448 top += params().options;
1451 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1452 << " file was created by LyX " << lyx_version
1453 << "\n See http://www.lyx.org/ for more information -->\n";
1455 params().documentClass().counters().reset();
1459 sgml::openTag(os, top);
1461 docbookParagraphs(text(), *this, os, runparams);
1462 sgml::closeTag(os, top_element);
1466 void Buffer::makeLyXHTMLFile(FileName const & fname,
1467 OutputParams const & runparams,
1468 bool const body_only) const
1470 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1473 if (!openFileWrite(ofs, fname))
1476 writeLyXHTMLSource(ofs, runparams, body_only);
1480 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1484 void Buffer::writeLyXHTMLSource(odocstream & os,
1485 OutputParams const & runparams,
1486 bool const only_body) const
1488 LaTeXFeatures features(*this, params(), runparams);
1490 updateLabels(UpdateMaster, true);
1491 checkBibInfoCache();
1492 d->bibinfo_.makeCitationLabels(*this);
1495 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1496 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";
1497 // FIXME Language should be set properly.
1498 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1501 // FIXME Presumably need to set this right
1502 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1503 // FIXME Get this during validation? What about other meta-data?
1504 os << "<title>TBA</title>\n";
1506 os << "\n<!-- Text Class Preamble -->\n"
1507 << features.getTClassHTMLPreamble()
1508 << "\n<!-- Premable Snippets -->\n"
1509 << from_utf8(features.getPreambleSnippets());
1511 os << "\n<!-- Layout-provided Styles -->\n";
1512 docstring const styleinfo = features.getTClassHTMLStyles();
1513 if (!styleinfo.empty()) {
1514 os << "<style type='text/css'>\n"
1518 os << "</head>\n<body>\n";
1522 params().documentClass().counters().reset();
1523 xhtmlParagraphs(text(), *this, xs, runparams);
1525 os << "</body>\n</html>\n";
1529 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1530 // Other flags: -wall -v0 -x
1531 int Buffer::runChktex()
1535 // get LaTeX-Filename
1536 FileName const path(temppath());
1537 string const name = addName(path.absFilename(), latexName());
1538 string const org_path = filePath();
1540 PathChanger p(path); // path to LaTeX file
1541 message(_("Running chktex..."));
1543 // Generate the LaTeX file if neccessary
1544 OutputParams runparams(¶ms().encoding());
1545 runparams.flavor = OutputParams::LATEX;
1546 runparams.nice = false;
1547 makeLaTeXFile(FileName(name), org_path, runparams);
1550 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1551 int const res = chktex.run(terr); // run chktex
1554 Alert::error(_("chktex failure"),
1555 _("Could not run chktex successfully."));
1556 } else if (res > 0) {
1557 ErrorList & errlist = d->errorLists["ChkTeX"];
1559 bufferErrors(terr, errlist);
1570 void Buffer::validate(LaTeXFeatures & features) const
1572 params().validate(features);
1576 for_each(paragraphs().begin(), paragraphs().end(),
1577 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1579 if (lyxerr.debugging(Debug::LATEX)) {
1580 features.showStruct();
1585 void Buffer::getLabelList(vector<docstring> & list) const
1587 // If this is a child document, use the parent's list instead.
1588 Buffer const * const pbuf = d->parent();
1590 pbuf->getLabelList(list);
1595 Toc & toc = d->toc_backend.toc("label");
1596 TocIterator toc_it = toc.begin();
1597 TocIterator end = toc.end();
1598 for (; toc_it != end; ++toc_it) {
1599 if (toc_it->depth() == 0)
1600 list.push_back(toc_it->str());
1605 void Buffer::updateBibfilesCache(UpdateScope scope) const
1607 // If this is a child document, use the parent's cache instead.
1608 Buffer const * const pbuf = d->parent();
1609 if (pbuf && scope != UpdateChildOnly) {
1610 pbuf->updateBibfilesCache();
1614 d->bibfiles_cache_.clear();
1615 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1616 if (it->lyxCode() == BIBTEX_CODE) {
1617 InsetBibtex const & inset =
1618 static_cast<InsetBibtex const &>(*it);
1619 support::FileNameList const bibfiles = inset.getBibFiles();
1620 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1623 } else if (it->lyxCode() == INCLUDE_CODE) {
1624 InsetInclude & inset =
1625 static_cast<InsetInclude &>(*it);
1626 inset.updateBibfilesCache();
1627 support::FileNameList const & bibfiles =
1628 inset.getBibfilesCache();
1629 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1634 // the bibinfo cache is now invalid
1635 d->bibinfo_cache_valid_ = false;
1639 void Buffer::invalidateBibinfoCache()
1641 d->bibinfo_cache_valid_ = false;
1645 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1647 // If this is a child document, use the parent's cache instead.
1648 Buffer const * const pbuf = d->parent();
1649 if (pbuf && scope != UpdateChildOnly)
1650 return pbuf->getBibfilesCache();
1652 // We update the cache when first used instead of at loading time.
1653 if (d->bibfiles_cache_.empty())
1654 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1656 return d->bibfiles_cache_;
1660 BiblioInfo const & Buffer::masterBibInfo() const
1662 // if this is a child document and the parent is already loaded
1663 // use the parent's list instead [ale990412]
1664 Buffer const * const tmp = masterBuffer();
1667 return tmp->masterBibInfo();
1668 return localBibInfo();
1672 BiblioInfo const & Buffer::localBibInfo() const
1678 void Buffer::checkBibInfoCache() const
1680 support::FileNameList const & bibfilesCache = getBibfilesCache();
1681 // compare the cached timestamps with the actual ones.
1682 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1683 support::FileNameList::const_iterator en = bibfilesCache.end();
1684 for (; ei != en; ++ ei) {
1685 time_t lastw = ei->lastModified();
1686 time_t prevw = d->bibfile_status_[*ei];
1687 if (lastw != prevw) {
1688 d->bibinfo_cache_valid_ = false;
1689 d->bibfile_status_[*ei] = lastw;
1693 if (!d->bibinfo_cache_valid_) {
1694 d->bibinfo_.clear();
1695 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1696 it->fillWithBibKeys(d->bibinfo_, it);
1697 d->bibinfo_cache_valid_ = true;
1702 bool Buffer::isDepClean(string const & name) const
1704 DepClean::const_iterator const it = d->dep_clean.find(name);
1705 if (it == d->dep_clean.end())
1711 void Buffer::markDepClean(string const & name)
1713 d->dep_clean[name] = true;
1717 bool Buffer::isExportableFormat(string const & format) const
1719 typedef vector<Format const *> Formats;
1721 formats = exportableFormats(true);
1722 Formats::const_iterator fit = formats.begin();
1723 Formats::const_iterator end = formats.end();
1724 for (; fit != end ; ++fit) {
1725 if ((*fit)->name() == format)
1732 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1735 // FIXME? if there is an Buffer LFUN that can be dispatched even
1736 // if internal, put a switch '(cmd.action)' here.
1742 switch (cmd.action) {
1744 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1745 flag.setOnOff(isReadonly());
1748 // FIXME: There is need for a command-line import.
1749 //case LFUN_BUFFER_IMPORT:
1751 case LFUN_BUFFER_AUTO_SAVE:
1754 case LFUN_BUFFER_EXPORT_CUSTOM:
1755 // FIXME: Nothing to check here?
1758 case LFUN_BUFFER_EXPORT: {
1759 docstring const arg = cmd.argument();
1760 enable = arg == "custom" || isExportable(to_utf8(arg));
1762 flag.message(bformat(
1763 _("Don't know how to export to format: %1$s"), arg));
1767 case LFUN_BUFFER_CHKTEX:
1768 enable = isLatex() && !lyxrc.chktex_command.empty();
1771 case LFUN_BUILD_PROGRAM:
1772 enable = isExportable("program");
1775 case LFUN_BRANCH_ACTIVATE:
1776 case LFUN_BRANCH_DEACTIVATE: {
1777 BranchList const & branchList = params().branchlist();
1778 docstring const branchName = cmd.argument();
1779 enable = !branchName.empty() && branchList.find(branchName);
1783 case LFUN_BRANCH_ADD:
1784 case LFUN_BRANCHES_RENAME:
1785 case LFUN_BUFFER_PRINT:
1786 // if no Buffer is present, then of course we won't be called!
1789 case LFUN_BUFFER_LANGUAGE:
1790 enable = !isReadonly();
1796 flag.setEnabled(enable);
1801 void Buffer::dispatch(string const & command, DispatchResult & result)
1803 return dispatch(lyxaction.lookupFunc(command), result);
1807 // NOTE We can end up here even if we have no GUI, because we are called
1808 // by LyX::exec to handled command-line requests. So we may need to check
1809 // whether we have a GUI or not. The boolean use_gui holds this information.
1810 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1813 // FIXME? if there is an Buffer LFUN that can be dispatched even
1814 // if internal, put a switch '(cmd.action)' here.
1815 dr.dispatched(false);
1818 string const argument = to_utf8(func.argument());
1819 // We'll set this back to false if need be.
1820 bool dispatched = true;
1821 undo().beginUndoGroup();
1823 switch (func.action) {
1824 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1825 if (lyxvc().inUse())
1826 lyxvc().toggleReadOnly();
1828 setReadonly(!isReadonly());
1831 case LFUN_BUFFER_EXPORT: {
1832 bool success = doExport(argument, false, false);
1833 dr.setError(success);
1835 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1840 case LFUN_BUILD_PROGRAM:
1841 doExport("program", true, false);
1844 case LFUN_BUFFER_CHKTEX:
1848 case LFUN_BUFFER_EXPORT_CUSTOM: {
1850 string command = split(argument, format_name, ' ');
1851 Format const * format = formats.getFormat(format_name);
1853 lyxerr << "Format \"" << format_name
1854 << "\" not recognized!"
1859 // The name of the file created by the conversion process
1862 // Output to filename
1863 if (format->name() == "lyx") {
1864 string const latexname = latexName(false);
1865 filename = changeExtension(latexname,
1866 format->extension());
1867 filename = addName(temppath(), filename);
1869 if (!writeFile(FileName(filename)))
1873 doExport(format_name, true, false, filename);
1876 // Substitute $$FName for filename
1877 if (!contains(command, "$$FName"))
1878 command = "( " + command + " ) < $$FName";
1879 command = subst(command, "$$FName", filename);
1881 // Execute the command in the background
1883 call.startscript(Systemcall::DontWait, command);
1887 // FIXME: There is need for a command-line import.
1889 case LFUN_BUFFER_IMPORT:
1894 case LFUN_BUFFER_AUTO_SAVE:
1898 case LFUN_BRANCH_ADD: {
1899 docstring const branch_name = func.argument();
1900 if (branch_name.empty()) {
1904 BranchList & branch_list = params().branchlist();
1905 Branch * branch = branch_list.find(branch_name);
1907 LYXERR0("Branch " << branch_name << " already exists.");
1909 docstring const msg =
1910 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1913 branch_list.add(branch_name);
1914 branch = branch_list.find(branch_name);
1915 string const x11hexname = X11hexname(branch->color());
1916 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1917 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1919 dr.update(Update::Force);
1924 case LFUN_BRANCH_ACTIVATE:
1925 case LFUN_BRANCH_DEACTIVATE: {
1926 BranchList & branchList = params().branchlist();
1927 docstring const branchName = func.argument();
1928 // the case without a branch name is handled elsewhere
1929 if (branchName.empty()) {
1933 Branch * branch = branchList.find(branchName);
1935 LYXERR0("Branch " << branchName << " does not exist.");
1937 docstring const msg =
1938 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1941 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1943 dr.update(Update::Force);
1948 case LFUN_BRANCHES_RENAME: {
1949 if (func.argument().empty())
1952 docstring const oldname = from_utf8(func.getArg(0));
1953 docstring const newname = from_utf8(func.getArg(1));
1954 InsetIterator it = inset_iterator_begin(inset());
1955 InsetIterator const end = inset_iterator_end(inset());
1956 bool success = false;
1957 for (; it != end; ++it) {
1958 if (it->lyxCode() == BRANCH_CODE) {
1959 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1960 if (ins.branch() == oldname) {
1961 undo().recordUndo(it);
1962 ins.rename(newname);
1967 if (it->lyxCode() == INCLUDE_CODE) {
1968 // get buffer of external file
1969 InsetInclude const & ins =
1970 static_cast<InsetInclude const &>(*it);
1971 Buffer * child = ins.getChildBuffer();
1974 child->dispatch(func, dr);
1979 dr.update(Update::Force);
1983 case LFUN_BUFFER_PRINT: {
1984 // we'll assume there's a problem until we succeed
1986 string target = func.getArg(0);
1987 string target_name = func.getArg(1);
1988 string command = func.getArg(2);
1991 || target_name.empty()
1992 || command.empty()) {
1993 LYXERR0("Unable to parse " << func.argument());
1994 docstring const msg =
1995 bformat(_("Unable to parse \"%1$s\""), func.argument());
1999 if (target != "printer" && target != "file") {
2000 LYXERR0("Unrecognized target \"" << target << '"');
2001 docstring const msg =
2002 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2007 bool const update_unincluded =
2008 params().maintain_unincluded_children
2009 && !params().getIncludedChildren().empty();
2010 if (!doExport("dvi", true, update_unincluded)) {
2011 showPrintError(absFileName());
2012 dr.setMessage(_("Error exporting to DVI."));
2016 // Push directory path.
2017 string const path = temppath();
2018 // Prevent the compiler from optimizing away p
2022 // there are three cases here:
2023 // 1. we print to a file
2024 // 2. we print directly to a printer
2025 // 3. we print using a spool command (print to file first)
2028 string const dviname = changeExtension(latexName(true), "dvi");
2030 if (target == "printer") {
2031 if (!lyxrc.print_spool_command.empty()) {
2032 // case 3: print using a spool
2033 string const psname = changeExtension(dviname,".ps");
2034 command += ' ' + lyxrc.print_to_file
2037 + quoteName(dviname);
2039 string command2 = lyxrc.print_spool_command + ' ';
2040 if (target_name != "default") {
2041 command2 += lyxrc.print_spool_printerprefix
2045 command2 += quoteName(psname);
2047 // If successful, then spool command
2048 res = one.startscript(Systemcall::Wait, command);
2051 // If there's no GUI, we have to wait on this command. Otherwise,
2052 // LyX deletes the temporary directory, and with it the spooled
2053 // file, before it can be printed!!
2054 Systemcall::Starttype stype = use_gui ?
2055 Systemcall::DontWait : Systemcall::Wait;
2056 res = one.startscript(stype, command2);
2059 // case 2: print directly to a printer
2060 if (target_name != "default")
2061 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2063 Systemcall::Starttype stype = use_gui ?
2064 Systemcall::DontWait : Systemcall::Wait;
2065 res = one.startscript(stype, command + quoteName(dviname));
2069 // case 1: print to a file
2070 FileName const filename(makeAbsPath(target_name, filePath()));
2071 FileName const dvifile(makeAbsPath(dviname, path));
2072 if (filename.exists()) {
2073 docstring text = bformat(
2074 _("The file %1$s already exists.\n\n"
2075 "Do you want to overwrite that file?"),
2076 makeDisplayPath(filename.absFilename()));
2077 if (Alert::prompt(_("Overwrite file?"),
2078 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2081 command += ' ' + lyxrc.print_to_file
2082 + quoteName(filename.toFilesystemEncoding())
2084 + quoteName(dvifile.toFilesystemEncoding());
2086 Systemcall::Starttype stype = use_gui ?
2087 Systemcall::DontWait : Systemcall::Wait;
2088 res = one.startscript(stype, command);
2094 dr.setMessage(_("Error running external commands."));
2095 showPrintError(absFileName());
2100 case LFUN_BUFFER_LANGUAGE: {
2101 Language const * oldL = params().language;
2102 Language const * newL = languages.getLanguage(argument);
2103 if (!newL || oldL == newL)
2105 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2106 changeLanguage(oldL, newL);
2114 dr.dispatched(dispatched);
2115 undo().endUndoGroup();
2119 void Buffer::changeLanguage(Language const * from, Language const * to)
2121 LASSERT(from, /**/);
2124 for_each(par_iterator_begin(),
2126 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2130 bool Buffer::isMultiLingual() const
2132 ParConstIterator end = par_iterator_end();
2133 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2134 if (it->isMultiLingual(params()))
2141 DocIterator Buffer::getParFromID(int const id) const
2143 Buffer * buf = const_cast<Buffer *>(this);
2145 // John says this is called with id == -1 from undo
2146 lyxerr << "getParFromID(), id: " << id << endl;
2147 return doc_iterator_end(buf);
2150 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2151 if (it.paragraph().id() == id)
2154 return doc_iterator_end(buf);
2158 bool Buffer::hasParWithID(int const id) const
2160 return !getParFromID(id).atEnd();
2164 ParIterator Buffer::par_iterator_begin()
2166 return ParIterator(doc_iterator_begin(this));
2170 ParIterator Buffer::par_iterator_end()
2172 return ParIterator(doc_iterator_end(this));
2176 ParConstIterator Buffer::par_iterator_begin() const
2178 return ParConstIterator(doc_iterator_begin(this));
2182 ParConstIterator Buffer::par_iterator_end() const
2184 return ParConstIterator(doc_iterator_end(this));
2188 Language const * Buffer::language() const
2190 return params().language;
2194 docstring const Buffer::B_(string const & l10n) const
2196 return params().B_(l10n);
2200 bool Buffer::isClean() const
2202 return d->lyx_clean;
2206 bool Buffer::isBakClean() const
2208 return d->bak_clean;
2212 bool Buffer::isExternallyModified(CheckMethod method) const
2214 LASSERT(d->filename.exists(), /**/);
2215 // if method == timestamp, check timestamp before checksum
2216 return (method == checksum_method
2217 || d->timestamp_ != d->filename.lastModified())
2218 && d->checksum_ != d->filename.checksum();
2222 void Buffer::saveCheckSum(FileName const & file) const
2224 if (file.exists()) {
2225 d->timestamp_ = file.lastModified();
2226 d->checksum_ = file.checksum();
2228 // in the case of save to a new file.
2235 void Buffer::markClean() const
2237 if (!d->lyx_clean) {
2238 d->lyx_clean = true;
2241 // if the .lyx file has been saved, we don't need an
2243 d->bak_clean = true;
2247 void Buffer::markBakClean() const
2249 d->bak_clean = true;
2253 void Buffer::setUnnamed(bool flag)
2259 bool Buffer::isUnnamed() const
2266 /// Don't check unnamed, here: isInternal() is used in
2267 /// newBuffer(), where the unnamed flag has not been set by anyone
2268 /// yet. Also, for an internal buffer, there should be no need for
2269 /// retrieving fileName() nor for checking if it is unnamed or not.
2270 bool Buffer::isInternal() const
2272 return fileName().extension() == "internal";
2276 void Buffer::markDirty()
2279 d->lyx_clean = false;
2282 d->bak_clean = false;
2284 DepClean::iterator it = d->dep_clean.begin();
2285 DepClean::const_iterator const end = d->dep_clean.end();
2287 for (; it != end; ++it)
2292 FileName Buffer::fileName() const
2298 string Buffer::absFileName() const
2300 return d->filename.absFilename();
2304 string Buffer::filePath() const
2306 return d->filename.onlyPath().absFilename() + "/";
2310 bool Buffer::isReadonly() const
2312 return d->read_only;
2316 void Buffer::setParent(Buffer const * buffer)
2318 // Avoids recursive include.
2319 d->setParent(buffer == this ? 0 : buffer);
2324 Buffer const * Buffer::parent() const
2330 void Buffer::collectRelatives(BufferSet & bufs) const
2334 parent()->collectRelatives(bufs);
2336 // loop over children
2337 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2338 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2339 for (; it != end; ++it)
2340 bufs.insert(const_cast<Buffer *>(it->first));
2344 std::vector<Buffer const *> Buffer::allRelatives() const
2347 collectRelatives(bufs);
2348 BufferSet::iterator it = bufs.begin();
2349 std::vector<Buffer const *> ret;
2350 for (; it != bufs.end(); ++it)
2356 Buffer const * Buffer::masterBuffer() const
2358 Buffer const * const pbuf = d->parent();
2362 return pbuf->masterBuffer();
2366 bool Buffer::isChild(Buffer * child) const
2368 return d->children_positions.find(child) != d->children_positions.end();
2372 DocIterator Buffer::firstChildPosition(Buffer const * child)
2374 Impl::BufferPositionMap::iterator it;
2375 it = d->children_positions.find(child);
2376 if (it == d->children_positions.end())
2377 return DocIterator(this);
2382 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2384 // loop over children
2385 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2386 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2387 for (; it != end; ++it) {
2388 Buffer * child = const_cast<Buffer *>(it->first);
2389 clist.push_back(child);
2390 if (grand_children) {
2391 // there might be grandchildren
2392 std::vector<Buffer *> glist = child->getChildren();
2393 for (vector<Buffer *>::const_iterator git = glist.begin();
2394 git != glist.end(); ++git)
2395 clist.push_back(*git);
2401 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2403 std::vector<Buffer *> v;
2404 getChildren(v, grand_children);
2409 template<typename M>
2410 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2415 typename M::iterator it = m.lower_bound(x);
2416 if (it == m.begin())
2424 MacroData const * Buffer::getBufferMacro(docstring const & name,
2425 DocIterator const & pos) const
2427 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2429 // if paragraphs have no macro context set, pos will be empty
2433 // we haven't found anything yet
2434 DocIterator bestPos = par_iterator_begin();
2435 MacroData const * bestData = 0;
2437 // find macro definitions for name
2438 Impl::NamePositionScopeMacroMap::iterator nameIt
2439 = d->macros.find(name);
2440 if (nameIt != d->macros.end()) {
2441 // find last definition in front of pos or at pos itself
2442 Impl::PositionScopeMacroMap::const_iterator it
2443 = greatest_below(nameIt->second, pos);
2444 if (it != nameIt->second.end()) {
2446 // scope ends behind pos?
2447 if (pos < it->second.first) {
2448 // Looks good, remember this. If there
2449 // is no external macro behind this,
2450 // we found the right one already.
2451 bestPos = it->first;
2452 bestData = &it->second.second;
2456 // try previous macro if there is one
2457 if (it == nameIt->second.begin())
2464 // find macros in included files
2465 Impl::PositionScopeBufferMap::const_iterator it
2466 = greatest_below(d->position_to_children, pos);
2467 if (it == d->position_to_children.end())
2468 // no children before
2472 // do we know something better (i.e. later) already?
2473 if (it->first < bestPos )
2476 // scope ends behind pos?
2477 if (pos < it->second.first) {
2478 // look for macro in external file
2479 d->macro_lock = true;
2480 MacroData const * data
2481 = it->second.second->getMacro(name, false);
2482 d->macro_lock = false;
2484 bestPos = it->first;
2490 // try previous file if there is one
2491 if (it == d->position_to_children.begin())
2496 // return the best macro we have found
2501 MacroData const * Buffer::getMacro(docstring const & name,
2502 DocIterator const & pos, bool global) const
2507 // query buffer macros
2508 MacroData const * data = getBufferMacro(name, pos);
2512 // If there is a master buffer, query that
2513 Buffer const * const pbuf = d->parent();
2515 d->macro_lock = true;
2516 MacroData const * macro = pbuf->getMacro(
2517 name, *this, false);
2518 d->macro_lock = false;
2524 data = MacroTable::globalMacros().get(name);
2533 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2535 // set scope end behind the last paragraph
2536 DocIterator scope = par_iterator_begin();
2537 scope.pit() = scope.lastpit() + 1;
2539 return getMacro(name, scope, global);
2543 MacroData const * Buffer::getMacro(docstring const & name,
2544 Buffer const & child, bool global) const
2546 // look where the child buffer is included first
2547 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2548 if (it == d->children_positions.end())
2551 // check for macros at the inclusion position
2552 return getMacro(name, it->second, global);
2556 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2558 pit_type lastpit = it.lastpit();
2560 // look for macros in each paragraph
2561 while (it.pit() <= lastpit) {
2562 Paragraph & par = it.paragraph();
2564 // iterate over the insets of the current paragraph
2565 InsetList const & insets = par.insetList();
2566 InsetList::const_iterator iit = insets.begin();
2567 InsetList::const_iterator end = insets.end();
2568 for (; iit != end; ++iit) {
2569 it.pos() = iit->pos;
2571 // is it a nested text inset?
2572 if (iit->inset->asInsetText()) {
2573 // Inset needs its own scope?
2574 InsetText const * itext = iit->inset->asInsetText();
2575 bool newScope = itext->isMacroScope();
2577 // scope which ends just behind the inset
2578 DocIterator insetScope = it;
2581 // collect macros in inset
2582 it.push_back(CursorSlice(*iit->inset));
2583 updateMacros(it, newScope ? insetScope : scope);
2588 // is it an external file?
2589 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2590 // get buffer of external file
2591 InsetInclude const & inset =
2592 static_cast<InsetInclude const &>(*iit->inset);
2593 d->macro_lock = true;
2594 Buffer * child = inset.getChildBuffer();
2595 d->macro_lock = false;
2599 // register its position, but only when it is
2600 // included first in the buffer
2601 if (d->children_positions.find(child) ==
2602 d->children_positions.end())
2603 d->children_positions[child] = it;
2605 // register child with its scope
2606 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2610 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2614 MathMacroTemplate & macroTemplate =
2615 static_cast<MathMacroTemplate &>(*iit->inset);
2616 MacroContext mc(this, it);
2617 macroTemplate.updateToContext(mc);
2620 bool valid = macroTemplate.validMacro();
2621 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2622 // then the BufferView's cursor will be invalid in
2623 // some cases which leads to crashes.
2628 // FIXME (Abdel), I don't understandt why we pass 'it' here
2629 // instead of 'macroTemplate' defined above... is this correct?
2630 d->macros[macroTemplate.name()][it] =
2631 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2641 void Buffer::updateMacros() const
2646 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2648 // start with empty table
2650 d->children_positions.clear();
2651 d->position_to_children.clear();
2653 // Iterate over buffer, starting with first paragraph
2654 // The scope must be bigger than any lookup DocIterator
2655 // later. For the global lookup, lastpit+1 is used, hence
2656 // we use lastpit+2 here.
2657 DocIterator it = par_iterator_begin();
2658 DocIterator outerScope = it;
2659 outerScope.pit() = outerScope.lastpit() + 2;
2660 updateMacros(it, outerScope);
2664 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2666 InsetIterator it = inset_iterator_begin(inset());
2667 InsetIterator const end = inset_iterator_end(inset());
2668 for (; it != end; ++it) {
2669 if (it->lyxCode() == BRANCH_CODE) {
2670 InsetBranch & br = static_cast<InsetBranch &>(*it);
2671 docstring const name = br.branch();
2672 if (!from_master && !params().branchlist().find(name))
2673 result.push_back(name);
2674 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2675 result.push_back(name);
2678 if (it->lyxCode() == INCLUDE_CODE) {
2679 // get buffer of external file
2680 InsetInclude const & ins =
2681 static_cast<InsetInclude const &>(*it);
2682 Buffer * child = ins.getChildBuffer();
2685 child->getUsedBranches(result, true);
2688 // remove duplicates
2693 void Buffer::updateMacroInstances() const
2695 LYXERR(Debug::MACROS, "updateMacroInstances for "
2696 << d->filename.onlyFileName());
2697 DocIterator it = doc_iterator_begin(this);
2699 DocIterator const end = doc_iterator_end(this);
2700 for (; it != end; it.forwardInset()) {
2701 // look for MathData cells in InsetMathNest insets
2702 InsetMath * minset = it.nextInset()->asInsetMath();
2706 // update macro in all cells of the InsetMathNest
2707 DocIterator::idx_type n = minset->nargs();
2708 MacroContext mc = MacroContext(this, it);
2709 for (DocIterator::idx_type i = 0; i < n; ++i) {
2710 MathData & data = minset->cell(i);
2711 data.updateMacros(0, mc);
2717 void Buffer::listMacroNames(MacroNameSet & macros) const
2722 d->macro_lock = true;
2724 // loop over macro names
2725 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2726 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2727 for (; nameIt != nameEnd; ++nameIt)
2728 macros.insert(nameIt->first);
2730 // loop over children
2731 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2732 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2733 for (; it != end; ++it)
2734 it->first->listMacroNames(macros);
2737 Buffer const * const pbuf = d->parent();
2739 pbuf->listMacroNames(macros);
2741 d->macro_lock = false;
2745 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2747 Buffer const * const pbuf = d->parent();
2752 pbuf->listMacroNames(names);
2755 MacroNameSet::iterator it = names.begin();
2756 MacroNameSet::iterator end = names.end();
2757 for (; it != end; ++it) {
2759 MacroData const * data =
2760 pbuf->getMacro(*it, *this, false);
2762 macros.insert(data);
2764 // we cannot access the original MathMacroTemplate anymore
2765 // here to calls validate method. So we do its work here manually.
2766 // FIXME: somehow make the template accessible here.
2767 if (data->optionals() > 0)
2768 features.require("xargs");
2774 Buffer::References & Buffer::references(docstring const & label)
2777 return const_cast<Buffer *>(masterBuffer())->references(label);
2779 RefCache::iterator it = d->ref_cache_.find(label);
2780 if (it != d->ref_cache_.end())
2781 return it->second.second;
2783 static InsetLabel const * dummy_il = 0;
2784 static References const dummy_refs;
2785 it = d->ref_cache_.insert(
2786 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2787 return it->second.second;
2791 Buffer::References const & Buffer::references(docstring const & label) const
2793 return const_cast<Buffer *>(this)->references(label);
2797 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2799 masterBuffer()->d->ref_cache_[label].first = il;
2803 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2805 return masterBuffer()->d->ref_cache_[label].first;
2809 void Buffer::clearReferenceCache() const
2812 d->ref_cache_.clear();
2816 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2819 //FIXME: This does not work for child documents yet.
2820 LASSERT(code == CITE_CODE, /**/);
2821 // Check if the label 'from' appears more than once
2822 vector<docstring> labels;
2824 checkBibInfoCache();
2825 BiblioInfo const & keys = masterBibInfo();
2826 BiblioInfo::const_iterator bit = keys.begin();
2827 BiblioInfo::const_iterator bend = keys.end();
2829 for (; bit != bend; ++bit)
2831 labels.push_back(bit->first);
2834 if (count(labels.begin(), labels.end(), from) > 1)
2837 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2838 if (it->lyxCode() == code) {
2839 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2840 docstring const oldValue = inset.getParam(paramName);
2841 if (oldValue == from)
2842 inset.setParam(paramName, to);
2848 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2849 pit_type par_end, bool full_source) const
2851 OutputParams runparams(¶ms().encoding());
2852 runparams.nice = true;
2853 runparams.flavor = params().useXetex ?
2854 OutputParams::XETEX : OutputParams::LATEX;
2855 runparams.linelen = lyxrc.plaintext_linelen;
2856 // No side effect of file copying and image conversion
2857 runparams.dryrun = true;
2860 os << "% " << _("Preview source code") << "\n\n";
2862 d->texrow.newline();
2863 d->texrow.newline();
2865 writeDocBookSource(os, absFileName(), runparams, false);
2867 // latex or literate
2868 writeLaTeXSource(os, string(), runparams, true, true);
2870 runparams.par_begin = par_begin;
2871 runparams.par_end = par_end;
2872 if (par_begin + 1 == par_end) {
2874 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2878 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2879 convert<docstring>(par_begin),
2880 convert<docstring>(par_end - 1))
2887 // output paragraphs
2889 docbookParagraphs(text(), *this, os, runparams);
2891 // latex or literate
2892 latexParagraphs(*this, text(), os, texrow, runparams);
2897 ErrorList & Buffer::errorList(string const & type) const
2899 static ErrorList emptyErrorList;
2900 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2901 if (I == d->errorLists.end())
2902 return emptyErrorList;
2908 void Buffer::updateTocItem(std::string const & type,
2909 DocIterator const & dit) const
2912 gui_->updateTocItem(type, dit);
2916 void Buffer::structureChanged() const
2919 gui_->structureChanged();
2923 void Buffer::errors(string const & err, bool from_master) const
2926 gui_->errors(err, from_master);
2930 void Buffer::message(docstring const & msg) const
2937 void Buffer::setBusy(bool on) const
2944 void Buffer::setReadOnly(bool on) const
2947 d->wa_->setReadOnly(on);
2951 void Buffer::updateTitles() const
2954 d->wa_->updateTitles();
2958 void Buffer::resetAutosaveTimers() const
2961 gui_->resetAutosaveTimers();
2965 bool Buffer::hasGuiDelegate() const
2971 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2980 class AutoSaveBuffer : public ForkedProcess {
2983 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2984 : buffer_(buffer), fname_(fname) {}
2986 virtual boost::shared_ptr<ForkedProcess> clone() const
2988 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2993 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2994 from_utf8(fname_.absFilename())));
2995 return run(DontWait);
2999 virtual int generateChild();
3001 Buffer const & buffer_;
3006 int AutoSaveBuffer::generateChild()
3008 #if defined(__APPLE__)
3009 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3010 * We should use something else like threads.
3012 * Since I do not know how to determine at run time what is the OS X
3013 * version, I just disable forking altogether for now (JMarc)
3015 pid_t const pid = -1;
3017 // tmp_ret will be located (usually) in /tmp
3018 // will that be a problem?
3019 // Note that this calls ForkedCalls::fork(), so it's
3020 // ok cross-platform.
3021 pid_t const pid = fork();
3022 // If you want to debug the autosave
3023 // you should set pid to -1, and comment out the fork.
3024 if (pid != 0 && pid != -1)
3028 // pid = -1 signifies that lyx was unable
3029 // to fork. But we will do the save
3031 bool failed = false;
3032 FileName const tmp_ret = FileName::tempName("lyxauto");
3033 if (!tmp_ret.empty()) {
3034 buffer_.writeFile(tmp_ret);
3035 // assume successful write of tmp_ret
3036 if (!tmp_ret.moveTo(fname_))
3042 // failed to write/rename tmp_ret so try writing direct
3043 if (!buffer_.writeFile(fname_)) {
3044 // It is dangerous to do this in the child,
3045 // but safe in the parent, so...
3046 if (pid == -1) // emit message signal.
3047 buffer_.message(_("Autosave failed!"));
3051 if (pid == 0) // we are the child so...
3060 FileName Buffer::getAutosaveFilename() const
3062 // if the document is unnamed try to save in the backup dir, else
3063 // in the default document path, and as a last try in the filePath,
3064 // which will most often be the temporary directory
3067 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3068 : lyxrc.backupdir_path;
3069 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3072 string const fname = "#" + d->filename.onlyFileName() + "#";
3073 return makeAbsPath(fname, fpath);
3077 void Buffer::removeAutosaveFile() const
3079 FileName const f = getAutosaveFilename();
3085 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3087 FileName const newauto = getAutosaveFilename();
3088 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3089 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3093 // Perfect target for a thread...
3094 void Buffer::autoSave() const
3096 if (isBakClean() || isReadonly()) {
3097 // We don't save now, but we'll try again later
3098 resetAutosaveTimers();
3102 // emit message signal.
3103 message(_("Autosaving current document..."));
3104 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3108 resetAutosaveTimers();
3112 string Buffer::bufferFormat() const
3114 string format = params().documentClass().outputFormat();
3115 if (format == "latex") {
3116 if (params().useXetex)
3118 if (params().encoding().package() == Encoding::japanese)
3125 string Buffer::getDefaultOutputFormat() const
3127 if (!params().defaultOutputFormat.empty()
3128 && params().defaultOutputFormat != "default")
3129 return params().defaultOutputFormat;
3130 typedef vector<Format const *> Formats;
3131 Formats formats = exportableFormats(true);
3134 || params().useXetex
3135 || params().encoding().package() == Encoding::japanese) {
3136 if (formats.empty())
3138 // return the first we find
3139 return formats.front()->name();
3141 return lyxrc.default_view_format;
3146 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3147 bool includeall, string & result_file) const
3149 string backend_format;
3150 OutputParams runparams(¶ms().encoding());
3151 runparams.flavor = OutputParams::LATEX;
3152 runparams.linelen = lyxrc.plaintext_linelen;
3153 runparams.includeall = includeall;
3154 vector<string> backs = backends();
3155 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3156 // Get shortest path to format
3157 Graph::EdgePath path;
3158 for (vector<string>::const_iterator it = backs.begin();
3159 it != backs.end(); ++it) {
3160 Graph::EdgePath p = theConverters().getPath(*it, format);
3161 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3162 backend_format = *it;
3167 if (!put_in_tempdir) {
3168 // Only show this alert if this is an export to a non-temporary
3169 // file (not for previewing).
3170 Alert::error(_("Couldn't export file"), bformat(
3171 _("No information for exporting the format %1$s."),
3172 formats.prettyName(format)));
3176 runparams.flavor = theConverters().getFlavor(path);
3179 backend_format = format;
3180 // FIXME: Don't hardcode format names here, but use a flag
3181 if (backend_format == "pdflatex")
3182 runparams.flavor = OutputParams::PDFLATEX;
3185 string filename = latexName(false);
3186 filename = addName(temppath(), filename);
3187 filename = changeExtension(filename,
3188 formats.extension(backend_format));
3191 updateMacroInstances();
3193 // Plain text backend
3194 if (backend_format == "text") {
3195 runparams.flavor = OutputParams::TEXT;
3196 writePlaintextFile(*this, FileName(filename), runparams);
3199 else if (backend_format == "xhtml") {
3200 runparams.flavor = OutputParams::HTML;
3201 makeLyXHTMLFile(FileName(filename), runparams);
3202 } else if (backend_format == "lyx")
3203 writeFile(FileName(filename));
3205 else if (isDocBook()) {
3206 runparams.nice = !put_in_tempdir;
3207 makeDocBookFile(FileName(filename), runparams);
3210 else if (backend_format == format) {
3211 runparams.nice = true;
3212 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3214 } else if (!lyxrc.tex_allows_spaces
3215 && contains(filePath(), ' ')) {
3216 Alert::error(_("File name error"),
3217 _("The directory path to the document cannot contain spaces."));
3220 runparams.nice = false;
3221 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3225 string const error_type = (format == "program")
3226 ? "Build" : bufferFormat();
3227 ErrorList & error_list = d->errorLists[error_type];
3228 string const ext = formats.extension(format);
3229 FileName const tmp_result_file(changeExtension(filename, ext));
3230 bool const success = theConverters().convert(this, FileName(filename),
3231 tmp_result_file, FileName(absFileName()), backend_format, format,
3233 // Emit the signal to show the error list.
3234 if (format != backend_format) {
3236 // also to the children, in case of master-buffer-view
3237 std::vector<Buffer *> clist = getChildren();
3238 for (vector<Buffer *>::const_iterator cit = clist.begin();
3239 cit != clist.end(); ++cit)
3240 (*cit)->errors(error_type, true);
3245 if (d->cloned_buffer_) {
3246 // Enable reverse dvi or pdf to work by copying back the texrow
3247 // object to the cloned buffer.
3248 // FIXME: There is a possibility of concurrent access to texrow
3249 // here from the main GUI thread that should be securized.
3250 d->cloned_buffer_->d->texrow = d->texrow;
3253 if (put_in_tempdir) {
3254 result_file = tmp_result_file.absFilename();
3258 result_file = changeExtension(exportFileName().absFilename(), ext);
3259 // We need to copy referenced files (e. g. included graphics
3260 // if format == "dvi") to the result dir.
3261 vector<ExportedFile> const files =
3262 runparams.exportdata->externalFiles(format);
3263 string const dest = onlyPath(result_file);
3264 CopyStatus status = SUCCESS;
3265 for (vector<ExportedFile>::const_iterator it = files.begin();
3266 it != files.end() && status != CANCEL; ++it) {
3267 string const fmt = formats.getFormatFromFile(it->sourceName);
3268 status = copyFile(fmt, it->sourceName,
3269 makeAbsPath(it->exportName, dest),
3270 it->exportName, status == FORCE);
3272 if (status == CANCEL) {
3273 message(_("Document export cancelled."));
3274 } else if (tmp_result_file.exists()) {
3275 // Finally copy the main file
3276 status = copyFile(format, tmp_result_file,
3277 FileName(result_file), result_file,
3279 message(bformat(_("Document exported as %1$s "
3281 formats.prettyName(format),
3282 makeDisplayPath(result_file)));
3284 // This must be a dummy converter like fax (bug 1888)
3285 message(bformat(_("Document exported as %1$s"),
3286 formats.prettyName(format)));
3293 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3294 bool includeall) const
3297 // (1) export with all included children (omit \includeonly)
3298 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3300 // (2) export with included children only
3301 return doExport(format, put_in_tempdir, false, result_file);
3305 bool Buffer::preview(string const & format, bool includeall) const
3308 // (1) export with all included children (omit \includeonly)
3309 if (includeall && !doExport(format, true, true))
3311 // (2) export with included children only
3312 if (!doExport(format, true, false, result_file))
3314 return formats.view(*this, FileName(result_file), format);
3318 bool Buffer::isExportable(string const & format) const
3320 vector<string> backs = backends();
3321 for (vector<string>::const_iterator it = backs.begin();
3322 it != backs.end(); ++it)
3323 if (theConverters().isReachable(*it, format))
3329 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3331 vector<string> const backs = backends();
3332 vector<Format const *> result =
3333 theConverters().getReachable(backs[0], only_viewable, true);
3334 for (vector<string>::const_iterator it = backs.begin() + 1;
3335 it != backs.end(); ++it) {
3336 vector<Format const *> r =
3337 theConverters().getReachable(*it, only_viewable, false);
3338 result.insert(result.end(), r.begin(), r.end());
3344 vector<string> Buffer::backends() const
3347 v.push_back(bufferFormat());
3348 // FIXME: Don't hardcode format names here, but use a flag
3349 if (v.back() == "latex")
3350 v.push_back("pdflatex");
3351 v.push_back("xhtml");
3352 v.push_back("text");
3358 bool Buffer::readFileHelper(FileName const & s)
3360 // File information about normal file
3362 docstring const file = makeDisplayPath(s.absFilename(), 50);
3363 docstring text = bformat(_("The specified document\n%1$s"
3364 "\ncould not be read."), file);
3365 Alert::error(_("Could not read document"), text);
3369 // Check if emergency save file exists and is newer.
3370 FileName const e(s.absFilename() + ".emergency");
3372 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3373 docstring const file = makeDisplayPath(s.absFilename(), 20);
3374 docstring const text =
3375 bformat(_("An emergency save of the document "
3377 "Recover emergency save?"), file);
3378 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3379 _("&Recover"), _("&Load Original"),
3383 // the file is not saved if we load the emergency file.
3388 if ((res = readFile(e)) == success)
3389 str = _("Document was successfully recovered.");
3391 str = _("Document was NOT successfully recovered.");
3392 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3393 from_utf8(e.absFilename()));
3395 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3396 _("&Remove"), _("&Keep it"))) {
3399 Alert::warning(_("Emergency file deleted"),
3400 _("Do not forget to save your file now!"), true);
3405 if (!Alert::prompt(_("Delete emergency file?"),
3406 _("Remove emergency file now?"), 1, 1,
3407 _("&Remove"), _("&Keep it")))
3415 // Now check if autosave file is newer.
3416 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3418 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3419 docstring const file = makeDisplayPath(s.absFilename(), 20);
3420 docstring const text =
3421 bformat(_("The backup of the document "
3422 "%1$s is newer.\n\nLoad the "
3423 "backup instead?"), file);
3424 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3425 _("&Load backup"), _("Load &original"),
3429 // the file is not saved if we load the autosave file.
3433 // Here we delete the autosave
3444 bool Buffer::loadLyXFile(FileName const & s)
3446 // If the file is not readable, we try to
3447 // retrieve the file from version control.
3448 if (!s.isReadableFile()
3449 && !LyXVC::file_not_found_hook(s))
3452 if (s.isReadableFile()
3453 && readFileHelper(s)) {
3454 lyxvc().file_found_hook(s);
3455 setReadonly(!s.isWritable());
3462 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3464 TeXErrors::Errors::const_iterator cit = terr.begin();
3465 TeXErrors::Errors::const_iterator end = terr.end();
3467 for (; cit != end; ++cit) {
3470 int errorRow = cit->error_in_line;
3471 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3477 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3478 } while (found && id_start == id_end && pos_start == pos_end);
3480 errorList.push_back(ErrorItem(cit->error_desc,
3481 cit->error_text, id_start, pos_start, pos_end));
3486 void Buffer::setBuffersForInsets() const
3488 inset().setBuffer(const_cast<Buffer &>(*this));
3492 void Buffer::updateLabels(UpdateScope scope, bool out) const
3494 // Use the master text class also for child documents
3495 Buffer const * const master = masterBuffer();
3496 DocumentClass const & textclass = master->params().documentClass();
3498 // do this only if we are the top-level Buffer
3499 if (scope != UpdateMaster || master == this)
3500 checkBibInfoCache();
3502 // keep the buffers to be children in this set. If the call from the
3503 // master comes back we can see which of them were actually seen (i.e.
3504 // via an InsetInclude). The remaining ones in the set need still be updated.
3505 static std::set<Buffer const *> bufToUpdate;
3506 if (scope == UpdateMaster) {
3507 // If this is a child document start with the master
3508 if (master != this) {
3509 bufToUpdate.insert(this);
3510 master->updateLabels(UpdateMaster, out);
3511 // Do this here in case the master has no gui associated with it. Then,
3512 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3516 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3517 if (bufToUpdate.find(this) == bufToUpdate.end())
3521 // start over the counters in the master
3522 textclass.counters().reset();
3525 // update will be done below for this buffer
3526 bufToUpdate.erase(this);
3528 // update all caches
3529 clearReferenceCache();
3532 Buffer & cbuf = const_cast<Buffer &>(*this);
3534 LASSERT(!text().paragraphs().empty(), /**/);
3537 ParIterator parit = cbuf.par_iterator_begin();
3538 updateLabels(parit, out);
3541 // TocBackend update will be done later.
3544 cbuf.tocBackend().update();
3545 if (scope == UpdateMaster)
3546 cbuf.structureChanged();
3550 static depth_type getDepth(DocIterator const & it)
3552 depth_type depth = 0;
3553 for (size_t i = 0 ; i < it.depth() ; ++i)
3554 if (!it[i].inset().inMathed())
3555 depth += it[i].paragraph().getDepth() + 1;
3556 // remove 1 since the outer inset does not count
3560 static depth_type getItemDepth(ParIterator const & it)
3562 Paragraph const & par = *it;
3563 LabelType const labeltype = par.layout().labeltype;
3565 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3568 // this will hold the lowest depth encountered up to now.
3569 depth_type min_depth = getDepth(it);
3570 ParIterator prev_it = it;
3573 --prev_it.top().pit();
3575 // start of nested inset: go to outer par
3577 if (prev_it.empty()) {
3578 // start of document: nothing to do
3583 // We search for the first paragraph with same label
3584 // that is not more deeply nested.
3585 Paragraph & prev_par = *prev_it;
3586 depth_type const prev_depth = getDepth(prev_it);
3587 if (labeltype == prev_par.layout().labeltype) {
3588 if (prev_depth < min_depth)
3589 return prev_par.itemdepth + 1;
3590 if (prev_depth == min_depth)
3591 return prev_par.itemdepth;
3593 min_depth = min(min_depth, prev_depth);
3594 // small optimization: if we are at depth 0, we won't
3595 // find anything else
3596 if (prev_depth == 0)
3602 static bool needEnumCounterReset(ParIterator const & it)
3604 Paragraph const & par = *it;
3605 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3606 depth_type const cur_depth = par.getDepth();
3607 ParIterator prev_it = it;
3608 while (prev_it.pit()) {
3609 --prev_it.top().pit();
3610 Paragraph const & prev_par = *prev_it;
3611 if (prev_par.getDepth() <= cur_depth)
3612 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3614 // start of nested inset: reset
3619 // set the label of a paragraph. This includes the counters.
3620 void Buffer::setLabel(ParIterator & it) const
3622 BufferParams const & bp = this->masterBuffer()->params();
3623 DocumentClass const & textclass = bp.documentClass();
3624 Paragraph & par = it.paragraph();
3625 Layout const & layout = par.layout();
3626 Counters & counters = textclass.counters();
3628 if (par.params().startOfAppendix()) {
3629 // FIXME: only the counter corresponding to toplevel
3630 // sectioning should be reset
3632 counters.appendix(true);
3634 par.params().appendix(counters.appendix());
3636 // Compute the item depth of the paragraph
3637 par.itemdepth = getItemDepth(it);
3639 if (layout.margintype == MARGIN_MANUAL
3640 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3641 if (par.params().labelWidthString().empty())
3642 par.params().labelWidthString(par.expandLabel(layout, bp));
3644 par.params().labelWidthString(docstring());
3647 switch(layout.labeltype) {
3649 if (layout.toclevel <= bp.secnumdepth
3650 && (layout.latextype != LATEX_ENVIRONMENT
3651 || it.text()->isFirstInSequence(it.pit()))) {
3652 counters.step(layout.counter);
3653 par.params().labelString(
3654 par.expandLabel(layout, bp));
3656 par.params().labelString(docstring());
3659 case LABEL_ITEMIZE: {
3660 // At some point of time we should do something more
3661 // clever here, like:
3662 // par.params().labelString(
3663 // bp.user_defined_bullet(par.itemdepth).getText());
3664 // for now, use a simple hardcoded label
3665 docstring itemlabel;
3666 switch (par.itemdepth) {
3668 itemlabel = char_type(0x2022);
3671 itemlabel = char_type(0x2013);
3674 itemlabel = char_type(0x2217);
3677 itemlabel = char_type(0x2219); // or 0x00b7
3680 par.params().labelString(itemlabel);
3684 case LABEL_ENUMERATE: {
3685 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3687 switch (par.itemdepth) {
3696 enumcounter += "iv";
3699 // not a valid enumdepth...
3703 // Maybe we have to reset the enumeration counter.
3704 if (needEnumCounterReset(it))
3705 counters.reset(enumcounter);
3706 counters.step(enumcounter);
3708 string const & lang = par.getParLanguage(bp)->code();
3709 par.params().labelString(counters.theCounter(enumcounter, lang));
3714 case LABEL_SENSITIVE: {
3715 string const & type = counters.current_float();
3716 docstring full_label;
3718 full_label = this->B_("Senseless!!! ");
3720 docstring name = this->B_(textclass.floats().getType(type).name());
3721 if (counters.hasCounter(from_utf8(type))) {
3722 string const & lang = par.getParLanguage(bp)->code();
3723 counters.step(from_utf8(type));
3724 full_label = bformat(from_ascii("%1$s %2$s:"),
3726 counters.theCounter(from_utf8(type), lang));
3728 full_label = bformat(from_ascii("%1$s #:"), name);
3730 par.params().labelString(full_label);
3734 case LABEL_NO_LABEL:
3735 par.params().labelString(docstring());
3739 case LABEL_TOP_ENVIRONMENT:
3740 case LABEL_CENTERED_TOP_ENVIRONMENT:
3743 par.params().labelString(par.expandLabel(layout, bp));
3749 void Buffer::updateLabels(ParIterator & parit, bool out) const
3751 LASSERT(parit.pit() == 0, /**/);
3753 // set the position of the text in the buffer to be able
3754 // to resolve macros in it. This has nothing to do with
3755 // labels, but by putting it here we avoid implementing
3756 // a whole bunch of traversal routines just for this call.
3757 parit.text()->setMacrocontextPosition(parit);
3759 depth_type maxdepth = 0;
3760 pit_type const lastpit = parit.lastpit();
3761 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3762 // reduce depth if necessary
3763 parit->params().depth(min(parit->params().depth(), maxdepth));
3764 maxdepth = parit->getMaxDepthAfter();
3766 // set the counter for this paragraph
3770 InsetList::const_iterator iit = parit->insetList().begin();
3771 InsetList::const_iterator end = parit->insetList().end();
3772 for (; iit != end; ++iit) {
3773 parit.pos() = iit->pos;
3774 iit->inset->updateLabels(parit, out);
3780 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3781 WordLangTuple & word_lang, docstring_list & suggestions) const
3785 suggestions.clear();
3786 word_lang = WordLangTuple();
3787 // OK, we start from here.
3788 DocIterator const end = doc_iterator_end(this);
3789 for (; from != end; from.forwardPos()) {
3790 // We are only interested in text so remove the math CursorSlice.
3791 while (from.inMathed()) {
3795 // If from is at the end of the document (which is possible
3796 // when leaving the mathed) LyX will crash later.
3800 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3805 // Do not increase progress when from == to, otherwise the word
3806 // count will be wrong.
3816 bool Buffer::reload()
3819 // e.g., read-only status could have changed due to version control
3820 d->filename.refresh();
3821 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3823 bool const success = loadLyXFile(d->filename);
3828 message(bformat(_("Document %1$s reloaded."), disp_fn));
3830 message(bformat(_("Could not reload document %1$s."), disp_fn));