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 = 373; // jspitzm: merge g-brief class
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 bibfilesCache_;
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 bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
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 /// So we can force access via the accessors.
263 mutable Buffer const * parent_buffer;
265 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
266 /// This one is useful for preview detached in a thread.
267 Buffer const * cloned_buffer_;
271 /// Creates the per buffer temporary directory
272 static FileName createBufferTmpDir()
275 // We are in our own directory. Why bother to mangle name?
276 // In fact I wrote this code to circumvent a problematic behaviour
277 // (bug?) of EMX mkstemp().
278 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
279 convert<string>(count++));
281 if (!tmpfl.createDirectory(0777)) {
282 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
283 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
284 from_utf8(tmpfl.absFilename())));
290 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
291 Buffer const * cloned_buffer)
292 : lyx_clean(true), bak_clean(true), unnamed(false),
293 read_only(readonly_), filename(file), file_fully_loaded(false),
294 toc_backend(&parent), macro_lock(false), timestamp_(0),
295 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
296 parent_buffer(0), cloned_buffer_(cloned_buffer)
298 if (!cloned_buffer_) {
299 temppath = createBufferTmpDir();
300 lyxvc.setBuffer(&parent);
302 wa_ = new frontend::WorkAreaManager;
305 temppath = cloned_buffer_->d->temppath;
306 file_fully_loaded = true;
307 params = cloned_buffer_->d->params;
308 inset = static_cast<InsetText *>(cloned_buffer_->d->inset->clone());
309 inset->setBuffer(parent);
313 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
314 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
316 LYXERR(Debug::INFO, "Buffer::Buffer()");
318 d->inset = new InsetText(this);
319 d->inset->setAutoBreakRows(true);
320 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
326 LYXERR(Debug::INFO, "Buffer::~Buffer()");
327 // here the buffer should take care that it is
328 // saved properly, before it goes into the void.
330 // GuiView already destroyed
334 // No need to do additional cleanups for internal buffer.
339 // loop over children
340 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
341 Impl::BufferPositionMap::iterator end = d->children_positions.end();
342 for (; it != end; ++it) {
343 Buffer * child = const_cast<Buffer *>(it->first);
344 // The child buffer might have been closed already.
345 if (theBufferList().isLoaded(child))
346 theBufferList().releaseChild(this, child);
350 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
351 msg += emergencyWrite();
352 frontend::Alert::warning(_("Attempting to close changed document!"), msg);
355 // clear references to children in macro tables
356 d->children_positions.clear();
357 d->position_to_children.clear();
359 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
360 Alert::warning(_("Could not remove temporary directory"),
361 bformat(_("Could not remove the temporary directory %1$s"),
362 from_utf8(d->temppath.absFilename())));
365 // Remove any previewed LaTeX snippets associated with this buffer.
366 thePreviews().removeLoader(*this);
372 Buffer * Buffer::clone() const
374 return new Buffer(fileName().absFilename(), false, this);
378 bool Buffer::isClone() const
380 return d->cloned_buffer_;
384 void Buffer::changed() const
391 frontend::WorkAreaManager & Buffer::workAreaManager() const
393 LASSERT(d->wa_, /**/);
398 Text & Buffer::text() const
400 return d->inset->text();
404 Inset & Buffer::inset() const
410 BufferParams & Buffer::params()
416 BufferParams const & Buffer::params() const
422 ParagraphList & Buffer::paragraphs()
424 return text().paragraphs();
428 ParagraphList const & Buffer::paragraphs() const
430 return text().paragraphs();
434 LyXVC & Buffer::lyxvc()
440 LyXVC const & Buffer::lyxvc() const
446 string const Buffer::temppath() const
448 return d->temppath.absFilename();
452 TexRow & Buffer::texrow()
458 TexRow const & Buffer::texrow() const
464 TocBackend & Buffer::tocBackend() const
466 return d->toc_backend;
470 Undo & Buffer::undo()
476 string Buffer::latexName(bool const no_path) const
478 FileName latex_name =
479 makeLatexName(exportFileName());
480 return no_path ? latex_name.onlyFileName()
481 : latex_name.absFilename();
485 FileName Buffer::exportFileName() const
487 docstring const branch_suffix =
488 params().branchlist().getFilenameSuffix();
489 if (branch_suffix.empty())
492 string const name = fileName().onlyFileNameWithoutExt()
493 + to_utf8(branch_suffix);
494 FileName res(fileName().onlyPath().absFilename() + "/" + name);
495 res.changeExtension(fileName().extension());
501 string Buffer::logName(LogType * type) const
503 string const filename = latexName(false);
505 if (filename.empty()) {
511 string const path = temppath();
513 FileName const fname(addName(temppath(),
514 onlyFilename(changeExtension(filename,
517 // FIXME: how do we know this is the name of the build log?
518 FileName const bname(
519 addName(path, onlyFilename(
520 changeExtension(filename,
521 formats.extension(bufferFormat()) + ".out"))));
523 // Also consider the master buffer log file
524 FileName masterfname = fname;
526 if (masterBuffer() != this) {
527 string const mlogfile = masterBuffer()->logName(&mtype);
528 masterfname = FileName(mlogfile);
531 // If no Latex log or Build log is newer, show Build log
532 if (bname.exists() &&
533 ((!fname.exists() && !masterfname.exists())
534 || (fname.lastModified() < bname.lastModified()
535 && masterfname.lastModified() < bname.lastModified()))) {
536 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
539 return bname.absFilename();
540 // If we have a newer master file log or only a master log, show this
541 } else if (fname != masterfname
542 && (!fname.exists() && (masterfname.exists()
543 || fname.lastModified() < masterfname.lastModified()))) {
544 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
547 return masterfname.absFilename();
549 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
552 return fname.absFilename();
556 void Buffer::setReadonly(bool const flag)
558 if (d->read_only != flag) {
565 void Buffer::setFileName(string const & newfile)
567 d->filename = makeAbsPath(newfile);
568 setReadonly(d->filename.isReadOnly());
573 int Buffer::readHeader(Lexer & lex)
575 int unknown_tokens = 0;
577 int begin_header_line = -1;
579 // Initialize parameters that may be/go lacking in header:
580 params().branchlist().clear();
581 params().preamble.erase();
582 params().options.erase();
583 params().master.erase();
584 params().float_placement.erase();
585 params().paperwidth.erase();
586 params().paperheight.erase();
587 params().leftmargin.erase();
588 params().rightmargin.erase();
589 params().topmargin.erase();
590 params().bottommargin.erase();
591 params().headheight.erase();
592 params().headsep.erase();
593 params().footskip.erase();
594 params().columnsep.erase();
595 params().fontsCJK.erase();
596 params().listings_params.clear();
597 params().clearLayoutModules();
598 params().clearRemovedModules();
599 params().pdfoptions().clear();
600 params().indiceslist().clear();
601 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
603 for (int i = 0; i < 4; ++i) {
604 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
605 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
608 ErrorList & errorList = d->errorLists["Parse"];
617 if (token == "\\end_header")
621 if (token == "\\begin_header") {
622 begin_header_line = line;
626 LYXERR(Debug::PARSER, "Handling document header token: `"
629 string unknown = params().readToken(lex, token, d->filename.onlyPath());
630 if (!unknown.empty()) {
631 if (unknown[0] != '\\' && token == "\\textclass") {
632 Alert::warning(_("Unknown document class"),
633 bformat(_("Using the default document class, because the "
634 "class %1$s is unknown."), from_utf8(unknown)));
637 docstring const s = bformat(_("Unknown token: "
641 errorList.push_back(ErrorItem(_("Document header error"),
646 if (begin_header_line) {
647 docstring const s = _("\\begin_header is missing");
648 errorList.push_back(ErrorItem(_("Document header error"),
652 params().makeDocumentClass();
654 return unknown_tokens;
659 // changed to be public and have one parameter
660 // Returns true if "\end_document" is not read (Asger)
661 bool Buffer::readDocument(Lexer & lex)
663 ErrorList & errorList = d->errorLists["Parse"];
666 if (!lex.checkFor("\\begin_document")) {
667 docstring const s = _("\\begin_document is missing");
668 errorList.push_back(ErrorItem(_("Document header error"),
672 // we are reading in a brand new document
673 LASSERT(paragraphs().empty(), /**/);
677 if (params().outputChanges) {
678 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
679 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
680 LaTeXFeatures::isAvailable("xcolor");
682 if (!dvipost && !xcolorulem) {
683 Alert::warning(_("Changes not shown in LaTeX output"),
684 _("Changes will not be highlighted in LaTeX output, "
685 "because neither dvipost nor xcolor/ulem are installed.\n"
686 "Please install these packages or redefine "
687 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
688 } else if (!xcolorulem) {
689 Alert::warning(_("Changes not shown in LaTeX output"),
690 _("Changes will not be highlighted in LaTeX output "
691 "when using pdflatex, because xcolor and ulem are not installed.\n"
692 "Please install both packages or redefine "
693 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
697 if (!params().master.empty()) {
698 FileName const master_file = makeAbsPath(params().master,
699 onlyPath(absFileName()));
700 if (isLyXFilename(master_file.absFilename())) {
702 checkAndLoadLyXFile(master_file, true);
704 // necessary e.g. after a reload
705 // to re-register the child (bug 5873)
706 // FIXME: clean up updateMacros (here, only
707 // child registering is needed).
708 master->updateMacros();
709 // set master as master buffer, but only
710 // if we are a real child
711 if (master->isChild(this))
713 // if the master is not fully loaded
714 // it is probably just loading this
715 // child. No warning needed then.
716 else if (master->isFullyLoaded())
717 LYXERR0("The master '"
719 << "' assigned to this document ("
721 << ") does not include "
722 "this document. Ignoring the master assignment.");
727 // assure we have a default index
728 params().indiceslist().addDefault(B_("Index"));
731 bool const res = text().read(lex, errorList, d->inset);
735 updateMacroInstances();
740 bool Buffer::readString(string const & s)
742 params().compressed = false;
744 // remove dummy empty par
745 paragraphs().clear();
749 FileName const name = FileName::tempName("Buffer_readString");
750 switch (readFile(lex, name, true)) {
754 // We need to call lyx2lyx, so write the input to a file
755 ofstream os(name.toFilesystemEncoding().c_str());
758 return readFile(name);
768 bool Buffer::readFile(FileName const & filename)
770 FileName fname(filename);
772 params().compressed = fname.isZippedFile();
774 // remove dummy empty par
775 paragraphs().clear();
778 if (readFile(lex, fname) != success)
785 bool Buffer::isFullyLoaded() const
787 return d->file_fully_loaded;
791 void Buffer::setFullyLoaded(bool value)
793 d->file_fully_loaded = value;
797 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
800 LASSERT(!filename.empty(), /**/);
802 // the first (non-comment) token _must_ be...
803 if (!lex.checkFor("\\lyxformat")) {
804 Alert::error(_("Document format failure"),
805 bformat(_("%1$s is not a readable LyX document."),
806 from_utf8(filename.absFilename())));
812 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
813 // if present remove ".," from string.
814 size_t dot = tmp_format.find_first_of(".,");
815 //lyxerr << " dot found at " << dot << endl;
816 if (dot != string::npos)
817 tmp_format.erase(dot, 1);
818 int const file_format = convert<int>(tmp_format);
819 //lyxerr << "format: " << file_format << endl;
821 // save timestamp and checksum of the original disk file, making sure
822 // to not overwrite them with those of the file created in the tempdir
823 // when it has to be converted to the current format.
825 // Save the timestamp and checksum of disk file. If filename is an
826 // emergency file, save the timestamp and checksum of the original lyx file
827 // because isExternallyModified will check for this file. (BUG4193)
828 string diskfile = filename.absFilename();
829 if (suffixIs(diskfile, ".emergency"))
830 diskfile = diskfile.substr(0, diskfile.size() - 10);
831 saveCheckSum(FileName(diskfile));
834 if (file_format != LYX_FORMAT) {
837 // lyx2lyx would fail
840 FileName const tmpfile = FileName::tempName("Buffer_readFile");
841 if (tmpfile.empty()) {
842 Alert::error(_("Conversion failed"),
843 bformat(_("%1$s is from a different"
844 " version of LyX, but a temporary"
845 " file for converting it could"
847 from_utf8(filename.absFilename())));
850 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
851 if (lyx2lyx.empty()) {
852 Alert::error(_("Conversion script not found"),
853 bformat(_("%1$s is from a different"
854 " version of LyX, but the"
855 " conversion script lyx2lyx"
856 " could not be found."),
857 from_utf8(filename.absFilename())));
860 ostringstream command;
861 command << os::python()
862 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
863 << " -t " << convert<string>(LYX_FORMAT)
864 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
865 << ' ' << quoteName(filename.toFilesystemEncoding());
866 string const command_str = command.str();
868 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
870 cmd_ret const ret = runCommand(command_str);
871 if (ret.first != 0) {
872 Alert::error(_("Conversion script failed"),
873 bformat(_("%1$s is from a different version"
874 " of LyX, but the lyx2lyx script"
875 " failed to convert it."),
876 from_utf8(filename.absFilename())));
879 bool const ret = readFile(tmpfile);
880 // Do stuff with tmpfile name and buffer name here.
881 return ret ? success : failure;
886 if (readDocument(lex)) {
887 Alert::error(_("Document format failure"),
888 bformat(_("%1$s ended unexpectedly, which means"
889 " that it is probably corrupted."),
890 from_utf8(filename.absFilename())));
893 d->file_fully_loaded = true;
898 // Should probably be moved to somewhere else: BufferView? LyXView?
899 bool Buffer::save() const
901 // We don't need autosaves in the immediate future. (Asger)
902 resetAutosaveTimers();
904 string const encodedFilename = d->filename.toFilesystemEncoding();
907 bool madeBackup = false;
909 // make a backup if the file already exists
910 if (lyxrc.make_backup && fileName().exists()) {
911 backupName = FileName(absFileName() + '~');
912 if (!lyxrc.backupdir_path.empty()) {
913 string const mangledName =
914 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
915 backupName = FileName(addName(lyxrc.backupdir_path,
918 if (fileName().copyTo(backupName)) {
921 Alert::error(_("Backup failure"),
922 bformat(_("Cannot create backup file %1$s.\n"
923 "Please check whether the directory exists and is writeable."),
924 from_utf8(backupName.absFilename())));
925 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
929 // ask if the disk file has been externally modified (use checksum method)
930 if (fileName().exists() && isExternallyModified(checksum_method)) {
931 docstring const file = makeDisplayPath(absFileName(), 20);
932 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
933 "you want to overwrite this file?"), file);
934 int const ret = Alert::prompt(_("Overwrite modified file?"),
935 text, 1, 1, _("&Overwrite"), _("&Cancel"));
940 if (writeFile(d->filename)) {
944 // Saving failed, so backup is not backup
946 backupName.moveTo(d->filename);
952 bool Buffer::writeFile(FileName const & fname) const
954 if (d->read_only && fname == d->filename)
959 docstring const str = bformat(_("Saving document %1$s..."),
960 makeDisplayPath(fname.absFilename()));
963 if (params().compressed) {
964 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
965 retval = ofs && write(ofs);
967 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
968 retval = ofs && write(ofs);
972 message(str + _(" could not write file!"));
976 removeAutosaveFile();
978 saveCheckSum(d->filename);
979 message(str + _(" done."));
985 docstring Buffer::emergencyWrite()
987 // No need to save if the buffer has not changed.
991 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
993 docstring user_message = bformat(
994 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
996 // We try to save three places:
997 // 1) Same place as document. Unless it is an unnamed doc.
999 string s = absFileName();
1002 if (writeFile(FileName(s))) {
1004 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1005 return user_message;
1007 user_message += _(" Save failed! Trying again...\n");
1011 // 2) In HOME directory.
1012 string s = addName(package().home_dir().absFilename(), absFileName());
1014 lyxerr << ' ' << s << endl;
1015 if (writeFile(FileName(s))) {
1017 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1018 return user_message;
1021 user_message += _(" Save failed! Trying yet again...\n");
1023 // 3) In "/tmp" directory.
1024 // MakeAbsPath to prepend the current
1025 // drive letter on OS/2
1026 s = addName(package().temp_dir().absFilename(), absFileName());
1028 lyxerr << ' ' << s << endl;
1029 if (writeFile(FileName(s))) {
1031 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1032 return user_message;
1035 user_message += _(" Save failed! Bummer. Document is lost.");
1038 return user_message;
1042 bool Buffer::write(ostream & ofs) const
1045 // Use the standard "C" locale for file output.
1046 ofs.imbue(locale::classic());
1049 // The top of the file should not be written by params().
1051 // write out a comment in the top of the file
1052 ofs << "#LyX " << lyx_version
1053 << " created this file. For more info see http://www.lyx.org/\n"
1054 << "\\lyxformat " << LYX_FORMAT << "\n"
1055 << "\\begin_document\n";
1057 /// For each author, set 'used' to true if there is a change
1058 /// by this author in the document; otherwise set it to 'false'.
1059 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1060 AuthorList::Authors::const_iterator a_end = params().authors().end();
1061 for (; a_it != a_end; ++a_it)
1062 a_it->setUsed(false);
1064 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1065 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1066 for ( ; it != end; ++it)
1067 it->checkAuthors(params().authors());
1069 // now write out the buffer parameters.
1070 ofs << "\\begin_header\n";
1071 params().writeFile(ofs);
1072 ofs << "\\end_header\n";
1075 ofs << "\n\\begin_body\n";
1077 ofs << "\n\\end_body\n";
1079 // Write marker that shows file is complete
1080 ofs << "\\end_document" << endl;
1082 // Shouldn't really be needed....
1085 // how to check if close went ok?
1086 // Following is an attempt... (BE 20001011)
1088 // good() returns false if any error occured, including some
1089 // formatting error.
1090 // bad() returns true if something bad happened in the buffer,
1091 // which should include file system full errors.
1096 lyxerr << "File was not closed properly." << endl;
1103 bool Buffer::makeLaTeXFile(FileName const & fname,
1104 string const & original_path,
1105 OutputParams const & runparams_in,
1106 bool output_preamble, bool output_body) const
1108 OutputParams runparams = runparams_in;
1109 if (params().useXetex)
1110 runparams.flavor = OutputParams::XETEX;
1112 string const encoding = runparams.encoding->iconvName();
1113 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1116 try { ofs.reset(encoding); }
1117 catch (iconv_codecvt_facet_exception & e) {
1118 lyxerr << "Caught iconv exception: " << e.what() << endl;
1119 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1120 "verify that the support software for your encoding (%1$s) is "
1121 "properly installed"), from_ascii(encoding)));
1124 if (!openFileWrite(ofs, fname))
1127 //TexStream ts(ofs.rdbuf(), &texrow());
1128 ErrorList & errorList = d->errorLists["Export"];
1130 bool failed_export = false;
1133 writeLaTeXSource(ofs, original_path,
1134 runparams, output_preamble, output_body);
1136 catch (EncodingException & e) {
1137 odocstringstream ods;
1138 ods.put(e.failed_char);
1140 oss << "0x" << hex << e.failed_char << dec;
1141 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1142 " (code point %2$s)"),
1143 ods.str(), from_utf8(oss.str()));
1144 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1145 "representable in the chosen encoding.\n"
1146 "Changing the document encoding to utf8 could help."),
1147 e.par_id, e.pos, e.pos + 1));
1148 failed_export = true;
1150 catch (iconv_codecvt_facet_exception & e) {
1151 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1152 _(e.what()), -1, 0, 0));
1153 failed_export = true;
1155 catch (exception const & e) {
1156 errorList.push_back(ErrorItem(_("conversion failed"),
1157 _(e.what()), -1, 0, 0));
1158 failed_export = true;
1161 lyxerr << "Caught some really weird exception..." << endl;
1167 failed_export = true;
1168 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1172 return !failed_export;
1176 void Buffer::writeLaTeXSource(odocstream & os,
1177 string const & original_path,
1178 OutputParams const & runparams_in,
1179 bool const output_preamble, bool const output_body) const
1181 // The child documents, if any, shall be already loaded at this point.
1183 OutputParams runparams = runparams_in;
1185 // Classify the unicode characters appearing in math insets
1186 Encodings::initUnicodeMath(*this);
1188 // validate the buffer.
1189 LYXERR(Debug::LATEX, " Validating buffer...");
1190 LaTeXFeatures features(*this, params(), runparams);
1192 LYXERR(Debug::LATEX, " Buffer validation done.");
1194 // The starting paragraph of the coming rows is the
1195 // first paragraph of the document. (Asger)
1196 if (output_preamble && runparams.nice) {
1197 os << "%% LyX " << lyx_version << " created this file. "
1198 "For more info, see http://www.lyx.org/.\n"
1199 "%% Do not edit unless you really know what "
1201 d->texrow.newline();
1202 d->texrow.newline();
1204 LYXERR(Debug::INFO, "lyx document header finished");
1206 // Don't move this behind the parent_buffer=0 code below,
1207 // because then the macros will not get the right "redefinition"
1208 // flag as they don't see the parent macros which are output before.
1211 // fold macros if possible, still with parent buffer as the
1212 // macros will be put in the prefix anyway.
1213 updateMacroInstances();
1215 // There are a few differences between nice LaTeX and usual files:
1216 // usual is \batchmode and has a
1217 // special input@path to allow the including of figures
1218 // with either \input or \includegraphics (what figinsets do).
1219 // input@path is set when the actual parameter
1220 // original_path is set. This is done for usual tex-file, but not
1221 // for nice-latex-file. (Matthias 250696)
1222 // Note that input@path is only needed for something the user does
1223 // in the preamble, included .tex files or ERT, files included by
1224 // LyX work without it.
1225 if (output_preamble) {
1226 if (!runparams.nice) {
1227 // code for usual, NOT nice-latex-file
1228 os << "\\batchmode\n"; // changed
1229 // from \nonstopmode
1230 d->texrow.newline();
1232 if (!original_path.empty()) {
1234 // We don't know the encoding of inputpath
1235 docstring const inputpath = from_utf8(latex_path(original_path));
1236 os << "\\makeatletter\n"
1237 << "\\def\\input@path{{"
1238 << inputpath << "/}}\n"
1239 << "\\makeatother\n";
1240 d->texrow.newline();
1241 d->texrow.newline();
1242 d->texrow.newline();
1245 // get parent macros (if this buffer has a parent) which will be
1246 // written at the document begin further down.
1247 MacroSet parentMacros;
1248 listParentMacros(parentMacros, features);
1250 // Write the preamble
1251 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1253 runparams.use_japanese = features.isRequired("japanese");
1259 os << "\\begin{document}\n";
1260 d->texrow.newline();
1262 // output the parent macros
1263 MacroSet::iterator it = parentMacros.begin();
1264 MacroSet::iterator end = parentMacros.end();
1265 for (; it != end; ++it)
1266 (*it)->write(os, true);
1267 } // output_preamble
1269 d->texrow.start(paragraphs().begin()->id(), 0);
1271 LYXERR(Debug::INFO, "preamble finished, now the body.");
1273 // if we are doing a real file with body, even if this is the
1274 // child of some other buffer, let's cut the link here.
1275 // This happens for example if only a child document is printed.
1276 Buffer const * save_parent = 0;
1277 if (output_preamble) {
1278 save_parent = d->parent();
1283 latexParagraphs(*this, text(), os, d->texrow, runparams);
1285 // Restore the parenthood if needed
1286 if (output_preamble)
1287 d->setParent(save_parent);
1289 // add this just in case after all the paragraphs
1291 d->texrow.newline();
1293 if (output_preamble) {
1294 os << "\\end{document}\n";
1295 d->texrow.newline();
1296 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1298 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1300 runparams_in.encoding = runparams.encoding;
1302 // Just to be sure. (Asger)
1303 d->texrow.newline();
1305 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1306 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1310 bool Buffer::isLatex() const
1312 return params().documentClass().outputType() == LATEX;
1316 bool Buffer::isLiterate() const
1318 return params().documentClass().outputType() == LITERATE;
1322 bool Buffer::isDocBook() const
1324 return params().documentClass().outputType() == DOCBOOK;
1328 void Buffer::makeDocBookFile(FileName const & fname,
1329 OutputParams const & runparams,
1330 bool const body_only) const
1332 LYXERR(Debug::LATEX, "makeDocBookFile...");
1335 if (!openFileWrite(ofs, fname))
1338 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1342 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1346 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1347 OutputParams const & runparams,
1348 bool const only_body) const
1350 LaTeXFeatures features(*this, params(), runparams);
1355 DocumentClass const & tclass = params().documentClass();
1356 string const top_element = tclass.latexname();
1359 if (runparams.flavor == OutputParams::XML)
1360 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1363 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1366 if (! tclass.class_header().empty())
1367 os << from_ascii(tclass.class_header());
1368 else if (runparams.flavor == OutputParams::XML)
1369 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1370 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1372 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1374 docstring preamble = from_utf8(params().preamble);
1375 if (runparams.flavor != OutputParams::XML ) {
1376 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1377 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1378 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1379 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1382 string const name = runparams.nice
1383 ? changeExtension(absFileName(), ".sgml") : fname;
1384 preamble += features.getIncludedFiles(name);
1385 preamble += features.getLyXSGMLEntities();
1387 if (!preamble.empty()) {
1388 os << "\n [ " << preamble << " ]";
1393 string top = top_element;
1395 if (runparams.flavor == OutputParams::XML)
1396 top += params().language->code();
1398 top += params().language->code().substr(0, 2);
1401 if (!params().options.empty()) {
1403 top += params().options;
1406 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1407 << " file was created by LyX " << lyx_version
1408 << "\n See http://www.lyx.org/ for more information -->\n";
1410 params().documentClass().counters().reset();
1414 sgml::openTag(os, top);
1416 docbookParagraphs(text(), *this, os, runparams);
1417 sgml::closeTag(os, top_element);
1421 void Buffer::makeLyXHTMLFile(FileName const & fname,
1422 OutputParams const & runparams,
1423 bool const body_only) const
1425 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1428 if (!openFileWrite(ofs, fname))
1431 writeLyXHTMLSource(ofs, runparams, body_only);
1435 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1439 void Buffer::writeLyXHTMLSource(odocstream & os,
1440 OutputParams const & runparams,
1441 bool const only_body) const
1443 LaTeXFeatures features(*this, params(), runparams);
1445 updateLabels(UpdateMaster, true);
1450 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1451 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";
1452 // FIXME Language should be set properly.
1453 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1456 // FIXME Presumably need to set this right
1457 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1458 // FIXME Get this during validation? What about other meta-data?
1459 os << "<title>TBA</title>\n";
1461 os << "\n<!-- Text Class Preamble -->\n"
1462 << features.getTClassHTMLPreamble()
1463 << "\n<!-- Premable Snippets -->\n"
1464 << from_utf8(features.getPreambleSnippets());
1466 os << "\n<!-- Layout-provided Styles -->\n";
1467 docstring const styleinfo = features.getTClassHTMLStyles();
1468 if (!styleinfo.empty()) {
1469 os << "<style type='text/css'>\n"
1473 os << "</head>\n<body>\n";
1477 params().documentClass().counters().reset();
1478 xhtmlParagraphs(text(), *this, xs, runparams);
1480 os << "</body>\n</html>\n";
1484 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1485 // Other flags: -wall -v0 -x
1486 int Buffer::runChktex()
1490 // get LaTeX-Filename
1491 FileName const path(temppath());
1492 string const name = addName(path.absFilename(), latexName());
1493 string const org_path = filePath();
1495 PathChanger p(path); // path to LaTeX file
1496 message(_("Running chktex..."));
1498 // Generate the LaTeX file if neccessary
1499 OutputParams runparams(¶ms().encoding());
1500 runparams.flavor = OutputParams::LATEX;
1501 runparams.nice = false;
1502 makeLaTeXFile(FileName(name), org_path, runparams);
1505 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1506 int const res = chktex.run(terr); // run chktex
1509 Alert::error(_("chktex failure"),
1510 _("Could not run chktex successfully."));
1511 } else if (res > 0) {
1512 ErrorList & errlist = d->errorLists["ChkTeX"];
1514 bufferErrors(terr, errlist);
1525 void Buffer::validate(LaTeXFeatures & features) const
1527 params().validate(features);
1531 for_each(paragraphs().begin(), paragraphs().end(),
1532 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1534 if (lyxerr.debugging(Debug::LATEX)) {
1535 features.showStruct();
1540 void Buffer::getLabelList(vector<docstring> & list) const
1542 // If this is a child document, use the parent's list instead.
1543 Buffer const * const pbuf = d->parent();
1545 pbuf->getLabelList(list);
1550 Toc & toc = d->toc_backend.toc("label");
1551 TocIterator toc_it = toc.begin();
1552 TocIterator end = toc.end();
1553 for (; toc_it != end; ++toc_it) {
1554 if (toc_it->depth() == 0)
1555 list.push_back(toc_it->str());
1560 void Buffer::updateBibfilesCache(UpdateScope scope) const
1562 // If this is a child document, use the parent's cache instead.
1563 Buffer const * const pbuf = d->parent();
1564 if (pbuf && scope != UpdateChildOnly) {
1565 pbuf->updateBibfilesCache();
1569 d->bibfilesCache_.clear();
1570 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1571 if (it->lyxCode() == BIBTEX_CODE) {
1572 InsetBibtex const & inset =
1573 static_cast<InsetBibtex const &>(*it);
1574 support::FileNameList const bibfiles = inset.getBibFiles();
1575 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1578 } else if (it->lyxCode() == INCLUDE_CODE) {
1579 InsetInclude & inset =
1580 static_cast<InsetInclude &>(*it);
1581 inset.updateBibfilesCache();
1582 support::FileNameList const & bibfiles =
1583 inset.getBibfilesCache();
1584 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1589 // the bibinfo cache is now invalid
1590 d->bibinfoCacheValid_ = false;
1594 void Buffer::invalidateBibinfoCache()
1596 d->bibinfoCacheValid_ = false;
1600 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1602 // If this is a child document, use the parent's cache instead.
1603 Buffer const * const pbuf = d->parent();
1604 if (pbuf && scope != UpdateChildOnly)
1605 return pbuf->getBibfilesCache();
1607 // We update the cache when first used instead of at loading time.
1608 if (d->bibfilesCache_.empty())
1609 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1611 return d->bibfilesCache_;
1615 BiblioInfo const & Buffer::masterBibInfo() const
1617 // if this is a child document and the parent is already loaded
1618 // use the parent's list instead [ale990412]
1619 Buffer const * const tmp = masterBuffer();
1622 return tmp->masterBibInfo();
1623 return localBibInfo();
1627 BiblioInfo const & Buffer::localBibInfo() const
1629 if (d->bibinfoCacheValid_) {
1630 support::FileNameList const & bibfilesCache = getBibfilesCache();
1631 // compare the cached timestamps with the actual ones.
1632 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1633 support::FileNameList::const_iterator en = bibfilesCache.end();
1634 for (; ei != en; ++ ei) {
1635 time_t lastw = ei->lastModified();
1636 if (lastw != d->bibfileStatus_[*ei]) {
1637 d->bibinfoCacheValid_ = false;
1638 d->bibfileStatus_[*ei] = lastw;
1644 if (!d->bibinfoCacheValid_) {
1645 d->bibinfo_.clear();
1646 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1647 it->fillWithBibKeys(d->bibinfo_, it);
1648 d->bibinfoCacheValid_ = true;
1654 bool Buffer::isDepClean(string const & name) const
1656 DepClean::const_iterator const it = d->dep_clean.find(name);
1657 if (it == d->dep_clean.end())
1663 void Buffer::markDepClean(string const & name)
1665 d->dep_clean[name] = true;
1669 bool Buffer::isExportableFormat(string const & format) const
1671 typedef vector<Format const *> Formats;
1673 formats = exportableFormats(true);
1674 Formats::const_iterator fit = formats.begin();
1675 Formats::const_iterator end = formats.end();
1676 for (; fit != end ; ++fit) {
1677 if ((*fit)->name() == format)
1684 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1687 // FIXME? if there is an Buffer LFUN that can be dispatched even
1688 // if internal, put a switch '(cmd.action)' here.
1694 switch (cmd.action) {
1696 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1697 flag.setOnOff(isReadonly());
1700 // FIXME: There is need for a command-line import.
1701 //case LFUN_BUFFER_IMPORT:
1703 case LFUN_BUFFER_AUTO_SAVE:
1706 case LFUN_BUFFER_EXPORT_CUSTOM:
1707 // FIXME: Nothing to check here?
1710 case LFUN_BUFFER_EXPORT: {
1711 docstring const arg = cmd.argument();
1712 enable = arg == "custom" || isExportable(to_utf8(arg));
1714 flag.message(bformat(
1715 _("Don't know how to export to format: %1$s"), arg));
1719 case LFUN_BUFFER_CHKTEX:
1720 enable = isLatex() && !lyxrc.chktex_command.empty();
1723 case LFUN_BUILD_PROGRAM:
1724 enable = isExportable("program");
1727 case LFUN_BRANCH_ACTIVATE:
1728 case LFUN_BRANCH_DEACTIVATE: {
1729 BranchList const & branchList = params().branchlist();
1730 docstring const branchName = cmd.argument();
1731 enable = !branchName.empty() && branchList.find(branchName);
1735 case LFUN_BRANCH_ADD:
1736 case LFUN_BRANCHES_RENAME:
1737 case LFUN_BUFFER_PRINT:
1738 // if no Buffer is present, then of course we won't be called!
1741 case LFUN_BUFFER_LANGUAGE:
1742 enable = !isReadonly();
1748 flag.setEnabled(enable);
1753 void Buffer::dispatch(string const & command, DispatchResult & result)
1755 return dispatch(lyxaction.lookupFunc(command), result);
1759 // NOTE We can end up here even if we have no GUI, because we are called
1760 // by LyX::exec to handled command-line requests. So we may need to check
1761 // whether we have a GUI or not. The boolean use_gui holds this information.
1762 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1765 // FIXME? if there is an Buffer LFUN that can be dispatched even
1766 // if internal, put a switch '(cmd.action)' here.
1767 dr.dispatched(false);
1770 string const argument = to_utf8(func.argument());
1771 // We'll set this back to false if need be.
1772 bool dispatched = true;
1773 undo().beginUndoGroup();
1775 switch (func.action) {
1776 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1777 if (lyxvc().inUse())
1778 lyxvc().toggleReadOnly();
1780 setReadonly(!isReadonly());
1783 case LFUN_BUFFER_EXPORT: {
1784 bool success = doExport(argument, false);
1785 dr.setError(success);
1787 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1792 case LFUN_BUILD_PROGRAM:
1793 doExport("program", true);
1796 case LFUN_BUFFER_CHKTEX:
1800 case LFUN_BUFFER_EXPORT_CUSTOM: {
1802 string command = split(argument, format_name, ' ');
1803 Format const * format = formats.getFormat(format_name);
1805 lyxerr << "Format \"" << format_name
1806 << "\" not recognized!"
1811 // The name of the file created by the conversion process
1814 // Output to filename
1815 if (format->name() == "lyx") {
1816 string const latexname = latexName(false);
1817 filename = changeExtension(latexname,
1818 format->extension());
1819 filename = addName(temppath(), filename);
1821 if (!writeFile(FileName(filename)))
1825 doExport(format_name, true, filename);
1828 // Substitute $$FName for filename
1829 if (!contains(command, "$$FName"))
1830 command = "( " + command + " ) < $$FName";
1831 command = subst(command, "$$FName", filename);
1833 // Execute the command in the background
1835 call.startscript(Systemcall::DontWait, command);
1839 // FIXME: There is need for a command-line import.
1841 case LFUN_BUFFER_IMPORT:
1846 case LFUN_BUFFER_AUTO_SAVE:
1850 case LFUN_BRANCH_ADD: {
1851 docstring const branch_name = func.argument();
1852 if (branch_name.empty()) {
1856 BranchList & branch_list = params().branchlist();
1857 Branch * branch = branch_list.find(branch_name);
1859 LYXERR0("Branch " << branch_name << " already exists.");
1861 docstring const msg =
1862 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1865 branch_list.add(branch_name);
1866 branch = branch_list.find(branch_name);
1867 string const x11hexname = X11hexname(branch->color());
1868 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1869 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1871 dr.update(Update::Force);
1876 case LFUN_BRANCH_ACTIVATE:
1877 case LFUN_BRANCH_DEACTIVATE: {
1878 BranchList & branchList = params().branchlist();
1879 docstring const branchName = func.argument();
1880 // the case without a branch name is handled elsewhere
1881 if (branchName.empty()) {
1885 Branch * branch = branchList.find(branchName);
1887 LYXERR0("Branch " << branchName << " does not exist.");
1889 docstring const msg =
1890 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1893 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1895 dr.update(Update::Force);
1900 case LFUN_BRANCHES_RENAME: {
1901 if (func.argument().empty())
1904 docstring const oldname = from_utf8(func.getArg(0));
1905 docstring const newname = from_utf8(func.getArg(1));
1906 InsetIterator it = inset_iterator_begin(inset());
1907 InsetIterator const end = inset_iterator_end(inset());
1908 bool success = false;
1909 for (; it != end; ++it) {
1910 if (it->lyxCode() == BRANCH_CODE) {
1911 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1912 if (ins.branch() == oldname) {
1913 undo().recordUndo(it);
1914 ins.rename(newname);
1919 if (it->lyxCode() == INCLUDE_CODE) {
1920 // get buffer of external file
1921 InsetInclude const & ins =
1922 static_cast<InsetInclude const &>(*it);
1923 Buffer * child = ins.getChildBuffer();
1926 child->dispatch(func, dr);
1931 dr.update(Update::Force);
1935 case LFUN_BUFFER_PRINT: {
1936 // we'll assume there's a problem until we succeed
1938 string target = func.getArg(0);
1939 string target_name = func.getArg(1);
1940 string command = func.getArg(2);
1943 || target_name.empty()
1944 || command.empty()) {
1945 LYXERR0("Unable to parse " << func.argument());
1946 docstring const msg =
1947 bformat(_("Unable to parse \"%1$s\""), func.argument());
1951 if (target != "printer" && target != "file") {
1952 LYXERR0("Unrecognized target \"" << target << '"');
1953 docstring const msg =
1954 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1959 if (!doExport("dvi", true)) {
1960 showPrintError(absFileName());
1961 dr.setMessage(_("Error exporting to DVI."));
1965 // Push directory path.
1966 string const path = temppath();
1967 // Prevent the compiler from optimizing away p
1971 // there are three cases here:
1972 // 1. we print to a file
1973 // 2. we print directly to a printer
1974 // 3. we print using a spool command (print to file first)
1977 string const dviname = changeExtension(latexName(true), "dvi");
1979 if (target == "printer") {
1980 if (!lyxrc.print_spool_command.empty()) {
1981 // case 3: print using a spool
1982 string const psname = changeExtension(dviname,".ps");
1983 command += ' ' + lyxrc.print_to_file
1986 + quoteName(dviname);
1988 string command2 = lyxrc.print_spool_command + ' ';
1989 if (target_name != "default") {
1990 command2 += lyxrc.print_spool_printerprefix
1994 command2 += quoteName(psname);
1996 // If successful, then spool command
1997 res = one.startscript(Systemcall::Wait, command);
2000 // If there's no GUI, we have to wait on this command. Otherwise,
2001 // LyX deletes the temporary directory, and with it the spooled
2002 // file, before it can be printed!!
2003 Systemcall::Starttype stype = use_gui ?
2004 Systemcall::DontWait : Systemcall::Wait;
2005 res = one.startscript(stype, command2);
2008 // case 2: print directly to a printer
2009 if (target_name != "default")
2010 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2012 Systemcall::Starttype stype = use_gui ?
2013 Systemcall::DontWait : Systemcall::Wait;
2014 res = one.startscript(stype, command + quoteName(dviname));
2018 // case 1: print to a file
2019 FileName const filename(makeAbsPath(target_name, filePath()));
2020 FileName const dvifile(makeAbsPath(dviname, path));
2021 if (filename.exists()) {
2022 docstring text = bformat(
2023 _("The file %1$s already exists.\n\n"
2024 "Do you want to overwrite that file?"),
2025 makeDisplayPath(filename.absFilename()));
2026 if (Alert::prompt(_("Overwrite file?"),
2027 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2030 command += ' ' + lyxrc.print_to_file
2031 + quoteName(filename.toFilesystemEncoding())
2033 + quoteName(dvifile.toFilesystemEncoding());
2035 Systemcall::Starttype stype = use_gui ?
2036 Systemcall::DontWait : Systemcall::Wait;
2037 res = one.startscript(stype, command);
2043 dr.setMessage(_("Error running external commands."));
2044 showPrintError(absFileName());
2049 case LFUN_BUFFER_LANGUAGE: {
2050 Language const * oldL = params().language;
2051 Language const * newL = languages.getLanguage(argument);
2052 if (!newL || oldL == newL)
2054 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2055 changeLanguage(oldL, newL);
2063 dr.dispatched(dispatched);
2064 undo().endUndoGroup();
2068 void Buffer::changeLanguage(Language const * from, Language const * to)
2070 LASSERT(from, /**/);
2073 for_each(par_iterator_begin(),
2075 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2079 bool Buffer::isMultiLingual() const
2081 ParConstIterator end = par_iterator_end();
2082 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2083 if (it->isMultiLingual(params()))
2090 DocIterator Buffer::getParFromID(int const id) const
2092 Buffer * buf = const_cast<Buffer *>(this);
2094 // John says this is called with id == -1 from undo
2095 lyxerr << "getParFromID(), id: " << id << endl;
2096 return doc_iterator_end(buf);
2099 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2100 if (it.paragraph().id() == id)
2103 return doc_iterator_end(buf);
2107 bool Buffer::hasParWithID(int const id) const
2109 return !getParFromID(id).atEnd();
2113 ParIterator Buffer::par_iterator_begin()
2115 return ParIterator(doc_iterator_begin(this));
2119 ParIterator Buffer::par_iterator_end()
2121 return ParIterator(doc_iterator_end(this));
2125 ParConstIterator Buffer::par_iterator_begin() const
2127 return ParConstIterator(doc_iterator_begin(this));
2131 ParConstIterator Buffer::par_iterator_end() const
2133 return ParConstIterator(doc_iterator_end(this));
2137 Language const * Buffer::language() const
2139 return params().language;
2143 docstring const Buffer::B_(string const & l10n) const
2145 return params().B_(l10n);
2149 bool Buffer::isClean() const
2151 return d->lyx_clean;
2155 bool Buffer::isBakClean() const
2157 return d->bak_clean;
2161 bool Buffer::isExternallyModified(CheckMethod method) const
2163 LASSERT(d->filename.exists(), /**/);
2164 // if method == timestamp, check timestamp before checksum
2165 return (method == checksum_method
2166 || d->timestamp_ != d->filename.lastModified())
2167 && d->checksum_ != d->filename.checksum();
2171 void Buffer::saveCheckSum(FileName const & file) const
2173 if (file.exists()) {
2174 d->timestamp_ = file.lastModified();
2175 d->checksum_ = file.checksum();
2177 // in the case of save to a new file.
2184 void Buffer::markClean() const
2186 if (!d->lyx_clean) {
2187 d->lyx_clean = true;
2190 // if the .lyx file has been saved, we don't need an
2192 d->bak_clean = true;
2196 void Buffer::markBakClean() const
2198 d->bak_clean = true;
2202 void Buffer::setUnnamed(bool flag)
2208 bool Buffer::isUnnamed() const
2215 /// Don't check unnamed, here: isInternal() is used in
2216 /// newBuffer(), where the unnamed flag has not been set by anyone
2217 /// yet. Also, for an internal buffer, there should be no need for
2218 /// retrieving fileName() nor for checking if it is unnamed or not.
2219 bool Buffer::isInternal() const
2221 return fileName().extension() == "internal";
2225 void Buffer::markDirty()
2228 d->lyx_clean = false;
2231 d->bak_clean = false;
2233 DepClean::iterator it = d->dep_clean.begin();
2234 DepClean::const_iterator const end = d->dep_clean.end();
2236 for (; it != end; ++it)
2241 FileName Buffer::fileName() const
2247 string Buffer::absFileName() const
2249 return d->filename.absFilename();
2253 string Buffer::filePath() const
2255 return d->filename.onlyPath().absFilename() + "/";
2259 bool Buffer::isReadonly() const
2261 return d->read_only;
2265 void Buffer::setParent(Buffer const * buffer)
2267 // Avoids recursive include.
2268 d->setParent(buffer == this ? 0 : buffer);
2273 Buffer const * Buffer::parent() const
2279 void Buffer::collectRelatives(BufferSet & bufs) const
2283 parent()->collectRelatives(bufs);
2285 // loop over children
2286 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2287 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2288 for (; it != end; ++it)
2289 bufs.insert(const_cast<Buffer *>(it->first));
2293 std::vector<Buffer const *> Buffer::allRelatives() const
2296 collectRelatives(bufs);
2297 BufferSet::iterator it = bufs.begin();
2298 std::vector<Buffer const *> ret;
2299 for (; it != bufs.end(); ++it)
2305 Buffer const * Buffer::masterBuffer() const
2307 Buffer const * const pbuf = d->parent();
2311 return pbuf->masterBuffer();
2315 bool Buffer::isChild(Buffer * child) const
2317 return d->children_positions.find(child) != d->children_positions.end();
2321 DocIterator Buffer::firstChildPosition(Buffer const * child)
2323 Impl::BufferPositionMap::iterator it;
2324 it = d->children_positions.find(child);
2325 if (it == d->children_positions.end())
2326 return DocIterator(this);
2331 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2333 std::vector<Buffer *> clist;
2334 // loop over children
2335 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2336 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2337 for (; it != end; ++it) {
2338 Buffer * child = const_cast<Buffer *>(it->first);
2339 clist.push_back(child);
2340 if (grand_children) {
2341 // there might be grandchildren
2342 std::vector<Buffer *> glist = child->getChildren();
2343 for (vector<Buffer *>::const_iterator git = glist.begin();
2344 git != glist.end(); ++git)
2345 clist.push_back(*git);
2352 template<typename M>
2353 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2358 typename M::iterator it = m.lower_bound(x);
2359 if (it == m.begin())
2367 MacroData const * Buffer::getBufferMacro(docstring const & name,
2368 DocIterator const & pos) const
2370 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2372 // if paragraphs have no macro context set, pos will be empty
2376 // we haven't found anything yet
2377 DocIterator bestPos = par_iterator_begin();
2378 MacroData const * bestData = 0;
2380 // find macro definitions for name
2381 Impl::NamePositionScopeMacroMap::iterator nameIt
2382 = d->macros.find(name);
2383 if (nameIt != d->macros.end()) {
2384 // find last definition in front of pos or at pos itself
2385 Impl::PositionScopeMacroMap::const_iterator it
2386 = greatest_below(nameIt->second, pos);
2387 if (it != nameIt->second.end()) {
2389 // scope ends behind pos?
2390 if (pos < it->second.first) {
2391 // Looks good, remember this. If there
2392 // is no external macro behind this,
2393 // we found the right one already.
2394 bestPos = it->first;
2395 bestData = &it->second.second;
2399 // try previous macro if there is one
2400 if (it == nameIt->second.begin())
2407 // find macros in included files
2408 Impl::PositionScopeBufferMap::const_iterator it
2409 = greatest_below(d->position_to_children, pos);
2410 if (it == d->position_to_children.end())
2411 // no children before
2415 // do we know something better (i.e. later) already?
2416 if (it->first < bestPos )
2419 // scope ends behind pos?
2420 if (pos < it->second.first) {
2421 // look for macro in external file
2422 d->macro_lock = true;
2423 MacroData const * data
2424 = it->second.second->getMacro(name, false);
2425 d->macro_lock = false;
2427 bestPos = it->first;
2433 // try previous file if there is one
2434 if (it == d->position_to_children.begin())
2439 // return the best macro we have found
2444 MacroData const * Buffer::getMacro(docstring const & name,
2445 DocIterator const & pos, bool global) const
2450 // query buffer macros
2451 MacroData const * data = getBufferMacro(name, pos);
2455 // If there is a master buffer, query that
2456 Buffer const * const pbuf = d->parent();
2458 d->macro_lock = true;
2459 MacroData const * macro = pbuf->getMacro(
2460 name, *this, false);
2461 d->macro_lock = false;
2467 data = MacroTable::globalMacros().get(name);
2476 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2478 // set scope end behind the last paragraph
2479 DocIterator scope = par_iterator_begin();
2480 scope.pit() = scope.lastpit() + 1;
2482 return getMacro(name, scope, global);
2486 MacroData const * Buffer::getMacro(docstring const & name,
2487 Buffer const & child, bool global) const
2489 // look where the child buffer is included first
2490 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2491 if (it == d->children_positions.end())
2494 // check for macros at the inclusion position
2495 return getMacro(name, it->second, global);
2499 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2501 pit_type lastpit = it.lastpit();
2503 // look for macros in each paragraph
2504 while (it.pit() <= lastpit) {
2505 Paragraph & par = it.paragraph();
2507 // iterate over the insets of the current paragraph
2508 InsetList const & insets = par.insetList();
2509 InsetList::const_iterator iit = insets.begin();
2510 InsetList::const_iterator end = insets.end();
2511 for (; iit != end; ++iit) {
2512 it.pos() = iit->pos;
2514 // is it a nested text inset?
2515 if (iit->inset->asInsetText()) {
2516 // Inset needs its own scope?
2517 InsetText const * itext = iit->inset->asInsetText();
2518 bool newScope = itext->isMacroScope();
2520 // scope which ends just behind the inset
2521 DocIterator insetScope = it;
2524 // collect macros in inset
2525 it.push_back(CursorSlice(*iit->inset));
2526 updateMacros(it, newScope ? insetScope : scope);
2531 // is it an external file?
2532 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2533 // get buffer of external file
2534 InsetInclude const & inset =
2535 static_cast<InsetInclude const &>(*iit->inset);
2536 d->macro_lock = true;
2537 Buffer * child = inset.getChildBuffer();
2538 d->macro_lock = false;
2542 // register its position, but only when it is
2543 // included first in the buffer
2544 if (d->children_positions.find(child) ==
2545 d->children_positions.end())
2546 d->children_positions[child] = it;
2548 // register child with its scope
2549 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2553 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2557 MathMacroTemplate & macroTemplate =
2558 static_cast<MathMacroTemplate &>(*iit->inset);
2559 MacroContext mc(this, it);
2560 macroTemplate.updateToContext(mc);
2563 bool valid = macroTemplate.validMacro();
2564 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2565 // then the BufferView's cursor will be invalid in
2566 // some cases which leads to crashes.
2571 // FIXME (Abdel), I don't understandt why we pass 'it' here
2572 // instead of 'macroTemplate' defined above... is this correct?
2573 d->macros[macroTemplate.name()][it] =
2574 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2584 void Buffer::updateMacros() const
2589 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2591 // start with empty table
2593 d->children_positions.clear();
2594 d->position_to_children.clear();
2596 // Iterate over buffer, starting with first paragraph
2597 // The scope must be bigger than any lookup DocIterator
2598 // later. For the global lookup, lastpit+1 is used, hence
2599 // we use lastpit+2 here.
2600 DocIterator it = par_iterator_begin();
2601 DocIterator outerScope = it;
2602 outerScope.pit() = outerScope.lastpit() + 2;
2603 updateMacros(it, outerScope);
2607 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2609 InsetIterator it = inset_iterator_begin(inset());
2610 InsetIterator const end = inset_iterator_end(inset());
2611 for (; it != end; ++it) {
2612 if (it->lyxCode() == BRANCH_CODE) {
2613 InsetBranch & br = static_cast<InsetBranch &>(*it);
2614 docstring const name = br.branch();
2615 if (!from_master && !params().branchlist().find(name))
2616 result.push_back(name);
2617 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2618 result.push_back(name);
2621 if (it->lyxCode() == INCLUDE_CODE) {
2622 // get buffer of external file
2623 InsetInclude const & ins =
2624 static_cast<InsetInclude const &>(*it);
2625 Buffer * child = ins.getChildBuffer();
2628 child->getUsedBranches(result, true);
2631 // remove duplicates
2636 void Buffer::updateMacroInstances() const
2638 LYXERR(Debug::MACROS, "updateMacroInstances for "
2639 << d->filename.onlyFileName());
2640 DocIterator it = doc_iterator_begin(this);
2642 DocIterator const end = doc_iterator_end(this);
2643 for (; it != end; it.forwardInset()) {
2644 // look for MathData cells in InsetMathNest insets
2645 InsetMath * minset = it.nextInset()->asInsetMath();
2649 // update macro in all cells of the InsetMathNest
2650 DocIterator::idx_type n = minset->nargs();
2651 MacroContext mc = MacroContext(this, it);
2652 for (DocIterator::idx_type i = 0; i < n; ++i) {
2653 MathData & data = minset->cell(i);
2654 data.updateMacros(0, mc);
2660 void Buffer::listMacroNames(MacroNameSet & macros) const
2665 d->macro_lock = true;
2667 // loop over macro names
2668 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2669 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2670 for (; nameIt != nameEnd; ++nameIt)
2671 macros.insert(nameIt->first);
2673 // loop over children
2674 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2675 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2676 for (; it != end; ++it)
2677 it->first->listMacroNames(macros);
2680 Buffer const * const pbuf = d->parent();
2682 pbuf->listMacroNames(macros);
2684 d->macro_lock = false;
2688 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2690 Buffer const * const pbuf = d->parent();
2695 pbuf->listMacroNames(names);
2698 MacroNameSet::iterator it = names.begin();
2699 MacroNameSet::iterator end = names.end();
2700 for (; it != end; ++it) {
2702 MacroData const * data =
2703 pbuf->getMacro(*it, *this, false);
2705 macros.insert(data);
2707 // we cannot access the original MathMacroTemplate anymore
2708 // here to calls validate method. So we do its work here manually.
2709 // FIXME: somehow make the template accessible here.
2710 if (data->optionals() > 0)
2711 features.require("xargs");
2717 Buffer::References & Buffer::references(docstring const & label)
2720 return const_cast<Buffer *>(masterBuffer())->references(label);
2722 RefCache::iterator it = d->ref_cache_.find(label);
2723 if (it != d->ref_cache_.end())
2724 return it->second.second;
2726 static InsetLabel const * dummy_il = 0;
2727 static References const dummy_refs;
2728 it = d->ref_cache_.insert(
2729 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2730 return it->second.second;
2734 Buffer::References const & Buffer::references(docstring const & label) const
2736 return const_cast<Buffer *>(this)->references(label);
2740 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2742 masterBuffer()->d->ref_cache_[label].first = il;
2746 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2748 return masterBuffer()->d->ref_cache_[label].first;
2752 void Buffer::clearReferenceCache() const
2755 d->ref_cache_.clear();
2759 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2762 //FIXME: This does not work for child documents yet.
2763 LASSERT(code == CITE_CODE, /**/);
2764 // Check if the label 'from' appears more than once
2765 vector<docstring> labels;
2767 BiblioInfo const & keys = masterBibInfo();
2768 BiblioInfo::const_iterator bit = keys.begin();
2769 BiblioInfo::const_iterator bend = keys.end();
2771 for (; bit != bend; ++bit)
2773 labels.push_back(bit->first);
2776 if (count(labels.begin(), labels.end(), from) > 1)
2779 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2780 if (it->lyxCode() == code) {
2781 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2782 docstring const oldValue = inset.getParam(paramName);
2783 if (oldValue == from)
2784 inset.setParam(paramName, to);
2790 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2791 pit_type par_end, bool full_source) const
2793 OutputParams runparams(¶ms().encoding());
2794 runparams.nice = true;
2795 runparams.flavor = params().useXetex ?
2796 OutputParams::XETEX : OutputParams::LATEX;
2797 runparams.linelen = lyxrc.plaintext_linelen;
2798 // No side effect of file copying and image conversion
2799 runparams.dryrun = true;
2802 os << "% " << _("Preview source code") << "\n\n";
2804 d->texrow.newline();
2805 d->texrow.newline();
2807 writeDocBookSource(os, absFileName(), runparams, false);
2809 // latex or literate
2810 writeLaTeXSource(os, string(), runparams, true, true);
2812 runparams.par_begin = par_begin;
2813 runparams.par_end = par_end;
2814 if (par_begin + 1 == par_end) {
2816 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2820 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2821 convert<docstring>(par_begin),
2822 convert<docstring>(par_end - 1))
2829 // output paragraphs
2831 docbookParagraphs(text(), *this, os, runparams);
2833 // latex or literate
2834 latexParagraphs(*this, text(), os, texrow, runparams);
2839 ErrorList & Buffer::errorList(string const & type) const
2841 static ErrorList emptyErrorList;
2842 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2843 if (I == d->errorLists.end())
2844 return emptyErrorList;
2850 void Buffer::updateTocItem(std::string const & type,
2851 DocIterator const & dit) const
2854 gui_->updateTocItem(type, dit);
2858 void Buffer::structureChanged() const
2861 gui_->structureChanged();
2865 void Buffer::errors(string const & err, bool from_master) const
2868 gui_->errors(err, from_master);
2872 void Buffer::message(docstring const & msg) const
2879 void Buffer::setBusy(bool on) const
2886 void Buffer::setReadOnly(bool on) const
2889 d->wa_->setReadOnly(on);
2893 void Buffer::updateTitles() const
2896 d->wa_->updateTitles();
2900 void Buffer::resetAutosaveTimers() const
2903 gui_->resetAutosaveTimers();
2907 bool Buffer::hasGuiDelegate() const
2913 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2922 class AutoSaveBuffer : public ForkedProcess {
2925 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2926 : buffer_(buffer), fname_(fname) {}
2928 virtual boost::shared_ptr<ForkedProcess> clone() const
2930 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2935 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2936 from_utf8(fname_.absFilename())));
2937 return run(DontWait);
2941 virtual int generateChild();
2943 Buffer const & buffer_;
2948 int AutoSaveBuffer::generateChild()
2950 #if defined(__APPLE__)
2951 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2952 * We should use something else like threads.
2954 * Since I do not know how to determine at run time what is the OS X
2955 * version, I just disable forking altogether for now (JMarc)
2957 pid_t const pid = -1;
2959 // tmp_ret will be located (usually) in /tmp
2960 // will that be a problem?
2961 // Note that this calls ForkedCalls::fork(), so it's
2962 // ok cross-platform.
2963 pid_t const pid = fork();
2964 // If you want to debug the autosave
2965 // you should set pid to -1, and comment out the fork.
2966 if (pid != 0 && pid != -1)
2970 // pid = -1 signifies that lyx was unable
2971 // to fork. But we will do the save
2973 bool failed = false;
2974 FileName const tmp_ret = FileName::tempName("lyxauto");
2975 if (!tmp_ret.empty()) {
2976 buffer_.writeFile(tmp_ret);
2977 // assume successful write of tmp_ret
2978 if (!tmp_ret.moveTo(fname_))
2984 // failed to write/rename tmp_ret so try writing direct
2985 if (!buffer_.writeFile(fname_)) {
2986 // It is dangerous to do this in the child,
2987 // but safe in the parent, so...
2988 if (pid == -1) // emit message signal.
2989 buffer_.message(_("Autosave failed!"));
2993 if (pid == 0) // we are the child so...
3002 FileName Buffer::getAutosaveFilename() const
3004 // if the document is unnamed try to save in the backup dir, else
3005 // in the default document path, and as a last try in the filePath,
3006 // which will most often be the temporary directory
3009 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3010 : lyxrc.backupdir_path;
3011 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3014 string const fname = "#" + d->filename.onlyFileName() + "#";
3015 return makeAbsPath(fname, fpath);
3019 void Buffer::removeAutosaveFile() const
3021 FileName const f = getAutosaveFilename();
3027 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3029 FileName const newauto = getAutosaveFilename();
3030 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3031 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3035 // Perfect target for a thread...
3036 void Buffer::autoSave() const
3038 if (isBakClean() || isReadonly()) {
3039 // We don't save now, but we'll try again later
3040 resetAutosaveTimers();
3044 // emit message signal.
3045 message(_("Autosaving current document..."));
3046 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3050 resetAutosaveTimers();
3054 string Buffer::bufferFormat() const
3056 string format = params().documentClass().outputFormat();
3057 if (format == "latex") {
3058 if (params().useXetex)
3060 if (params().encoding().package() == Encoding::japanese)
3067 string Buffer::getDefaultOutputFormat() const
3069 if (!params().defaultOutputFormat.empty()
3070 && params().defaultOutputFormat != "default")
3071 return params().defaultOutputFormat;
3072 typedef vector<Format const *> Formats;
3073 Formats formats = exportableFormats(true);
3076 || params().useXetex
3077 || params().encoding().package() == Encoding::japanese) {
3078 if (formats.empty())
3080 // return the first we find
3081 return formats.front()->name();
3083 return lyxrc.default_view_format;
3088 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3089 string & result_file) const
3091 string backend_format;
3092 OutputParams runparams(¶ms().encoding());
3093 runparams.flavor = OutputParams::LATEX;
3094 runparams.linelen = lyxrc.plaintext_linelen;
3095 vector<string> backs = backends();
3096 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3097 // Get shortest path to format
3098 Graph::EdgePath path;
3099 for (vector<string>::const_iterator it = backs.begin();
3100 it != backs.end(); ++it) {
3101 Graph::EdgePath p = theConverters().getPath(*it, format);
3102 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3103 backend_format = *it;
3108 if (!put_in_tempdir) {
3109 // Only show this alert if this is an export to a non-temporary
3110 // file (not for previewing).
3111 Alert::error(_("Couldn't export file"), bformat(
3112 _("No information for exporting the format %1$s."),
3113 formats.prettyName(format)));
3117 runparams.flavor = theConverters().getFlavor(path);
3120 backend_format = format;
3121 // FIXME: Don't hardcode format names here, but use a flag
3122 if (backend_format == "pdflatex")
3123 runparams.flavor = OutputParams::PDFLATEX;
3126 string filename = latexName(false);
3127 filename = addName(temppath(), filename);
3128 filename = changeExtension(filename,
3129 formats.extension(backend_format));
3132 updateMacroInstances();
3134 // Plain text backend
3135 if (backend_format == "text") {
3136 runparams.flavor = OutputParams::TEXT;
3137 writePlaintextFile(*this, FileName(filename), runparams);
3140 else if (backend_format == "xhtml") {
3141 runparams.flavor = OutputParams::HTML;
3142 makeLyXHTMLFile(FileName(filename), runparams);
3143 } else if (backend_format == "lyx")
3144 writeFile(FileName(filename));
3146 else if (isDocBook()) {
3147 runparams.nice = !put_in_tempdir;
3148 makeDocBookFile(FileName(filename), runparams);
3151 else if (backend_format == format) {
3152 runparams.nice = true;
3153 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3155 } else if (!lyxrc.tex_allows_spaces
3156 && contains(filePath(), ' ')) {
3157 Alert::error(_("File name error"),
3158 _("The directory path to the document cannot contain spaces."));
3161 runparams.nice = false;
3162 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3166 string const error_type = (format == "program")
3167 ? "Build" : bufferFormat();
3168 ErrorList & error_list = d->errorLists[error_type];
3169 string const ext = formats.extension(format);
3170 FileName const tmp_result_file(changeExtension(filename, ext));
3171 bool const success = theConverters().convert(this, FileName(filename),
3172 tmp_result_file, FileName(absFileName()), backend_format, format,
3174 // Emit the signal to show the error list.
3175 if (format != backend_format) {
3177 // also to the children, in case of master-buffer-view
3178 std::vector<Buffer *> clist = getChildren();
3179 for (vector<Buffer *>::const_iterator cit = clist.begin();
3180 cit != clist.end(); ++cit)
3181 (*cit)->errors(error_type, true);
3186 if (put_in_tempdir) {
3187 result_file = tmp_result_file.absFilename();
3191 result_file = changeExtension(exportFileName().absFilename(), ext);
3192 // We need to copy referenced files (e. g. included graphics
3193 // if format == "dvi") to the result dir.
3194 vector<ExportedFile> const files =
3195 runparams.exportdata->externalFiles(format);
3196 string const dest = onlyPath(result_file);
3197 CopyStatus status = SUCCESS;
3198 for (vector<ExportedFile>::const_iterator it = files.begin();
3199 it != files.end() && status != CANCEL; ++it) {
3200 string const fmt = formats.getFormatFromFile(it->sourceName);
3201 status = copyFile(fmt, it->sourceName,
3202 makeAbsPath(it->exportName, dest),
3203 it->exportName, status == FORCE);
3205 if (status == CANCEL) {
3206 message(_("Document export cancelled."));
3207 } else if (tmp_result_file.exists()) {
3208 // Finally copy the main file
3209 status = copyFile(format, tmp_result_file,
3210 FileName(result_file), result_file,
3212 message(bformat(_("Document exported as %1$s "
3214 formats.prettyName(format),
3215 makeDisplayPath(result_file)));
3217 // This must be a dummy converter like fax (bug 1888)
3218 message(bformat(_("Document exported as %1$s"),
3219 formats.prettyName(format)));
3226 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3229 return doExport(format, put_in_tempdir, result_file);
3233 bool Buffer::preview(string const & format) const
3236 if (!doExport(format, true, result_file))
3238 return formats.view(*this, FileName(result_file), format);
3242 bool Buffer::isExportable(string const & format) const
3244 vector<string> backs = backends();
3245 for (vector<string>::const_iterator it = backs.begin();
3246 it != backs.end(); ++it)
3247 if (theConverters().isReachable(*it, format))
3253 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3255 vector<string> const backs = backends();
3256 vector<Format const *> result =
3257 theConverters().getReachable(backs[0], only_viewable, true);
3258 for (vector<string>::const_iterator it = backs.begin() + 1;
3259 it != backs.end(); ++it) {
3260 vector<Format const *> r =
3261 theConverters().getReachable(*it, only_viewable, false);
3262 result.insert(result.end(), r.begin(), r.end());
3268 vector<string> Buffer::backends() const
3271 v.push_back(bufferFormat());
3272 // FIXME: Don't hardcode format names here, but use a flag
3273 if (v.back() == "latex")
3274 v.push_back("pdflatex");
3275 v.push_back("xhtml");
3276 v.push_back("text");
3282 bool Buffer::readFileHelper(FileName const & s)
3284 // File information about normal file
3286 docstring const file = makeDisplayPath(s.absFilename(), 50);
3287 docstring text = bformat(_("The specified document\n%1$s"
3288 "\ncould not be read."), file);
3289 Alert::error(_("Could not read document"), text);
3293 // Check if emergency save file exists and is newer.
3294 FileName const e(s.absFilename() + ".emergency");
3296 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3297 docstring const file = makeDisplayPath(s.absFilename(), 20);
3298 docstring const text =
3299 bformat(_("An emergency save of the document "
3301 "Recover emergency save?"), file);
3302 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3303 _("&Recover"), _("&Load Original"),
3307 // the file is not saved if we load the emergency file.
3312 if ((res = readFile(e)) == success)
3313 str = _("Document was successfully recovered.");
3315 str = _("Document was NOT successfully recovered.");
3316 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3317 from_utf8(e.absFilename()));
3319 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3320 _("&Remove"), _("&Keep it"))) {
3323 Alert::warning(_("Emergency file deleted"),
3324 _("Do not forget to save your file now!"), true);
3329 if (!Alert::prompt(_("Delete emergency file?"),
3330 _("Remove emergency file now?"), 1, 1,
3331 _("&Remove"), _("&Keep it")))
3339 // Now check if autosave file is newer.
3340 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3342 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3343 docstring const file = makeDisplayPath(s.absFilename(), 20);
3344 docstring const text =
3345 bformat(_("The backup of the document "
3346 "%1$s is newer.\n\nLoad the "
3347 "backup instead?"), file);
3348 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3349 _("&Load backup"), _("Load &original"),
3353 // the file is not saved if we load the autosave file.
3357 // Here we delete the autosave
3368 bool Buffer::loadLyXFile(FileName const & s)
3370 if (s.isReadableFile()) {
3371 if (readFileHelper(s)) {
3372 lyxvc().file_found_hook(s);
3373 if (!s.isWritable())
3378 docstring const file = makeDisplayPath(s.absFilename(), 20);
3379 // Here we probably should run
3380 if (LyXVC::file_not_found_hook(s)) {
3381 docstring const text =
3382 bformat(_("Do you want to retrieve the document"
3383 " %1$s from version control?"), file);
3384 int const ret = Alert::prompt(_("Retrieve from version control?"),
3385 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3388 // How can we know _how_ to do the checkout?
3389 // With the current VC support it has to be,
3390 // a RCS file since CVS do not have special ,v files.
3392 return loadLyXFile(s);
3400 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3402 TeXErrors::Errors::const_iterator cit = terr.begin();
3403 TeXErrors::Errors::const_iterator end = terr.end();
3405 for (; cit != end; ++cit) {
3408 int errorRow = cit->error_in_line;
3409 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3415 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3416 } while (found && id_start == id_end && pos_start == pos_end);
3418 errorList.push_back(ErrorItem(cit->error_desc,
3419 cit->error_text, id_start, pos_start, pos_end));
3424 void Buffer::setBuffersForInsets() const
3426 inset().setBuffer(const_cast<Buffer &>(*this));
3430 void Buffer::updateLabels(UpdateScope scope, bool out) const
3432 // Use the master text class also for child documents
3433 Buffer const * const master = masterBuffer();
3434 DocumentClass const & textclass = master->params().documentClass();
3436 // keep the buffers to be children in this set. If the call from the
3437 // master comes back we can see which of them were actually seen (i.e.
3438 // via an InsetInclude). The remaining ones in the set need still be updated.
3439 static std::set<Buffer const *> bufToUpdate;
3440 if (scope == UpdateMaster) {
3441 // If this is a child document start with the master
3442 if (master != this) {
3443 bufToUpdate.insert(this);
3444 master->updateLabels(UpdateMaster, out);
3445 // Do this here in case the master has no gui associated with it. Then,
3446 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3450 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3451 if (bufToUpdate.find(this) == bufToUpdate.end())
3455 // start over the counters in the master
3456 textclass.counters().reset();
3459 // update will be done below for this buffer
3460 bufToUpdate.erase(this);
3462 // update all caches
3463 clearReferenceCache();
3466 Buffer & cbuf = const_cast<Buffer &>(*this);
3468 LASSERT(!text().paragraphs().empty(), /**/);
3471 ParIterator parit = cbuf.par_iterator_begin();
3472 updateLabels(parit, out);
3475 // TocBackend update will be done later.
3478 cbuf.tocBackend().update();
3479 if (scope == UpdateMaster)
3480 cbuf.structureChanged();
3484 static depth_type getDepth(DocIterator const & it)
3486 depth_type depth = 0;
3487 for (size_t i = 0 ; i < it.depth() ; ++i)
3488 if (!it[i].inset().inMathed())
3489 depth += it[i].paragraph().getDepth() + 1;
3490 // remove 1 since the outer inset does not count
3494 static depth_type getItemDepth(ParIterator const & it)
3496 Paragraph const & par = *it;
3497 LabelType const labeltype = par.layout().labeltype;
3499 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3502 // this will hold the lowest depth encountered up to now.
3503 depth_type min_depth = getDepth(it);
3504 ParIterator prev_it = it;
3507 --prev_it.top().pit();
3509 // start of nested inset: go to outer par
3511 if (prev_it.empty()) {
3512 // start of document: nothing to do
3517 // We search for the first paragraph with same label
3518 // that is not more deeply nested.
3519 Paragraph & prev_par = *prev_it;
3520 depth_type const prev_depth = getDepth(prev_it);
3521 if (labeltype == prev_par.layout().labeltype) {
3522 if (prev_depth < min_depth)
3523 return prev_par.itemdepth + 1;
3524 if (prev_depth == min_depth)
3525 return prev_par.itemdepth;
3527 min_depth = min(min_depth, prev_depth);
3528 // small optimization: if we are at depth 0, we won't
3529 // find anything else
3530 if (prev_depth == 0)
3536 static bool needEnumCounterReset(ParIterator const & it)
3538 Paragraph const & par = *it;
3539 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3540 depth_type const cur_depth = par.getDepth();
3541 ParIterator prev_it = it;
3542 while (prev_it.pit()) {
3543 --prev_it.top().pit();
3544 Paragraph const & prev_par = *prev_it;
3545 if (prev_par.getDepth() <= cur_depth)
3546 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3548 // start of nested inset: reset
3553 // set the label of a paragraph. This includes the counters.
3554 void Buffer::setLabel(ParIterator & it) const
3556 BufferParams const & bp = this->masterBuffer()->params();
3557 DocumentClass const & textclass = bp.documentClass();
3558 Paragraph & par = it.paragraph();
3559 Layout const & layout = par.layout();
3560 Counters & counters = textclass.counters();
3562 if (par.params().startOfAppendix()) {
3563 // FIXME: only the counter corresponding to toplevel
3564 // sectioning should be reset
3566 counters.appendix(true);
3568 par.params().appendix(counters.appendix());
3570 // Compute the item depth of the paragraph
3571 par.itemdepth = getItemDepth(it);
3573 if (layout.margintype == MARGIN_MANUAL
3574 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3575 if (par.params().labelWidthString().empty())
3576 par.params().labelWidthString(par.expandLabel(layout, bp));
3578 par.params().labelWidthString(docstring());
3581 switch(layout.labeltype) {
3583 if (layout.toclevel <= bp.secnumdepth
3584 && (layout.latextype != LATEX_ENVIRONMENT
3585 || it.text()->isFirstInSequence(it.pit()))) {
3586 counters.step(layout.counter);
3587 par.params().labelString(
3588 par.expandLabel(layout, bp));
3590 par.params().labelString(docstring());
3593 case LABEL_ITEMIZE: {
3594 // At some point of time we should do something more
3595 // clever here, like:
3596 // par.params().labelString(
3597 // bp.user_defined_bullet(par.itemdepth).getText());
3598 // for now, use a simple hardcoded label
3599 docstring itemlabel;
3600 switch (par.itemdepth) {
3602 itemlabel = char_type(0x2022);
3605 itemlabel = char_type(0x2013);
3608 itemlabel = char_type(0x2217);
3611 itemlabel = char_type(0x2219); // or 0x00b7
3614 par.params().labelString(itemlabel);
3618 case LABEL_ENUMERATE: {
3619 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3621 switch (par.itemdepth) {
3630 enumcounter += "iv";
3633 // not a valid enumdepth...
3637 // Maybe we have to reset the enumeration counter.
3638 if (needEnumCounterReset(it))
3639 counters.reset(enumcounter);
3640 counters.step(enumcounter);
3642 string const & lang = par.getParLanguage(bp)->code();
3643 par.params().labelString(counters.theCounter(enumcounter, lang));
3648 case LABEL_SENSITIVE: {
3649 string const & type = counters.current_float();
3650 docstring full_label;
3652 full_label = this->B_("Senseless!!! ");
3654 docstring name = this->B_(textclass.floats().getType(type).name());
3655 if (counters.hasCounter(from_utf8(type))) {
3656 string const & lang = par.getParLanguage(bp)->code();
3657 counters.step(from_utf8(type));
3658 full_label = bformat(from_ascii("%1$s %2$s:"),
3660 counters.theCounter(from_utf8(type), lang));
3662 full_label = bformat(from_ascii("%1$s #:"), name);
3664 par.params().labelString(full_label);
3668 case LABEL_NO_LABEL:
3669 par.params().labelString(docstring());
3673 case LABEL_TOP_ENVIRONMENT:
3674 case LABEL_CENTERED_TOP_ENVIRONMENT:
3677 par.params().labelString(par.expandLabel(layout, bp));
3683 void Buffer::updateLabels(ParIterator & parit, bool out) const
3685 LASSERT(parit.pit() == 0, /**/);
3687 // set the position of the text in the buffer to be able
3688 // to resolve macros in it. This has nothing to do with
3689 // labels, but by putting it here we avoid implementing
3690 // a whole bunch of traversal routines just for this call.
3691 parit.text()->setMacrocontextPosition(parit);
3693 depth_type maxdepth = 0;
3694 pit_type const lastpit = parit.lastpit();
3695 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3696 // reduce depth if necessary
3697 parit->params().depth(min(parit->params().depth(), maxdepth));
3698 maxdepth = parit->getMaxDepthAfter();
3700 // set the counter for this paragraph
3704 InsetList::const_iterator iit = parit->insetList().begin();
3705 InsetList::const_iterator end = parit->insetList().end();
3706 for (; iit != end; ++iit) {
3707 parit.pos() = iit->pos;
3708 iit->inset->updateLabels(parit, out);
3714 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3715 WordLangTuple & word_lang, docstring_list & suggestions) const
3719 suggestions.clear();
3720 word_lang = WordLangTuple();
3721 // OK, we start from here.
3722 DocIterator const end = doc_iterator_end(this);
3723 for (; from != end; from.forwardPos()) {
3724 // We are only interested in text so remove the math CursorSlice.
3725 while (from.inMathed()) {
3729 // If from is at the end of the document (which is possible
3730 // when leaving the mathed) LyX will crash later.
3734 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3739 // Do not increase progress when from == to, otherwise the word
3740 // count will be wrong.