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;
311 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
312 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
314 LYXERR(Debug::INFO, "Buffer::Buffer()");
316 d->inset = static_cast<InsetText *>(cloned_buffer->d->inset->clone());
317 d->inset->setBuffer(*this);
319 d->inset = new InsetText(this);
320 d->inset->setAutoBreakRows(true);
321 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
327 LYXERR(Debug::INFO, "Buffer::~Buffer()");
328 // here the buffer should take care that it is
329 // saved properly, before it goes into the void.
331 // GuiView already destroyed
335 // No need to do additional cleanups for internal buffer.
340 // loop over children
341 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
342 Impl::BufferPositionMap::iterator end = d->children_positions.end();
343 for (; it != end; ++it) {
344 Buffer * child = const_cast<Buffer *>(it->first);
345 // The child buffer might have been closed already.
346 if (theBufferList().isLoaded(child))
347 theBufferList().releaseChild(this, child);
351 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
352 msg += emergencyWrite();
353 Alert::warning(_("Attempting to close changed document!"), msg);
356 // clear references to children in macro tables
357 d->children_positions.clear();
358 d->position_to_children.clear();
360 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
361 Alert::warning(_("Could not remove temporary directory"),
362 bformat(_("Could not remove the temporary directory %1$s"),
363 from_utf8(d->temppath.absFilename())));
366 // Remove any previewed LaTeX snippets associated with this buffer.
367 thePreviews().removeLoader(*this);
373 Buffer * Buffer::clone() const
375 return new Buffer(fileName().absFilename(), false, this);
379 bool Buffer::isClone() const
381 return d->cloned_buffer_;
385 void Buffer::changed() const
392 frontend::WorkAreaManager & Buffer::workAreaManager() const
394 LASSERT(d->wa_, /**/);
399 Text & Buffer::text() const
401 return d->inset->text();
405 Inset & Buffer::inset() const
411 BufferParams & Buffer::params()
417 BufferParams const & Buffer::params() const
423 ParagraphList & Buffer::paragraphs()
425 return text().paragraphs();
429 ParagraphList const & Buffer::paragraphs() const
431 return text().paragraphs();
435 LyXVC & Buffer::lyxvc()
441 LyXVC const & Buffer::lyxvc() const
447 string const Buffer::temppath() const
449 return d->temppath.absFilename();
453 TexRow & Buffer::texrow()
459 TexRow const & Buffer::texrow() const
465 TocBackend & Buffer::tocBackend() const
467 return d->toc_backend;
471 Undo & Buffer::undo()
477 string Buffer::latexName(bool const no_path) const
479 FileName latex_name =
480 makeLatexName(exportFileName());
481 return no_path ? latex_name.onlyFileName()
482 : latex_name.absFilename();
486 FileName Buffer::exportFileName() const
488 docstring const branch_suffix =
489 params().branchlist().getFilenameSuffix();
490 if (branch_suffix.empty())
493 string const name = fileName().onlyFileNameWithoutExt()
494 + to_utf8(branch_suffix);
495 FileName res(fileName().onlyPath().absFilename() + "/" + name);
496 res.changeExtension(fileName().extension());
502 string Buffer::logName(LogType * type) const
504 string const filename = latexName(false);
506 if (filename.empty()) {
512 string const path = temppath();
514 FileName const fname(addName(temppath(),
515 onlyFilename(changeExtension(filename,
518 // FIXME: how do we know this is the name of the build log?
519 FileName const bname(
520 addName(path, onlyFilename(
521 changeExtension(filename,
522 formats.extension(bufferFormat()) + ".out"))));
524 // Also consider the master buffer log file
525 FileName masterfname = fname;
527 if (masterBuffer() != this) {
528 string const mlogfile = masterBuffer()->logName(&mtype);
529 masterfname = FileName(mlogfile);
532 // If no Latex log or Build log is newer, show Build log
533 if (bname.exists() &&
534 ((!fname.exists() && !masterfname.exists())
535 || (fname.lastModified() < bname.lastModified()
536 && masterfname.lastModified() < bname.lastModified()))) {
537 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
540 return bname.absFilename();
541 // If we have a newer master file log or only a master log, show this
542 } else if (fname != masterfname
543 && (!fname.exists() && (masterfname.exists()
544 || fname.lastModified() < masterfname.lastModified()))) {
545 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
548 return masterfname.absFilename();
550 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
553 return fname.absFilename();
557 void Buffer::setReadonly(bool const flag)
559 if (d->read_only != flag) {
566 void Buffer::setFileName(string const & newfile)
568 d->filename = makeAbsPath(newfile);
569 setReadonly(d->filename.isReadOnly());
574 int Buffer::readHeader(Lexer & lex)
576 int unknown_tokens = 0;
578 int begin_header_line = -1;
580 // Initialize parameters that may be/go lacking in header:
581 params().branchlist().clear();
582 params().preamble.erase();
583 params().options.erase();
584 params().master.erase();
585 params().float_placement.erase();
586 params().paperwidth.erase();
587 params().paperheight.erase();
588 params().leftmargin.erase();
589 params().rightmargin.erase();
590 params().topmargin.erase();
591 params().bottommargin.erase();
592 params().headheight.erase();
593 params().headsep.erase();
594 params().footskip.erase();
595 params().columnsep.erase();
596 params().fontsCJK.erase();
597 params().listings_params.clear();
598 params().clearLayoutModules();
599 params().clearRemovedModules();
600 params().pdfoptions().clear();
601 params().indiceslist().clear();
602 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
604 for (int i = 0; i < 4; ++i) {
605 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
606 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
609 ErrorList & errorList = d->errorLists["Parse"];
618 if (token == "\\end_header")
622 if (token == "\\begin_header") {
623 begin_header_line = line;
627 LYXERR(Debug::PARSER, "Handling document header token: `"
630 string unknown = params().readToken(lex, token, d->filename.onlyPath());
631 if (!unknown.empty()) {
632 if (unknown[0] != '\\' && token == "\\textclass") {
633 Alert::warning(_("Unknown document class"),
634 bformat(_("Using the default document class, because the "
635 "class %1$s is unknown."), from_utf8(unknown)));
638 docstring const s = bformat(_("Unknown token: "
642 errorList.push_back(ErrorItem(_("Document header error"),
647 if (begin_header_line) {
648 docstring const s = _("\\begin_header is missing");
649 errorList.push_back(ErrorItem(_("Document header error"),
653 params().makeDocumentClass();
655 return unknown_tokens;
660 // changed to be public and have one parameter
661 // Returns true if "\end_document" is not read (Asger)
662 bool Buffer::readDocument(Lexer & lex)
664 ErrorList & errorList = d->errorLists["Parse"];
667 if (!lex.checkFor("\\begin_document")) {
668 docstring const s = _("\\begin_document is missing");
669 errorList.push_back(ErrorItem(_("Document header error"),
673 // we are reading in a brand new document
674 LASSERT(paragraphs().empty(), /**/);
678 if (params().outputChanges) {
679 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
680 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
681 LaTeXFeatures::isAvailable("xcolor");
683 if (!dvipost && !xcolorulem) {
684 Alert::warning(_("Changes not shown in LaTeX output"),
685 _("Changes will not be highlighted in LaTeX output, "
686 "because neither dvipost nor xcolor/ulem are installed.\n"
687 "Please install these packages or redefine "
688 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
689 } else if (!xcolorulem) {
690 Alert::warning(_("Changes not shown in LaTeX output"),
691 _("Changes will not be highlighted in LaTeX output "
692 "when using pdflatex, because xcolor and ulem are not installed.\n"
693 "Please install both packages or redefine "
694 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
698 if (!params().master.empty()) {
699 FileName const master_file = makeAbsPath(params().master,
700 onlyPath(absFileName()));
701 if (isLyXFilename(master_file.absFilename())) {
703 checkAndLoadLyXFile(master_file, true);
705 // necessary e.g. after a reload
706 // to re-register the child (bug 5873)
707 // FIXME: clean up updateMacros (here, only
708 // child registering is needed).
709 master->updateMacros();
710 // set master as master buffer, but only
711 // if we are a real child
712 if (master->isChild(this))
714 // if the master is not fully loaded
715 // it is probably just loading this
716 // child. No warning needed then.
717 else if (master->isFullyLoaded())
718 LYXERR0("The master '"
720 << "' assigned to this document ("
722 << ") does not include "
723 "this document. Ignoring the master assignment.");
728 // assure we have a default index
729 params().indiceslist().addDefault(B_("Index"));
732 bool const res = text().read(lex, errorList, d->inset);
736 updateMacroInstances();
741 bool Buffer::readString(string const & s)
743 params().compressed = false;
745 // remove dummy empty par
746 paragraphs().clear();
750 FileName const name = FileName::tempName("Buffer_readString");
751 switch (readFile(lex, name, true)) {
755 // We need to call lyx2lyx, so write the input to a file
756 ofstream os(name.toFilesystemEncoding().c_str());
759 return readFile(name);
769 bool Buffer::readFile(FileName const & filename)
771 FileName fname(filename);
773 params().compressed = fname.isZippedFile();
775 // remove dummy empty par
776 paragraphs().clear();
779 if (readFile(lex, fname) != success)
786 bool Buffer::isFullyLoaded() const
788 return d->file_fully_loaded;
792 void Buffer::setFullyLoaded(bool value)
794 d->file_fully_loaded = value;
798 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
801 LASSERT(!filename.empty(), /**/);
803 // the first (non-comment) token _must_ be...
804 if (!lex.checkFor("\\lyxformat")) {
805 Alert::error(_("Document format failure"),
806 bformat(_("%1$s is not a readable LyX document."),
807 from_utf8(filename.absFilename())));
813 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
814 // if present remove ".," from string.
815 size_t dot = tmp_format.find_first_of(".,");
816 //lyxerr << " dot found at " << dot << endl;
817 if (dot != string::npos)
818 tmp_format.erase(dot, 1);
819 int const file_format = convert<int>(tmp_format);
820 //lyxerr << "format: " << file_format << endl;
822 // save timestamp and checksum of the original disk file, making sure
823 // to not overwrite them with those of the file created in the tempdir
824 // when it has to be converted to the current format.
826 // Save the timestamp and checksum of disk file. If filename is an
827 // emergency file, save the timestamp and checksum of the original lyx file
828 // because isExternallyModified will check for this file. (BUG4193)
829 string diskfile = filename.absFilename();
830 if (suffixIs(diskfile, ".emergency"))
831 diskfile = diskfile.substr(0, diskfile.size() - 10);
832 saveCheckSum(FileName(diskfile));
835 if (file_format != LYX_FORMAT) {
838 // lyx2lyx would fail
841 FileName const tmpfile = FileName::tempName("Buffer_readFile");
842 if (tmpfile.empty()) {
843 Alert::error(_("Conversion failed"),
844 bformat(_("%1$s is from a different"
845 " version of LyX, but a temporary"
846 " file for converting it could"
848 from_utf8(filename.absFilename())));
851 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
852 if (lyx2lyx.empty()) {
853 Alert::error(_("Conversion script not found"),
854 bformat(_("%1$s is from a different"
855 " version of LyX, but the"
856 " conversion script lyx2lyx"
857 " could not be found."),
858 from_utf8(filename.absFilename())));
861 ostringstream command;
862 command << os::python()
863 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
864 << " -t " << convert<string>(LYX_FORMAT)
865 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
866 << ' ' << quoteName(filename.toFilesystemEncoding());
867 string const command_str = command.str();
869 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
871 cmd_ret const ret = runCommand(command_str);
872 if (ret.first != 0) {
873 Alert::error(_("Conversion script failed"),
874 bformat(_("%1$s is from a different version"
875 " of LyX, but the lyx2lyx script"
876 " failed to convert it."),
877 from_utf8(filename.absFilename())));
880 bool const ret = readFile(tmpfile);
881 // Do stuff with tmpfile name and buffer name here.
882 return ret ? success : failure;
887 if (readDocument(lex)) {
888 Alert::error(_("Document format failure"),
889 bformat(_("%1$s ended unexpectedly, which means"
890 " that it is probably corrupted."),
891 from_utf8(filename.absFilename())));
894 d->file_fully_loaded = true;
899 // Should probably be moved to somewhere else: BufferView? LyXView?
900 bool Buffer::save() const
902 // We don't need autosaves in the immediate future. (Asger)
903 resetAutosaveTimers();
905 string const encodedFilename = d->filename.toFilesystemEncoding();
908 bool madeBackup = false;
910 // make a backup if the file already exists
911 if (lyxrc.make_backup && fileName().exists()) {
912 backupName = FileName(absFileName() + '~');
913 if (!lyxrc.backupdir_path.empty()) {
914 string const mangledName =
915 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
916 backupName = FileName(addName(lyxrc.backupdir_path,
919 if (fileName().copyTo(backupName)) {
922 Alert::error(_("Backup failure"),
923 bformat(_("Cannot create backup file %1$s.\n"
924 "Please check whether the directory exists and is writeable."),
925 from_utf8(backupName.absFilename())));
926 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
930 // ask if the disk file has been externally modified (use checksum method)
931 if (fileName().exists() && isExternallyModified(checksum_method)) {
932 docstring const file = makeDisplayPath(absFileName(), 20);
933 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
934 "you want to overwrite this file?"), file);
935 int const ret = Alert::prompt(_("Overwrite modified file?"),
936 text, 1, 1, _("&Overwrite"), _("&Cancel"));
941 if (writeFile(d->filename)) {
945 // Saving failed, so backup is not backup
947 backupName.moveTo(d->filename);
953 bool Buffer::writeFile(FileName const & fname) const
955 if (d->read_only && fname == d->filename)
960 docstring const str = bformat(_("Saving document %1$s..."),
961 makeDisplayPath(fname.absFilename()));
964 if (params().compressed) {
965 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
966 retval = ofs && write(ofs);
968 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
969 retval = ofs && write(ofs);
973 message(str + _(" could not write file!"));
977 removeAutosaveFile();
979 saveCheckSum(d->filename);
980 message(str + _(" done."));
986 docstring Buffer::emergencyWrite()
988 // No need to save if the buffer has not changed.
992 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
994 docstring user_message = bformat(
995 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
997 // We try to save three places:
998 // 1) Same place as document. Unless it is an unnamed doc.
1000 string s = absFileName();
1003 if (writeFile(FileName(s))) {
1005 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1006 return user_message;
1008 user_message += _(" Save failed! Trying again...\n");
1012 // 2) In HOME directory.
1013 string s = addName(package().home_dir().absFilename(), absFileName());
1015 lyxerr << ' ' << s << endl;
1016 if (writeFile(FileName(s))) {
1018 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1019 return user_message;
1022 user_message += _(" Save failed! Trying yet again...\n");
1024 // 3) In "/tmp" directory.
1025 // MakeAbsPath to prepend the current
1026 // drive letter on OS/2
1027 s = addName(package().temp_dir().absFilename(), absFileName());
1029 lyxerr << ' ' << s << endl;
1030 if (writeFile(FileName(s))) {
1032 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1033 return user_message;
1036 user_message += _(" Save failed! Bummer. Document is lost.");
1039 return user_message;
1043 bool Buffer::write(ostream & ofs) const
1046 // Use the standard "C" locale for file output.
1047 ofs.imbue(locale::classic());
1050 // The top of the file should not be written by params().
1052 // write out a comment in the top of the file
1053 ofs << "#LyX " << lyx_version
1054 << " created this file. For more info see http://www.lyx.org/\n"
1055 << "\\lyxformat " << LYX_FORMAT << "\n"
1056 << "\\begin_document\n";
1058 /// For each author, set 'used' to true if there is a change
1059 /// by this author in the document; otherwise set it to 'false'.
1060 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1061 AuthorList::Authors::const_iterator a_end = params().authors().end();
1062 for (; a_it != a_end; ++a_it)
1063 a_it->setUsed(false);
1065 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1066 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1067 for ( ; it != end; ++it)
1068 it->checkAuthors(params().authors());
1070 // now write out the buffer parameters.
1071 ofs << "\\begin_header\n";
1072 params().writeFile(ofs);
1073 ofs << "\\end_header\n";
1076 ofs << "\n\\begin_body\n";
1078 ofs << "\n\\end_body\n";
1080 // Write marker that shows file is complete
1081 ofs << "\\end_document" << endl;
1083 // Shouldn't really be needed....
1086 // how to check if close went ok?
1087 // Following is an attempt... (BE 20001011)
1089 // good() returns false if any error occured, including some
1090 // formatting error.
1091 // bad() returns true if something bad happened in the buffer,
1092 // which should include file system full errors.
1097 lyxerr << "File was not closed properly." << endl;
1104 bool Buffer::makeLaTeXFile(FileName const & fname,
1105 string const & original_path,
1106 OutputParams const & runparams_in,
1107 bool output_preamble, bool output_body) const
1109 OutputParams runparams = runparams_in;
1110 if (params().useXetex)
1111 runparams.flavor = OutputParams::XETEX;
1113 string const encoding = runparams.encoding->iconvName();
1114 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1117 try { ofs.reset(encoding); }
1118 catch (iconv_codecvt_facet_exception & e) {
1119 lyxerr << "Caught iconv exception: " << e.what() << endl;
1120 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1121 "verify that the support software for your encoding (%1$s) is "
1122 "properly installed"), from_ascii(encoding)));
1125 if (!openFileWrite(ofs, fname))
1128 //TexStream ts(ofs.rdbuf(), &texrow());
1129 ErrorList & errorList = d->errorLists["Export"];
1131 bool failed_export = false;
1134 writeLaTeXSource(ofs, original_path,
1135 runparams, output_preamble, output_body);
1137 catch (EncodingException & e) {
1138 odocstringstream ods;
1139 ods.put(e.failed_char);
1141 oss << "0x" << hex << e.failed_char << dec;
1142 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1143 " (code point %2$s)"),
1144 ods.str(), from_utf8(oss.str()));
1145 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1146 "representable in the chosen encoding.\n"
1147 "Changing the document encoding to utf8 could help."),
1148 e.par_id, e.pos, e.pos + 1));
1149 failed_export = true;
1151 catch (iconv_codecvt_facet_exception & e) {
1152 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1153 _(e.what()), -1, 0, 0));
1154 failed_export = true;
1156 catch (exception const & e) {
1157 errorList.push_back(ErrorItem(_("conversion failed"),
1158 _(e.what()), -1, 0, 0));
1159 failed_export = true;
1162 lyxerr << "Caught some really weird exception..." << endl;
1168 failed_export = true;
1169 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1173 return !failed_export;
1177 void Buffer::writeLaTeXSource(odocstream & os,
1178 string const & original_path,
1179 OutputParams const & runparams_in,
1180 bool const output_preamble, bool const output_body) const
1182 // The child documents, if any, shall be already loaded at this point.
1184 OutputParams runparams = runparams_in;
1186 // Classify the unicode characters appearing in math insets
1187 Encodings::initUnicodeMath(*this);
1189 // validate the buffer.
1190 LYXERR(Debug::LATEX, " Validating buffer...");
1191 LaTeXFeatures features(*this, params(), runparams);
1193 LYXERR(Debug::LATEX, " Buffer validation done.");
1195 // The starting paragraph of the coming rows is the
1196 // first paragraph of the document. (Asger)
1197 if (output_preamble && runparams.nice) {
1198 os << "%% LyX " << lyx_version << " created this file. "
1199 "For more info, see http://www.lyx.org/.\n"
1200 "%% Do not edit unless you really know what "
1202 d->texrow.newline();
1203 d->texrow.newline();
1205 LYXERR(Debug::INFO, "lyx document header finished");
1207 // Don't move this behind the parent_buffer=0 code below,
1208 // because then the macros will not get the right "redefinition"
1209 // flag as they don't see the parent macros which are output before.
1212 // fold macros if possible, still with parent buffer as the
1213 // macros will be put in the prefix anyway.
1214 updateMacroInstances();
1216 // There are a few differences between nice LaTeX and usual files:
1217 // usual is \batchmode and has a
1218 // special input@path to allow the including of figures
1219 // with either \input or \includegraphics (what figinsets do).
1220 // input@path is set when the actual parameter
1221 // original_path is set. This is done for usual tex-file, but not
1222 // for nice-latex-file. (Matthias 250696)
1223 // Note that input@path is only needed for something the user does
1224 // in the preamble, included .tex files or ERT, files included by
1225 // LyX work without it.
1226 if (output_preamble) {
1227 if (!runparams.nice) {
1228 // code for usual, NOT nice-latex-file
1229 os << "\\batchmode\n"; // changed
1230 // from \nonstopmode
1231 d->texrow.newline();
1233 if (!original_path.empty()) {
1235 // We don't know the encoding of inputpath
1236 docstring const inputpath = from_utf8(latex_path(original_path));
1237 os << "\\makeatletter\n"
1238 << "\\def\\input@path{{"
1239 << inputpath << "/}}\n"
1240 << "\\makeatother\n";
1241 d->texrow.newline();
1242 d->texrow.newline();
1243 d->texrow.newline();
1246 // get parent macros (if this buffer has a parent) which will be
1247 // written at the document begin further down.
1248 MacroSet parentMacros;
1249 listParentMacros(parentMacros, features);
1251 // Write the preamble
1252 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1254 runparams.use_japanese = features.isRequired("japanese");
1260 os << "\\begin{document}\n";
1261 d->texrow.newline();
1263 // output the parent macros
1264 MacroSet::iterator it = parentMacros.begin();
1265 MacroSet::iterator end = parentMacros.end();
1266 for (; it != end; ++it)
1267 (*it)->write(os, true);
1268 } // output_preamble
1270 d->texrow.start(paragraphs().begin()->id(), 0);
1272 LYXERR(Debug::INFO, "preamble finished, now the body.");
1274 // if we are doing a real file with body, even if this is the
1275 // child of some other buffer, let's cut the link here.
1276 // This happens for example if only a child document is printed.
1277 Buffer const * save_parent = 0;
1278 if (output_preamble) {
1279 save_parent = d->parent();
1284 latexParagraphs(*this, text(), os, d->texrow, runparams);
1286 // Restore the parenthood if needed
1287 if (output_preamble)
1288 d->setParent(save_parent);
1290 // add this just in case after all the paragraphs
1292 d->texrow.newline();
1294 if (output_preamble) {
1295 os << "\\end{document}\n";
1296 d->texrow.newline();
1297 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1299 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1301 runparams_in.encoding = runparams.encoding;
1303 // Just to be sure. (Asger)
1304 d->texrow.newline();
1306 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1307 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1311 bool Buffer::isLatex() const
1313 return params().documentClass().outputType() == LATEX;
1317 bool Buffer::isLiterate() const
1319 return params().documentClass().outputType() == LITERATE;
1323 bool Buffer::isDocBook() const
1325 return params().documentClass().outputType() == DOCBOOK;
1329 void Buffer::makeDocBookFile(FileName const & fname,
1330 OutputParams const & runparams,
1331 bool const body_only) const
1333 LYXERR(Debug::LATEX, "makeDocBookFile...");
1336 if (!openFileWrite(ofs, fname))
1339 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1343 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1347 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1348 OutputParams const & runparams,
1349 bool const only_body) const
1351 LaTeXFeatures features(*this, params(), runparams);
1356 DocumentClass const & tclass = params().documentClass();
1357 string const top_element = tclass.latexname();
1360 if (runparams.flavor == OutputParams::XML)
1361 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1364 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1367 if (! tclass.class_header().empty())
1368 os << from_ascii(tclass.class_header());
1369 else if (runparams.flavor == OutputParams::XML)
1370 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1371 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1373 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1375 docstring preamble = from_utf8(params().preamble);
1376 if (runparams.flavor != OutputParams::XML ) {
1377 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1378 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1379 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1380 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1383 string const name = runparams.nice
1384 ? changeExtension(absFileName(), ".sgml") : fname;
1385 preamble += features.getIncludedFiles(name);
1386 preamble += features.getLyXSGMLEntities();
1388 if (!preamble.empty()) {
1389 os << "\n [ " << preamble << " ]";
1394 string top = top_element;
1396 if (runparams.flavor == OutputParams::XML)
1397 top += params().language->code();
1399 top += params().language->code().substr(0, 2);
1402 if (!params().options.empty()) {
1404 top += params().options;
1407 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1408 << " file was created by LyX " << lyx_version
1409 << "\n See http://www.lyx.org/ for more information -->\n";
1411 params().documentClass().counters().reset();
1415 sgml::openTag(os, top);
1417 docbookParagraphs(text(), *this, os, runparams);
1418 sgml::closeTag(os, top_element);
1422 void Buffer::makeLyXHTMLFile(FileName const & fname,
1423 OutputParams const & runparams,
1424 bool const body_only) const
1426 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1429 if (!openFileWrite(ofs, fname))
1432 writeLyXHTMLSource(ofs, runparams, body_only);
1436 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1440 void Buffer::writeLyXHTMLSource(odocstream & os,
1441 OutputParams const & runparams,
1442 bool const only_body) const
1444 LaTeXFeatures features(*this, params(), runparams);
1446 updateLabels(UpdateMaster, true);
1451 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1452 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";
1453 // FIXME Language should be set properly.
1454 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1457 // FIXME Presumably need to set this right
1458 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1459 // FIXME Get this during validation? What about other meta-data?
1460 os << "<title>TBA</title>\n";
1462 os << "\n<!-- Text Class Preamble -->\n"
1463 << features.getTClassHTMLPreamble()
1464 << "\n<!-- Premable Snippets -->\n"
1465 << from_utf8(features.getPreambleSnippets());
1467 os << "\n<!-- Layout-provided Styles -->\n";
1468 docstring const styleinfo = features.getTClassHTMLStyles();
1469 if (!styleinfo.empty()) {
1470 os << "<style type='text/css'>\n"
1474 os << "</head>\n<body>\n";
1478 params().documentClass().counters().reset();
1479 xhtmlParagraphs(text(), *this, xs, runparams);
1481 os << "</body>\n</html>\n";
1485 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1486 // Other flags: -wall -v0 -x
1487 int Buffer::runChktex()
1491 // get LaTeX-Filename
1492 FileName const path(temppath());
1493 string const name = addName(path.absFilename(), latexName());
1494 string const org_path = filePath();
1496 PathChanger p(path); // path to LaTeX file
1497 message(_("Running chktex..."));
1499 // Generate the LaTeX file if neccessary
1500 OutputParams runparams(¶ms().encoding());
1501 runparams.flavor = OutputParams::LATEX;
1502 runparams.nice = false;
1503 makeLaTeXFile(FileName(name), org_path, runparams);
1506 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1507 int const res = chktex.run(terr); // run chktex
1510 Alert::error(_("chktex failure"),
1511 _("Could not run chktex successfully."));
1512 } else if (res > 0) {
1513 ErrorList & errlist = d->errorLists["ChkTeX"];
1515 bufferErrors(terr, errlist);
1526 void Buffer::validate(LaTeXFeatures & features) const
1528 params().validate(features);
1532 for_each(paragraphs().begin(), paragraphs().end(),
1533 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1535 if (lyxerr.debugging(Debug::LATEX)) {
1536 features.showStruct();
1541 void Buffer::getLabelList(vector<docstring> & list) const
1543 // If this is a child document, use the parent's list instead.
1544 Buffer const * const pbuf = d->parent();
1546 pbuf->getLabelList(list);
1551 Toc & toc = d->toc_backend.toc("label");
1552 TocIterator toc_it = toc.begin();
1553 TocIterator end = toc.end();
1554 for (; toc_it != end; ++toc_it) {
1555 if (toc_it->depth() == 0)
1556 list.push_back(toc_it->str());
1561 void Buffer::updateBibfilesCache(UpdateScope scope) const
1563 // If this is a child document, use the parent's cache instead.
1564 Buffer const * const pbuf = d->parent();
1565 if (pbuf && scope != UpdateChildOnly) {
1566 pbuf->updateBibfilesCache();
1570 d->bibfilesCache_.clear();
1571 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1572 if (it->lyxCode() == BIBTEX_CODE) {
1573 InsetBibtex const & inset =
1574 static_cast<InsetBibtex const &>(*it);
1575 support::FileNameList const bibfiles = inset.getBibFiles();
1576 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1579 } else if (it->lyxCode() == INCLUDE_CODE) {
1580 InsetInclude & inset =
1581 static_cast<InsetInclude &>(*it);
1582 inset.updateBibfilesCache();
1583 support::FileNameList const & bibfiles =
1584 inset.getBibfilesCache();
1585 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1590 // the bibinfo cache is now invalid
1591 d->bibinfoCacheValid_ = false;
1595 void Buffer::invalidateBibinfoCache()
1597 d->bibinfoCacheValid_ = false;
1601 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1603 // If this is a child document, use the parent's cache instead.
1604 Buffer const * const pbuf = d->parent();
1605 if (pbuf && scope != UpdateChildOnly)
1606 return pbuf->getBibfilesCache();
1608 // We update the cache when first used instead of at loading time.
1609 if (d->bibfilesCache_.empty())
1610 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1612 return d->bibfilesCache_;
1616 BiblioInfo const & Buffer::masterBibInfo() const
1618 // if this is a child document and the parent is already loaded
1619 // use the parent's list instead [ale990412]
1620 Buffer const * const tmp = masterBuffer();
1623 return tmp->masterBibInfo();
1624 return localBibInfo();
1628 BiblioInfo const & Buffer::localBibInfo() const
1630 if (d->bibinfoCacheValid_) {
1631 support::FileNameList const & bibfilesCache = getBibfilesCache();
1632 // compare the cached timestamps with the actual ones.
1633 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1634 support::FileNameList::const_iterator en = bibfilesCache.end();
1635 for (; ei != en; ++ ei) {
1636 time_t lastw = ei->lastModified();
1637 if (lastw != d->bibfileStatus_[*ei]) {
1638 d->bibinfoCacheValid_ = false;
1639 d->bibfileStatus_[*ei] = lastw;
1645 if (!d->bibinfoCacheValid_) {
1646 d->bibinfo_.clear();
1647 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1648 it->fillWithBibKeys(d->bibinfo_, it);
1649 d->bibinfoCacheValid_ = true;
1655 bool Buffer::isDepClean(string const & name) const
1657 DepClean::const_iterator const it = d->dep_clean.find(name);
1658 if (it == d->dep_clean.end())
1664 void Buffer::markDepClean(string const & name)
1666 d->dep_clean[name] = true;
1670 bool Buffer::isExportableFormat(string const & format) const
1672 typedef vector<Format const *> Formats;
1674 formats = exportableFormats(true);
1675 Formats::const_iterator fit = formats.begin();
1676 Formats::const_iterator end = formats.end();
1677 for (; fit != end ; ++fit) {
1678 if ((*fit)->name() == format)
1685 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1688 // FIXME? if there is an Buffer LFUN that can be dispatched even
1689 // if internal, put a switch '(cmd.action)' here.
1695 switch (cmd.action) {
1697 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1698 flag.setOnOff(isReadonly());
1701 // FIXME: There is need for a command-line import.
1702 //case LFUN_BUFFER_IMPORT:
1704 case LFUN_BUFFER_AUTO_SAVE:
1707 case LFUN_BUFFER_EXPORT_CUSTOM:
1708 // FIXME: Nothing to check here?
1711 case LFUN_BUFFER_EXPORT: {
1712 docstring const arg = cmd.argument();
1713 enable = arg == "custom" || isExportable(to_utf8(arg));
1715 flag.message(bformat(
1716 _("Don't know how to export to format: %1$s"), arg));
1720 case LFUN_BUFFER_CHKTEX:
1721 enable = isLatex() && !lyxrc.chktex_command.empty();
1724 case LFUN_BUILD_PROGRAM:
1725 enable = isExportable("program");
1728 case LFUN_BRANCH_ACTIVATE:
1729 case LFUN_BRANCH_DEACTIVATE: {
1730 BranchList const & branchList = params().branchlist();
1731 docstring const branchName = cmd.argument();
1732 enable = !branchName.empty() && branchList.find(branchName);
1736 case LFUN_BRANCH_ADD:
1737 case LFUN_BRANCHES_RENAME:
1738 case LFUN_BUFFER_PRINT:
1739 // if no Buffer is present, then of course we won't be called!
1742 case LFUN_BUFFER_LANGUAGE:
1743 enable = !isReadonly();
1749 flag.setEnabled(enable);
1754 void Buffer::dispatch(string const & command, DispatchResult & result)
1756 return dispatch(lyxaction.lookupFunc(command), result);
1760 // NOTE We can end up here even if we have no GUI, because we are called
1761 // by LyX::exec to handled command-line requests. So we may need to check
1762 // whether we have a GUI or not. The boolean use_gui holds this information.
1763 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1766 // FIXME? if there is an Buffer LFUN that can be dispatched even
1767 // if internal, put a switch '(cmd.action)' here.
1768 dr.dispatched(false);
1771 string const argument = to_utf8(func.argument());
1772 // We'll set this back to false if need be.
1773 bool dispatched = true;
1774 undo().beginUndoGroup();
1776 switch (func.action) {
1777 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1778 if (lyxvc().inUse())
1779 lyxvc().toggleReadOnly();
1781 setReadonly(!isReadonly());
1784 case LFUN_BUFFER_EXPORT: {
1785 bool success = doExport(argument, false);
1786 dr.setError(success);
1788 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1793 case LFUN_BUILD_PROGRAM:
1794 doExport("program", true);
1797 case LFUN_BUFFER_CHKTEX:
1801 case LFUN_BUFFER_EXPORT_CUSTOM: {
1803 string command = split(argument, format_name, ' ');
1804 Format const * format = formats.getFormat(format_name);
1806 lyxerr << "Format \"" << format_name
1807 << "\" not recognized!"
1812 // The name of the file created by the conversion process
1815 // Output to filename
1816 if (format->name() == "lyx") {
1817 string const latexname = latexName(false);
1818 filename = changeExtension(latexname,
1819 format->extension());
1820 filename = addName(temppath(), filename);
1822 if (!writeFile(FileName(filename)))
1826 doExport(format_name, true, filename);
1829 // Substitute $$FName for filename
1830 if (!contains(command, "$$FName"))
1831 command = "( " + command + " ) < $$FName";
1832 command = subst(command, "$$FName", filename);
1834 // Execute the command in the background
1836 call.startscript(Systemcall::DontWait, command);
1840 // FIXME: There is need for a command-line import.
1842 case LFUN_BUFFER_IMPORT:
1847 case LFUN_BUFFER_AUTO_SAVE:
1851 case LFUN_BRANCH_ADD: {
1852 docstring const branch_name = func.argument();
1853 if (branch_name.empty()) {
1857 BranchList & branch_list = params().branchlist();
1858 Branch * branch = branch_list.find(branch_name);
1860 LYXERR0("Branch " << branch_name << " already exists.");
1862 docstring const msg =
1863 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1866 branch_list.add(branch_name);
1867 branch = branch_list.find(branch_name);
1868 string const x11hexname = X11hexname(branch->color());
1869 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1870 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1872 dr.update(Update::Force);
1877 case LFUN_BRANCH_ACTIVATE:
1878 case LFUN_BRANCH_DEACTIVATE: {
1879 BranchList & branchList = params().branchlist();
1880 docstring const branchName = func.argument();
1881 // the case without a branch name is handled elsewhere
1882 if (branchName.empty()) {
1886 Branch * branch = branchList.find(branchName);
1888 LYXERR0("Branch " << branchName << " does not exist.");
1890 docstring const msg =
1891 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1894 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1896 dr.update(Update::Force);
1901 case LFUN_BRANCHES_RENAME: {
1902 if (func.argument().empty())
1905 docstring const oldname = from_utf8(func.getArg(0));
1906 docstring const newname = from_utf8(func.getArg(1));
1907 InsetIterator it = inset_iterator_begin(inset());
1908 InsetIterator const end = inset_iterator_end(inset());
1909 bool success = false;
1910 for (; it != end; ++it) {
1911 if (it->lyxCode() == BRANCH_CODE) {
1912 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1913 if (ins.branch() == oldname) {
1914 undo().recordUndo(it);
1915 ins.rename(newname);
1920 if (it->lyxCode() == INCLUDE_CODE) {
1921 // get buffer of external file
1922 InsetInclude const & ins =
1923 static_cast<InsetInclude const &>(*it);
1924 Buffer * child = ins.getChildBuffer();
1927 child->dispatch(func, dr);
1932 dr.update(Update::Force);
1936 case LFUN_BUFFER_PRINT: {
1937 // we'll assume there's a problem until we succeed
1939 string target = func.getArg(0);
1940 string target_name = func.getArg(1);
1941 string command = func.getArg(2);
1944 || target_name.empty()
1945 || command.empty()) {
1946 LYXERR0("Unable to parse " << func.argument());
1947 docstring const msg =
1948 bformat(_("Unable to parse \"%1$s\""), func.argument());
1952 if (target != "printer" && target != "file") {
1953 LYXERR0("Unrecognized target \"" << target << '"');
1954 docstring const msg =
1955 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1960 if (!doExport("dvi", true)) {
1961 showPrintError(absFileName());
1962 dr.setMessage(_("Error exporting to DVI."));
1966 // Push directory path.
1967 string const path = temppath();
1968 // Prevent the compiler from optimizing away p
1972 // there are three cases here:
1973 // 1. we print to a file
1974 // 2. we print directly to a printer
1975 // 3. we print using a spool command (print to file first)
1978 string const dviname = changeExtension(latexName(true), "dvi");
1980 if (target == "printer") {
1981 if (!lyxrc.print_spool_command.empty()) {
1982 // case 3: print using a spool
1983 string const psname = changeExtension(dviname,".ps");
1984 command += ' ' + lyxrc.print_to_file
1987 + quoteName(dviname);
1989 string command2 = lyxrc.print_spool_command + ' ';
1990 if (target_name != "default") {
1991 command2 += lyxrc.print_spool_printerprefix
1995 command2 += quoteName(psname);
1997 // If successful, then spool command
1998 res = one.startscript(Systemcall::Wait, command);
2001 // If there's no GUI, we have to wait on this command. Otherwise,
2002 // LyX deletes the temporary directory, and with it the spooled
2003 // file, before it can be printed!!
2004 Systemcall::Starttype stype = use_gui ?
2005 Systemcall::DontWait : Systemcall::Wait;
2006 res = one.startscript(stype, command2);
2009 // case 2: print directly to a printer
2010 if (target_name != "default")
2011 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2013 Systemcall::Starttype stype = use_gui ?
2014 Systemcall::DontWait : Systemcall::Wait;
2015 res = one.startscript(stype, command + quoteName(dviname));
2019 // case 1: print to a file
2020 FileName const filename(makeAbsPath(target_name, filePath()));
2021 FileName const dvifile(makeAbsPath(dviname, path));
2022 if (filename.exists()) {
2023 docstring text = bformat(
2024 _("The file %1$s already exists.\n\n"
2025 "Do you want to overwrite that file?"),
2026 makeDisplayPath(filename.absFilename()));
2027 if (Alert::prompt(_("Overwrite file?"),
2028 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2031 command += ' ' + lyxrc.print_to_file
2032 + quoteName(filename.toFilesystemEncoding())
2034 + quoteName(dvifile.toFilesystemEncoding());
2036 Systemcall::Starttype stype = use_gui ?
2037 Systemcall::DontWait : Systemcall::Wait;
2038 res = one.startscript(stype, command);
2044 dr.setMessage(_("Error running external commands."));
2045 showPrintError(absFileName());
2050 case LFUN_BUFFER_LANGUAGE: {
2051 Language const * oldL = params().language;
2052 Language const * newL = languages.getLanguage(argument);
2053 if (!newL || oldL == newL)
2055 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2056 changeLanguage(oldL, newL);
2064 dr.dispatched(dispatched);
2065 undo().endUndoGroup();
2069 void Buffer::changeLanguage(Language const * from, Language const * to)
2071 LASSERT(from, /**/);
2074 for_each(par_iterator_begin(),
2076 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2080 bool Buffer::isMultiLingual() const
2082 ParConstIterator end = par_iterator_end();
2083 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2084 if (it->isMultiLingual(params()))
2091 DocIterator Buffer::getParFromID(int const id) const
2093 Buffer * buf = const_cast<Buffer *>(this);
2095 // John says this is called with id == -1 from undo
2096 lyxerr << "getParFromID(), id: " << id << endl;
2097 return doc_iterator_end(buf);
2100 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2101 if (it.paragraph().id() == id)
2104 return doc_iterator_end(buf);
2108 bool Buffer::hasParWithID(int const id) const
2110 return !getParFromID(id).atEnd();
2114 ParIterator Buffer::par_iterator_begin()
2116 return ParIterator(doc_iterator_begin(this));
2120 ParIterator Buffer::par_iterator_end()
2122 return ParIterator(doc_iterator_end(this));
2126 ParConstIterator Buffer::par_iterator_begin() const
2128 return ParConstIterator(doc_iterator_begin(this));
2132 ParConstIterator Buffer::par_iterator_end() const
2134 return ParConstIterator(doc_iterator_end(this));
2138 Language const * Buffer::language() const
2140 return params().language;
2144 docstring const Buffer::B_(string const & l10n) const
2146 return params().B_(l10n);
2150 bool Buffer::isClean() const
2152 return d->lyx_clean;
2156 bool Buffer::isBakClean() const
2158 return d->bak_clean;
2162 bool Buffer::isExternallyModified(CheckMethod method) const
2164 LASSERT(d->filename.exists(), /**/);
2165 // if method == timestamp, check timestamp before checksum
2166 return (method == checksum_method
2167 || d->timestamp_ != d->filename.lastModified())
2168 && d->checksum_ != d->filename.checksum();
2172 void Buffer::saveCheckSum(FileName const & file) const
2174 if (file.exists()) {
2175 d->timestamp_ = file.lastModified();
2176 d->checksum_ = file.checksum();
2178 // in the case of save to a new file.
2185 void Buffer::markClean() const
2187 if (!d->lyx_clean) {
2188 d->lyx_clean = true;
2191 // if the .lyx file has been saved, we don't need an
2193 d->bak_clean = true;
2197 void Buffer::markBakClean() const
2199 d->bak_clean = true;
2203 void Buffer::setUnnamed(bool flag)
2209 bool Buffer::isUnnamed() const
2216 /// Don't check unnamed, here: isInternal() is used in
2217 /// newBuffer(), where the unnamed flag has not been set by anyone
2218 /// yet. Also, for an internal buffer, there should be no need for
2219 /// retrieving fileName() nor for checking if it is unnamed or not.
2220 bool Buffer::isInternal() const
2222 return fileName().extension() == "internal";
2226 void Buffer::markDirty()
2229 d->lyx_clean = false;
2232 d->bak_clean = false;
2234 DepClean::iterator it = d->dep_clean.begin();
2235 DepClean::const_iterator const end = d->dep_clean.end();
2237 for (; it != end; ++it)
2242 FileName Buffer::fileName() const
2248 string Buffer::absFileName() const
2250 return d->filename.absFilename();
2254 string Buffer::filePath() const
2256 return d->filename.onlyPath().absFilename() + "/";
2260 bool Buffer::isReadonly() const
2262 return d->read_only;
2266 void Buffer::setParent(Buffer const * buffer)
2268 // Avoids recursive include.
2269 d->setParent(buffer == this ? 0 : buffer);
2274 Buffer const * Buffer::parent() const
2280 void Buffer::collectRelatives(BufferSet & bufs) const
2284 parent()->collectRelatives(bufs);
2286 // loop over children
2287 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2288 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2289 for (; it != end; ++it)
2290 bufs.insert(const_cast<Buffer *>(it->first));
2294 std::vector<Buffer const *> Buffer::allRelatives() const
2297 collectRelatives(bufs);
2298 BufferSet::iterator it = bufs.begin();
2299 std::vector<Buffer const *> ret;
2300 for (; it != bufs.end(); ++it)
2306 Buffer const * Buffer::masterBuffer() const
2308 Buffer const * const pbuf = d->parent();
2312 return pbuf->masterBuffer();
2316 bool Buffer::isChild(Buffer * child) const
2318 return d->children_positions.find(child) != d->children_positions.end();
2322 DocIterator Buffer::firstChildPosition(Buffer const * child)
2324 Impl::BufferPositionMap::iterator it;
2325 it = d->children_positions.find(child);
2326 if (it == d->children_positions.end())
2327 return DocIterator(this);
2332 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2334 std::vector<Buffer *> clist;
2335 // loop over children
2336 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2337 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2338 for (; it != end; ++it) {
2339 Buffer * child = const_cast<Buffer *>(it->first);
2340 clist.push_back(child);
2341 if (grand_children) {
2342 // there might be grandchildren
2343 std::vector<Buffer *> glist = child->getChildren();
2344 for (vector<Buffer *>::const_iterator git = glist.begin();
2345 git != glist.end(); ++git)
2346 clist.push_back(*git);
2353 template<typename M>
2354 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2359 typename M::iterator it = m.lower_bound(x);
2360 if (it == m.begin())
2368 MacroData const * Buffer::getBufferMacro(docstring const & name,
2369 DocIterator const & pos) const
2371 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2373 // if paragraphs have no macro context set, pos will be empty
2377 // we haven't found anything yet
2378 DocIterator bestPos = par_iterator_begin();
2379 MacroData const * bestData = 0;
2381 // find macro definitions for name
2382 Impl::NamePositionScopeMacroMap::iterator nameIt
2383 = d->macros.find(name);
2384 if (nameIt != d->macros.end()) {
2385 // find last definition in front of pos or at pos itself
2386 Impl::PositionScopeMacroMap::const_iterator it
2387 = greatest_below(nameIt->second, pos);
2388 if (it != nameIt->second.end()) {
2390 // scope ends behind pos?
2391 if (pos < it->second.first) {
2392 // Looks good, remember this. If there
2393 // is no external macro behind this,
2394 // we found the right one already.
2395 bestPos = it->first;
2396 bestData = &it->second.second;
2400 // try previous macro if there is one
2401 if (it == nameIt->second.begin())
2408 // find macros in included files
2409 Impl::PositionScopeBufferMap::const_iterator it
2410 = greatest_below(d->position_to_children, pos);
2411 if (it == d->position_to_children.end())
2412 // no children before
2416 // do we know something better (i.e. later) already?
2417 if (it->first < bestPos )
2420 // scope ends behind pos?
2421 if (pos < it->second.first) {
2422 // look for macro in external file
2423 d->macro_lock = true;
2424 MacroData const * data
2425 = it->second.second->getMacro(name, false);
2426 d->macro_lock = false;
2428 bestPos = it->first;
2434 // try previous file if there is one
2435 if (it == d->position_to_children.begin())
2440 // return the best macro we have found
2445 MacroData const * Buffer::getMacro(docstring const & name,
2446 DocIterator const & pos, bool global) const
2451 // query buffer macros
2452 MacroData const * data = getBufferMacro(name, pos);
2456 // If there is a master buffer, query that
2457 Buffer const * const pbuf = d->parent();
2459 d->macro_lock = true;
2460 MacroData const * macro = pbuf->getMacro(
2461 name, *this, false);
2462 d->macro_lock = false;
2468 data = MacroTable::globalMacros().get(name);
2477 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2479 // set scope end behind the last paragraph
2480 DocIterator scope = par_iterator_begin();
2481 scope.pit() = scope.lastpit() + 1;
2483 return getMacro(name, scope, global);
2487 MacroData const * Buffer::getMacro(docstring const & name,
2488 Buffer const & child, bool global) const
2490 // look where the child buffer is included first
2491 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2492 if (it == d->children_positions.end())
2495 // check for macros at the inclusion position
2496 return getMacro(name, it->second, global);
2500 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2502 pit_type lastpit = it.lastpit();
2504 // look for macros in each paragraph
2505 while (it.pit() <= lastpit) {
2506 Paragraph & par = it.paragraph();
2508 // iterate over the insets of the current paragraph
2509 InsetList const & insets = par.insetList();
2510 InsetList::const_iterator iit = insets.begin();
2511 InsetList::const_iterator end = insets.end();
2512 for (; iit != end; ++iit) {
2513 it.pos() = iit->pos;
2515 // is it a nested text inset?
2516 if (iit->inset->asInsetText()) {
2517 // Inset needs its own scope?
2518 InsetText const * itext = iit->inset->asInsetText();
2519 bool newScope = itext->isMacroScope();
2521 // scope which ends just behind the inset
2522 DocIterator insetScope = it;
2525 // collect macros in inset
2526 it.push_back(CursorSlice(*iit->inset));
2527 updateMacros(it, newScope ? insetScope : scope);
2532 // is it an external file?
2533 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2534 // get buffer of external file
2535 InsetInclude const & inset =
2536 static_cast<InsetInclude const &>(*iit->inset);
2537 d->macro_lock = true;
2538 Buffer * child = inset.getChildBuffer();
2539 d->macro_lock = false;
2543 // register its position, but only when it is
2544 // included first in the buffer
2545 if (d->children_positions.find(child) ==
2546 d->children_positions.end())
2547 d->children_positions[child] = it;
2549 // register child with its scope
2550 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2554 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2558 MathMacroTemplate & macroTemplate =
2559 static_cast<MathMacroTemplate &>(*iit->inset);
2560 MacroContext mc(this, it);
2561 macroTemplate.updateToContext(mc);
2564 bool valid = macroTemplate.validMacro();
2565 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2566 // then the BufferView's cursor will be invalid in
2567 // some cases which leads to crashes.
2572 // FIXME (Abdel), I don't understandt why we pass 'it' here
2573 // instead of 'macroTemplate' defined above... is this correct?
2574 d->macros[macroTemplate.name()][it] =
2575 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2585 void Buffer::updateMacros() const
2590 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2592 // start with empty table
2594 d->children_positions.clear();
2595 d->position_to_children.clear();
2597 // Iterate over buffer, starting with first paragraph
2598 // The scope must be bigger than any lookup DocIterator
2599 // later. For the global lookup, lastpit+1 is used, hence
2600 // we use lastpit+2 here.
2601 DocIterator it = par_iterator_begin();
2602 DocIterator outerScope = it;
2603 outerScope.pit() = outerScope.lastpit() + 2;
2604 updateMacros(it, outerScope);
2608 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2610 InsetIterator it = inset_iterator_begin(inset());
2611 InsetIterator const end = inset_iterator_end(inset());
2612 for (; it != end; ++it) {
2613 if (it->lyxCode() == BRANCH_CODE) {
2614 InsetBranch & br = static_cast<InsetBranch &>(*it);
2615 docstring const name = br.branch();
2616 if (!from_master && !params().branchlist().find(name))
2617 result.push_back(name);
2618 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2619 result.push_back(name);
2622 if (it->lyxCode() == INCLUDE_CODE) {
2623 // get buffer of external file
2624 InsetInclude const & ins =
2625 static_cast<InsetInclude const &>(*it);
2626 Buffer * child = ins.getChildBuffer();
2629 child->getUsedBranches(result, true);
2632 // remove duplicates
2637 void Buffer::updateMacroInstances() const
2639 LYXERR(Debug::MACROS, "updateMacroInstances for "
2640 << d->filename.onlyFileName());
2641 DocIterator it = doc_iterator_begin(this);
2643 DocIterator const end = doc_iterator_end(this);
2644 for (; it != end; it.forwardInset()) {
2645 // look for MathData cells in InsetMathNest insets
2646 InsetMath * minset = it.nextInset()->asInsetMath();
2650 // update macro in all cells of the InsetMathNest
2651 DocIterator::idx_type n = minset->nargs();
2652 MacroContext mc = MacroContext(this, it);
2653 for (DocIterator::idx_type i = 0; i < n; ++i) {
2654 MathData & data = minset->cell(i);
2655 data.updateMacros(0, mc);
2661 void Buffer::listMacroNames(MacroNameSet & macros) const
2666 d->macro_lock = true;
2668 // loop over macro names
2669 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2670 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2671 for (; nameIt != nameEnd; ++nameIt)
2672 macros.insert(nameIt->first);
2674 // loop over children
2675 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2676 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2677 for (; it != end; ++it)
2678 it->first->listMacroNames(macros);
2681 Buffer const * const pbuf = d->parent();
2683 pbuf->listMacroNames(macros);
2685 d->macro_lock = false;
2689 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2691 Buffer const * const pbuf = d->parent();
2696 pbuf->listMacroNames(names);
2699 MacroNameSet::iterator it = names.begin();
2700 MacroNameSet::iterator end = names.end();
2701 for (; it != end; ++it) {
2703 MacroData const * data =
2704 pbuf->getMacro(*it, *this, false);
2706 macros.insert(data);
2708 // we cannot access the original MathMacroTemplate anymore
2709 // here to calls validate method. So we do its work here manually.
2710 // FIXME: somehow make the template accessible here.
2711 if (data->optionals() > 0)
2712 features.require("xargs");
2718 Buffer::References & Buffer::references(docstring const & label)
2721 return const_cast<Buffer *>(masterBuffer())->references(label);
2723 RefCache::iterator it = d->ref_cache_.find(label);
2724 if (it != d->ref_cache_.end())
2725 return it->second.second;
2727 static InsetLabel const * dummy_il = 0;
2728 static References const dummy_refs;
2729 it = d->ref_cache_.insert(
2730 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2731 return it->second.second;
2735 Buffer::References const & Buffer::references(docstring const & label) const
2737 return const_cast<Buffer *>(this)->references(label);
2741 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2743 masterBuffer()->d->ref_cache_[label].first = il;
2747 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2749 return masterBuffer()->d->ref_cache_[label].first;
2753 void Buffer::clearReferenceCache() const
2756 d->ref_cache_.clear();
2760 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2763 //FIXME: This does not work for child documents yet.
2764 LASSERT(code == CITE_CODE, /**/);
2765 // Check if the label 'from' appears more than once
2766 vector<docstring> labels;
2768 BiblioInfo const & keys = masterBibInfo();
2769 BiblioInfo::const_iterator bit = keys.begin();
2770 BiblioInfo::const_iterator bend = keys.end();
2772 for (; bit != bend; ++bit)
2774 labels.push_back(bit->first);
2777 if (count(labels.begin(), labels.end(), from) > 1)
2780 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2781 if (it->lyxCode() == code) {
2782 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2783 docstring const oldValue = inset.getParam(paramName);
2784 if (oldValue == from)
2785 inset.setParam(paramName, to);
2791 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2792 pit_type par_end, bool full_source) const
2794 OutputParams runparams(¶ms().encoding());
2795 runparams.nice = true;
2796 runparams.flavor = params().useXetex ?
2797 OutputParams::XETEX : OutputParams::LATEX;
2798 runparams.linelen = lyxrc.plaintext_linelen;
2799 // No side effect of file copying and image conversion
2800 runparams.dryrun = true;
2803 os << "% " << _("Preview source code") << "\n\n";
2805 d->texrow.newline();
2806 d->texrow.newline();
2808 writeDocBookSource(os, absFileName(), runparams, false);
2810 // latex or literate
2811 writeLaTeXSource(os, string(), runparams, true, true);
2813 runparams.par_begin = par_begin;
2814 runparams.par_end = par_end;
2815 if (par_begin + 1 == par_end) {
2817 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2821 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2822 convert<docstring>(par_begin),
2823 convert<docstring>(par_end - 1))
2830 // output paragraphs
2832 docbookParagraphs(text(), *this, os, runparams);
2834 // latex or literate
2835 latexParagraphs(*this, text(), os, texrow, runparams);
2840 ErrorList & Buffer::errorList(string const & type) const
2842 static ErrorList emptyErrorList;
2843 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2844 if (I == d->errorLists.end())
2845 return emptyErrorList;
2851 void Buffer::updateTocItem(std::string const & type,
2852 DocIterator const & dit) const
2855 gui_->updateTocItem(type, dit);
2859 void Buffer::structureChanged() const
2862 gui_->structureChanged();
2866 void Buffer::errors(string const & err, bool from_master) const
2869 gui_->errors(err, from_master);
2873 void Buffer::message(docstring const & msg) const
2880 void Buffer::setBusy(bool on) const
2887 void Buffer::setReadOnly(bool on) const
2890 d->wa_->setReadOnly(on);
2894 void Buffer::updateTitles() const
2897 d->wa_->updateTitles();
2901 void Buffer::resetAutosaveTimers() const
2904 gui_->resetAutosaveTimers();
2908 bool Buffer::hasGuiDelegate() const
2914 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2923 class AutoSaveBuffer : public ForkedProcess {
2926 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2927 : buffer_(buffer), fname_(fname) {}
2929 virtual boost::shared_ptr<ForkedProcess> clone() const
2931 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2936 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2937 from_utf8(fname_.absFilename())));
2938 return run(DontWait);
2942 virtual int generateChild();
2944 Buffer const & buffer_;
2949 int AutoSaveBuffer::generateChild()
2951 #if defined(__APPLE__)
2952 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
2953 * We should use something else like threads.
2955 * Since I do not know how to determine at run time what is the OS X
2956 * version, I just disable forking altogether for now (JMarc)
2958 pid_t const pid = -1;
2960 // tmp_ret will be located (usually) in /tmp
2961 // will that be a problem?
2962 // Note that this calls ForkedCalls::fork(), so it's
2963 // ok cross-platform.
2964 pid_t const pid = fork();
2965 // If you want to debug the autosave
2966 // you should set pid to -1, and comment out the fork.
2967 if (pid != 0 && pid != -1)
2971 // pid = -1 signifies that lyx was unable
2972 // to fork. But we will do the save
2974 bool failed = false;
2975 FileName const tmp_ret = FileName::tempName("lyxauto");
2976 if (!tmp_ret.empty()) {
2977 buffer_.writeFile(tmp_ret);
2978 // assume successful write of tmp_ret
2979 if (!tmp_ret.moveTo(fname_))
2985 // failed to write/rename tmp_ret so try writing direct
2986 if (!buffer_.writeFile(fname_)) {
2987 // It is dangerous to do this in the child,
2988 // but safe in the parent, so...
2989 if (pid == -1) // emit message signal.
2990 buffer_.message(_("Autosave failed!"));
2994 if (pid == 0) // we are the child so...
3003 FileName Buffer::getAutosaveFilename() const
3005 // if the document is unnamed try to save in the backup dir, else
3006 // in the default document path, and as a last try in the filePath,
3007 // which will most often be the temporary directory
3010 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3011 : lyxrc.backupdir_path;
3012 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3015 string const fname = "#" + d->filename.onlyFileName() + "#";
3016 return makeAbsPath(fname, fpath);
3020 void Buffer::removeAutosaveFile() const
3022 FileName const f = getAutosaveFilename();
3028 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3030 FileName const newauto = getAutosaveFilename();
3031 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3032 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3036 // Perfect target for a thread...
3037 void Buffer::autoSave() const
3039 if (isBakClean() || isReadonly()) {
3040 // We don't save now, but we'll try again later
3041 resetAutosaveTimers();
3045 // emit message signal.
3046 message(_("Autosaving current document..."));
3047 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3051 resetAutosaveTimers();
3055 string Buffer::bufferFormat() const
3057 string format = params().documentClass().outputFormat();
3058 if (format == "latex") {
3059 if (params().useXetex)
3061 if (params().encoding().package() == Encoding::japanese)
3068 string Buffer::getDefaultOutputFormat() const
3070 if (!params().defaultOutputFormat.empty()
3071 && params().defaultOutputFormat != "default")
3072 return params().defaultOutputFormat;
3073 typedef vector<Format const *> Formats;
3074 Formats formats = exportableFormats(true);
3077 || params().useXetex
3078 || params().encoding().package() == Encoding::japanese) {
3079 if (formats.empty())
3081 // return the first we find
3082 return formats.front()->name();
3084 return lyxrc.default_view_format;
3089 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3090 string & result_file) const
3092 string backend_format;
3093 OutputParams runparams(¶ms().encoding());
3094 runparams.flavor = OutputParams::LATEX;
3095 runparams.linelen = lyxrc.plaintext_linelen;
3096 vector<string> backs = backends();
3097 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3098 // Get shortest path to format
3099 Graph::EdgePath path;
3100 for (vector<string>::const_iterator it = backs.begin();
3101 it != backs.end(); ++it) {
3102 Graph::EdgePath p = theConverters().getPath(*it, format);
3103 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3104 backend_format = *it;
3109 if (!put_in_tempdir) {
3110 // Only show this alert if this is an export to a non-temporary
3111 // file (not for previewing).
3112 Alert::error(_("Couldn't export file"), bformat(
3113 _("No information for exporting the format %1$s."),
3114 formats.prettyName(format)));
3118 runparams.flavor = theConverters().getFlavor(path);
3121 backend_format = format;
3122 // FIXME: Don't hardcode format names here, but use a flag
3123 if (backend_format == "pdflatex")
3124 runparams.flavor = OutputParams::PDFLATEX;
3127 string filename = latexName(false);
3128 filename = addName(temppath(), filename);
3129 filename = changeExtension(filename,
3130 formats.extension(backend_format));
3133 updateMacroInstances();
3135 // Plain text backend
3136 if (backend_format == "text") {
3137 runparams.flavor = OutputParams::TEXT;
3138 writePlaintextFile(*this, FileName(filename), runparams);
3141 else if (backend_format == "xhtml") {
3142 runparams.flavor = OutputParams::HTML;
3143 makeLyXHTMLFile(FileName(filename), runparams);
3144 } else if (backend_format == "lyx")
3145 writeFile(FileName(filename));
3147 else if (isDocBook()) {
3148 runparams.nice = !put_in_tempdir;
3149 makeDocBookFile(FileName(filename), runparams);
3152 else if (backend_format == format) {
3153 runparams.nice = true;
3154 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3156 } else if (!lyxrc.tex_allows_spaces
3157 && contains(filePath(), ' ')) {
3158 Alert::error(_("File name error"),
3159 _("The directory path to the document cannot contain spaces."));
3162 runparams.nice = false;
3163 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3167 string const error_type = (format == "program")
3168 ? "Build" : bufferFormat();
3169 ErrorList & error_list = d->errorLists[error_type];
3170 string const ext = formats.extension(format);
3171 FileName const tmp_result_file(changeExtension(filename, ext));
3172 bool const success = theConverters().convert(this, FileName(filename),
3173 tmp_result_file, FileName(absFileName()), backend_format, format,
3175 // Emit the signal to show the error list.
3176 if (format != backend_format) {
3178 // also to the children, in case of master-buffer-view
3179 std::vector<Buffer *> clist = getChildren();
3180 for (vector<Buffer *>::const_iterator cit = clist.begin();
3181 cit != clist.end(); ++cit)
3182 (*cit)->errors(error_type, true);
3187 if (put_in_tempdir) {
3188 result_file = tmp_result_file.absFilename();
3192 result_file = changeExtension(exportFileName().absFilename(), ext);
3193 // We need to copy referenced files (e. g. included graphics
3194 // if format == "dvi") to the result dir.
3195 vector<ExportedFile> const files =
3196 runparams.exportdata->externalFiles(format);
3197 string const dest = onlyPath(result_file);
3198 CopyStatus status = SUCCESS;
3199 for (vector<ExportedFile>::const_iterator it = files.begin();
3200 it != files.end() && status != CANCEL; ++it) {
3201 string const fmt = formats.getFormatFromFile(it->sourceName);
3202 status = copyFile(fmt, it->sourceName,
3203 makeAbsPath(it->exportName, dest),
3204 it->exportName, status == FORCE);
3206 if (status == CANCEL) {
3207 message(_("Document export cancelled."));
3208 } else if (tmp_result_file.exists()) {
3209 // Finally copy the main file
3210 status = copyFile(format, tmp_result_file,
3211 FileName(result_file), result_file,
3213 message(bformat(_("Document exported as %1$s "
3215 formats.prettyName(format),
3216 makeDisplayPath(result_file)));
3218 // This must be a dummy converter like fax (bug 1888)
3219 message(bformat(_("Document exported as %1$s"),
3220 formats.prettyName(format)));
3227 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3230 return doExport(format, put_in_tempdir, result_file);
3234 bool Buffer::preview(string const & format) const
3237 if (!doExport(format, true, result_file))
3239 return formats.view(*this, FileName(result_file), format);
3243 bool Buffer::isExportable(string const & format) const
3245 vector<string> backs = backends();
3246 for (vector<string>::const_iterator it = backs.begin();
3247 it != backs.end(); ++it)
3248 if (theConverters().isReachable(*it, format))
3254 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3256 vector<string> const backs = backends();
3257 vector<Format const *> result =
3258 theConverters().getReachable(backs[0], only_viewable, true);
3259 for (vector<string>::const_iterator it = backs.begin() + 1;
3260 it != backs.end(); ++it) {
3261 vector<Format const *> r =
3262 theConverters().getReachable(*it, only_viewable, false);
3263 result.insert(result.end(), r.begin(), r.end());
3269 vector<string> Buffer::backends() const
3272 v.push_back(bufferFormat());
3273 // FIXME: Don't hardcode format names here, but use a flag
3274 if (v.back() == "latex")
3275 v.push_back("pdflatex");
3276 v.push_back("xhtml");
3277 v.push_back("text");
3283 bool Buffer::readFileHelper(FileName const & s)
3285 // File information about normal file
3287 docstring const file = makeDisplayPath(s.absFilename(), 50);
3288 docstring text = bformat(_("The specified document\n%1$s"
3289 "\ncould not be read."), file);
3290 Alert::error(_("Could not read document"), text);
3294 // Check if emergency save file exists and is newer.
3295 FileName const e(s.absFilename() + ".emergency");
3297 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3298 docstring const file = makeDisplayPath(s.absFilename(), 20);
3299 docstring const text =
3300 bformat(_("An emergency save of the document "
3302 "Recover emergency save?"), file);
3303 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3304 _("&Recover"), _("&Load Original"),
3308 // the file is not saved if we load the emergency file.
3313 if ((res = readFile(e)) == success)
3314 str = _("Document was successfully recovered.");
3316 str = _("Document was NOT successfully recovered.");
3317 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3318 from_utf8(e.absFilename()));
3320 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3321 _("&Remove"), _("&Keep it"))) {
3324 Alert::warning(_("Emergency file deleted"),
3325 _("Do not forget to save your file now!"), true);
3330 if (!Alert::prompt(_("Delete emergency file?"),
3331 _("Remove emergency file now?"), 1, 1,
3332 _("&Remove"), _("&Keep it")))
3340 // Now check if autosave file is newer.
3341 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3343 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3344 docstring const file = makeDisplayPath(s.absFilename(), 20);
3345 docstring const text =
3346 bformat(_("The backup of the document "
3347 "%1$s is newer.\n\nLoad the "
3348 "backup instead?"), file);
3349 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3350 _("&Load backup"), _("Load &original"),
3354 // the file is not saved if we load the autosave file.
3358 // Here we delete the autosave
3369 bool Buffer::loadLyXFile(FileName const & s)
3371 if (s.isReadableFile()) {
3372 if (readFileHelper(s)) {
3373 lyxvc().file_found_hook(s);
3374 if (!s.isWritable())
3379 docstring const file = makeDisplayPath(s.absFilename(), 20);
3380 // Here we probably should run
3381 if (LyXVC::file_not_found_hook(s)) {
3382 docstring const text =
3383 bformat(_("Do you want to retrieve the document"
3384 " %1$s from version control?"), file);
3385 int const ret = Alert::prompt(_("Retrieve from version control?"),
3386 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3389 // How can we know _how_ to do the checkout?
3390 // With the current VC support it has to be,
3391 // a RCS file since CVS do not have special ,v files.
3393 return loadLyXFile(s);
3401 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3403 TeXErrors::Errors::const_iterator cit = terr.begin();
3404 TeXErrors::Errors::const_iterator end = terr.end();
3406 for (; cit != end; ++cit) {
3409 int errorRow = cit->error_in_line;
3410 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3416 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3417 } while (found && id_start == id_end && pos_start == pos_end);
3419 errorList.push_back(ErrorItem(cit->error_desc,
3420 cit->error_text, id_start, pos_start, pos_end));
3425 void Buffer::setBuffersForInsets() const
3427 inset().setBuffer(const_cast<Buffer &>(*this));
3431 void Buffer::updateLabels(UpdateScope scope, bool out) const
3433 // Use the master text class also for child documents
3434 Buffer const * const master = masterBuffer();
3435 DocumentClass const & textclass = master->params().documentClass();
3437 // keep the buffers to be children in this set. If the call from the
3438 // master comes back we can see which of them were actually seen (i.e.
3439 // via an InsetInclude). The remaining ones in the set need still be updated.
3440 static std::set<Buffer const *> bufToUpdate;
3441 if (scope == UpdateMaster) {
3442 // If this is a child document start with the master
3443 if (master != this) {
3444 bufToUpdate.insert(this);
3445 master->updateLabels(UpdateMaster, out);
3446 // Do this here in case the master has no gui associated with it. Then,
3447 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3451 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3452 if (bufToUpdate.find(this) == bufToUpdate.end())
3456 // start over the counters in the master
3457 textclass.counters().reset();
3460 // update will be done below for this buffer
3461 bufToUpdate.erase(this);
3463 // update all caches
3464 clearReferenceCache();
3467 Buffer & cbuf = const_cast<Buffer &>(*this);
3469 LASSERT(!text().paragraphs().empty(), /**/);
3472 ParIterator parit = cbuf.par_iterator_begin();
3473 updateLabels(parit, out);
3476 // TocBackend update will be done later.
3479 cbuf.tocBackend().update();
3480 if (scope == UpdateMaster)
3481 cbuf.structureChanged();
3485 static depth_type getDepth(DocIterator const & it)
3487 depth_type depth = 0;
3488 for (size_t i = 0 ; i < it.depth() ; ++i)
3489 if (!it[i].inset().inMathed())
3490 depth += it[i].paragraph().getDepth() + 1;
3491 // remove 1 since the outer inset does not count
3495 static depth_type getItemDepth(ParIterator const & it)
3497 Paragraph const & par = *it;
3498 LabelType const labeltype = par.layout().labeltype;
3500 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3503 // this will hold the lowest depth encountered up to now.
3504 depth_type min_depth = getDepth(it);
3505 ParIterator prev_it = it;
3508 --prev_it.top().pit();
3510 // start of nested inset: go to outer par
3512 if (prev_it.empty()) {
3513 // start of document: nothing to do
3518 // We search for the first paragraph with same label
3519 // that is not more deeply nested.
3520 Paragraph & prev_par = *prev_it;
3521 depth_type const prev_depth = getDepth(prev_it);
3522 if (labeltype == prev_par.layout().labeltype) {
3523 if (prev_depth < min_depth)
3524 return prev_par.itemdepth + 1;
3525 if (prev_depth == min_depth)
3526 return prev_par.itemdepth;
3528 min_depth = min(min_depth, prev_depth);
3529 // small optimization: if we are at depth 0, we won't
3530 // find anything else
3531 if (prev_depth == 0)
3537 static bool needEnumCounterReset(ParIterator const & it)
3539 Paragraph const & par = *it;
3540 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3541 depth_type const cur_depth = par.getDepth();
3542 ParIterator prev_it = it;
3543 while (prev_it.pit()) {
3544 --prev_it.top().pit();
3545 Paragraph const & prev_par = *prev_it;
3546 if (prev_par.getDepth() <= cur_depth)
3547 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3549 // start of nested inset: reset
3554 // set the label of a paragraph. This includes the counters.
3555 void Buffer::setLabel(ParIterator & it) const
3557 BufferParams const & bp = this->masterBuffer()->params();
3558 DocumentClass const & textclass = bp.documentClass();
3559 Paragraph & par = it.paragraph();
3560 Layout const & layout = par.layout();
3561 Counters & counters = textclass.counters();
3563 if (par.params().startOfAppendix()) {
3564 // FIXME: only the counter corresponding to toplevel
3565 // sectioning should be reset
3567 counters.appendix(true);
3569 par.params().appendix(counters.appendix());
3571 // Compute the item depth of the paragraph
3572 par.itemdepth = getItemDepth(it);
3574 if (layout.margintype == MARGIN_MANUAL
3575 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3576 if (par.params().labelWidthString().empty())
3577 par.params().labelWidthString(par.expandLabel(layout, bp));
3579 par.params().labelWidthString(docstring());
3582 switch(layout.labeltype) {
3584 if (layout.toclevel <= bp.secnumdepth
3585 && (layout.latextype != LATEX_ENVIRONMENT
3586 || it.text()->isFirstInSequence(it.pit()))) {
3587 counters.step(layout.counter);
3588 par.params().labelString(
3589 par.expandLabel(layout, bp));
3591 par.params().labelString(docstring());
3594 case LABEL_ITEMIZE: {
3595 // At some point of time we should do something more
3596 // clever here, like:
3597 // par.params().labelString(
3598 // bp.user_defined_bullet(par.itemdepth).getText());
3599 // for now, use a simple hardcoded label
3600 docstring itemlabel;
3601 switch (par.itemdepth) {
3603 itemlabel = char_type(0x2022);
3606 itemlabel = char_type(0x2013);
3609 itemlabel = char_type(0x2217);
3612 itemlabel = char_type(0x2219); // or 0x00b7
3615 par.params().labelString(itemlabel);
3619 case LABEL_ENUMERATE: {
3620 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3622 switch (par.itemdepth) {
3631 enumcounter += "iv";
3634 // not a valid enumdepth...
3638 // Maybe we have to reset the enumeration counter.
3639 if (needEnumCounterReset(it))
3640 counters.reset(enumcounter);
3641 counters.step(enumcounter);
3643 string const & lang = par.getParLanguage(bp)->code();
3644 par.params().labelString(counters.theCounter(enumcounter, lang));
3649 case LABEL_SENSITIVE: {
3650 string const & type = counters.current_float();
3651 docstring full_label;
3653 full_label = this->B_("Senseless!!! ");
3655 docstring name = this->B_(textclass.floats().getType(type).name());
3656 if (counters.hasCounter(from_utf8(type))) {
3657 string const & lang = par.getParLanguage(bp)->code();
3658 counters.step(from_utf8(type));
3659 full_label = bformat(from_ascii("%1$s %2$s:"),
3661 counters.theCounter(from_utf8(type), lang));
3663 full_label = bformat(from_ascii("%1$s #:"), name);
3665 par.params().labelString(full_label);
3669 case LABEL_NO_LABEL:
3670 par.params().labelString(docstring());
3674 case LABEL_TOP_ENVIRONMENT:
3675 case LABEL_CENTERED_TOP_ENVIRONMENT:
3678 par.params().labelString(par.expandLabel(layout, bp));
3684 void Buffer::updateLabels(ParIterator & parit, bool out) const
3686 LASSERT(parit.pit() == 0, /**/);
3688 // set the position of the text in the buffer to be able
3689 // to resolve macros in it. This has nothing to do with
3690 // labels, but by putting it here we avoid implementing
3691 // a whole bunch of traversal routines just for this call.
3692 parit.text()->setMacrocontextPosition(parit);
3694 depth_type maxdepth = 0;
3695 pit_type const lastpit = parit.lastpit();
3696 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3697 // reduce depth if necessary
3698 parit->params().depth(min(parit->params().depth(), maxdepth));
3699 maxdepth = parit->getMaxDepthAfter();
3701 // set the counter for this paragraph
3705 InsetList::const_iterator iit = parit->insetList().begin();
3706 InsetList::const_iterator end = parit->insetList().end();
3707 for (; iit != end; ++iit) {
3708 parit.pos() = iit->pos;
3709 iit->inset->updateLabels(parit, out);
3715 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3716 WordLangTuple & word_lang, docstring_list & suggestions) const
3720 suggestions.clear();
3721 word_lang = WordLangTuple();
3722 // OK, we start from here.
3723 DocIterator const end = doc_iterator_end(this);
3724 for (; from != end; from.forwardPos()) {
3725 // We are only interested in text so remove the math CursorSlice.
3726 while (from.inMathed()) {
3730 // If from is at the end of the document (which is possible
3731 // when leaving the mathed) LyX will crash later.
3735 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3740 // Do not increase progress when from == to, otherwise the word
3741 // count will be wrong.