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 = 375; // jspitzm: includeonly support
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfiles_cache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfo_cache_valid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfile_status_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) {
257 if (parent_buffer && pb && parent_buffer != pb)
258 LYXERR0("Warning: a buffer should not have two parents!");
262 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263 /// This one is useful for preview detached in a thread.
264 Buffer const * cloned_buffer_;
267 /// So we can force access via the accessors.
268 mutable Buffer const * parent_buffer;
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
277 // We are in our own directory. Why bother to mangle name?
278 // In fact I wrote this code to circumvent a problematic behaviour
279 // (bug?) of EMX mkstemp().
280 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281 convert<string>(count++));
283 if (!tmpfl.createDirectory(0777)) {
284 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286 from_utf8(tmpfl.absFilename())));
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293 Buffer const * cloned_buffer)
294 : lyx_clean(true), bak_clean(true), unnamed(false),
295 read_only(readonly_), filename(file), file_fully_loaded(false),
296 toc_backend(&parent), macro_lock(false), timestamp_(0),
297 checksum_(0), wa_(0), undo_(parent), bibinfo_cache_valid_(false),
298 cloned_buffer_(cloned_buffer), parent_buffer(0)
300 if (!cloned_buffer_) {
301 temppath = createBufferTmpDir();
302 lyxvc.setBuffer(&parent);
304 wa_ = new frontend::WorkAreaManager;
307 temppath = cloned_buffer_->d->temppath;
308 file_fully_loaded = true;
309 params = cloned_buffer_->d->params;
313 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
314 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
316 LYXERR(Debug::INFO, "Buffer::Buffer()");
318 d->inset = new InsetText(*cloned_buffer->d->inset);
319 d->inset->setBuffer(*this);
320 // FIXME: optimize this loop somewhat, maybe by creating a new
321 // general recursive Inset::setId().
322 DocIterator it = doc_iterator_begin(this);
323 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
324 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
325 it.paragraph().setId(cloned_it.paragraph().id());
327 d->inset = new InsetText(this);
328 d->inset->setAutoBreakRows(true);
329 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
335 LYXERR(Debug::INFO, "Buffer::~Buffer()");
336 // here the buffer should take care that it is
337 // saved properly, before it goes into the void.
339 // GuiView already destroyed
343 // No need to do additional cleanups for internal buffer.
348 // loop over children
349 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
350 Impl::BufferPositionMap::iterator end = d->children_positions.end();
351 for (; it != end; ++it) {
352 Buffer * child = const_cast<Buffer *>(it->first);
353 if (d->cloned_buffer_)
355 // The child buffer might have been closed already.
356 else if (theBufferList().isLoaded(child))
357 theBufferList().releaseChild(this, child);
361 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
362 msg += emergencyWrite();
363 Alert::warning(_("Attempting to close changed document!"), msg);
366 // clear references to children in macro tables
367 d->children_positions.clear();
368 d->position_to_children.clear();
370 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
371 Alert::warning(_("Could not remove temporary directory"),
372 bformat(_("Could not remove the temporary directory %1$s"),
373 from_utf8(d->temppath.absFilename())));
376 // Remove any previewed LaTeX snippets associated with this buffer.
377 thePreviews().removeLoader(*this);
383 Buffer * Buffer::clone() const
385 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
386 buffer_clone->d->macro_lock = true;
387 buffer_clone->d->children_positions.clear();
388 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
389 // math macro caches need to be rethought and simplified.
390 // I am not sure wether we should handle Buffer cloning here or in BufferList.
391 // Right now BufferList knows nothing about buffer clones.
392 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
393 Impl::BufferPositionMap::iterator end = d->children_positions.end();
394 for (; it != end; ++it) {
395 DocIterator dit = it->second.clone(buffer_clone);
396 dit.setBuffer(buffer_clone);
397 Buffer * child = const_cast<Buffer *>(it->first);
398 Buffer * child_clone = child->clone();
399 Inset * inset = dit.nextInset();
400 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
401 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
402 inset_inc->setChildBuffer(child_clone);
403 child_clone->d->setParent(buffer_clone);
404 buffer_clone->setChild(dit, child_clone);
410 bool Buffer::isClone() const
412 return d->cloned_buffer_;
416 void Buffer::changed(bool update_metrics) const
419 d->wa_->redrawAll(update_metrics);
423 frontend::WorkAreaManager & Buffer::workAreaManager() const
425 LASSERT(d->wa_, /**/);
430 Text & Buffer::text() const
432 return d->inset->text();
436 Inset & Buffer::inset() const
442 BufferParams & Buffer::params()
448 BufferParams const & Buffer::params() const
454 ParagraphList & Buffer::paragraphs()
456 return text().paragraphs();
460 ParagraphList const & Buffer::paragraphs() const
462 return text().paragraphs();
466 LyXVC & Buffer::lyxvc()
472 LyXVC const & Buffer::lyxvc() const
478 string const Buffer::temppath() const
480 return d->temppath.absFilename();
484 TexRow & Buffer::texrow()
490 TexRow const & Buffer::texrow() const
496 TocBackend & Buffer::tocBackend() const
498 return d->toc_backend;
502 Undo & Buffer::undo()
508 void Buffer::setChild(DocIterator const & dit, Buffer * child)
510 d->children_positions[child] = dit;
514 string Buffer::latexName(bool const no_path) const
516 FileName latex_name =
517 makeLatexName(exportFileName());
518 return no_path ? latex_name.onlyFileName()
519 : latex_name.absFilename();
523 FileName Buffer::exportFileName() const
525 docstring const branch_suffix =
526 params().branchlist().getFilenameSuffix();
527 if (branch_suffix.empty())
530 string const name = fileName().onlyFileNameWithoutExt()
531 + to_utf8(branch_suffix);
532 FileName res(fileName().onlyPath().absFilename() + "/" + name);
533 res.changeExtension(fileName().extension());
539 string Buffer::logName(LogType * type) const
541 string const filename = latexName(false);
543 if (filename.empty()) {
549 string const path = temppath();
551 FileName const fname(addName(temppath(),
552 onlyFilename(changeExtension(filename,
555 // FIXME: how do we know this is the name of the build log?
556 FileName const bname(
557 addName(path, onlyFilename(
558 changeExtension(filename,
559 formats.extension(bufferFormat()) + ".out"))));
561 // Also consider the master buffer log file
562 FileName masterfname = fname;
564 if (masterBuffer() != this) {
565 string const mlogfile = masterBuffer()->logName(&mtype);
566 masterfname = FileName(mlogfile);
569 // If no Latex log or Build log is newer, show Build log
570 if (bname.exists() &&
571 ((!fname.exists() && !masterfname.exists())
572 || (fname.lastModified() < bname.lastModified()
573 && masterfname.lastModified() < bname.lastModified()))) {
574 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
577 return bname.absFilename();
578 // If we have a newer master file log or only a master log, show this
579 } else if (fname != masterfname
580 && (!fname.exists() && (masterfname.exists()
581 || fname.lastModified() < masterfname.lastModified()))) {
582 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
585 return masterfname.absFilename();
587 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
590 return fname.absFilename();
594 void Buffer::setReadonly(bool const flag)
596 if (d->read_only != flag) {
603 void Buffer::setFileName(string const & newfile)
605 d->filename = makeAbsPath(newfile);
606 setReadonly(d->filename.isReadOnly());
611 int Buffer::readHeader(Lexer & lex)
613 int unknown_tokens = 0;
615 int begin_header_line = -1;
617 // Initialize parameters that may be/go lacking in header:
618 params().branchlist().clear();
619 params().preamble.erase();
620 params().options.erase();
621 params().master.erase();
622 params().float_placement.erase();
623 params().paperwidth.erase();
624 params().paperheight.erase();
625 params().leftmargin.erase();
626 params().rightmargin.erase();
627 params().topmargin.erase();
628 params().bottommargin.erase();
629 params().headheight.erase();
630 params().headsep.erase();
631 params().footskip.erase();
632 params().columnsep.erase();
633 params().fontsCJK.erase();
634 params().listings_params.clear();
635 params().clearLayoutModules();
636 params().clearRemovedModules();
637 params().clearIncludedChildren();
638 params().pdfoptions().clear();
639 params().indiceslist().clear();
640 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
642 for (int i = 0; i < 4; ++i) {
643 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
644 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
647 ErrorList & errorList = d->errorLists["Parse"];
656 if (token == "\\end_header")
660 if (token == "\\begin_header") {
661 begin_header_line = line;
665 LYXERR(Debug::PARSER, "Handling document header token: `"
668 string unknown = params().readToken(lex, token, d->filename.onlyPath());
669 if (!unknown.empty()) {
670 if (unknown[0] != '\\' && token == "\\textclass") {
671 Alert::warning(_("Unknown document class"),
672 bformat(_("Using the default document class, because the "
673 "class %1$s is unknown."), from_utf8(unknown)));
676 docstring const s = bformat(_("Unknown token: "
680 errorList.push_back(ErrorItem(_("Document header error"),
685 if (begin_header_line) {
686 docstring const s = _("\\begin_header is missing");
687 errorList.push_back(ErrorItem(_("Document header error"),
691 params().makeDocumentClass();
693 return unknown_tokens;
698 // changed to be public and have one parameter
699 // Returns true if "\end_document" is not read (Asger)
700 bool Buffer::readDocument(Lexer & lex)
702 ErrorList & errorList = d->errorLists["Parse"];
705 if (!lex.checkFor("\\begin_document")) {
706 docstring const s = _("\\begin_document is missing");
707 errorList.push_back(ErrorItem(_("Document header error"),
711 // we are reading in a brand new document
712 LASSERT(paragraphs().empty(), /**/);
716 if (params().outputChanges) {
717 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
718 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
719 LaTeXFeatures::isAvailable("xcolor");
721 if (!dvipost && !xcolorulem) {
722 Alert::warning(_("Changes not shown in LaTeX output"),
723 _("Changes will not be highlighted in LaTeX output, "
724 "because neither dvipost nor xcolor/ulem are installed.\n"
725 "Please install these packages or redefine "
726 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
727 } else if (!xcolorulem) {
728 Alert::warning(_("Changes not shown in LaTeX output"),
729 _("Changes will not be highlighted in LaTeX output "
730 "when using pdflatex, because xcolor and ulem are not installed.\n"
731 "Please install both packages or redefine "
732 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
736 if (!params().master.empty()) {
737 FileName const master_file = makeAbsPath(params().master,
738 onlyPath(absFileName()));
739 if (isLyXFilename(master_file.absFilename())) {
741 checkAndLoadLyXFile(master_file, true);
743 // necessary e.g. after a reload
744 // to re-register the child (bug 5873)
745 // FIXME: clean up updateMacros (here, only
746 // child registering is needed).
747 master->updateMacros();
748 // set master as master buffer, but only
749 // if we are a real child
750 if (master->isChild(this))
752 // if the master is not fully loaded
753 // it is probably just loading this
754 // child. No warning needed then.
755 else if (master->isFullyLoaded())
756 LYXERR0("The master '"
758 << "' assigned to this document ("
760 << ") does not include "
761 "this document. Ignoring the master assignment.");
766 // assure we have a default index
767 params().indiceslist().addDefault(B_("Index"));
770 bool const res = text().read(lex, errorList, d->inset);
774 updateMacroInstances();
779 bool Buffer::readString(string const & s)
781 params().compressed = false;
783 // remove dummy empty par
784 paragraphs().clear();
788 FileName const name = FileName::tempName("Buffer_readString");
789 switch (readFile(lex, name, true)) {
793 // We need to call lyx2lyx, so write the input to a file
794 ofstream os(name.toFilesystemEncoding().c_str());
797 return readFile(name);
807 bool Buffer::readFile(FileName const & filename)
809 FileName fname(filename);
811 params().compressed = fname.isZippedFile();
813 // remove dummy empty par
814 paragraphs().clear();
817 if (readFile(lex, fname) != success)
824 bool Buffer::isFullyLoaded() const
826 return d->file_fully_loaded;
830 void Buffer::setFullyLoaded(bool value)
832 d->file_fully_loaded = value;
836 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
839 LASSERT(!filename.empty(), /**/);
841 // the first (non-comment) token _must_ be...
842 if (!lex.checkFor("\\lyxformat")) {
843 Alert::error(_("Document format failure"),
844 bformat(_("%1$s is not a readable LyX document."),
845 from_utf8(filename.absFilename())));
851 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
852 // if present remove ".," from string.
853 size_t dot = tmp_format.find_first_of(".,");
854 //lyxerr << " dot found at " << dot << endl;
855 if (dot != string::npos)
856 tmp_format.erase(dot, 1);
857 int const file_format = convert<int>(tmp_format);
858 //lyxerr << "format: " << file_format << endl;
860 // save timestamp and checksum of the original disk file, making sure
861 // to not overwrite them with those of the file created in the tempdir
862 // when it has to be converted to the current format.
864 // Save the timestamp and checksum of disk file. If filename is an
865 // emergency file, save the timestamp and checksum of the original lyx file
866 // because isExternallyModified will check for this file. (BUG4193)
867 string diskfile = filename.absFilename();
868 if (suffixIs(diskfile, ".emergency"))
869 diskfile = diskfile.substr(0, diskfile.size() - 10);
870 saveCheckSum(FileName(diskfile));
873 if (file_format != LYX_FORMAT) {
876 // lyx2lyx would fail
879 FileName const tmpfile = FileName::tempName("Buffer_readFile");
880 if (tmpfile.empty()) {
881 Alert::error(_("Conversion failed"),
882 bformat(_("%1$s is from a different"
883 " version of LyX, but a temporary"
884 " file for converting it could"
886 from_utf8(filename.absFilename())));
889 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
890 if (lyx2lyx.empty()) {
891 Alert::error(_("Conversion script not found"),
892 bformat(_("%1$s is from a different"
893 " version of LyX, but the"
894 " conversion script lyx2lyx"
895 " could not be found."),
896 from_utf8(filename.absFilename())));
899 ostringstream command;
900 command << os::python()
901 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
902 << " -t " << convert<string>(LYX_FORMAT)
903 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
904 << ' ' << quoteName(filename.toFilesystemEncoding());
905 string const command_str = command.str();
907 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
909 cmd_ret const ret = runCommand(command_str);
910 if (ret.first != 0) {
911 Alert::error(_("Conversion script failed"),
912 bformat(_("%1$s is from a different version"
913 " of LyX, but the lyx2lyx script"
914 " failed to convert it."),
915 from_utf8(filename.absFilename())));
918 bool const ret = readFile(tmpfile);
919 // Do stuff with tmpfile name and buffer name here.
920 return ret ? success : failure;
925 if (readDocument(lex)) {
926 Alert::error(_("Document format failure"),
927 bformat(_("%1$s ended unexpectedly, which means"
928 " that it is probably corrupted."),
929 from_utf8(filename.absFilename())));
932 d->file_fully_loaded = true;
937 // Should probably be moved to somewhere else: BufferView? LyXView?
938 bool Buffer::save() const
940 // We don't need autosaves in the immediate future. (Asger)
941 resetAutosaveTimers();
943 string const encodedFilename = d->filename.toFilesystemEncoding();
946 bool madeBackup = false;
948 // make a backup if the file already exists
949 if (lyxrc.make_backup && fileName().exists()) {
950 backupName = FileName(absFileName() + '~');
951 if (!lyxrc.backupdir_path.empty()) {
952 string const mangledName =
953 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
954 backupName = FileName(addName(lyxrc.backupdir_path,
957 if (fileName().copyTo(backupName)) {
960 Alert::error(_("Backup failure"),
961 bformat(_("Cannot create backup file %1$s.\n"
962 "Please check whether the directory exists and is writeable."),
963 from_utf8(backupName.absFilename())));
964 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
968 // ask if the disk file has been externally modified (use checksum method)
969 if (fileName().exists() && isExternallyModified(checksum_method)) {
970 docstring const file = makeDisplayPath(absFileName(), 20);
971 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
972 "you want to overwrite this file?"), file);
973 int const ret = Alert::prompt(_("Overwrite modified file?"),
974 text, 1, 1, _("&Overwrite"), _("&Cancel"));
979 if (writeFile(d->filename)) {
983 // Saving failed, so backup is not backup
985 backupName.moveTo(d->filename);
991 bool Buffer::writeFile(FileName const & fname) const
993 if (d->read_only && fname == d->filename)
998 docstring const str = bformat(_("Saving document %1$s..."),
999 makeDisplayPath(fname.absFilename()));
1002 if (params().compressed) {
1003 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1004 retval = ofs && write(ofs);
1006 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1007 retval = ofs && write(ofs);
1011 message(str + _(" could not write file!"));
1015 removeAutosaveFile();
1017 saveCheckSum(d->filename);
1018 message(str + _(" done."));
1024 docstring Buffer::emergencyWrite()
1026 // No need to save if the buffer has not changed.
1030 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1032 docstring user_message = bformat(
1033 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1035 // We try to save three places:
1036 // 1) Same place as document. Unless it is an unnamed doc.
1038 string s = absFileName();
1041 if (writeFile(FileName(s))) {
1043 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1044 return user_message;
1046 user_message += _(" Save failed! Trying again...\n");
1050 // 2) In HOME directory.
1051 string s = addName(package().home_dir().absFilename(), absFileName());
1053 lyxerr << ' ' << s << endl;
1054 if (writeFile(FileName(s))) {
1056 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1057 return user_message;
1060 user_message += _(" Save failed! Trying yet again...\n");
1062 // 3) In "/tmp" directory.
1063 // MakeAbsPath to prepend the current
1064 // drive letter on OS/2
1065 s = addName(package().temp_dir().absFilename(), absFileName());
1067 lyxerr << ' ' << s << endl;
1068 if (writeFile(FileName(s))) {
1070 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1071 return user_message;
1074 user_message += _(" Save failed! Bummer. Document is lost.");
1077 return user_message;
1081 bool Buffer::write(ostream & ofs) const
1084 // Use the standard "C" locale for file output.
1085 ofs.imbue(locale::classic());
1088 // The top of the file should not be written by params().
1090 // write out a comment in the top of the file
1091 ofs << "#LyX " << lyx_version
1092 << " created this file. For more info see http://www.lyx.org/\n"
1093 << "\\lyxformat " << LYX_FORMAT << "\n"
1094 << "\\begin_document\n";
1096 /// For each author, set 'used' to true if there is a change
1097 /// by this author in the document; otherwise set it to 'false'.
1098 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1099 AuthorList::Authors::const_iterator a_end = params().authors().end();
1100 for (; a_it != a_end; ++a_it)
1101 a_it->setUsed(false);
1103 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1104 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1105 for ( ; it != end; ++it)
1106 it->checkAuthors(params().authors());
1108 // now write out the buffer parameters.
1109 ofs << "\\begin_header\n";
1110 params().writeFile(ofs);
1111 ofs << "\\end_header\n";
1114 ofs << "\n\\begin_body\n";
1116 ofs << "\n\\end_body\n";
1118 // Write marker that shows file is complete
1119 ofs << "\\end_document" << endl;
1121 // Shouldn't really be needed....
1124 // how to check if close went ok?
1125 // Following is an attempt... (BE 20001011)
1127 // good() returns false if any error occured, including some
1128 // formatting error.
1129 // bad() returns true if something bad happened in the buffer,
1130 // which should include file system full errors.
1135 lyxerr << "File was not closed properly." << endl;
1142 bool Buffer::makeLaTeXFile(FileName const & fname,
1143 string const & original_path,
1144 OutputParams const & runparams_in,
1145 bool output_preamble, bool output_body) const
1147 OutputParams runparams = runparams_in;
1148 if (params().useXetex)
1149 runparams.flavor = OutputParams::XETEX;
1151 string const encoding = runparams.encoding->iconvName();
1152 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1155 try { ofs.reset(encoding); }
1156 catch (iconv_codecvt_facet_exception & e) {
1157 lyxerr << "Caught iconv exception: " << e.what() << endl;
1158 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1159 "verify that the support software for your encoding (%1$s) is "
1160 "properly installed"), from_ascii(encoding)));
1163 if (!openFileWrite(ofs, fname))
1166 //TexStream ts(ofs.rdbuf(), &texrow());
1167 ErrorList & errorList = d->errorLists["Export"];
1169 bool failed_export = false;
1172 writeLaTeXSource(ofs, original_path,
1173 runparams, output_preamble, output_body);
1175 catch (EncodingException & e) {
1176 odocstringstream ods;
1177 ods.put(e.failed_char);
1179 oss << "0x" << hex << e.failed_char << dec;
1180 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1181 " (code point %2$s)"),
1182 ods.str(), from_utf8(oss.str()));
1183 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1184 "representable in the chosen encoding.\n"
1185 "Changing the document encoding to utf8 could help."),
1186 e.par_id, e.pos, e.pos + 1));
1187 failed_export = true;
1189 catch (iconv_codecvt_facet_exception & e) {
1190 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1191 _(e.what()), -1, 0, 0));
1192 failed_export = true;
1194 catch (exception const & e) {
1195 errorList.push_back(ErrorItem(_("conversion failed"),
1196 _(e.what()), -1, 0, 0));
1197 failed_export = true;
1200 lyxerr << "Caught some really weird exception..." << endl;
1206 failed_export = true;
1207 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1211 return !failed_export;
1215 void Buffer::writeLaTeXSource(odocstream & os,
1216 string const & original_path,
1217 OutputParams const & runparams_in,
1218 bool const output_preamble, bool const output_body) const
1220 // The child documents, if any, shall be already loaded at this point.
1222 OutputParams runparams = runparams_in;
1224 // Classify the unicode characters appearing in math insets
1225 Encodings::initUnicodeMath(*this);
1227 // validate the buffer.
1228 LYXERR(Debug::LATEX, " Validating buffer...");
1229 LaTeXFeatures features(*this, params(), runparams);
1231 LYXERR(Debug::LATEX, " Buffer validation done.");
1233 // The starting paragraph of the coming rows is the
1234 // first paragraph of the document. (Asger)
1235 if (output_preamble && runparams.nice) {
1236 os << "%% LyX " << lyx_version << " created this file. "
1237 "For more info, see http://www.lyx.org/.\n"
1238 "%% Do not edit unless you really know what "
1240 d->texrow.newline();
1241 d->texrow.newline();
1243 LYXERR(Debug::INFO, "lyx document header finished");
1245 // Don't move this behind the parent_buffer=0 code below,
1246 // because then the macros will not get the right "redefinition"
1247 // flag as they don't see the parent macros which are output before.
1250 // fold macros if possible, still with parent buffer as the
1251 // macros will be put in the prefix anyway.
1252 updateMacroInstances();
1254 // There are a few differences between nice LaTeX and usual files:
1255 // usual is \batchmode and has a
1256 // special input@path to allow the including of figures
1257 // with either \input or \includegraphics (what figinsets do).
1258 // input@path is set when the actual parameter
1259 // original_path is set. This is done for usual tex-file, but not
1260 // for nice-latex-file. (Matthias 250696)
1261 // Note that input@path is only needed for something the user does
1262 // in the preamble, included .tex files or ERT, files included by
1263 // LyX work without it.
1264 if (output_preamble) {
1265 if (!runparams.nice) {
1266 // code for usual, NOT nice-latex-file
1267 os << "\\batchmode\n"; // changed
1268 // from \nonstopmode
1269 d->texrow.newline();
1271 if (!original_path.empty()) {
1273 // We don't know the encoding of inputpath
1274 docstring const inputpath = from_utf8(latex_path(original_path));
1275 os << "\\makeatletter\n"
1276 << "\\def\\input@path{{"
1277 << inputpath << "/}}\n"
1278 << "\\makeatother\n";
1279 d->texrow.newline();
1280 d->texrow.newline();
1281 d->texrow.newline();
1284 // get parent macros (if this buffer has a parent) which will be
1285 // written at the document begin further down.
1286 MacroSet parentMacros;
1287 listParentMacros(parentMacros, features);
1289 // Write the preamble
1290 runparams.use_babel = params().writeLaTeX(os, features,
1292 d->filename.onlyPath());
1294 runparams.use_japanese = features.isRequired("japanese");
1300 os << "\\begin{document}\n";
1301 d->texrow.newline();
1303 // output the parent macros
1304 MacroSet::iterator it = parentMacros.begin();
1305 MacroSet::iterator end = parentMacros.end();
1306 for (; it != end; ++it)
1307 (*it)->write(os, true);
1308 } // output_preamble
1310 d->texrow.start(paragraphs().begin()->id(), 0);
1312 LYXERR(Debug::INFO, "preamble finished, now the body.");
1314 // if we are doing a real file with body, even if this is the
1315 // child of some other buffer, let's cut the link here.
1316 // This happens for example if only a child document is printed.
1317 Buffer const * save_parent = 0;
1318 if (output_preamble) {
1319 save_parent = d->parent();
1324 latexParagraphs(*this, text(), os, d->texrow, runparams);
1326 // Restore the parenthood if needed
1327 if (output_preamble)
1328 d->setParent(save_parent);
1330 // add this just in case after all the paragraphs
1332 d->texrow.newline();
1334 if (output_preamble) {
1335 os << "\\end{document}\n";
1336 d->texrow.newline();
1337 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1339 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1341 runparams_in.encoding = runparams.encoding;
1343 // Just to be sure. (Asger)
1344 d->texrow.newline();
1346 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1347 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1351 bool Buffer::isLatex() const
1353 return params().documentClass().outputType() == LATEX;
1357 bool Buffer::isLiterate() const
1359 return params().documentClass().outputType() == LITERATE;
1363 bool Buffer::isDocBook() const
1365 return params().documentClass().outputType() == DOCBOOK;
1369 void Buffer::makeDocBookFile(FileName const & fname,
1370 OutputParams const & runparams,
1371 bool const body_only) const
1373 LYXERR(Debug::LATEX, "makeDocBookFile...");
1376 if (!openFileWrite(ofs, fname))
1379 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1383 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1387 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1388 OutputParams const & runparams,
1389 bool const only_body) const
1391 LaTeXFeatures features(*this, params(), runparams);
1396 DocumentClass const & tclass = params().documentClass();
1397 string const top_element = tclass.latexname();
1400 if (runparams.flavor == OutputParams::XML)
1401 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1404 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1407 if (! tclass.class_header().empty())
1408 os << from_ascii(tclass.class_header());
1409 else if (runparams.flavor == OutputParams::XML)
1410 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1411 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1413 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1415 docstring preamble = from_utf8(params().preamble);
1416 if (runparams.flavor != OutputParams::XML ) {
1417 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1418 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1419 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1420 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1423 string const name = runparams.nice
1424 ? changeExtension(absFileName(), ".sgml") : fname;
1425 preamble += features.getIncludedFiles(name);
1426 preamble += features.getLyXSGMLEntities();
1428 if (!preamble.empty()) {
1429 os << "\n [ " << preamble << " ]";
1434 string top = top_element;
1436 if (runparams.flavor == OutputParams::XML)
1437 top += params().language->code();
1439 top += params().language->code().substr(0, 2);
1442 if (!params().options.empty()) {
1444 top += params().options;
1447 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1448 << " file was created by LyX " << lyx_version
1449 << "\n See http://www.lyx.org/ for more information -->\n";
1451 params().documentClass().counters().reset();
1455 sgml::openTag(os, top);
1457 docbookParagraphs(text(), *this, os, runparams);
1458 sgml::closeTag(os, top_element);
1462 void Buffer::makeLyXHTMLFile(FileName const & fname,
1463 OutputParams const & runparams,
1464 bool const body_only) const
1466 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1469 if (!openFileWrite(ofs, fname))
1472 writeLyXHTMLSource(ofs, runparams, body_only);
1476 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1480 void Buffer::writeLyXHTMLSource(odocstream & os,
1481 OutputParams const & runparams,
1482 bool const only_body) const
1484 LaTeXFeatures features(*this, params(), runparams);
1486 updateLabels(UpdateMaster, true);
1487 checkBibInfoCache();
1488 d->bibinfo_.makeCitationLabels(*this);
1491 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1492 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";
1493 // FIXME Language should be set properly.
1494 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1497 // FIXME Presumably need to set this right
1498 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1499 // FIXME Get this during validation? What about other meta-data?
1500 os << "<title>TBA</title>\n";
1502 os << "\n<!-- Text Class Preamble -->\n"
1503 << features.getTClassHTMLPreamble()
1504 << "\n<!-- Premable Snippets -->\n"
1505 << from_utf8(features.getPreambleSnippets());
1507 os << "\n<!-- Layout-provided Styles -->\n";
1508 docstring const styleinfo = features.getTClassHTMLStyles();
1509 if (!styleinfo.empty()) {
1510 os << "<style type='text/css'>\n"
1514 os << "</head>\n<body>\n";
1518 params().documentClass().counters().reset();
1519 xhtmlParagraphs(text(), *this, xs, runparams);
1521 os << "</body>\n</html>\n";
1525 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1526 // Other flags: -wall -v0 -x
1527 int Buffer::runChktex()
1531 // get LaTeX-Filename
1532 FileName const path(temppath());
1533 string const name = addName(path.absFilename(), latexName());
1534 string const org_path = filePath();
1536 PathChanger p(path); // path to LaTeX file
1537 message(_("Running chktex..."));
1539 // Generate the LaTeX file if neccessary
1540 OutputParams runparams(¶ms().encoding());
1541 runparams.flavor = OutputParams::LATEX;
1542 runparams.nice = false;
1543 makeLaTeXFile(FileName(name), org_path, runparams);
1546 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1547 int const res = chktex.run(terr); // run chktex
1550 Alert::error(_("chktex failure"),
1551 _("Could not run chktex successfully."));
1552 } else if (res > 0) {
1553 ErrorList & errlist = d->errorLists["ChkTeX"];
1555 bufferErrors(terr, errlist);
1566 void Buffer::validate(LaTeXFeatures & features) const
1568 params().validate(features);
1572 for_each(paragraphs().begin(), paragraphs().end(),
1573 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1575 if (lyxerr.debugging(Debug::LATEX)) {
1576 features.showStruct();
1581 void Buffer::getLabelList(vector<docstring> & list) const
1583 // If this is a child document, use the parent's list instead.
1584 Buffer const * const pbuf = d->parent();
1586 pbuf->getLabelList(list);
1591 Toc & toc = d->toc_backend.toc("label");
1592 TocIterator toc_it = toc.begin();
1593 TocIterator end = toc.end();
1594 for (; toc_it != end; ++toc_it) {
1595 if (toc_it->depth() == 0)
1596 list.push_back(toc_it->str());
1601 void Buffer::updateBibfilesCache(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 pbuf->updateBibfilesCache();
1610 d->bibfiles_cache_.clear();
1611 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1612 if (it->lyxCode() == BIBTEX_CODE) {
1613 InsetBibtex const & inset =
1614 static_cast<InsetBibtex const &>(*it);
1615 support::FileNameList const bibfiles = inset.getBibFiles();
1616 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1619 } else if (it->lyxCode() == INCLUDE_CODE) {
1620 InsetInclude & inset =
1621 static_cast<InsetInclude &>(*it);
1622 inset.updateBibfilesCache();
1623 support::FileNameList const & bibfiles =
1624 inset.getBibfilesCache();
1625 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1630 // the bibinfo cache is now invalid
1631 d->bibinfo_cache_valid_ = false;
1635 void Buffer::invalidateBibinfoCache()
1637 d->bibinfo_cache_valid_ = false;
1641 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1643 // If this is a child document, use the parent's cache instead.
1644 Buffer const * const pbuf = d->parent();
1645 if (pbuf && scope != UpdateChildOnly)
1646 return pbuf->getBibfilesCache();
1648 // We update the cache when first used instead of at loading time.
1649 if (d->bibfiles_cache_.empty())
1650 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1652 return d->bibfiles_cache_;
1656 BiblioInfo const & Buffer::masterBibInfo() const
1658 // if this is a child document and the parent is already loaded
1659 // use the parent's list instead [ale990412]
1660 Buffer const * const tmp = masterBuffer();
1663 return tmp->masterBibInfo();
1664 return localBibInfo();
1668 BiblioInfo const & Buffer::localBibInfo() const
1670 checkBibInfoCache();
1675 void Buffer::checkBibInfoCache() const
1677 support::FileNameList const & bibfilesCache = getBibfilesCache();
1678 // compare the cached timestamps with the actual ones.
1679 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1680 support::FileNameList::const_iterator en = bibfilesCache.end();
1681 for (; ei != en; ++ ei) {
1682 time_t lastw = ei->lastModified();
1683 time_t prevw = d->bibfile_status_[*ei];
1684 if (lastw != prevw) {
1685 d->bibinfo_cache_valid_ = false;
1686 d->bibfile_status_[*ei] = lastw;
1690 if (!d->bibinfo_cache_valid_) {
1691 d->bibinfo_.clear();
1692 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1693 it->fillWithBibKeys(d->bibinfo_, it);
1694 d->bibinfo_cache_valid_ = true;
1699 bool Buffer::isDepClean(string const & name) const
1701 DepClean::const_iterator const it = d->dep_clean.find(name);
1702 if (it == d->dep_clean.end())
1708 void Buffer::markDepClean(string const & name)
1710 d->dep_clean[name] = true;
1714 bool Buffer::isExportableFormat(string const & format) const
1716 typedef vector<Format const *> Formats;
1718 formats = exportableFormats(true);
1719 Formats::const_iterator fit = formats.begin();
1720 Formats::const_iterator end = formats.end();
1721 for (; fit != end ; ++fit) {
1722 if ((*fit)->name() == format)
1729 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1732 // FIXME? if there is an Buffer LFUN that can be dispatched even
1733 // if internal, put a switch '(cmd.action)' here.
1739 switch (cmd.action) {
1741 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1742 flag.setOnOff(isReadonly());
1745 // FIXME: There is need for a command-line import.
1746 //case LFUN_BUFFER_IMPORT:
1748 case LFUN_BUFFER_AUTO_SAVE:
1751 case LFUN_BUFFER_EXPORT_CUSTOM:
1752 // FIXME: Nothing to check here?
1755 case LFUN_BUFFER_EXPORT: {
1756 docstring const arg = cmd.argument();
1757 enable = arg == "custom" || isExportable(to_utf8(arg));
1759 flag.message(bformat(
1760 _("Don't know how to export to format: %1$s"), arg));
1764 case LFUN_BUFFER_CHKTEX:
1765 enable = isLatex() && !lyxrc.chktex_command.empty();
1768 case LFUN_BUILD_PROGRAM:
1769 enable = isExportable("program");
1772 case LFUN_BRANCH_ACTIVATE:
1773 case LFUN_BRANCH_DEACTIVATE: {
1774 BranchList const & branchList = params().branchlist();
1775 docstring const branchName = cmd.argument();
1776 enable = !branchName.empty() && branchList.find(branchName);
1780 case LFUN_BRANCH_ADD:
1781 case LFUN_BRANCHES_RENAME:
1782 case LFUN_BUFFER_PRINT:
1783 // if no Buffer is present, then of course we won't be called!
1786 case LFUN_BUFFER_LANGUAGE:
1787 enable = !isReadonly();
1793 flag.setEnabled(enable);
1798 void Buffer::dispatch(string const & command, DispatchResult & result)
1800 return dispatch(lyxaction.lookupFunc(command), result);
1804 // NOTE We can end up here even if we have no GUI, because we are called
1805 // by LyX::exec to handled command-line requests. So we may need to check
1806 // whether we have a GUI or not. The boolean use_gui holds this information.
1807 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1810 // FIXME? if there is an Buffer LFUN that can be dispatched even
1811 // if internal, put a switch '(cmd.action)' here.
1812 dr.dispatched(false);
1815 string const argument = to_utf8(func.argument());
1816 // We'll set this back to false if need be.
1817 bool dispatched = true;
1818 undo().beginUndoGroup();
1820 switch (func.action) {
1821 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1822 if (lyxvc().inUse())
1823 lyxvc().toggleReadOnly();
1825 setReadonly(!isReadonly());
1828 case LFUN_BUFFER_EXPORT: {
1829 bool success = doExport(argument, false);
1830 dr.setError(success);
1832 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1837 case LFUN_BUILD_PROGRAM:
1838 doExport("program", true);
1841 case LFUN_BUFFER_CHKTEX:
1845 case LFUN_BUFFER_EXPORT_CUSTOM: {
1847 string command = split(argument, format_name, ' ');
1848 Format const * format = formats.getFormat(format_name);
1850 lyxerr << "Format \"" << format_name
1851 << "\" not recognized!"
1856 // The name of the file created by the conversion process
1859 // Output to filename
1860 if (format->name() == "lyx") {
1861 string const latexname = latexName(false);
1862 filename = changeExtension(latexname,
1863 format->extension());
1864 filename = addName(temppath(), filename);
1866 if (!writeFile(FileName(filename)))
1870 doExport(format_name, true, filename);
1873 // Substitute $$FName for filename
1874 if (!contains(command, "$$FName"))
1875 command = "( " + command + " ) < $$FName";
1876 command = subst(command, "$$FName", filename);
1878 // Execute the command in the background
1880 call.startscript(Systemcall::DontWait, command);
1884 // FIXME: There is need for a command-line import.
1886 case LFUN_BUFFER_IMPORT:
1891 case LFUN_BUFFER_AUTO_SAVE:
1895 case LFUN_BRANCH_ADD: {
1896 docstring const branch_name = func.argument();
1897 if (branch_name.empty()) {
1901 BranchList & branch_list = params().branchlist();
1902 Branch * branch = branch_list.find(branch_name);
1904 LYXERR0("Branch " << branch_name << " already exists.");
1906 docstring const msg =
1907 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1910 branch_list.add(branch_name);
1911 branch = branch_list.find(branch_name);
1912 string const x11hexname = X11hexname(branch->color());
1913 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1914 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1916 dr.update(Update::Force);
1921 case LFUN_BRANCH_ACTIVATE:
1922 case LFUN_BRANCH_DEACTIVATE: {
1923 BranchList & branchList = params().branchlist();
1924 docstring const branchName = func.argument();
1925 // the case without a branch name is handled elsewhere
1926 if (branchName.empty()) {
1930 Branch * branch = branchList.find(branchName);
1932 LYXERR0("Branch " << branchName << " does not exist.");
1934 docstring const msg =
1935 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1938 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1940 dr.update(Update::Force);
1945 case LFUN_BRANCHES_RENAME: {
1946 if (func.argument().empty())
1949 docstring const oldname = from_utf8(func.getArg(0));
1950 docstring const newname = from_utf8(func.getArg(1));
1951 InsetIterator it = inset_iterator_begin(inset());
1952 InsetIterator const end = inset_iterator_end(inset());
1953 bool success = false;
1954 for (; it != end; ++it) {
1955 if (it->lyxCode() == BRANCH_CODE) {
1956 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1957 if (ins.branch() == oldname) {
1958 undo().recordUndo(it);
1959 ins.rename(newname);
1964 if (it->lyxCode() == INCLUDE_CODE) {
1965 // get buffer of external file
1966 InsetInclude const & ins =
1967 static_cast<InsetInclude const &>(*it);
1968 Buffer * child = ins.getChildBuffer();
1971 child->dispatch(func, dr);
1976 dr.update(Update::Force);
1980 case LFUN_BUFFER_PRINT: {
1981 // we'll assume there's a problem until we succeed
1983 string target = func.getArg(0);
1984 string target_name = func.getArg(1);
1985 string command = func.getArg(2);
1988 || target_name.empty()
1989 || command.empty()) {
1990 LYXERR0("Unable to parse " << func.argument());
1991 docstring const msg =
1992 bformat(_("Unable to parse \"%1$s\""), func.argument());
1996 if (target != "printer" && target != "file") {
1997 LYXERR0("Unrecognized target \"" << target << '"');
1998 docstring const msg =
1999 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2004 if (!doExport("dvi", true)) {
2005 showPrintError(absFileName());
2006 dr.setMessage(_("Error exporting to DVI."));
2010 // Push directory path.
2011 string const path = temppath();
2012 // Prevent the compiler from optimizing away p
2016 // there are three cases here:
2017 // 1. we print to a file
2018 // 2. we print directly to a printer
2019 // 3. we print using a spool command (print to file first)
2022 string const dviname = changeExtension(latexName(true), "dvi");
2024 if (target == "printer") {
2025 if (!lyxrc.print_spool_command.empty()) {
2026 // case 3: print using a spool
2027 string const psname = changeExtension(dviname,".ps");
2028 command += ' ' + lyxrc.print_to_file
2031 + quoteName(dviname);
2033 string command2 = lyxrc.print_spool_command + ' ';
2034 if (target_name != "default") {
2035 command2 += lyxrc.print_spool_printerprefix
2039 command2 += quoteName(psname);
2041 // If successful, then spool command
2042 res = one.startscript(Systemcall::Wait, command);
2045 // If there's no GUI, we have to wait on this command. Otherwise,
2046 // LyX deletes the temporary directory, and with it the spooled
2047 // file, before it can be printed!!
2048 Systemcall::Starttype stype = use_gui ?
2049 Systemcall::DontWait : Systemcall::Wait;
2050 res = one.startscript(stype, command2);
2053 // case 2: print directly to a printer
2054 if (target_name != "default")
2055 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2057 Systemcall::Starttype stype = use_gui ?
2058 Systemcall::DontWait : Systemcall::Wait;
2059 res = one.startscript(stype, command + quoteName(dviname));
2063 // case 1: print to a file
2064 FileName const filename(makeAbsPath(target_name, filePath()));
2065 FileName const dvifile(makeAbsPath(dviname, path));
2066 if (filename.exists()) {
2067 docstring text = bformat(
2068 _("The file %1$s already exists.\n\n"
2069 "Do you want to overwrite that file?"),
2070 makeDisplayPath(filename.absFilename()));
2071 if (Alert::prompt(_("Overwrite file?"),
2072 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2075 command += ' ' + lyxrc.print_to_file
2076 + quoteName(filename.toFilesystemEncoding())
2078 + quoteName(dvifile.toFilesystemEncoding());
2080 Systemcall::Starttype stype = use_gui ?
2081 Systemcall::DontWait : Systemcall::Wait;
2082 res = one.startscript(stype, command);
2088 dr.setMessage(_("Error running external commands."));
2089 showPrintError(absFileName());
2094 case LFUN_BUFFER_LANGUAGE: {
2095 Language const * oldL = params().language;
2096 Language const * newL = languages.getLanguage(argument);
2097 if (!newL || oldL == newL)
2099 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2100 changeLanguage(oldL, newL);
2108 dr.dispatched(dispatched);
2109 undo().endUndoGroup();
2113 void Buffer::changeLanguage(Language const * from, Language const * to)
2115 LASSERT(from, /**/);
2118 for_each(par_iterator_begin(),
2120 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2124 bool Buffer::isMultiLingual() const
2126 ParConstIterator end = par_iterator_end();
2127 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2128 if (it->isMultiLingual(params()))
2135 DocIterator Buffer::getParFromID(int const id) const
2137 Buffer * buf = const_cast<Buffer *>(this);
2139 // John says this is called with id == -1 from undo
2140 lyxerr << "getParFromID(), id: " << id << endl;
2141 return doc_iterator_end(buf);
2144 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2145 if (it.paragraph().id() == id)
2148 return doc_iterator_end(buf);
2152 bool Buffer::hasParWithID(int const id) const
2154 return !getParFromID(id).atEnd();
2158 ParIterator Buffer::par_iterator_begin()
2160 return ParIterator(doc_iterator_begin(this));
2164 ParIterator Buffer::par_iterator_end()
2166 return ParIterator(doc_iterator_end(this));
2170 ParConstIterator Buffer::par_iterator_begin() const
2172 return ParConstIterator(doc_iterator_begin(this));
2176 ParConstIterator Buffer::par_iterator_end() const
2178 return ParConstIterator(doc_iterator_end(this));
2182 Language const * Buffer::language() const
2184 return params().language;
2188 docstring const Buffer::B_(string const & l10n) const
2190 return params().B_(l10n);
2194 bool Buffer::isClean() const
2196 return d->lyx_clean;
2200 bool Buffer::isBakClean() const
2202 return d->bak_clean;
2206 bool Buffer::isExternallyModified(CheckMethod method) const
2208 LASSERT(d->filename.exists(), /**/);
2209 // if method == timestamp, check timestamp before checksum
2210 return (method == checksum_method
2211 || d->timestamp_ != d->filename.lastModified())
2212 && d->checksum_ != d->filename.checksum();
2216 void Buffer::saveCheckSum(FileName const & file) const
2218 if (file.exists()) {
2219 d->timestamp_ = file.lastModified();
2220 d->checksum_ = file.checksum();
2222 // in the case of save to a new file.
2229 void Buffer::markClean() const
2231 if (!d->lyx_clean) {
2232 d->lyx_clean = true;
2235 // if the .lyx file has been saved, we don't need an
2237 d->bak_clean = true;
2241 void Buffer::markBakClean() const
2243 d->bak_clean = true;
2247 void Buffer::setUnnamed(bool flag)
2253 bool Buffer::isUnnamed() const
2260 /// Don't check unnamed, here: isInternal() is used in
2261 /// newBuffer(), where the unnamed flag has not been set by anyone
2262 /// yet. Also, for an internal buffer, there should be no need for
2263 /// retrieving fileName() nor for checking if it is unnamed or not.
2264 bool Buffer::isInternal() const
2266 return fileName().extension() == "internal";
2270 void Buffer::markDirty()
2273 d->lyx_clean = false;
2276 d->bak_clean = false;
2278 DepClean::iterator it = d->dep_clean.begin();
2279 DepClean::const_iterator const end = d->dep_clean.end();
2281 for (; it != end; ++it)
2286 FileName Buffer::fileName() const
2292 string Buffer::absFileName() const
2294 return d->filename.absFilename();
2298 string Buffer::filePath() const
2300 return d->filename.onlyPath().absFilename() + "/";
2304 bool Buffer::isReadonly() const
2306 return d->read_only;
2310 void Buffer::setParent(Buffer const * buffer)
2312 // Avoids recursive include.
2313 d->setParent(buffer == this ? 0 : buffer);
2318 Buffer const * Buffer::parent() const
2324 void Buffer::collectRelatives(BufferSet & bufs) const
2328 parent()->collectRelatives(bufs);
2330 // loop over children
2331 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2332 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2333 for (; it != end; ++it)
2334 bufs.insert(const_cast<Buffer *>(it->first));
2338 std::vector<Buffer const *> Buffer::allRelatives() const
2341 collectRelatives(bufs);
2342 BufferSet::iterator it = bufs.begin();
2343 std::vector<Buffer const *> ret;
2344 for (; it != bufs.end(); ++it)
2350 Buffer const * Buffer::masterBuffer() const
2352 Buffer const * const pbuf = d->parent();
2356 return pbuf->masterBuffer();
2360 bool Buffer::isChild(Buffer * child) const
2362 return d->children_positions.find(child) != d->children_positions.end();
2366 DocIterator Buffer::firstChildPosition(Buffer const * child)
2368 Impl::BufferPositionMap::iterator it;
2369 it = d->children_positions.find(child);
2370 if (it == d->children_positions.end())
2371 return DocIterator(this);
2376 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2378 // loop over children
2379 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2380 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2381 for (; it != end; ++it) {
2382 Buffer * child = const_cast<Buffer *>(it->first);
2383 clist.push_back(child);
2384 if (grand_children) {
2385 // there might be grandchildren
2386 std::vector<Buffer *> glist = child->getChildren();
2387 for (vector<Buffer *>::const_iterator git = glist.begin();
2388 git != glist.end(); ++git)
2389 clist.push_back(*git);
2395 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2397 std::vector<Buffer *> v;
2398 getChildren(v, grand_children);
2403 template<typename M>
2404 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2409 typename M::iterator it = m.lower_bound(x);
2410 if (it == m.begin())
2418 MacroData const * Buffer::getBufferMacro(docstring const & name,
2419 DocIterator const & pos) const
2421 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2423 // if paragraphs have no macro context set, pos will be empty
2427 // we haven't found anything yet
2428 DocIterator bestPos = par_iterator_begin();
2429 MacroData const * bestData = 0;
2431 // find macro definitions for name
2432 Impl::NamePositionScopeMacroMap::iterator nameIt
2433 = d->macros.find(name);
2434 if (nameIt != d->macros.end()) {
2435 // find last definition in front of pos or at pos itself
2436 Impl::PositionScopeMacroMap::const_iterator it
2437 = greatest_below(nameIt->second, pos);
2438 if (it != nameIt->second.end()) {
2440 // scope ends behind pos?
2441 if (pos < it->second.first) {
2442 // Looks good, remember this. If there
2443 // is no external macro behind this,
2444 // we found the right one already.
2445 bestPos = it->first;
2446 bestData = &it->second.second;
2450 // try previous macro if there is one
2451 if (it == nameIt->second.begin())
2458 // find macros in included files
2459 Impl::PositionScopeBufferMap::const_iterator it
2460 = greatest_below(d->position_to_children, pos);
2461 if (it == d->position_to_children.end())
2462 // no children before
2466 // do we know something better (i.e. later) already?
2467 if (it->first < bestPos )
2470 // scope ends behind pos?
2471 if (pos < it->second.first) {
2472 // look for macro in external file
2473 d->macro_lock = true;
2474 MacroData const * data
2475 = it->second.second->getMacro(name, false);
2476 d->macro_lock = false;
2478 bestPos = it->first;
2484 // try previous file if there is one
2485 if (it == d->position_to_children.begin())
2490 // return the best macro we have found
2495 MacroData const * Buffer::getMacro(docstring const & name,
2496 DocIterator const & pos, bool global) const
2501 // query buffer macros
2502 MacroData const * data = getBufferMacro(name, pos);
2506 // If there is a master buffer, query that
2507 Buffer const * const pbuf = d->parent();
2509 d->macro_lock = true;
2510 MacroData const * macro = pbuf->getMacro(
2511 name, *this, false);
2512 d->macro_lock = false;
2518 data = MacroTable::globalMacros().get(name);
2527 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2529 // set scope end behind the last paragraph
2530 DocIterator scope = par_iterator_begin();
2531 scope.pit() = scope.lastpit() + 1;
2533 return getMacro(name, scope, global);
2537 MacroData const * Buffer::getMacro(docstring const & name,
2538 Buffer const & child, bool global) const
2540 // look where the child buffer is included first
2541 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2542 if (it == d->children_positions.end())
2545 // check for macros at the inclusion position
2546 return getMacro(name, it->second, global);
2550 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2552 pit_type lastpit = it.lastpit();
2554 // look for macros in each paragraph
2555 while (it.pit() <= lastpit) {
2556 Paragraph & par = it.paragraph();
2558 // iterate over the insets of the current paragraph
2559 InsetList const & insets = par.insetList();
2560 InsetList::const_iterator iit = insets.begin();
2561 InsetList::const_iterator end = insets.end();
2562 for (; iit != end; ++iit) {
2563 it.pos() = iit->pos;
2565 // is it a nested text inset?
2566 if (iit->inset->asInsetText()) {
2567 // Inset needs its own scope?
2568 InsetText const * itext = iit->inset->asInsetText();
2569 bool newScope = itext->isMacroScope();
2571 // scope which ends just behind the inset
2572 DocIterator insetScope = it;
2575 // collect macros in inset
2576 it.push_back(CursorSlice(*iit->inset));
2577 updateMacros(it, newScope ? insetScope : scope);
2582 // is it an external file?
2583 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2584 // get buffer of external file
2585 InsetInclude const & inset =
2586 static_cast<InsetInclude const &>(*iit->inset);
2587 d->macro_lock = true;
2588 Buffer * child = inset.getChildBuffer();
2589 d->macro_lock = false;
2593 // register its position, but only when it is
2594 // included first in the buffer
2595 if (d->children_positions.find(child) ==
2596 d->children_positions.end())
2597 d->children_positions[child] = it;
2599 // register child with its scope
2600 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2604 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2608 MathMacroTemplate & macroTemplate =
2609 static_cast<MathMacroTemplate &>(*iit->inset);
2610 MacroContext mc(this, it);
2611 macroTemplate.updateToContext(mc);
2614 bool valid = macroTemplate.validMacro();
2615 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2616 // then the BufferView's cursor will be invalid in
2617 // some cases which leads to crashes.
2622 // FIXME (Abdel), I don't understandt why we pass 'it' here
2623 // instead of 'macroTemplate' defined above... is this correct?
2624 d->macros[macroTemplate.name()][it] =
2625 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2635 void Buffer::updateMacros() const
2640 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2642 // start with empty table
2644 d->children_positions.clear();
2645 d->position_to_children.clear();
2647 // Iterate over buffer, starting with first paragraph
2648 // The scope must be bigger than any lookup DocIterator
2649 // later. For the global lookup, lastpit+1 is used, hence
2650 // we use lastpit+2 here.
2651 DocIterator it = par_iterator_begin();
2652 DocIterator outerScope = it;
2653 outerScope.pit() = outerScope.lastpit() + 2;
2654 updateMacros(it, outerScope);
2658 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2660 InsetIterator it = inset_iterator_begin(inset());
2661 InsetIterator const end = inset_iterator_end(inset());
2662 for (; it != end; ++it) {
2663 if (it->lyxCode() == BRANCH_CODE) {
2664 InsetBranch & br = static_cast<InsetBranch &>(*it);
2665 docstring const name = br.branch();
2666 if (!from_master && !params().branchlist().find(name))
2667 result.push_back(name);
2668 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2669 result.push_back(name);
2672 if (it->lyxCode() == INCLUDE_CODE) {
2673 // get buffer of external file
2674 InsetInclude const & ins =
2675 static_cast<InsetInclude const &>(*it);
2676 Buffer * child = ins.getChildBuffer();
2679 child->getUsedBranches(result, true);
2682 // remove duplicates
2687 void Buffer::updateMacroInstances() const
2689 LYXERR(Debug::MACROS, "updateMacroInstances for "
2690 << d->filename.onlyFileName());
2691 DocIterator it = doc_iterator_begin(this);
2693 DocIterator const end = doc_iterator_end(this);
2694 for (; it != end; it.forwardInset()) {
2695 // look for MathData cells in InsetMathNest insets
2696 InsetMath * minset = it.nextInset()->asInsetMath();
2700 // update macro in all cells of the InsetMathNest
2701 DocIterator::idx_type n = minset->nargs();
2702 MacroContext mc = MacroContext(this, it);
2703 for (DocIterator::idx_type i = 0; i < n; ++i) {
2704 MathData & data = minset->cell(i);
2705 data.updateMacros(0, mc);
2711 void Buffer::listMacroNames(MacroNameSet & macros) const
2716 d->macro_lock = true;
2718 // loop over macro names
2719 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2720 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2721 for (; nameIt != nameEnd; ++nameIt)
2722 macros.insert(nameIt->first);
2724 // loop over children
2725 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2726 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2727 for (; it != end; ++it)
2728 it->first->listMacroNames(macros);
2731 Buffer const * const pbuf = d->parent();
2733 pbuf->listMacroNames(macros);
2735 d->macro_lock = false;
2739 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2741 Buffer const * const pbuf = d->parent();
2746 pbuf->listMacroNames(names);
2749 MacroNameSet::iterator it = names.begin();
2750 MacroNameSet::iterator end = names.end();
2751 for (; it != end; ++it) {
2753 MacroData const * data =
2754 pbuf->getMacro(*it, *this, false);
2756 macros.insert(data);
2758 // we cannot access the original MathMacroTemplate anymore
2759 // here to calls validate method. So we do its work here manually.
2760 // FIXME: somehow make the template accessible here.
2761 if (data->optionals() > 0)
2762 features.require("xargs");
2768 Buffer::References & Buffer::references(docstring const & label)
2771 return const_cast<Buffer *>(masterBuffer())->references(label);
2773 RefCache::iterator it = d->ref_cache_.find(label);
2774 if (it != d->ref_cache_.end())
2775 return it->second.second;
2777 static InsetLabel const * dummy_il = 0;
2778 static References const dummy_refs;
2779 it = d->ref_cache_.insert(
2780 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2781 return it->second.second;
2785 Buffer::References const & Buffer::references(docstring const & label) const
2787 return const_cast<Buffer *>(this)->references(label);
2791 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2793 masterBuffer()->d->ref_cache_[label].first = il;
2797 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2799 return masterBuffer()->d->ref_cache_[label].first;
2803 void Buffer::clearReferenceCache() const
2806 d->ref_cache_.clear();
2810 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2813 //FIXME: This does not work for child documents yet.
2814 LASSERT(code == CITE_CODE, /**/);
2815 // Check if the label 'from' appears more than once
2816 vector<docstring> labels;
2818 BiblioInfo const & keys = masterBibInfo();
2819 BiblioInfo::const_iterator bit = keys.begin();
2820 BiblioInfo::const_iterator bend = keys.end();
2822 for (; bit != bend; ++bit)
2824 labels.push_back(bit->first);
2827 if (count(labels.begin(), labels.end(), from) > 1)
2830 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2831 if (it->lyxCode() == code) {
2832 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2833 docstring const oldValue = inset.getParam(paramName);
2834 if (oldValue == from)
2835 inset.setParam(paramName, to);
2841 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2842 pit_type par_end, bool full_source) const
2844 OutputParams runparams(¶ms().encoding());
2845 runparams.nice = true;
2846 runparams.flavor = params().useXetex ?
2847 OutputParams::XETEX : OutputParams::LATEX;
2848 runparams.linelen = lyxrc.plaintext_linelen;
2849 // No side effect of file copying and image conversion
2850 runparams.dryrun = true;
2853 os << "% " << _("Preview source code") << "\n\n";
2855 d->texrow.newline();
2856 d->texrow.newline();
2858 writeDocBookSource(os, absFileName(), runparams, false);
2860 // latex or literate
2861 writeLaTeXSource(os, string(), runparams, true, true);
2863 runparams.par_begin = par_begin;
2864 runparams.par_end = par_end;
2865 if (par_begin + 1 == par_end) {
2867 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2871 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2872 convert<docstring>(par_begin),
2873 convert<docstring>(par_end - 1))
2880 // output paragraphs
2882 docbookParagraphs(text(), *this, os, runparams);
2884 // latex or literate
2885 latexParagraphs(*this, text(), os, texrow, runparams);
2890 ErrorList & Buffer::errorList(string const & type) const
2892 static ErrorList emptyErrorList;
2893 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2894 if (I == d->errorLists.end())
2895 return emptyErrorList;
2901 void Buffer::updateTocItem(std::string const & type,
2902 DocIterator const & dit) const
2905 gui_->updateTocItem(type, dit);
2909 void Buffer::structureChanged() const
2912 gui_->structureChanged();
2916 void Buffer::errors(string const & err, bool from_master) const
2919 gui_->errors(err, from_master);
2923 void Buffer::message(docstring const & msg) const
2930 void Buffer::setBusy(bool on) const
2937 void Buffer::setReadOnly(bool on) const
2940 d->wa_->setReadOnly(on);
2944 void Buffer::updateTitles() const
2947 d->wa_->updateTitles();
2951 void Buffer::resetAutosaveTimers() const
2954 gui_->resetAutosaveTimers();
2958 bool Buffer::hasGuiDelegate() const
2964 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2973 class AutoSaveBuffer : public ForkedProcess {
2976 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2977 : buffer_(buffer), fname_(fname) {}
2979 virtual boost::shared_ptr<ForkedProcess> clone() const
2981 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2986 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2987 from_utf8(fname_.absFilename())));
2988 return run(DontWait);
2992 virtual int generateChild();
2994 Buffer const & buffer_;
2999 int AutoSaveBuffer::generateChild()
3001 #if defined(__APPLE__)
3002 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3003 * We should use something else like threads.
3005 * Since I do not know how to determine at run time what is the OS X
3006 * version, I just disable forking altogether for now (JMarc)
3008 pid_t const pid = -1;
3010 // tmp_ret will be located (usually) in /tmp
3011 // will that be a problem?
3012 // Note that this calls ForkedCalls::fork(), so it's
3013 // ok cross-platform.
3014 pid_t const pid = fork();
3015 // If you want to debug the autosave
3016 // you should set pid to -1, and comment out the fork.
3017 if (pid != 0 && pid != -1)
3021 // pid = -1 signifies that lyx was unable
3022 // to fork. But we will do the save
3024 bool failed = false;
3025 FileName const tmp_ret = FileName::tempName("lyxauto");
3026 if (!tmp_ret.empty()) {
3027 buffer_.writeFile(tmp_ret);
3028 // assume successful write of tmp_ret
3029 if (!tmp_ret.moveTo(fname_))
3035 // failed to write/rename tmp_ret so try writing direct
3036 if (!buffer_.writeFile(fname_)) {
3037 // It is dangerous to do this in the child,
3038 // but safe in the parent, so...
3039 if (pid == -1) // emit message signal.
3040 buffer_.message(_("Autosave failed!"));
3044 if (pid == 0) // we are the child so...
3053 FileName Buffer::getAutosaveFilename() const
3055 // if the document is unnamed try to save in the backup dir, else
3056 // in the default document path, and as a last try in the filePath,
3057 // which will most often be the temporary directory
3060 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3061 : lyxrc.backupdir_path;
3062 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3065 string const fname = "#" + d->filename.onlyFileName() + "#";
3066 return makeAbsPath(fname, fpath);
3070 void Buffer::removeAutosaveFile() const
3072 FileName const f = getAutosaveFilename();
3078 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3080 FileName const newauto = getAutosaveFilename();
3081 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3082 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3086 // Perfect target for a thread...
3087 void Buffer::autoSave() const
3089 if (isBakClean() || isReadonly()) {
3090 // We don't save now, but we'll try again later
3091 resetAutosaveTimers();
3095 // emit message signal.
3096 message(_("Autosaving current document..."));
3097 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3101 resetAutosaveTimers();
3105 string Buffer::bufferFormat() const
3107 string format = params().documentClass().outputFormat();
3108 if (format == "latex") {
3109 if (params().useXetex)
3111 if (params().encoding().package() == Encoding::japanese)
3118 string Buffer::getDefaultOutputFormat() const
3120 if (!params().defaultOutputFormat.empty()
3121 && params().defaultOutputFormat != "default")
3122 return params().defaultOutputFormat;
3123 typedef vector<Format const *> Formats;
3124 Formats formats = exportableFormats(true);
3127 || params().useXetex
3128 || params().encoding().package() == Encoding::japanese) {
3129 if (formats.empty())
3131 // return the first we find
3132 return formats.front()->name();
3134 return lyxrc.default_view_format;
3139 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3140 string & result_file) const
3142 string backend_format;
3143 OutputParams runparams(¶ms().encoding());
3144 runparams.flavor = OutputParams::LATEX;
3145 runparams.linelen = lyxrc.plaintext_linelen;
3146 vector<string> backs = backends();
3147 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3148 // Get shortest path to format
3149 Graph::EdgePath path;
3150 for (vector<string>::const_iterator it = backs.begin();
3151 it != backs.end(); ++it) {
3152 Graph::EdgePath p = theConverters().getPath(*it, format);
3153 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3154 backend_format = *it;
3159 if (!put_in_tempdir) {
3160 // Only show this alert if this is an export to a non-temporary
3161 // file (not for previewing).
3162 Alert::error(_("Couldn't export file"), bformat(
3163 _("No information for exporting the format %1$s."),
3164 formats.prettyName(format)));
3168 runparams.flavor = theConverters().getFlavor(path);
3171 backend_format = format;
3172 // FIXME: Don't hardcode format names here, but use a flag
3173 if (backend_format == "pdflatex")
3174 runparams.flavor = OutputParams::PDFLATEX;
3177 string filename = latexName(false);
3178 filename = addName(temppath(), filename);
3179 filename = changeExtension(filename,
3180 formats.extension(backend_format));
3183 updateMacroInstances();
3185 // Plain text backend
3186 if (backend_format == "text") {
3187 runparams.flavor = OutputParams::TEXT;
3188 writePlaintextFile(*this, FileName(filename), runparams);
3191 else if (backend_format == "xhtml") {
3192 runparams.flavor = OutputParams::HTML;
3193 makeLyXHTMLFile(FileName(filename), runparams);
3194 } else if (backend_format == "lyx")
3195 writeFile(FileName(filename));
3197 else if (isDocBook()) {
3198 runparams.nice = !put_in_tempdir;
3199 makeDocBookFile(FileName(filename), runparams);
3202 else if (backend_format == format) {
3203 runparams.nice = true;
3204 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3206 } else if (!lyxrc.tex_allows_spaces
3207 && contains(filePath(), ' ')) {
3208 Alert::error(_("File name error"),
3209 _("The directory path to the document cannot contain spaces."));
3212 runparams.nice = false;
3213 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3217 string const error_type = (format == "program")
3218 ? "Build" : bufferFormat();
3219 ErrorList & error_list = d->errorLists[error_type];
3220 string const ext = formats.extension(format);
3221 FileName const tmp_result_file(changeExtension(filename, ext));
3222 bool const success = theConverters().convert(this, FileName(filename),
3223 tmp_result_file, FileName(absFileName()), backend_format, format,
3225 // Emit the signal to show the error list.
3226 if (format != backend_format) {
3228 // also to the children, in case of master-buffer-view
3229 std::vector<Buffer *> clist = getChildren();
3230 for (vector<Buffer *>::const_iterator cit = clist.begin();
3231 cit != clist.end(); ++cit)
3232 (*cit)->errors(error_type, true);
3237 if (d->cloned_buffer_) {
3238 // Enable reverse dvi or pdf to work by copying back the texrow
3239 // object to the cloned buffer.
3240 // FIXME: There is a possibility of concurrent access to texrow
3241 // here from the main GUI thread that should be securized.
3242 d->cloned_buffer_->d->texrow = d->texrow;
3245 if (put_in_tempdir) {
3246 result_file = tmp_result_file.absFilename();
3250 result_file = changeExtension(exportFileName().absFilename(), ext);
3251 // We need to copy referenced files (e. g. included graphics
3252 // if format == "dvi") to the result dir.
3253 vector<ExportedFile> const files =
3254 runparams.exportdata->externalFiles(format);
3255 string const dest = onlyPath(result_file);
3256 CopyStatus status = SUCCESS;
3257 for (vector<ExportedFile>::const_iterator it = files.begin();
3258 it != files.end() && status != CANCEL; ++it) {
3259 string const fmt = formats.getFormatFromFile(it->sourceName);
3260 status = copyFile(fmt, it->sourceName,
3261 makeAbsPath(it->exportName, dest),
3262 it->exportName, status == FORCE);
3264 if (status == CANCEL) {
3265 message(_("Document export cancelled."));
3266 } else if (tmp_result_file.exists()) {
3267 // Finally copy the main file
3268 status = copyFile(format, tmp_result_file,
3269 FileName(result_file), result_file,
3271 message(bformat(_("Document exported as %1$s "
3273 formats.prettyName(format),
3274 makeDisplayPath(result_file)));
3276 // This must be a dummy converter like fax (bug 1888)
3277 message(bformat(_("Document exported as %1$s"),
3278 formats.prettyName(format)));
3285 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3288 return doExport(format, put_in_tempdir, result_file);
3292 bool Buffer::preview(string const & format) const
3295 if (!doExport(format, true, result_file))
3297 return formats.view(*this, FileName(result_file), format);
3301 bool Buffer::isExportable(string const & format) const
3303 vector<string> backs = backends();
3304 for (vector<string>::const_iterator it = backs.begin();
3305 it != backs.end(); ++it)
3306 if (theConverters().isReachable(*it, format))
3312 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3314 vector<string> const backs = backends();
3315 vector<Format const *> result =
3316 theConverters().getReachable(backs[0], only_viewable, true);
3317 for (vector<string>::const_iterator it = backs.begin() + 1;
3318 it != backs.end(); ++it) {
3319 vector<Format const *> r =
3320 theConverters().getReachable(*it, only_viewable, false);
3321 result.insert(result.end(), r.begin(), r.end());
3327 vector<string> Buffer::backends() const
3330 v.push_back(bufferFormat());
3331 // FIXME: Don't hardcode format names here, but use a flag
3332 if (v.back() == "latex")
3333 v.push_back("pdflatex");
3334 v.push_back("xhtml");
3335 v.push_back("text");
3341 bool Buffer::readFileHelper(FileName const & s)
3343 // File information about normal file
3345 docstring const file = makeDisplayPath(s.absFilename(), 50);
3346 docstring text = bformat(_("The specified document\n%1$s"
3347 "\ncould not be read."), file);
3348 Alert::error(_("Could not read document"), text);
3352 // Check if emergency save file exists and is newer.
3353 FileName const e(s.absFilename() + ".emergency");
3355 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3356 docstring const file = makeDisplayPath(s.absFilename(), 20);
3357 docstring const text =
3358 bformat(_("An emergency save of the document "
3360 "Recover emergency save?"), file);
3361 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3362 _("&Recover"), _("&Load Original"),
3366 // the file is not saved if we load the emergency file.
3371 if ((res = readFile(e)) == success)
3372 str = _("Document was successfully recovered.");
3374 str = _("Document was NOT successfully recovered.");
3375 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3376 from_utf8(e.absFilename()));
3378 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3379 _("&Remove"), _("&Keep it"))) {
3382 Alert::warning(_("Emergency file deleted"),
3383 _("Do not forget to save your file now!"), true);
3388 if (!Alert::prompt(_("Delete emergency file?"),
3389 _("Remove emergency file now?"), 1, 1,
3390 _("&Remove"), _("&Keep it")))
3398 // Now check if autosave file is newer.
3399 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3401 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3402 docstring const file = makeDisplayPath(s.absFilename(), 20);
3403 docstring const text =
3404 bformat(_("The backup of the document "
3405 "%1$s is newer.\n\nLoad the "
3406 "backup instead?"), file);
3407 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3408 _("&Load backup"), _("Load &original"),
3412 // the file is not saved if we load the autosave file.
3416 // Here we delete the autosave
3427 bool Buffer::loadLyXFile(FileName const & s)
3429 // If the file is not readable, we try to
3430 // retrieve the file from version control.
3431 if (!s.isReadableFile()
3432 && !LyXVC::file_not_found_hook(s))
3435 if (s.isReadableFile()
3436 && readFileHelper(s)) {
3437 lyxvc().file_found_hook(s);
3438 setReadonly(!s.isWritable());
3445 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3447 TeXErrors::Errors::const_iterator cit = terr.begin();
3448 TeXErrors::Errors::const_iterator end = terr.end();
3450 for (; cit != end; ++cit) {
3453 int errorRow = cit->error_in_line;
3454 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3460 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3461 } while (found && id_start == id_end && pos_start == pos_end);
3463 errorList.push_back(ErrorItem(cit->error_desc,
3464 cit->error_text, id_start, pos_start, pos_end));
3469 void Buffer::setBuffersForInsets() const
3471 inset().setBuffer(const_cast<Buffer &>(*this));
3475 void Buffer::updateLabels(UpdateScope scope, bool out) const
3477 // Use the master text class also for child documents
3478 Buffer const * const master = masterBuffer();
3479 DocumentClass const & textclass = master->params().documentClass();
3481 // keep the buffers to be children in this set. If the call from the
3482 // master comes back we can see which of them were actually seen (i.e.
3483 // via an InsetInclude). The remaining ones in the set need still be updated.
3484 static std::set<Buffer const *> bufToUpdate;
3485 if (scope == UpdateMaster) {
3486 // If this is a child document start with the master
3487 if (master != this) {
3488 bufToUpdate.insert(this);
3489 master->updateLabels(UpdateMaster, out);
3490 // Do this here in case the master has no gui associated with it. Then,
3491 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3495 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3496 if (bufToUpdate.find(this) == bufToUpdate.end())
3500 // start over the counters in the master
3501 textclass.counters().reset();
3504 // update will be done below for this buffer
3505 bufToUpdate.erase(this);
3507 // update all caches
3508 clearReferenceCache();
3511 Buffer & cbuf = const_cast<Buffer &>(*this);
3513 LASSERT(!text().paragraphs().empty(), /**/);
3516 ParIterator parit = cbuf.par_iterator_begin();
3517 updateLabels(parit, out);
3520 // TocBackend update will be done later.
3523 cbuf.tocBackend().update();
3524 if (scope == UpdateMaster)
3525 cbuf.structureChanged();
3529 static depth_type getDepth(DocIterator const & it)
3531 depth_type depth = 0;
3532 for (size_t i = 0 ; i < it.depth() ; ++i)
3533 if (!it[i].inset().inMathed())
3534 depth += it[i].paragraph().getDepth() + 1;
3535 // remove 1 since the outer inset does not count
3539 static depth_type getItemDepth(ParIterator const & it)
3541 Paragraph const & par = *it;
3542 LabelType const labeltype = par.layout().labeltype;
3544 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3547 // this will hold the lowest depth encountered up to now.
3548 depth_type min_depth = getDepth(it);
3549 ParIterator prev_it = it;
3552 --prev_it.top().pit();
3554 // start of nested inset: go to outer par
3556 if (prev_it.empty()) {
3557 // start of document: nothing to do
3562 // We search for the first paragraph with same label
3563 // that is not more deeply nested.
3564 Paragraph & prev_par = *prev_it;
3565 depth_type const prev_depth = getDepth(prev_it);
3566 if (labeltype == prev_par.layout().labeltype) {
3567 if (prev_depth < min_depth)
3568 return prev_par.itemdepth + 1;
3569 if (prev_depth == min_depth)
3570 return prev_par.itemdepth;
3572 min_depth = min(min_depth, prev_depth);
3573 // small optimization: if we are at depth 0, we won't
3574 // find anything else
3575 if (prev_depth == 0)
3581 static bool needEnumCounterReset(ParIterator const & it)
3583 Paragraph const & par = *it;
3584 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3585 depth_type const cur_depth = par.getDepth();
3586 ParIterator prev_it = it;
3587 while (prev_it.pit()) {
3588 --prev_it.top().pit();
3589 Paragraph const & prev_par = *prev_it;
3590 if (prev_par.getDepth() <= cur_depth)
3591 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3593 // start of nested inset: reset
3598 // set the label of a paragraph. This includes the counters.
3599 void Buffer::setLabel(ParIterator & it) const
3601 BufferParams const & bp = this->masterBuffer()->params();
3602 DocumentClass const & textclass = bp.documentClass();
3603 Paragraph & par = it.paragraph();
3604 Layout const & layout = par.layout();
3605 Counters & counters = textclass.counters();
3607 if (par.params().startOfAppendix()) {
3608 // FIXME: only the counter corresponding to toplevel
3609 // sectioning should be reset
3611 counters.appendix(true);
3613 par.params().appendix(counters.appendix());
3615 // Compute the item depth of the paragraph
3616 par.itemdepth = getItemDepth(it);
3618 if (layout.margintype == MARGIN_MANUAL
3619 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3620 if (par.params().labelWidthString().empty())
3621 par.params().labelWidthString(par.expandLabel(layout, bp));
3623 par.params().labelWidthString(docstring());
3626 switch(layout.labeltype) {
3628 if (layout.toclevel <= bp.secnumdepth
3629 && (layout.latextype != LATEX_ENVIRONMENT
3630 || it.text()->isFirstInSequence(it.pit()))) {
3631 counters.step(layout.counter);
3632 par.params().labelString(
3633 par.expandLabel(layout, bp));
3635 par.params().labelString(docstring());
3638 case LABEL_ITEMIZE: {
3639 // At some point of time we should do something more
3640 // clever here, like:
3641 // par.params().labelString(
3642 // bp.user_defined_bullet(par.itemdepth).getText());
3643 // for now, use a simple hardcoded label
3644 docstring itemlabel;
3645 switch (par.itemdepth) {
3647 itemlabel = char_type(0x2022);
3650 itemlabel = char_type(0x2013);
3653 itemlabel = char_type(0x2217);
3656 itemlabel = char_type(0x2219); // or 0x00b7
3659 par.params().labelString(itemlabel);
3663 case LABEL_ENUMERATE: {
3664 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3666 switch (par.itemdepth) {
3675 enumcounter += "iv";
3678 // not a valid enumdepth...
3682 // Maybe we have to reset the enumeration counter.
3683 if (needEnumCounterReset(it))
3684 counters.reset(enumcounter);
3685 counters.step(enumcounter);
3687 string const & lang = par.getParLanguage(bp)->code();
3688 par.params().labelString(counters.theCounter(enumcounter, lang));
3693 case LABEL_SENSITIVE: {
3694 string const & type = counters.current_float();
3695 docstring full_label;
3697 full_label = this->B_("Senseless!!! ");
3699 docstring name = this->B_(textclass.floats().getType(type).name());
3700 if (counters.hasCounter(from_utf8(type))) {
3701 string const & lang = par.getParLanguage(bp)->code();
3702 counters.step(from_utf8(type));
3703 full_label = bformat(from_ascii("%1$s %2$s:"),
3705 counters.theCounter(from_utf8(type), lang));
3707 full_label = bformat(from_ascii("%1$s #:"), name);
3709 par.params().labelString(full_label);
3713 case LABEL_NO_LABEL:
3714 par.params().labelString(docstring());
3718 case LABEL_TOP_ENVIRONMENT:
3719 case LABEL_CENTERED_TOP_ENVIRONMENT:
3722 par.params().labelString(par.expandLabel(layout, bp));
3728 void Buffer::updateLabels(ParIterator & parit, bool out) const
3730 LASSERT(parit.pit() == 0, /**/);
3732 // set the position of the text in the buffer to be able
3733 // to resolve macros in it. This has nothing to do with
3734 // labels, but by putting it here we avoid implementing
3735 // a whole bunch of traversal routines just for this call.
3736 parit.text()->setMacrocontextPosition(parit);
3738 depth_type maxdepth = 0;
3739 pit_type const lastpit = parit.lastpit();
3740 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3741 // reduce depth if necessary
3742 parit->params().depth(min(parit->params().depth(), maxdepth));
3743 maxdepth = parit->getMaxDepthAfter();
3745 // set the counter for this paragraph
3749 InsetList::const_iterator iit = parit->insetList().begin();
3750 InsetList::const_iterator end = parit->insetList().end();
3751 for (; iit != end; ++iit) {
3752 parit.pos() = iit->pos;
3753 iit->inset->updateLabels(parit, out);
3759 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3760 WordLangTuple & word_lang, docstring_list & suggestions) const
3764 suggestions.clear();
3765 word_lang = WordLangTuple();
3766 // OK, we start from here.
3767 DocIterator const end = doc_iterator_end(this);
3768 for (; from != end; from.forwardPos()) {
3769 // We are only interested in text so remove the math CursorSlice.
3770 while (from.inMathed()) {
3774 // If from is at the end of the document (which is possible
3775 // when leaving the mathed) LyX will crash later.
3779 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3784 // Do not increase progress when from == to, otherwise the word
3785 // count will be wrong.
3795 bool Buffer::reload()
3798 // e.g., read-only status could have changed due to version control
3799 d->filename.refresh();
3800 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3802 bool const success = loadLyXFile(d->filename);
3807 message(bformat(_("Document %1$s reloaded."), disp_fn));
3809 message(bformat(_("Could not reload document %1$s."), disp_fn));