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 = 374; // rgheck: HTML output options
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 /// 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), bibinfoCacheValid_(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;
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 = static_cast<InsetText *>(cloned_buffer->d->inset->clone());
319 d->inset->setBuffer(*this);
321 d->inset = new InsetText(this);
322 d->inset->setAutoBreakRows(true);
323 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
329 LYXERR(Debug::INFO, "Buffer::~Buffer()");
330 // here the buffer should take care that it is
331 // saved properly, before it goes into the void.
333 // GuiView already destroyed
337 // No need to do additional cleanups for internal buffer.
342 // loop over children
343 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
344 Impl::BufferPositionMap::iterator end = d->children_positions.end();
345 for (; it != end; ++it) {
346 Buffer * child = const_cast<Buffer *>(it->first);
347 // The child buffer might have been closed already.
348 if (theBufferList().isLoaded(child))
349 theBufferList().releaseChild(this, child);
353 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
354 msg += emergencyWrite();
355 Alert::warning(_("Attempting to close changed document!"), msg);
358 // clear references to children in macro tables
359 d->children_positions.clear();
360 d->position_to_children.clear();
362 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
363 Alert::warning(_("Could not remove temporary directory"),
364 bformat(_("Could not remove the temporary directory %1$s"),
365 from_utf8(d->temppath.absFilename())));
368 // Remove any previewed LaTeX snippets associated with this buffer.
369 thePreviews().removeLoader(*this);
375 Buffer * Buffer::clone() const
377 return new Buffer(fileName().absFilename(), false, this);
381 bool Buffer::isClone() const
383 return d->cloned_buffer_;
387 void Buffer::changed() const
394 frontend::WorkAreaManager & Buffer::workAreaManager() const
396 LASSERT(d->wa_, /**/);
401 Text & Buffer::text() const
403 return d->inset->text();
407 Inset & Buffer::inset() const
413 BufferParams & Buffer::params()
419 BufferParams const & Buffer::params() const
425 ParagraphList & Buffer::paragraphs()
427 return text().paragraphs();
431 ParagraphList const & Buffer::paragraphs() const
433 return text().paragraphs();
437 LyXVC & Buffer::lyxvc()
443 LyXVC const & Buffer::lyxvc() const
449 string const Buffer::temppath() const
451 return d->temppath.absFilename();
455 TexRow & Buffer::texrow()
461 TexRow const & Buffer::texrow() const
467 TocBackend & Buffer::tocBackend() const
469 return d->toc_backend;
473 Undo & Buffer::undo()
479 string Buffer::latexName(bool const no_path) const
481 FileName latex_name =
482 makeLatexName(exportFileName());
483 return no_path ? latex_name.onlyFileName()
484 : latex_name.absFilename();
488 FileName Buffer::exportFileName() const
490 docstring const branch_suffix =
491 params().branchlist().getFilenameSuffix();
492 if (branch_suffix.empty())
495 string const name = fileName().onlyFileNameWithoutExt()
496 + to_utf8(branch_suffix);
497 FileName res(fileName().onlyPath().absFilename() + "/" + name);
498 res.changeExtension(fileName().extension());
504 string Buffer::logName(LogType * type) const
506 string const filename = latexName(false);
508 if (filename.empty()) {
514 string const path = temppath();
516 FileName const fname(addName(temppath(),
517 onlyFilename(changeExtension(filename,
520 // FIXME: how do we know this is the name of the build log?
521 FileName const bname(
522 addName(path, onlyFilename(
523 changeExtension(filename,
524 formats.extension(bufferFormat()) + ".out"))));
526 // Also consider the master buffer log file
527 FileName masterfname = fname;
529 if (masterBuffer() != this) {
530 string const mlogfile = masterBuffer()->logName(&mtype);
531 masterfname = FileName(mlogfile);
534 // If no Latex log or Build log is newer, show Build log
535 if (bname.exists() &&
536 ((!fname.exists() && !masterfname.exists())
537 || (fname.lastModified() < bname.lastModified()
538 && masterfname.lastModified() < bname.lastModified()))) {
539 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
542 return bname.absFilename();
543 // If we have a newer master file log or only a master log, show this
544 } else if (fname != masterfname
545 && (!fname.exists() && (masterfname.exists()
546 || fname.lastModified() < masterfname.lastModified()))) {
547 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
550 return masterfname.absFilename();
552 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
555 return fname.absFilename();
559 void Buffer::setReadonly(bool const flag)
561 if (d->read_only != flag) {
568 void Buffer::setFileName(string const & newfile)
570 d->filename = makeAbsPath(newfile);
571 setReadonly(d->filename.isReadOnly());
576 int Buffer::readHeader(Lexer & lex)
578 int unknown_tokens = 0;
580 int begin_header_line = -1;
582 // Initialize parameters that may be/go lacking in header:
583 params().branchlist().clear();
584 params().preamble.erase();
585 params().options.erase();
586 params().master.erase();
587 params().float_placement.erase();
588 params().paperwidth.erase();
589 params().paperheight.erase();
590 params().leftmargin.erase();
591 params().rightmargin.erase();
592 params().topmargin.erase();
593 params().bottommargin.erase();
594 params().headheight.erase();
595 params().headsep.erase();
596 params().footskip.erase();
597 params().columnsep.erase();
598 params().fontsCJK.erase();
599 params().listings_params.clear();
600 params().clearLayoutModules();
601 params().clearRemovedModules();
602 params().pdfoptions().clear();
603 params().indiceslist().clear();
604 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
606 for (int i = 0; i < 4; ++i) {
607 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
608 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
611 ErrorList & errorList = d->errorLists["Parse"];
620 if (token == "\\end_header")
624 if (token == "\\begin_header") {
625 begin_header_line = line;
629 LYXERR(Debug::PARSER, "Handling document header token: `"
632 string unknown = params().readToken(lex, token, d->filename.onlyPath());
633 if (!unknown.empty()) {
634 if (unknown[0] != '\\' && token == "\\textclass") {
635 Alert::warning(_("Unknown document class"),
636 bformat(_("Using the default document class, because the "
637 "class %1$s is unknown."), from_utf8(unknown)));
640 docstring const s = bformat(_("Unknown token: "
644 errorList.push_back(ErrorItem(_("Document header error"),
649 if (begin_header_line) {
650 docstring const s = _("\\begin_header is missing");
651 errorList.push_back(ErrorItem(_("Document header error"),
655 params().makeDocumentClass();
657 return unknown_tokens;
662 // changed to be public and have one parameter
663 // Returns true if "\end_document" is not read (Asger)
664 bool Buffer::readDocument(Lexer & lex)
666 ErrorList & errorList = d->errorLists["Parse"];
669 if (!lex.checkFor("\\begin_document")) {
670 docstring const s = _("\\begin_document is missing");
671 errorList.push_back(ErrorItem(_("Document header error"),
675 // we are reading in a brand new document
676 LASSERT(paragraphs().empty(), /**/);
680 if (params().outputChanges) {
681 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
682 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
683 LaTeXFeatures::isAvailable("xcolor");
685 if (!dvipost && !xcolorulem) {
686 Alert::warning(_("Changes not shown in LaTeX output"),
687 _("Changes will not be highlighted in LaTeX output, "
688 "because neither dvipost nor xcolor/ulem are installed.\n"
689 "Please install these packages or redefine "
690 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
691 } else if (!xcolorulem) {
692 Alert::warning(_("Changes not shown in LaTeX output"),
693 _("Changes will not be highlighted in LaTeX output "
694 "when using pdflatex, because xcolor and ulem are not installed.\n"
695 "Please install both packages or redefine "
696 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
700 if (!params().master.empty()) {
701 FileName const master_file = makeAbsPath(params().master,
702 onlyPath(absFileName()));
703 if (isLyXFilename(master_file.absFilename())) {
705 checkAndLoadLyXFile(master_file, true);
707 // necessary e.g. after a reload
708 // to re-register the child (bug 5873)
709 // FIXME: clean up updateMacros (here, only
710 // child registering is needed).
711 master->updateMacros();
712 // set master as master buffer, but only
713 // if we are a real child
714 if (master->isChild(this))
716 // if the master is not fully loaded
717 // it is probably just loading this
718 // child. No warning needed then.
719 else if (master->isFullyLoaded())
720 LYXERR0("The master '"
722 << "' assigned to this document ("
724 << ") does not include "
725 "this document. Ignoring the master assignment.");
730 // assure we have a default index
731 params().indiceslist().addDefault(B_("Index"));
734 bool const res = text().read(lex, errorList, d->inset);
738 updateMacroInstances();
743 bool Buffer::readString(string const & s)
745 params().compressed = false;
747 // remove dummy empty par
748 paragraphs().clear();
752 FileName const name = FileName::tempName("Buffer_readString");
753 switch (readFile(lex, name, true)) {
757 // We need to call lyx2lyx, so write the input to a file
758 ofstream os(name.toFilesystemEncoding().c_str());
761 return readFile(name);
771 bool Buffer::readFile(FileName const & filename)
773 FileName fname(filename);
775 params().compressed = fname.isZippedFile();
777 // remove dummy empty par
778 paragraphs().clear();
781 if (readFile(lex, fname) != success)
788 bool Buffer::isFullyLoaded() const
790 return d->file_fully_loaded;
794 void Buffer::setFullyLoaded(bool value)
796 d->file_fully_loaded = value;
800 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
803 LASSERT(!filename.empty(), /**/);
805 // the first (non-comment) token _must_ be...
806 if (!lex.checkFor("\\lyxformat")) {
807 Alert::error(_("Document format failure"),
808 bformat(_("%1$s is not a readable LyX document."),
809 from_utf8(filename.absFilename())));
815 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
816 // if present remove ".," from string.
817 size_t dot = tmp_format.find_first_of(".,");
818 //lyxerr << " dot found at " << dot << endl;
819 if (dot != string::npos)
820 tmp_format.erase(dot, 1);
821 int const file_format = convert<int>(tmp_format);
822 //lyxerr << "format: " << file_format << endl;
824 // save timestamp and checksum of the original disk file, making sure
825 // to not overwrite them with those of the file created in the tempdir
826 // when it has to be converted to the current format.
828 // Save the timestamp and checksum of disk file. If filename is an
829 // emergency file, save the timestamp and checksum of the original lyx file
830 // because isExternallyModified will check for this file. (BUG4193)
831 string diskfile = filename.absFilename();
832 if (suffixIs(diskfile, ".emergency"))
833 diskfile = diskfile.substr(0, diskfile.size() - 10);
834 saveCheckSum(FileName(diskfile));
837 if (file_format != LYX_FORMAT) {
840 // lyx2lyx would fail
843 FileName const tmpfile = FileName::tempName("Buffer_readFile");
844 if (tmpfile.empty()) {
845 Alert::error(_("Conversion failed"),
846 bformat(_("%1$s is from a different"
847 " version of LyX, but a temporary"
848 " file for converting it could"
850 from_utf8(filename.absFilename())));
853 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
854 if (lyx2lyx.empty()) {
855 Alert::error(_("Conversion script not found"),
856 bformat(_("%1$s is from a different"
857 " version of LyX, but the"
858 " conversion script lyx2lyx"
859 " could not be found."),
860 from_utf8(filename.absFilename())));
863 ostringstream command;
864 command << os::python()
865 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
866 << " -t " << convert<string>(LYX_FORMAT)
867 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
868 << ' ' << quoteName(filename.toFilesystemEncoding());
869 string const command_str = command.str();
871 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
873 cmd_ret const ret = runCommand(command_str);
874 if (ret.first != 0) {
875 Alert::error(_("Conversion script failed"),
876 bformat(_("%1$s is from a different version"
877 " of LyX, but the lyx2lyx script"
878 " failed to convert it."),
879 from_utf8(filename.absFilename())));
882 bool const ret = readFile(tmpfile);
883 // Do stuff with tmpfile name and buffer name here.
884 return ret ? success : failure;
889 if (readDocument(lex)) {
890 Alert::error(_("Document format failure"),
891 bformat(_("%1$s ended unexpectedly, which means"
892 " that it is probably corrupted."),
893 from_utf8(filename.absFilename())));
896 d->file_fully_loaded = true;
901 // Should probably be moved to somewhere else: BufferView? LyXView?
902 bool Buffer::save() const
904 // We don't need autosaves in the immediate future. (Asger)
905 resetAutosaveTimers();
907 string const encodedFilename = d->filename.toFilesystemEncoding();
910 bool madeBackup = false;
912 // make a backup if the file already exists
913 if (lyxrc.make_backup && fileName().exists()) {
914 backupName = FileName(absFileName() + '~');
915 if (!lyxrc.backupdir_path.empty()) {
916 string const mangledName =
917 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
918 backupName = FileName(addName(lyxrc.backupdir_path,
921 if (fileName().copyTo(backupName)) {
924 Alert::error(_("Backup failure"),
925 bformat(_("Cannot create backup file %1$s.\n"
926 "Please check whether the directory exists and is writeable."),
927 from_utf8(backupName.absFilename())));
928 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
932 // ask if the disk file has been externally modified (use checksum method)
933 if (fileName().exists() && isExternallyModified(checksum_method)) {
934 docstring const file = makeDisplayPath(absFileName(), 20);
935 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
936 "you want to overwrite this file?"), file);
937 int const ret = Alert::prompt(_("Overwrite modified file?"),
938 text, 1, 1, _("&Overwrite"), _("&Cancel"));
943 if (writeFile(d->filename)) {
947 // Saving failed, so backup is not backup
949 backupName.moveTo(d->filename);
955 bool Buffer::writeFile(FileName const & fname) const
957 if (d->read_only && fname == d->filename)
962 docstring const str = bformat(_("Saving document %1$s..."),
963 makeDisplayPath(fname.absFilename()));
966 if (params().compressed) {
967 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
968 retval = ofs && write(ofs);
970 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
971 retval = ofs && write(ofs);
975 message(str + _(" could not write file!"));
979 removeAutosaveFile();
981 saveCheckSum(d->filename);
982 message(str + _(" done."));
988 docstring Buffer::emergencyWrite()
990 // No need to save if the buffer has not changed.
994 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
996 docstring user_message = bformat(
997 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
999 // We try to save three places:
1000 // 1) Same place as document. Unless it is an unnamed doc.
1002 string s = absFileName();
1005 if (writeFile(FileName(s))) {
1007 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1008 return user_message;
1010 user_message += _(" Save failed! Trying again...\n");
1014 // 2) In HOME directory.
1015 string s = addName(package().home_dir().absFilename(), absFileName());
1017 lyxerr << ' ' << s << endl;
1018 if (writeFile(FileName(s))) {
1020 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1021 return user_message;
1024 user_message += _(" Save failed! Trying yet again...\n");
1026 // 3) In "/tmp" directory.
1027 // MakeAbsPath to prepend the current
1028 // drive letter on OS/2
1029 s = addName(package().temp_dir().absFilename(), absFileName());
1031 lyxerr << ' ' << s << endl;
1032 if (writeFile(FileName(s))) {
1034 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1035 return user_message;
1038 user_message += _(" Save failed! Bummer. Document is lost.");
1041 return user_message;
1045 bool Buffer::write(ostream & ofs) const
1048 // Use the standard "C" locale for file output.
1049 ofs.imbue(locale::classic());
1052 // The top of the file should not be written by params().
1054 // write out a comment in the top of the file
1055 ofs << "#LyX " << lyx_version
1056 << " created this file. For more info see http://www.lyx.org/\n"
1057 << "\\lyxformat " << LYX_FORMAT << "\n"
1058 << "\\begin_document\n";
1060 /// For each author, set 'used' to true if there is a change
1061 /// by this author in the document; otherwise set it to 'false'.
1062 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1063 AuthorList::Authors::const_iterator a_end = params().authors().end();
1064 for (; a_it != a_end; ++a_it)
1065 a_it->setUsed(false);
1067 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1068 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1069 for ( ; it != end; ++it)
1070 it->checkAuthors(params().authors());
1072 // now write out the buffer parameters.
1073 ofs << "\\begin_header\n";
1074 params().writeFile(ofs);
1075 ofs << "\\end_header\n";
1078 ofs << "\n\\begin_body\n";
1080 ofs << "\n\\end_body\n";
1082 // Write marker that shows file is complete
1083 ofs << "\\end_document" << endl;
1085 // Shouldn't really be needed....
1088 // how to check if close went ok?
1089 // Following is an attempt... (BE 20001011)
1091 // good() returns false if any error occured, including some
1092 // formatting error.
1093 // bad() returns true if something bad happened in the buffer,
1094 // which should include file system full errors.
1099 lyxerr << "File was not closed properly." << endl;
1106 bool Buffer::makeLaTeXFile(FileName const & fname,
1107 string const & original_path,
1108 OutputParams const & runparams_in,
1109 bool output_preamble, bool output_body) const
1111 OutputParams runparams = runparams_in;
1112 if (params().useXetex)
1113 runparams.flavor = OutputParams::XETEX;
1115 string const encoding = runparams.encoding->iconvName();
1116 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1119 try { ofs.reset(encoding); }
1120 catch (iconv_codecvt_facet_exception & e) {
1121 lyxerr << "Caught iconv exception: " << e.what() << endl;
1122 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1123 "verify that the support software for your encoding (%1$s) is "
1124 "properly installed"), from_ascii(encoding)));
1127 if (!openFileWrite(ofs, fname))
1130 //TexStream ts(ofs.rdbuf(), &texrow());
1131 ErrorList & errorList = d->errorLists["Export"];
1133 bool failed_export = false;
1136 writeLaTeXSource(ofs, original_path,
1137 runparams, output_preamble, output_body);
1139 catch (EncodingException & e) {
1140 odocstringstream ods;
1141 ods.put(e.failed_char);
1143 oss << "0x" << hex << e.failed_char << dec;
1144 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1145 " (code point %2$s)"),
1146 ods.str(), from_utf8(oss.str()));
1147 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1148 "representable in the chosen encoding.\n"
1149 "Changing the document encoding to utf8 could help."),
1150 e.par_id, e.pos, e.pos + 1));
1151 failed_export = true;
1153 catch (iconv_codecvt_facet_exception & e) {
1154 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1155 _(e.what()), -1, 0, 0));
1156 failed_export = true;
1158 catch (exception const & e) {
1159 errorList.push_back(ErrorItem(_("conversion failed"),
1160 _(e.what()), -1, 0, 0));
1161 failed_export = true;
1164 lyxerr << "Caught some really weird exception..." << endl;
1170 failed_export = true;
1171 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1175 return !failed_export;
1179 void Buffer::writeLaTeXSource(odocstream & os,
1180 string const & original_path,
1181 OutputParams const & runparams_in,
1182 bool const output_preamble, bool const output_body) const
1184 // The child documents, if any, shall be already loaded at this point.
1186 OutputParams runparams = runparams_in;
1188 // Classify the unicode characters appearing in math insets
1189 Encodings::initUnicodeMath(*this);
1191 // validate the buffer.
1192 LYXERR(Debug::LATEX, " Validating buffer...");
1193 LaTeXFeatures features(*this, params(), runparams);
1195 LYXERR(Debug::LATEX, " Buffer validation done.");
1197 // The starting paragraph of the coming rows is the
1198 // first paragraph of the document. (Asger)
1199 if (output_preamble && runparams.nice) {
1200 os << "%% LyX " << lyx_version << " created this file. "
1201 "For more info, see http://www.lyx.org/.\n"
1202 "%% Do not edit unless you really know what "
1204 d->texrow.newline();
1205 d->texrow.newline();
1207 LYXERR(Debug::INFO, "lyx document header finished");
1209 // Don't move this behind the parent_buffer=0 code below,
1210 // because then the macros will not get the right "redefinition"
1211 // flag as they don't see the parent macros which are output before.
1214 // fold macros if possible, still with parent buffer as the
1215 // macros will be put in the prefix anyway.
1216 updateMacroInstances();
1218 // There are a few differences between nice LaTeX and usual files:
1219 // usual is \batchmode and has a
1220 // special input@path to allow the including of figures
1221 // with either \input or \includegraphics (what figinsets do).
1222 // input@path is set when the actual parameter
1223 // original_path is set. This is done for usual tex-file, but not
1224 // for nice-latex-file. (Matthias 250696)
1225 // Note that input@path is only needed for something the user does
1226 // in the preamble, included .tex files or ERT, files included by
1227 // LyX work without it.
1228 if (output_preamble) {
1229 if (!runparams.nice) {
1230 // code for usual, NOT nice-latex-file
1231 os << "\\batchmode\n"; // changed
1232 // from \nonstopmode
1233 d->texrow.newline();
1235 if (!original_path.empty()) {
1237 // We don't know the encoding of inputpath
1238 docstring const inputpath = from_utf8(latex_path(original_path));
1239 os << "\\makeatletter\n"
1240 << "\\def\\input@path{{"
1241 << inputpath << "/}}\n"
1242 << "\\makeatother\n";
1243 d->texrow.newline();
1244 d->texrow.newline();
1245 d->texrow.newline();
1248 // get parent macros (if this buffer has a parent) which will be
1249 // written at the document begin further down.
1250 MacroSet parentMacros;
1251 listParentMacros(parentMacros, features);
1253 // Write the preamble
1254 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1256 runparams.use_japanese = features.isRequired("japanese");
1262 os << "\\begin{document}\n";
1263 d->texrow.newline();
1265 // output the parent macros
1266 MacroSet::iterator it = parentMacros.begin();
1267 MacroSet::iterator end = parentMacros.end();
1268 for (; it != end; ++it)
1269 (*it)->write(os, true);
1270 } // output_preamble
1272 d->texrow.start(paragraphs().begin()->id(), 0);
1274 LYXERR(Debug::INFO, "preamble finished, now the body.");
1276 // if we are doing a real file with body, even if this is the
1277 // child of some other buffer, let's cut the link here.
1278 // This happens for example if only a child document is printed.
1279 Buffer const * save_parent = 0;
1280 if (output_preamble) {
1281 save_parent = d->parent();
1286 latexParagraphs(*this, text(), os, d->texrow, runparams);
1288 // Restore the parenthood if needed
1289 if (output_preamble)
1290 d->setParent(save_parent);
1292 // add this just in case after all the paragraphs
1294 d->texrow.newline();
1296 if (output_preamble) {
1297 os << "\\end{document}\n";
1298 d->texrow.newline();
1299 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1301 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1303 runparams_in.encoding = runparams.encoding;
1305 // Just to be sure. (Asger)
1306 d->texrow.newline();
1308 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1309 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1313 bool Buffer::isLatex() const
1315 return params().documentClass().outputType() == LATEX;
1319 bool Buffer::isLiterate() const
1321 return params().documentClass().outputType() == LITERATE;
1325 bool Buffer::isDocBook() const
1327 return params().documentClass().outputType() == DOCBOOK;
1331 void Buffer::makeDocBookFile(FileName const & fname,
1332 OutputParams const & runparams,
1333 bool const body_only) const
1335 LYXERR(Debug::LATEX, "makeDocBookFile...");
1338 if (!openFileWrite(ofs, fname))
1341 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1345 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1349 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1350 OutputParams const & runparams,
1351 bool const only_body) const
1353 LaTeXFeatures features(*this, params(), runparams);
1358 DocumentClass const & tclass = params().documentClass();
1359 string const top_element = tclass.latexname();
1362 if (runparams.flavor == OutputParams::XML)
1363 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1366 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1369 if (! tclass.class_header().empty())
1370 os << from_ascii(tclass.class_header());
1371 else if (runparams.flavor == OutputParams::XML)
1372 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1373 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1375 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1377 docstring preamble = from_utf8(params().preamble);
1378 if (runparams.flavor != OutputParams::XML ) {
1379 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1380 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1381 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1382 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1385 string const name = runparams.nice
1386 ? changeExtension(absFileName(), ".sgml") : fname;
1387 preamble += features.getIncludedFiles(name);
1388 preamble += features.getLyXSGMLEntities();
1390 if (!preamble.empty()) {
1391 os << "\n [ " << preamble << " ]";
1396 string top = top_element;
1398 if (runparams.flavor == OutputParams::XML)
1399 top += params().language->code();
1401 top += params().language->code().substr(0, 2);
1404 if (!params().options.empty()) {
1406 top += params().options;
1409 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1410 << " file was created by LyX " << lyx_version
1411 << "\n See http://www.lyx.org/ for more information -->\n";
1413 params().documentClass().counters().reset();
1417 sgml::openTag(os, top);
1419 docbookParagraphs(text(), *this, os, runparams);
1420 sgml::closeTag(os, top_element);
1424 void Buffer::makeLyXHTMLFile(FileName const & fname,
1425 OutputParams const & runparams,
1426 bool const body_only) const
1428 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1431 if (!openFileWrite(ofs, fname))
1434 writeLyXHTMLSource(ofs, runparams, body_only);
1438 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1442 void Buffer::writeLyXHTMLSource(odocstream & os,
1443 OutputParams const & runparams,
1444 bool const only_body) const
1446 LaTeXFeatures features(*this, params(), runparams);
1448 updateLabels(UpdateMaster, true);
1453 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1454 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";
1455 // FIXME Language should be set properly.
1456 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1459 // FIXME Presumably need to set this right
1460 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1461 // FIXME Get this during validation? What about other meta-data?
1462 os << "<title>TBA</title>\n";
1464 os << "\n<!-- Text Class Preamble -->\n"
1465 << features.getTClassHTMLPreamble()
1466 << "\n<!-- Premable Snippets -->\n"
1467 << from_utf8(features.getPreambleSnippets());
1469 os << "\n<!-- Layout-provided Styles -->\n";
1470 docstring const styleinfo = features.getTClassHTMLStyles();
1471 if (!styleinfo.empty()) {
1472 os << "<style type='text/css'>\n"
1476 os << "</head>\n<body>\n";
1480 params().documentClass().counters().reset();
1481 xhtmlParagraphs(text(), *this, xs, runparams);
1483 os << "</body>\n</html>\n";
1487 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1488 // Other flags: -wall -v0 -x
1489 int Buffer::runChktex()
1493 // get LaTeX-Filename
1494 FileName const path(temppath());
1495 string const name = addName(path.absFilename(), latexName());
1496 string const org_path = filePath();
1498 PathChanger p(path); // path to LaTeX file
1499 message(_("Running chktex..."));
1501 // Generate the LaTeX file if neccessary
1502 OutputParams runparams(¶ms().encoding());
1503 runparams.flavor = OutputParams::LATEX;
1504 runparams.nice = false;
1505 makeLaTeXFile(FileName(name), org_path, runparams);
1508 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1509 int const res = chktex.run(terr); // run chktex
1512 Alert::error(_("chktex failure"),
1513 _("Could not run chktex successfully."));
1514 } else if (res > 0) {
1515 ErrorList & errlist = d->errorLists["ChkTeX"];
1517 bufferErrors(terr, errlist);
1528 void Buffer::validate(LaTeXFeatures & features) const
1530 params().validate(features);
1534 for_each(paragraphs().begin(), paragraphs().end(),
1535 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1537 if (lyxerr.debugging(Debug::LATEX)) {
1538 features.showStruct();
1543 void Buffer::getLabelList(vector<docstring> & list) const
1545 // If this is a child document, use the parent's list instead.
1546 Buffer const * const pbuf = d->parent();
1548 pbuf->getLabelList(list);
1553 Toc & toc = d->toc_backend.toc("label");
1554 TocIterator toc_it = toc.begin();
1555 TocIterator end = toc.end();
1556 for (; toc_it != end; ++toc_it) {
1557 if (toc_it->depth() == 0)
1558 list.push_back(toc_it->str());
1563 void Buffer::updateBibfilesCache(UpdateScope scope) const
1565 // If this is a child document, use the parent's cache instead.
1566 Buffer const * const pbuf = d->parent();
1567 if (pbuf && scope != UpdateChildOnly) {
1568 pbuf->updateBibfilesCache();
1572 d->bibfilesCache_.clear();
1573 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1574 if (it->lyxCode() == BIBTEX_CODE) {
1575 InsetBibtex const & inset =
1576 static_cast<InsetBibtex const &>(*it);
1577 support::FileNameList const bibfiles = inset.getBibFiles();
1578 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1581 } else if (it->lyxCode() == INCLUDE_CODE) {
1582 InsetInclude & inset =
1583 static_cast<InsetInclude &>(*it);
1584 inset.updateBibfilesCache();
1585 support::FileNameList const & bibfiles =
1586 inset.getBibfilesCache();
1587 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1592 // the bibinfo cache is now invalid
1593 d->bibinfoCacheValid_ = false;
1597 void Buffer::invalidateBibinfoCache()
1599 d->bibinfoCacheValid_ = false;
1603 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1605 // If this is a child document, use the parent's cache instead.
1606 Buffer const * const pbuf = d->parent();
1607 if (pbuf && scope != UpdateChildOnly)
1608 return pbuf->getBibfilesCache();
1610 // We update the cache when first used instead of at loading time.
1611 if (d->bibfilesCache_.empty())
1612 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1614 return d->bibfilesCache_;
1618 BiblioInfo const & Buffer::masterBibInfo() const
1620 // if this is a child document and the parent is already loaded
1621 // use the parent's list instead [ale990412]
1622 Buffer const * const tmp = masterBuffer();
1625 return tmp->masterBibInfo();
1626 return localBibInfo();
1630 BiblioInfo const & Buffer::localBibInfo() const
1632 if (d->bibinfoCacheValid_) {
1633 support::FileNameList const & bibfilesCache = getBibfilesCache();
1634 // compare the cached timestamps with the actual ones.
1635 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1636 support::FileNameList::const_iterator en = bibfilesCache.end();
1637 for (; ei != en; ++ ei) {
1638 time_t lastw = ei->lastModified();
1639 if (lastw != d->bibfileStatus_[*ei]) {
1640 d->bibinfoCacheValid_ = false;
1641 d->bibfileStatus_[*ei] = lastw;
1647 if (!d->bibinfoCacheValid_) {
1648 d->bibinfo_.clear();
1649 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1650 it->fillWithBibKeys(d->bibinfo_, it);
1651 d->bibinfoCacheValid_ = true;
1657 bool Buffer::isDepClean(string const & name) const
1659 DepClean::const_iterator const it = d->dep_clean.find(name);
1660 if (it == d->dep_clean.end())
1666 void Buffer::markDepClean(string const & name)
1668 d->dep_clean[name] = true;
1672 bool Buffer::isExportableFormat(string const & format) const
1674 typedef vector<Format const *> Formats;
1676 formats = exportableFormats(true);
1677 Formats::const_iterator fit = formats.begin();
1678 Formats::const_iterator end = formats.end();
1679 for (; fit != end ; ++fit) {
1680 if ((*fit)->name() == format)
1687 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1690 // FIXME? if there is an Buffer LFUN that can be dispatched even
1691 // if internal, put a switch '(cmd.action)' here.
1697 switch (cmd.action) {
1699 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1700 flag.setOnOff(isReadonly());
1703 // FIXME: There is need for a command-line import.
1704 //case LFUN_BUFFER_IMPORT:
1706 case LFUN_BUFFER_AUTO_SAVE:
1709 case LFUN_BUFFER_EXPORT_CUSTOM:
1710 // FIXME: Nothing to check here?
1713 case LFUN_BUFFER_EXPORT: {
1714 docstring const arg = cmd.argument();
1715 enable = arg == "custom" || isExportable(to_utf8(arg));
1717 flag.message(bformat(
1718 _("Don't know how to export to format: %1$s"), arg));
1722 case LFUN_BUFFER_CHKTEX:
1723 enable = isLatex() && !lyxrc.chktex_command.empty();
1726 case LFUN_BUILD_PROGRAM:
1727 enable = isExportable("program");
1730 case LFUN_BRANCH_ACTIVATE:
1731 case LFUN_BRANCH_DEACTIVATE: {
1732 BranchList const & branchList = params().branchlist();
1733 docstring const branchName = cmd.argument();
1734 enable = !branchName.empty() && branchList.find(branchName);
1738 case LFUN_BRANCH_ADD:
1739 case LFUN_BRANCHES_RENAME:
1740 case LFUN_BUFFER_PRINT:
1741 // if no Buffer is present, then of course we won't be called!
1744 case LFUN_BUFFER_LANGUAGE:
1745 enable = !isReadonly();
1751 flag.setEnabled(enable);
1756 void Buffer::dispatch(string const & command, DispatchResult & result)
1758 return dispatch(lyxaction.lookupFunc(command), result);
1762 // NOTE We can end up here even if we have no GUI, because we are called
1763 // by LyX::exec to handled command-line requests. So we may need to check
1764 // whether we have a GUI or not. The boolean use_gui holds this information.
1765 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1768 // FIXME? if there is an Buffer LFUN that can be dispatched even
1769 // if internal, put a switch '(cmd.action)' here.
1770 dr.dispatched(false);
1773 string const argument = to_utf8(func.argument());
1774 // We'll set this back to false if need be.
1775 bool dispatched = true;
1776 undo().beginUndoGroup();
1778 switch (func.action) {
1779 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1780 if (lyxvc().inUse())
1781 lyxvc().toggleReadOnly();
1783 setReadonly(!isReadonly());
1786 case LFUN_BUFFER_EXPORT: {
1787 bool success = doExport(argument, false);
1788 dr.setError(success);
1790 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1795 case LFUN_BUILD_PROGRAM:
1796 doExport("program", true);
1799 case LFUN_BUFFER_CHKTEX:
1803 case LFUN_BUFFER_EXPORT_CUSTOM: {
1805 string command = split(argument, format_name, ' ');
1806 Format const * format = formats.getFormat(format_name);
1808 lyxerr << "Format \"" << format_name
1809 << "\" not recognized!"
1814 // The name of the file created by the conversion process
1817 // Output to filename
1818 if (format->name() == "lyx") {
1819 string const latexname = latexName(false);
1820 filename = changeExtension(latexname,
1821 format->extension());
1822 filename = addName(temppath(), filename);
1824 if (!writeFile(FileName(filename)))
1828 doExport(format_name, true, filename);
1831 // Substitute $$FName for filename
1832 if (!contains(command, "$$FName"))
1833 command = "( " + command + " ) < $$FName";
1834 command = subst(command, "$$FName", filename);
1836 // Execute the command in the background
1838 call.startscript(Systemcall::DontWait, command);
1842 // FIXME: There is need for a command-line import.
1844 case LFUN_BUFFER_IMPORT:
1849 case LFUN_BUFFER_AUTO_SAVE:
1853 case LFUN_BRANCH_ADD: {
1854 docstring const branch_name = func.argument();
1855 if (branch_name.empty()) {
1859 BranchList & branch_list = params().branchlist();
1860 Branch * branch = branch_list.find(branch_name);
1862 LYXERR0("Branch " << branch_name << " already exists.");
1864 docstring const msg =
1865 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1868 branch_list.add(branch_name);
1869 branch = branch_list.find(branch_name);
1870 string const x11hexname = X11hexname(branch->color());
1871 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1872 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1874 dr.update(Update::Force);
1879 case LFUN_BRANCH_ACTIVATE:
1880 case LFUN_BRANCH_DEACTIVATE: {
1881 BranchList & branchList = params().branchlist();
1882 docstring const branchName = func.argument();
1883 // the case without a branch name is handled elsewhere
1884 if (branchName.empty()) {
1888 Branch * branch = branchList.find(branchName);
1890 LYXERR0("Branch " << branchName << " does not exist.");
1892 docstring const msg =
1893 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1896 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1898 dr.update(Update::Force);
1903 case LFUN_BRANCHES_RENAME: {
1904 if (func.argument().empty())
1907 docstring const oldname = from_utf8(func.getArg(0));
1908 docstring const newname = from_utf8(func.getArg(1));
1909 InsetIterator it = inset_iterator_begin(inset());
1910 InsetIterator const end = inset_iterator_end(inset());
1911 bool success = false;
1912 for (; it != end; ++it) {
1913 if (it->lyxCode() == BRANCH_CODE) {
1914 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1915 if (ins.branch() == oldname) {
1916 undo().recordUndo(it);
1917 ins.rename(newname);
1922 if (it->lyxCode() == INCLUDE_CODE) {
1923 // get buffer of external file
1924 InsetInclude const & ins =
1925 static_cast<InsetInclude const &>(*it);
1926 Buffer * child = ins.getChildBuffer();
1929 child->dispatch(func, dr);
1934 dr.update(Update::Force);
1938 case LFUN_BUFFER_PRINT: {
1939 // we'll assume there's a problem until we succeed
1941 string target = func.getArg(0);
1942 string target_name = func.getArg(1);
1943 string command = func.getArg(2);
1946 || target_name.empty()
1947 || command.empty()) {
1948 LYXERR0("Unable to parse " << func.argument());
1949 docstring const msg =
1950 bformat(_("Unable to parse \"%1$s\""), func.argument());
1954 if (target != "printer" && target != "file") {
1955 LYXERR0("Unrecognized target \"" << target << '"');
1956 docstring const msg =
1957 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1962 if (!doExport("dvi", true)) {
1963 showPrintError(absFileName());
1964 dr.setMessage(_("Error exporting to DVI."));
1968 // Push directory path.
1969 string const path = temppath();
1970 // Prevent the compiler from optimizing away p
1974 // there are three cases here:
1975 // 1. we print to a file
1976 // 2. we print directly to a printer
1977 // 3. we print using a spool command (print to file first)
1980 string const dviname = changeExtension(latexName(true), "dvi");
1982 if (target == "printer") {
1983 if (!lyxrc.print_spool_command.empty()) {
1984 // case 3: print using a spool
1985 string const psname = changeExtension(dviname,".ps");
1986 command += ' ' + lyxrc.print_to_file
1989 + quoteName(dviname);
1991 string command2 = lyxrc.print_spool_command + ' ';
1992 if (target_name != "default") {
1993 command2 += lyxrc.print_spool_printerprefix
1997 command2 += quoteName(psname);
1999 // If successful, then spool command
2000 res = one.startscript(Systemcall::Wait, command);
2003 // If there's no GUI, we have to wait on this command. Otherwise,
2004 // LyX deletes the temporary directory, and with it the spooled
2005 // file, before it can be printed!!
2006 Systemcall::Starttype stype = use_gui ?
2007 Systemcall::DontWait : Systemcall::Wait;
2008 res = one.startscript(stype, command2);
2011 // case 2: print directly to a printer
2012 if (target_name != "default")
2013 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2015 Systemcall::Starttype stype = use_gui ?
2016 Systemcall::DontWait : Systemcall::Wait;
2017 res = one.startscript(stype, command + quoteName(dviname));
2021 // case 1: print to a file
2022 FileName const filename(makeAbsPath(target_name, filePath()));
2023 FileName const dvifile(makeAbsPath(dviname, path));
2024 if (filename.exists()) {
2025 docstring text = bformat(
2026 _("The file %1$s already exists.\n\n"
2027 "Do you want to overwrite that file?"),
2028 makeDisplayPath(filename.absFilename()));
2029 if (Alert::prompt(_("Overwrite file?"),
2030 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2033 command += ' ' + lyxrc.print_to_file
2034 + quoteName(filename.toFilesystemEncoding())
2036 + quoteName(dvifile.toFilesystemEncoding());
2038 Systemcall::Starttype stype = use_gui ?
2039 Systemcall::DontWait : Systemcall::Wait;
2040 res = one.startscript(stype, command);
2046 dr.setMessage(_("Error running external commands."));
2047 showPrintError(absFileName());
2052 case LFUN_BUFFER_LANGUAGE: {
2053 Language const * oldL = params().language;
2054 Language const * newL = languages.getLanguage(argument);
2055 if (!newL || oldL == newL)
2057 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2058 changeLanguage(oldL, newL);
2066 dr.dispatched(dispatched);
2067 undo().endUndoGroup();
2071 void Buffer::changeLanguage(Language const * from, Language const * to)
2073 LASSERT(from, /**/);
2076 for_each(par_iterator_begin(),
2078 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2082 bool Buffer::isMultiLingual() const
2084 ParConstIterator end = par_iterator_end();
2085 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2086 if (it->isMultiLingual(params()))
2093 DocIterator Buffer::getParFromID(int const id) const
2095 Buffer * buf = const_cast<Buffer *>(this);
2097 // John says this is called with id == -1 from undo
2098 lyxerr << "getParFromID(), id: " << id << endl;
2099 return doc_iterator_end(buf);
2102 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2103 if (it.paragraph().id() == id)
2106 return doc_iterator_end(buf);
2110 bool Buffer::hasParWithID(int const id) const
2112 return !getParFromID(id).atEnd();
2116 ParIterator Buffer::par_iterator_begin()
2118 return ParIterator(doc_iterator_begin(this));
2122 ParIterator Buffer::par_iterator_end()
2124 return ParIterator(doc_iterator_end(this));
2128 ParConstIterator Buffer::par_iterator_begin() const
2130 return ParConstIterator(doc_iterator_begin(this));
2134 ParConstIterator Buffer::par_iterator_end() const
2136 return ParConstIterator(doc_iterator_end(this));
2140 Language const * Buffer::language() const
2142 return params().language;
2146 docstring const Buffer::B_(string const & l10n) const
2148 return params().B_(l10n);
2152 bool Buffer::isClean() const
2154 return d->lyx_clean;
2158 bool Buffer::isBakClean() const
2160 return d->bak_clean;
2164 bool Buffer::isExternallyModified(CheckMethod method) const
2166 LASSERT(d->filename.exists(), /**/);
2167 // if method == timestamp, check timestamp before checksum
2168 return (method == checksum_method
2169 || d->timestamp_ != d->filename.lastModified())
2170 && d->checksum_ != d->filename.checksum();
2174 void Buffer::saveCheckSum(FileName const & file) const
2176 if (file.exists()) {
2177 d->timestamp_ = file.lastModified();
2178 d->checksum_ = file.checksum();
2180 // in the case of save to a new file.
2187 void Buffer::markClean() const
2189 if (!d->lyx_clean) {
2190 d->lyx_clean = true;
2193 // if the .lyx file has been saved, we don't need an
2195 d->bak_clean = true;
2199 void Buffer::markBakClean() const
2201 d->bak_clean = true;
2205 void Buffer::setUnnamed(bool flag)
2211 bool Buffer::isUnnamed() const
2218 /// Don't check unnamed, here: isInternal() is used in
2219 /// newBuffer(), where the unnamed flag has not been set by anyone
2220 /// yet. Also, for an internal buffer, there should be no need for
2221 /// retrieving fileName() nor for checking if it is unnamed or not.
2222 bool Buffer::isInternal() const
2224 return fileName().extension() == "internal";
2228 void Buffer::markDirty()
2231 d->lyx_clean = false;
2234 d->bak_clean = false;
2236 DepClean::iterator it = d->dep_clean.begin();
2237 DepClean::const_iterator const end = d->dep_clean.end();
2239 for (; it != end; ++it)
2244 FileName Buffer::fileName() const
2250 string Buffer::absFileName() const
2252 return d->filename.absFilename();
2256 string Buffer::filePath() const
2258 return d->filename.onlyPath().absFilename() + "/";
2262 bool Buffer::isReadonly() const
2264 return d->read_only;
2268 void Buffer::setParent(Buffer const * buffer)
2270 // Avoids recursive include.
2271 d->setParent(buffer == this ? 0 : buffer);
2276 Buffer const * Buffer::parent() const
2282 void Buffer::collectRelatives(BufferSet & bufs) const
2286 parent()->collectRelatives(bufs);
2288 // loop over children
2289 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2290 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2291 for (; it != end; ++it)
2292 bufs.insert(const_cast<Buffer *>(it->first));
2296 std::vector<Buffer const *> Buffer::allRelatives() const
2299 collectRelatives(bufs);
2300 BufferSet::iterator it = bufs.begin();
2301 std::vector<Buffer const *> ret;
2302 for (; it != bufs.end(); ++it)
2308 Buffer const * Buffer::masterBuffer() const
2310 Buffer const * const pbuf = d->parent();
2314 return pbuf->masterBuffer();
2318 bool Buffer::isChild(Buffer * child) const
2320 return d->children_positions.find(child) != d->children_positions.end();
2324 DocIterator Buffer::firstChildPosition(Buffer const * child)
2326 Impl::BufferPositionMap::iterator it;
2327 it = d->children_positions.find(child);
2328 if (it == d->children_positions.end())
2329 return DocIterator(this);
2334 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
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 Buffer * child = const_cast<Buffer *>(it->first);
2341 clist.push_back(child);
2342 if (grand_children) {
2343 // there might be grandchildren
2344 std::vector<Buffer *> glist = child->getChildren();
2345 for (vector<Buffer *>::const_iterator git = glist.begin();
2346 git != glist.end(); ++git)
2347 clist.push_back(*git);
2353 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2355 std::vector<Buffer *> v;
2356 getChildren(v, grand_children);
2361 template<typename M>
2362 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2367 typename M::iterator it = m.lower_bound(x);
2368 if (it == m.begin())
2376 MacroData const * Buffer::getBufferMacro(docstring const & name,
2377 DocIterator const & pos) const
2379 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2381 // if paragraphs have no macro context set, pos will be empty
2385 // we haven't found anything yet
2386 DocIterator bestPos = par_iterator_begin();
2387 MacroData const * bestData = 0;
2389 // find macro definitions for name
2390 Impl::NamePositionScopeMacroMap::iterator nameIt
2391 = d->macros.find(name);
2392 if (nameIt != d->macros.end()) {
2393 // find last definition in front of pos or at pos itself
2394 Impl::PositionScopeMacroMap::const_iterator it
2395 = greatest_below(nameIt->second, pos);
2396 if (it != nameIt->second.end()) {
2398 // scope ends behind pos?
2399 if (pos < it->second.first) {
2400 // Looks good, remember this. If there
2401 // is no external macro behind this,
2402 // we found the right one already.
2403 bestPos = it->first;
2404 bestData = &it->second.second;
2408 // try previous macro if there is one
2409 if (it == nameIt->second.begin())
2416 // find macros in included files
2417 Impl::PositionScopeBufferMap::const_iterator it
2418 = greatest_below(d->position_to_children, pos);
2419 if (it == d->position_to_children.end())
2420 // no children before
2424 // do we know something better (i.e. later) already?
2425 if (it->first < bestPos )
2428 // scope ends behind pos?
2429 if (pos < it->second.first) {
2430 // look for macro in external file
2431 d->macro_lock = true;
2432 MacroData const * data
2433 = it->second.second->getMacro(name, false);
2434 d->macro_lock = false;
2436 bestPos = it->first;
2442 // try previous file if there is one
2443 if (it == d->position_to_children.begin())
2448 // return the best macro we have found
2453 MacroData const * Buffer::getMacro(docstring const & name,
2454 DocIterator const & pos, bool global) const
2459 // query buffer macros
2460 MacroData const * data = getBufferMacro(name, pos);
2464 // If there is a master buffer, query that
2465 Buffer const * const pbuf = d->parent();
2467 d->macro_lock = true;
2468 MacroData const * macro = pbuf->getMacro(
2469 name, *this, false);
2470 d->macro_lock = false;
2476 data = MacroTable::globalMacros().get(name);
2485 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2487 // set scope end behind the last paragraph
2488 DocIterator scope = par_iterator_begin();
2489 scope.pit() = scope.lastpit() + 1;
2491 return getMacro(name, scope, global);
2495 MacroData const * Buffer::getMacro(docstring const & name,
2496 Buffer const & child, bool global) const
2498 // look where the child buffer is included first
2499 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2500 if (it == d->children_positions.end())
2503 // check for macros at the inclusion position
2504 return getMacro(name, it->second, global);
2508 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2510 pit_type lastpit = it.lastpit();
2512 // look for macros in each paragraph
2513 while (it.pit() <= lastpit) {
2514 Paragraph & par = it.paragraph();
2516 // iterate over the insets of the current paragraph
2517 InsetList const & insets = par.insetList();
2518 InsetList::const_iterator iit = insets.begin();
2519 InsetList::const_iterator end = insets.end();
2520 for (; iit != end; ++iit) {
2521 it.pos() = iit->pos;
2523 // is it a nested text inset?
2524 if (iit->inset->asInsetText()) {
2525 // Inset needs its own scope?
2526 InsetText const * itext = iit->inset->asInsetText();
2527 bool newScope = itext->isMacroScope();
2529 // scope which ends just behind the inset
2530 DocIterator insetScope = it;
2533 // collect macros in inset
2534 it.push_back(CursorSlice(*iit->inset));
2535 updateMacros(it, newScope ? insetScope : scope);
2540 // is it an external file?
2541 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2542 // get buffer of external file
2543 InsetInclude const & inset =
2544 static_cast<InsetInclude const &>(*iit->inset);
2545 d->macro_lock = true;
2546 Buffer * child = inset.getChildBuffer();
2547 d->macro_lock = false;
2551 // register its position, but only when it is
2552 // included first in the buffer
2553 if (d->children_positions.find(child) ==
2554 d->children_positions.end())
2555 d->children_positions[child] = it;
2557 // register child with its scope
2558 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2562 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2566 MathMacroTemplate & macroTemplate =
2567 static_cast<MathMacroTemplate &>(*iit->inset);
2568 MacroContext mc(this, it);
2569 macroTemplate.updateToContext(mc);
2572 bool valid = macroTemplate.validMacro();
2573 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2574 // then the BufferView's cursor will be invalid in
2575 // some cases which leads to crashes.
2580 // FIXME (Abdel), I don't understandt why we pass 'it' here
2581 // instead of 'macroTemplate' defined above... is this correct?
2582 d->macros[macroTemplate.name()][it] =
2583 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2593 void Buffer::updateMacros() const
2598 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2600 // start with empty table
2602 d->children_positions.clear();
2603 d->position_to_children.clear();
2605 // Iterate over buffer, starting with first paragraph
2606 // The scope must be bigger than any lookup DocIterator
2607 // later. For the global lookup, lastpit+1 is used, hence
2608 // we use lastpit+2 here.
2609 DocIterator it = par_iterator_begin();
2610 DocIterator outerScope = it;
2611 outerScope.pit() = outerScope.lastpit() + 2;
2612 updateMacros(it, outerScope);
2616 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2618 InsetIterator it = inset_iterator_begin(inset());
2619 InsetIterator const end = inset_iterator_end(inset());
2620 for (; it != end; ++it) {
2621 if (it->lyxCode() == BRANCH_CODE) {
2622 InsetBranch & br = static_cast<InsetBranch &>(*it);
2623 docstring const name = br.branch();
2624 if (!from_master && !params().branchlist().find(name))
2625 result.push_back(name);
2626 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2627 result.push_back(name);
2630 if (it->lyxCode() == INCLUDE_CODE) {
2631 // get buffer of external file
2632 InsetInclude const & ins =
2633 static_cast<InsetInclude const &>(*it);
2634 Buffer * child = ins.getChildBuffer();
2637 child->getUsedBranches(result, true);
2640 // remove duplicates
2645 void Buffer::updateMacroInstances() const
2647 LYXERR(Debug::MACROS, "updateMacroInstances for "
2648 << d->filename.onlyFileName());
2649 DocIterator it = doc_iterator_begin(this);
2651 DocIterator const end = doc_iterator_end(this);
2652 for (; it != end; it.forwardInset()) {
2653 // look for MathData cells in InsetMathNest insets
2654 InsetMath * minset = it.nextInset()->asInsetMath();
2658 // update macro in all cells of the InsetMathNest
2659 DocIterator::idx_type n = minset->nargs();
2660 MacroContext mc = MacroContext(this, it);
2661 for (DocIterator::idx_type i = 0; i < n; ++i) {
2662 MathData & data = minset->cell(i);
2663 data.updateMacros(0, mc);
2669 void Buffer::listMacroNames(MacroNameSet & macros) const
2674 d->macro_lock = true;
2676 // loop over macro names
2677 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2678 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2679 for (; nameIt != nameEnd; ++nameIt)
2680 macros.insert(nameIt->first);
2682 // loop over children
2683 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2684 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2685 for (; it != end; ++it)
2686 it->first->listMacroNames(macros);
2689 Buffer const * const pbuf = d->parent();
2691 pbuf->listMacroNames(macros);
2693 d->macro_lock = false;
2697 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2699 Buffer const * const pbuf = d->parent();
2704 pbuf->listMacroNames(names);
2707 MacroNameSet::iterator it = names.begin();
2708 MacroNameSet::iterator end = names.end();
2709 for (; it != end; ++it) {
2711 MacroData const * data =
2712 pbuf->getMacro(*it, *this, false);
2714 macros.insert(data);
2716 // we cannot access the original MathMacroTemplate anymore
2717 // here to calls validate method. So we do its work here manually.
2718 // FIXME: somehow make the template accessible here.
2719 if (data->optionals() > 0)
2720 features.require("xargs");
2726 Buffer::References & Buffer::references(docstring const & label)
2729 return const_cast<Buffer *>(masterBuffer())->references(label);
2731 RefCache::iterator it = d->ref_cache_.find(label);
2732 if (it != d->ref_cache_.end())
2733 return it->second.second;
2735 static InsetLabel const * dummy_il = 0;
2736 static References const dummy_refs;
2737 it = d->ref_cache_.insert(
2738 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2739 return it->second.second;
2743 Buffer::References const & Buffer::references(docstring const & label) const
2745 return const_cast<Buffer *>(this)->references(label);
2749 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2751 masterBuffer()->d->ref_cache_[label].first = il;
2755 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2757 return masterBuffer()->d->ref_cache_[label].first;
2761 void Buffer::clearReferenceCache() const
2764 d->ref_cache_.clear();
2768 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2771 //FIXME: This does not work for child documents yet.
2772 LASSERT(code == CITE_CODE, /**/);
2773 // Check if the label 'from' appears more than once
2774 vector<docstring> labels;
2776 BiblioInfo const & keys = masterBibInfo();
2777 BiblioInfo::const_iterator bit = keys.begin();
2778 BiblioInfo::const_iterator bend = keys.end();
2780 for (; bit != bend; ++bit)
2782 labels.push_back(bit->first);
2785 if (count(labels.begin(), labels.end(), from) > 1)
2788 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2789 if (it->lyxCode() == code) {
2790 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2791 docstring const oldValue = inset.getParam(paramName);
2792 if (oldValue == from)
2793 inset.setParam(paramName, to);
2799 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2800 pit_type par_end, bool full_source) const
2802 OutputParams runparams(¶ms().encoding());
2803 runparams.nice = true;
2804 runparams.flavor = params().useXetex ?
2805 OutputParams::XETEX : OutputParams::LATEX;
2806 runparams.linelen = lyxrc.plaintext_linelen;
2807 // No side effect of file copying and image conversion
2808 runparams.dryrun = true;
2811 os << "% " << _("Preview source code") << "\n\n";
2813 d->texrow.newline();
2814 d->texrow.newline();
2816 writeDocBookSource(os, absFileName(), runparams, false);
2818 // latex or literate
2819 writeLaTeXSource(os, string(), runparams, true, true);
2821 runparams.par_begin = par_begin;
2822 runparams.par_end = par_end;
2823 if (par_begin + 1 == par_end) {
2825 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2829 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2830 convert<docstring>(par_begin),
2831 convert<docstring>(par_end - 1))
2838 // output paragraphs
2840 docbookParagraphs(text(), *this, os, runparams);
2842 // latex or literate
2843 latexParagraphs(*this, text(), os, texrow, runparams);
2848 ErrorList & Buffer::errorList(string const & type) const
2850 static ErrorList emptyErrorList;
2851 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2852 if (I == d->errorLists.end())
2853 return emptyErrorList;
2859 void Buffer::updateTocItem(std::string const & type,
2860 DocIterator const & dit) const
2863 gui_->updateTocItem(type, dit);
2867 void Buffer::structureChanged() const
2870 gui_->structureChanged();
2874 void Buffer::errors(string const & err, bool from_master) const
2877 gui_->errors(err, from_master);
2881 void Buffer::message(docstring const & msg) const
2888 void Buffer::setBusy(bool on) const
2895 void Buffer::setReadOnly(bool on) const
2898 d->wa_->setReadOnly(on);
2902 void Buffer::updateTitles() const
2905 d->wa_->updateTitles();
2909 void Buffer::resetAutosaveTimers() const
2912 gui_->resetAutosaveTimers();
2916 bool Buffer::hasGuiDelegate() const
2922 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2931 class AutoSaveBuffer : public ForkedProcess {
2934 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2935 : buffer_(buffer), fname_(fname) {}
2937 virtual boost::shared_ptr<ForkedProcess> clone() const
2939 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2944 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2945 from_utf8(fname_.absFilename())));
2946 return run(DontWait);
2950 virtual int generateChild();
2952 Buffer const & buffer_;
2957 int AutoSaveBuffer::generateChild()
2959 #if defined(__APPLE__)
2960 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2961 * We should use something else like threads.
2963 * Since I do not know how to determine at run time what is the OS X
2964 * version, I just disable forking altogether for now (JMarc)
2966 pid_t const pid = -1;
2968 // tmp_ret will be located (usually) in /tmp
2969 // will that be a problem?
2970 // Note that this calls ForkedCalls::fork(), so it's
2971 // ok cross-platform.
2972 pid_t const pid = fork();
2973 // If you want to debug the autosave
2974 // you should set pid to -1, and comment out the fork.
2975 if (pid != 0 && pid != -1)
2979 // pid = -1 signifies that lyx was unable
2980 // to fork. But we will do the save
2982 bool failed = false;
2983 FileName const tmp_ret = FileName::tempName("lyxauto");
2984 if (!tmp_ret.empty()) {
2985 buffer_.writeFile(tmp_ret);
2986 // assume successful write of tmp_ret
2987 if (!tmp_ret.moveTo(fname_))
2993 // failed to write/rename tmp_ret so try writing direct
2994 if (!buffer_.writeFile(fname_)) {
2995 // It is dangerous to do this in the child,
2996 // but safe in the parent, so...
2997 if (pid == -1) // emit message signal.
2998 buffer_.message(_("Autosave failed!"));
3002 if (pid == 0) // we are the child so...
3011 FileName Buffer::getAutosaveFilename() const
3013 // if the document is unnamed try to save in the backup dir, else
3014 // in the default document path, and as a last try in the filePath,
3015 // which will most often be the temporary directory
3018 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3019 : lyxrc.backupdir_path;
3020 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3023 string const fname = "#" + d->filename.onlyFileName() + "#";
3024 return makeAbsPath(fname, fpath);
3028 void Buffer::removeAutosaveFile() const
3030 FileName const f = getAutosaveFilename();
3036 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3038 FileName const newauto = getAutosaveFilename();
3039 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3040 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3044 // Perfect target for a thread...
3045 void Buffer::autoSave() const
3047 if (isBakClean() || isReadonly()) {
3048 // We don't save now, but we'll try again later
3049 resetAutosaveTimers();
3053 // emit message signal.
3054 message(_("Autosaving current document..."));
3055 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3059 resetAutosaveTimers();
3063 string Buffer::bufferFormat() const
3065 string format = params().documentClass().outputFormat();
3066 if (format == "latex") {
3067 if (params().useXetex)
3069 if (params().encoding().package() == Encoding::japanese)
3076 string Buffer::getDefaultOutputFormat() const
3078 if (!params().defaultOutputFormat.empty()
3079 && params().defaultOutputFormat != "default")
3080 return params().defaultOutputFormat;
3081 typedef vector<Format const *> Formats;
3082 Formats formats = exportableFormats(true);
3085 || params().useXetex
3086 || params().encoding().package() == Encoding::japanese) {
3087 if (formats.empty())
3089 // return the first we find
3090 return formats.front()->name();
3092 return lyxrc.default_view_format;
3097 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3098 string & result_file) const
3100 string backend_format;
3101 OutputParams runparams(¶ms().encoding());
3102 runparams.flavor = OutputParams::LATEX;
3103 runparams.linelen = lyxrc.plaintext_linelen;
3104 vector<string> backs = backends();
3105 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3106 // Get shortest path to format
3107 Graph::EdgePath path;
3108 for (vector<string>::const_iterator it = backs.begin();
3109 it != backs.end(); ++it) {
3110 Graph::EdgePath p = theConverters().getPath(*it, format);
3111 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3112 backend_format = *it;
3117 if (!put_in_tempdir) {
3118 // Only show this alert if this is an export to a non-temporary
3119 // file (not for previewing).
3120 Alert::error(_("Couldn't export file"), bformat(
3121 _("No information for exporting the format %1$s."),
3122 formats.prettyName(format)));
3126 runparams.flavor = theConverters().getFlavor(path);
3129 backend_format = format;
3130 // FIXME: Don't hardcode format names here, but use a flag
3131 if (backend_format == "pdflatex")
3132 runparams.flavor = OutputParams::PDFLATEX;
3135 string filename = latexName(false);
3136 filename = addName(temppath(), filename);
3137 filename = changeExtension(filename,
3138 formats.extension(backend_format));
3141 updateMacroInstances();
3143 // Plain text backend
3144 if (backend_format == "text") {
3145 runparams.flavor = OutputParams::TEXT;
3146 writePlaintextFile(*this, FileName(filename), runparams);
3149 else if (backend_format == "xhtml") {
3150 runparams.flavor = OutputParams::HTML;
3151 makeLyXHTMLFile(FileName(filename), runparams);
3152 } else if (backend_format == "lyx")
3153 writeFile(FileName(filename));
3155 else if (isDocBook()) {
3156 runparams.nice = !put_in_tempdir;
3157 makeDocBookFile(FileName(filename), runparams);
3160 else if (backend_format == format) {
3161 runparams.nice = true;
3162 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3164 } else if (!lyxrc.tex_allows_spaces
3165 && contains(filePath(), ' ')) {
3166 Alert::error(_("File name error"),
3167 _("The directory path to the document cannot contain spaces."));
3170 runparams.nice = false;
3171 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3175 string const error_type = (format == "program")
3176 ? "Build" : bufferFormat();
3177 ErrorList & error_list = d->errorLists[error_type];
3178 string const ext = formats.extension(format);
3179 FileName const tmp_result_file(changeExtension(filename, ext));
3180 bool const success = theConverters().convert(this, FileName(filename),
3181 tmp_result_file, FileName(absFileName()), backend_format, format,
3183 // Emit the signal to show the error list.
3184 if (format != backend_format) {
3186 // also to the children, in case of master-buffer-view
3187 std::vector<Buffer *> clist = getChildren();
3188 for (vector<Buffer *>::const_iterator cit = clist.begin();
3189 cit != clist.end(); ++cit)
3190 (*cit)->errors(error_type, true);
3195 if (put_in_tempdir) {
3196 result_file = tmp_result_file.absFilename();
3200 result_file = changeExtension(exportFileName().absFilename(), ext);
3201 // We need to copy referenced files (e. g. included graphics
3202 // if format == "dvi") to the result dir.
3203 vector<ExportedFile> const files =
3204 runparams.exportdata->externalFiles(format);
3205 string const dest = onlyPath(result_file);
3206 CopyStatus status = SUCCESS;
3207 for (vector<ExportedFile>::const_iterator it = files.begin();
3208 it != files.end() && status != CANCEL; ++it) {
3209 string const fmt = formats.getFormatFromFile(it->sourceName);
3210 status = copyFile(fmt, it->sourceName,
3211 makeAbsPath(it->exportName, dest),
3212 it->exportName, status == FORCE);
3214 if (status == CANCEL) {
3215 message(_("Document export cancelled."));
3216 } else if (tmp_result_file.exists()) {
3217 // Finally copy the main file
3218 status = copyFile(format, tmp_result_file,
3219 FileName(result_file), result_file,
3221 message(bformat(_("Document exported as %1$s "
3223 formats.prettyName(format),
3224 makeDisplayPath(result_file)));
3226 // This must be a dummy converter like fax (bug 1888)
3227 message(bformat(_("Document exported as %1$s"),
3228 formats.prettyName(format)));
3235 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3238 return doExport(format, put_in_tempdir, result_file);
3242 bool Buffer::preview(string const & format) const
3245 if (!doExport(format, true, result_file))
3247 return formats.view(*this, FileName(result_file), format);
3251 bool Buffer::isExportable(string const & format) const
3253 vector<string> backs = backends();
3254 for (vector<string>::const_iterator it = backs.begin();
3255 it != backs.end(); ++it)
3256 if (theConverters().isReachable(*it, format))
3262 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3264 vector<string> const backs = backends();
3265 vector<Format const *> result =
3266 theConverters().getReachable(backs[0], only_viewable, true);
3267 for (vector<string>::const_iterator it = backs.begin() + 1;
3268 it != backs.end(); ++it) {
3269 vector<Format const *> r =
3270 theConverters().getReachable(*it, only_viewable, false);
3271 result.insert(result.end(), r.begin(), r.end());
3277 vector<string> Buffer::backends() const
3280 v.push_back(bufferFormat());
3281 // FIXME: Don't hardcode format names here, but use a flag
3282 if (v.back() == "latex")
3283 v.push_back("pdflatex");
3284 v.push_back("xhtml");
3285 v.push_back("text");
3291 bool Buffer::readFileHelper(FileName const & s)
3293 // File information about normal file
3295 docstring const file = makeDisplayPath(s.absFilename(), 50);
3296 docstring text = bformat(_("The specified document\n%1$s"
3297 "\ncould not be read."), file);
3298 Alert::error(_("Could not read document"), text);
3302 // Check if emergency save file exists and is newer.
3303 FileName const e(s.absFilename() + ".emergency");
3305 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3306 docstring const file = makeDisplayPath(s.absFilename(), 20);
3307 docstring const text =
3308 bformat(_("An emergency save of the document "
3310 "Recover emergency save?"), file);
3311 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3312 _("&Recover"), _("&Load Original"),
3316 // the file is not saved if we load the emergency file.
3321 if ((res = readFile(e)) == success)
3322 str = _("Document was successfully recovered.");
3324 str = _("Document was NOT successfully recovered.");
3325 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3326 from_utf8(e.absFilename()));
3328 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3329 _("&Remove"), _("&Keep it"))) {
3332 Alert::warning(_("Emergency file deleted"),
3333 _("Do not forget to save your file now!"), true);
3338 if (!Alert::prompt(_("Delete emergency file?"),
3339 _("Remove emergency file now?"), 1, 1,
3340 _("&Remove"), _("&Keep it")))
3348 // Now check if autosave file is newer.
3349 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3351 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3352 docstring const file = makeDisplayPath(s.absFilename(), 20);
3353 docstring const text =
3354 bformat(_("The backup of the document "
3355 "%1$s is newer.\n\nLoad the "
3356 "backup instead?"), file);
3357 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3358 _("&Load backup"), _("Load &original"),
3362 // the file is not saved if we load the autosave file.
3366 // Here we delete the autosave
3377 bool Buffer::loadLyXFile(FileName const & s)
3379 if (s.isReadableFile()) {
3380 if (readFileHelper(s)) {
3381 lyxvc().file_found_hook(s);
3382 if (!s.isWritable())
3387 docstring const file = makeDisplayPath(s.absFilename(), 20);
3388 // Here we probably should run
3389 if (LyXVC::file_not_found_hook(s)) {
3390 docstring const text =
3391 bformat(_("Do you want to retrieve the document"
3392 " %1$s from version control?"), file);
3393 int const ret = Alert::prompt(_("Retrieve from version control?"),
3394 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3397 // How can we know _how_ to do the checkout?
3398 // With the current VC support it has to be,
3399 // a RCS file since CVS do not have special ,v files.
3401 return loadLyXFile(s);
3409 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3411 TeXErrors::Errors::const_iterator cit = terr.begin();
3412 TeXErrors::Errors::const_iterator end = terr.end();
3414 for (; cit != end; ++cit) {
3417 int errorRow = cit->error_in_line;
3418 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3424 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3425 } while (found && id_start == id_end && pos_start == pos_end);
3427 errorList.push_back(ErrorItem(cit->error_desc,
3428 cit->error_text, id_start, pos_start, pos_end));
3433 void Buffer::setBuffersForInsets() const
3435 inset().setBuffer(const_cast<Buffer &>(*this));
3439 void Buffer::updateLabels(UpdateScope scope, bool out) const
3441 // Use the master text class also for child documents
3442 Buffer const * const master = masterBuffer();
3443 DocumentClass const & textclass = master->params().documentClass();
3445 // keep the buffers to be children in this set. If the call from the
3446 // master comes back we can see which of them were actually seen (i.e.
3447 // via an InsetInclude). The remaining ones in the set need still be updated.
3448 static std::set<Buffer const *> bufToUpdate;
3449 if (scope == UpdateMaster) {
3450 // If this is a child document start with the master
3451 if (master != this) {
3452 bufToUpdate.insert(this);
3453 master->updateLabels(UpdateMaster, out);
3454 // Do this here in case the master has no gui associated with it. Then,
3455 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3459 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3460 if (bufToUpdate.find(this) == bufToUpdate.end())
3464 // start over the counters in the master
3465 textclass.counters().reset();
3468 // update will be done below for this buffer
3469 bufToUpdate.erase(this);
3471 // update all caches
3472 clearReferenceCache();
3475 Buffer & cbuf = const_cast<Buffer &>(*this);
3477 LASSERT(!text().paragraphs().empty(), /**/);
3480 ParIterator parit = cbuf.par_iterator_begin();
3481 updateLabels(parit, out);
3484 // TocBackend update will be done later.
3487 cbuf.tocBackend().update();
3488 if (scope == UpdateMaster)
3489 cbuf.structureChanged();
3493 static depth_type getDepth(DocIterator const & it)
3495 depth_type depth = 0;
3496 for (size_t i = 0 ; i < it.depth() ; ++i)
3497 if (!it[i].inset().inMathed())
3498 depth += it[i].paragraph().getDepth() + 1;
3499 // remove 1 since the outer inset does not count
3503 static depth_type getItemDepth(ParIterator const & it)
3505 Paragraph const & par = *it;
3506 LabelType const labeltype = par.layout().labeltype;
3508 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3511 // this will hold the lowest depth encountered up to now.
3512 depth_type min_depth = getDepth(it);
3513 ParIterator prev_it = it;
3516 --prev_it.top().pit();
3518 // start of nested inset: go to outer par
3520 if (prev_it.empty()) {
3521 // start of document: nothing to do
3526 // We search for the first paragraph with same label
3527 // that is not more deeply nested.
3528 Paragraph & prev_par = *prev_it;
3529 depth_type const prev_depth = getDepth(prev_it);
3530 if (labeltype == prev_par.layout().labeltype) {
3531 if (prev_depth < min_depth)
3532 return prev_par.itemdepth + 1;
3533 if (prev_depth == min_depth)
3534 return prev_par.itemdepth;
3536 min_depth = min(min_depth, prev_depth);
3537 // small optimization: if we are at depth 0, we won't
3538 // find anything else
3539 if (prev_depth == 0)
3545 static bool needEnumCounterReset(ParIterator const & it)
3547 Paragraph const & par = *it;
3548 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3549 depth_type const cur_depth = par.getDepth();
3550 ParIterator prev_it = it;
3551 while (prev_it.pit()) {
3552 --prev_it.top().pit();
3553 Paragraph const & prev_par = *prev_it;
3554 if (prev_par.getDepth() <= cur_depth)
3555 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3557 // start of nested inset: reset
3562 // set the label of a paragraph. This includes the counters.
3563 void Buffer::setLabel(ParIterator & it) const
3565 BufferParams const & bp = this->masterBuffer()->params();
3566 DocumentClass const & textclass = bp.documentClass();
3567 Paragraph & par = it.paragraph();
3568 Layout const & layout = par.layout();
3569 Counters & counters = textclass.counters();
3571 if (par.params().startOfAppendix()) {
3572 // FIXME: only the counter corresponding to toplevel
3573 // sectioning should be reset
3575 counters.appendix(true);
3577 par.params().appendix(counters.appendix());
3579 // Compute the item depth of the paragraph
3580 par.itemdepth = getItemDepth(it);
3582 if (layout.margintype == MARGIN_MANUAL
3583 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3584 if (par.params().labelWidthString().empty())
3585 par.params().labelWidthString(par.expandLabel(layout, bp));
3587 par.params().labelWidthString(docstring());
3590 switch(layout.labeltype) {
3592 if (layout.toclevel <= bp.secnumdepth
3593 && (layout.latextype != LATEX_ENVIRONMENT
3594 || it.text()->isFirstInSequence(it.pit()))) {
3595 counters.step(layout.counter);
3596 par.params().labelString(
3597 par.expandLabel(layout, bp));
3599 par.params().labelString(docstring());
3602 case LABEL_ITEMIZE: {
3603 // At some point of time we should do something more
3604 // clever here, like:
3605 // par.params().labelString(
3606 // bp.user_defined_bullet(par.itemdepth).getText());
3607 // for now, use a simple hardcoded label
3608 docstring itemlabel;
3609 switch (par.itemdepth) {
3611 itemlabel = char_type(0x2022);
3614 itemlabel = char_type(0x2013);
3617 itemlabel = char_type(0x2217);
3620 itemlabel = char_type(0x2219); // or 0x00b7
3623 par.params().labelString(itemlabel);
3627 case LABEL_ENUMERATE: {
3628 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3630 switch (par.itemdepth) {
3639 enumcounter += "iv";
3642 // not a valid enumdepth...
3646 // Maybe we have to reset the enumeration counter.
3647 if (needEnumCounterReset(it))
3648 counters.reset(enumcounter);
3649 counters.step(enumcounter);
3651 string const & lang = par.getParLanguage(bp)->code();
3652 par.params().labelString(counters.theCounter(enumcounter, lang));
3657 case LABEL_SENSITIVE: {
3658 string const & type = counters.current_float();
3659 docstring full_label;
3661 full_label = this->B_("Senseless!!! ");
3663 docstring name = this->B_(textclass.floats().getType(type).name());
3664 if (counters.hasCounter(from_utf8(type))) {
3665 string const & lang = par.getParLanguage(bp)->code();
3666 counters.step(from_utf8(type));
3667 full_label = bformat(from_ascii("%1$s %2$s:"),
3669 counters.theCounter(from_utf8(type), lang));
3671 full_label = bformat(from_ascii("%1$s #:"), name);
3673 par.params().labelString(full_label);
3677 case LABEL_NO_LABEL:
3678 par.params().labelString(docstring());
3682 case LABEL_TOP_ENVIRONMENT:
3683 case LABEL_CENTERED_TOP_ENVIRONMENT:
3686 par.params().labelString(par.expandLabel(layout, bp));
3692 void Buffer::updateLabels(ParIterator & parit, bool out) const
3694 LASSERT(parit.pit() == 0, /**/);
3696 // set the position of the text in the buffer to be able
3697 // to resolve macros in it. This has nothing to do with
3698 // labels, but by putting it here we avoid implementing
3699 // a whole bunch of traversal routines just for this call.
3700 parit.text()->setMacrocontextPosition(parit);
3702 depth_type maxdepth = 0;
3703 pit_type const lastpit = parit.lastpit();
3704 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3705 // reduce depth if necessary
3706 parit->params().depth(min(parit->params().depth(), maxdepth));
3707 maxdepth = parit->getMaxDepthAfter();
3709 // set the counter for this paragraph
3713 InsetList::const_iterator iit = parit->insetList().begin();
3714 InsetList::const_iterator end = parit->insetList().end();
3715 for (; iit != end; ++iit) {
3716 parit.pos() = iit->pos;
3717 iit->inset->updateLabels(parit, out);
3723 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3724 WordLangTuple & word_lang, docstring_list & suggestions) const
3728 suggestions.clear();
3729 word_lang = WordLangTuple();
3730 // OK, we start from here.
3731 DocIterator const end = doc_iterator_end(this);
3732 for (; from != end; from.forwardPos()) {
3733 // We are only interested in text so remove the math CursorSlice.
3734 while (from.inMathed()) {
3738 // If from is at the end of the document (which is possible
3739 // when leaving the mathed) LyX will crash later.
3743 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3748 // Do not increase progress when from == to, otherwise the word
3749 // count will be wrong.