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;
310 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
311 bibinfo_ = cloned_buffer_->d->bibinfo_;
312 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
313 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
317 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
318 : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
320 LYXERR(Debug::INFO, "Buffer::Buffer()");
322 d->inset = new InsetText(*cloned_buffer->d->inset);
323 d->inset->setBuffer(*this);
324 // FIXME: optimize this loop somewhat, maybe by creating a new
325 // general recursive Inset::setId().
326 DocIterator it = doc_iterator_begin(this);
327 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
328 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
329 it.paragraph().setId(cloned_it.paragraph().id());
331 d->inset = new InsetText(this);
332 d->inset->setAutoBreakRows(true);
333 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
339 LYXERR(Debug::INFO, "Buffer::~Buffer()");
340 // here the buffer should take care that it is
341 // saved properly, before it goes into the void.
343 // GuiView already destroyed
347 // No need to do additional cleanups for internal buffer.
352 // loop over children
353 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
354 Impl::BufferPositionMap::iterator end = d->children_positions.end();
355 for (; it != end; ++it) {
356 Buffer * child = const_cast<Buffer *>(it->first);
357 if (d->cloned_buffer_)
359 // The child buffer might have been closed already.
360 else if (theBufferList().isLoaded(child))
361 theBufferList().releaseChild(this, child);
365 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
366 msg += emergencyWrite();
367 Alert::warning(_("Attempting to close changed document!"), msg);
370 // clear references to children in macro tables
371 d->children_positions.clear();
372 d->position_to_children.clear();
374 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
375 Alert::warning(_("Could not remove temporary directory"),
376 bformat(_("Could not remove the temporary directory %1$s"),
377 from_utf8(d->temppath.absFilename())));
380 // Remove any previewed LaTeX snippets associated with this buffer.
381 thePreviews().removeLoader(*this);
387 Buffer * Buffer::clone() const
389 Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
390 buffer_clone->d->macro_lock = true;
391 buffer_clone->d->children_positions.clear();
392 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
393 // math macro caches need to be rethought and simplified.
394 // I am not sure wether we should handle Buffer cloning here or in BufferList.
395 // Right now BufferList knows nothing about buffer clones.
396 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
397 Impl::BufferPositionMap::iterator end = d->children_positions.end();
398 for (; it != end; ++it) {
399 DocIterator dit = it->second.clone(buffer_clone);
400 dit.setBuffer(buffer_clone);
401 Buffer * child = const_cast<Buffer *>(it->first);
402 Buffer * child_clone = child->clone();
403 Inset * inset = dit.nextInset();
404 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
405 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
406 inset_inc->setChildBuffer(child_clone);
407 child_clone->d->setParent(buffer_clone);
408 buffer_clone->setChild(dit, child_clone);
414 bool Buffer::isClone() const
416 return d->cloned_buffer_;
420 void Buffer::changed(bool update_metrics) const
423 d->wa_->redrawAll(update_metrics);
427 frontend::WorkAreaManager & Buffer::workAreaManager() const
429 LASSERT(d->wa_, /**/);
434 Text & Buffer::text() const
436 return d->inset->text();
440 Inset & Buffer::inset() const
446 BufferParams & Buffer::params()
452 BufferParams const & Buffer::params() const
458 ParagraphList & Buffer::paragraphs()
460 return text().paragraphs();
464 ParagraphList const & Buffer::paragraphs() const
466 return text().paragraphs();
470 LyXVC & Buffer::lyxvc()
476 LyXVC const & Buffer::lyxvc() const
482 string const Buffer::temppath() const
484 return d->temppath.absFilename();
488 TexRow & Buffer::texrow()
494 TexRow const & Buffer::texrow() const
500 TocBackend & Buffer::tocBackend() const
502 return d->toc_backend;
506 Undo & Buffer::undo()
512 void Buffer::setChild(DocIterator const & dit, Buffer * child)
514 d->children_positions[child] = dit;
518 string Buffer::latexName(bool const no_path) const
520 FileName latex_name =
521 makeLatexName(exportFileName());
522 return no_path ? latex_name.onlyFileName()
523 : latex_name.absFilename();
527 FileName Buffer::exportFileName() const
529 docstring const branch_suffix =
530 params().branchlist().getFilenameSuffix();
531 if (branch_suffix.empty())
534 string const name = fileName().onlyFileNameWithoutExt()
535 + to_utf8(branch_suffix);
536 FileName res(fileName().onlyPath().absFilename() + "/" + name);
537 res.changeExtension(fileName().extension());
543 string Buffer::logName(LogType * type) const
545 string const filename = latexName(false);
547 if (filename.empty()) {
553 string const path = temppath();
555 FileName const fname(addName(temppath(),
556 onlyFilename(changeExtension(filename,
559 // FIXME: how do we know this is the name of the build log?
560 FileName const bname(
561 addName(path, onlyFilename(
562 changeExtension(filename,
563 formats.extension(bufferFormat()) + ".out"))));
565 // Also consider the master buffer log file
566 FileName masterfname = fname;
568 if (masterBuffer() != this) {
569 string const mlogfile = masterBuffer()->logName(&mtype);
570 masterfname = FileName(mlogfile);
573 // If no Latex log or Build log is newer, show Build log
574 if (bname.exists() &&
575 ((!fname.exists() && !masterfname.exists())
576 || (fname.lastModified() < bname.lastModified()
577 && masterfname.lastModified() < bname.lastModified()))) {
578 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
581 return bname.absFilename();
582 // If we have a newer master file log or only a master log, show this
583 } else if (fname != masterfname
584 && (!fname.exists() && (masterfname.exists()
585 || fname.lastModified() < masterfname.lastModified()))) {
586 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
589 return masterfname.absFilename();
591 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
594 return fname.absFilename();
598 void Buffer::setReadonly(bool const flag)
600 if (d->read_only != flag) {
607 void Buffer::setFileName(string const & newfile)
609 d->filename = makeAbsPath(newfile);
610 setReadonly(d->filename.isReadOnly());
615 int Buffer::readHeader(Lexer & lex)
617 int unknown_tokens = 0;
619 int begin_header_line = -1;
621 // Initialize parameters that may be/go lacking in header:
622 params().branchlist().clear();
623 params().preamble.erase();
624 params().options.erase();
625 params().master.erase();
626 params().float_placement.erase();
627 params().paperwidth.erase();
628 params().paperheight.erase();
629 params().leftmargin.erase();
630 params().rightmargin.erase();
631 params().topmargin.erase();
632 params().bottommargin.erase();
633 params().headheight.erase();
634 params().headsep.erase();
635 params().footskip.erase();
636 params().columnsep.erase();
637 params().fontsCJK.erase();
638 params().listings_params.clear();
639 params().clearLayoutModules();
640 params().clearRemovedModules();
641 params().clearIncludedChildren();
642 params().pdfoptions().clear();
643 params().indiceslist().clear();
644 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
646 for (int i = 0; i < 4; ++i) {
647 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
648 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
651 ErrorList & errorList = d->errorLists["Parse"];
660 if (token == "\\end_header")
664 if (token == "\\begin_header") {
665 begin_header_line = line;
669 LYXERR(Debug::PARSER, "Handling document header token: `"
672 string unknown = params().readToken(lex, token, d->filename.onlyPath());
673 if (!unknown.empty()) {
674 if (unknown[0] != '\\' && token == "\\textclass") {
675 Alert::warning(_("Unknown document class"),
676 bformat(_("Using the default document class, because the "
677 "class %1$s is unknown."), from_utf8(unknown)));
680 docstring const s = bformat(_("Unknown token: "
684 errorList.push_back(ErrorItem(_("Document header error"),
689 if (begin_header_line) {
690 docstring const s = _("\\begin_header is missing");
691 errorList.push_back(ErrorItem(_("Document header error"),
695 params().makeDocumentClass();
697 return unknown_tokens;
702 // changed to be public and have one parameter
703 // Returns true if "\end_document" is not read (Asger)
704 bool Buffer::readDocument(Lexer & lex)
706 ErrorList & errorList = d->errorLists["Parse"];
709 if (!lex.checkFor("\\begin_document")) {
710 docstring const s = _("\\begin_document is missing");
711 errorList.push_back(ErrorItem(_("Document header error"),
715 // we are reading in a brand new document
716 LASSERT(paragraphs().empty(), /**/);
720 if (params().outputChanges) {
721 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
722 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
723 LaTeXFeatures::isAvailable("xcolor");
725 if (!dvipost && !xcolorulem) {
726 Alert::warning(_("Changes not shown in LaTeX output"),
727 _("Changes will not be highlighted in LaTeX output, "
728 "because neither dvipost nor xcolor/ulem are installed.\n"
729 "Please install these packages or redefine "
730 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
731 } else if (!xcolorulem) {
732 Alert::warning(_("Changes not shown in LaTeX output"),
733 _("Changes will not be highlighted in LaTeX output "
734 "when using pdflatex, because xcolor and ulem are not installed.\n"
735 "Please install both packages or redefine "
736 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
740 if (!params().master.empty()) {
741 FileName const master_file = makeAbsPath(params().master,
742 onlyPath(absFileName()));
743 if (isLyXFilename(master_file.absFilename())) {
745 checkAndLoadLyXFile(master_file, true);
747 // necessary e.g. after a reload
748 // to re-register the child (bug 5873)
749 // FIXME: clean up updateMacros (here, only
750 // child registering is needed).
751 master->updateMacros();
752 // set master as master buffer, but only
753 // if we are a real child
754 if (master->isChild(this))
756 // if the master is not fully loaded
757 // it is probably just loading this
758 // child. No warning needed then.
759 else if (master->isFullyLoaded())
760 LYXERR0("The master '"
762 << "' assigned to this document ("
764 << ") does not include "
765 "this document. Ignoring the master assignment.");
770 // assure we have a default index
771 params().indiceslist().addDefault(B_("Index"));
774 bool const res = text().read(lex, errorList, d->inset);
778 updateMacroInstances();
783 bool Buffer::readString(string const & s)
785 params().compressed = false;
787 // remove dummy empty par
788 paragraphs().clear();
792 FileName const name = FileName::tempName("Buffer_readString");
793 switch (readFile(lex, name, true)) {
797 // We need to call lyx2lyx, so write the input to a file
798 ofstream os(name.toFilesystemEncoding().c_str());
801 return readFile(name);
811 bool Buffer::readFile(FileName const & filename)
813 FileName fname(filename);
815 params().compressed = fname.isZippedFile();
817 // remove dummy empty par
818 paragraphs().clear();
821 if (readFile(lex, fname) != success)
828 bool Buffer::isFullyLoaded() const
830 return d->file_fully_loaded;
834 void Buffer::setFullyLoaded(bool value)
836 d->file_fully_loaded = value;
840 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
843 LASSERT(!filename.empty(), /**/);
845 // the first (non-comment) token _must_ be...
846 if (!lex.checkFor("\\lyxformat")) {
847 Alert::error(_("Document format failure"),
848 bformat(_("%1$s is not a readable LyX document."),
849 from_utf8(filename.absFilename())));
855 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
856 // if present remove ".," from string.
857 size_t dot = tmp_format.find_first_of(".,");
858 //lyxerr << " dot found at " << dot << endl;
859 if (dot != string::npos)
860 tmp_format.erase(dot, 1);
861 int const file_format = convert<int>(tmp_format);
862 //lyxerr << "format: " << file_format << endl;
864 // save timestamp and checksum of the original disk file, making sure
865 // to not overwrite them with those of the file created in the tempdir
866 // when it has to be converted to the current format.
868 // Save the timestamp and checksum of disk file. If filename is an
869 // emergency file, save the timestamp and checksum of the original lyx file
870 // because isExternallyModified will check for this file. (BUG4193)
871 string diskfile = filename.absFilename();
872 if (suffixIs(diskfile, ".emergency"))
873 diskfile = diskfile.substr(0, diskfile.size() - 10);
874 saveCheckSum(FileName(diskfile));
877 if (file_format != LYX_FORMAT) {
880 // lyx2lyx would fail
883 FileName const tmpfile = FileName::tempName("Buffer_readFile");
884 if (tmpfile.empty()) {
885 Alert::error(_("Conversion failed"),
886 bformat(_("%1$s is from a different"
887 " version of LyX, but a temporary"
888 " file for converting it could"
890 from_utf8(filename.absFilename())));
893 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
894 if (lyx2lyx.empty()) {
895 Alert::error(_("Conversion script not found"),
896 bformat(_("%1$s is from a different"
897 " version of LyX, but the"
898 " conversion script lyx2lyx"
899 " could not be found."),
900 from_utf8(filename.absFilename())));
903 ostringstream command;
904 command << os::python()
905 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
906 << " -t " << convert<string>(LYX_FORMAT)
907 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
908 << ' ' << quoteName(filename.toFilesystemEncoding());
909 string const command_str = command.str();
911 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
913 cmd_ret const ret = runCommand(command_str);
914 if (ret.first != 0) {
915 Alert::error(_("Conversion script failed"),
916 bformat(_("%1$s is from a different version"
917 " of LyX, but the lyx2lyx script"
918 " failed to convert it."),
919 from_utf8(filename.absFilename())));
922 bool const ret = readFile(tmpfile);
923 // Do stuff with tmpfile name and buffer name here.
924 return ret ? success : failure;
929 if (readDocument(lex)) {
930 Alert::error(_("Document format failure"),
931 bformat(_("%1$s ended unexpectedly, which means"
932 " that it is probably corrupted."),
933 from_utf8(filename.absFilename())));
936 d->file_fully_loaded = true;
941 // Should probably be moved to somewhere else: BufferView? LyXView?
942 bool Buffer::save() const
944 // We don't need autosaves in the immediate future. (Asger)
945 resetAutosaveTimers();
947 string const encodedFilename = d->filename.toFilesystemEncoding();
950 bool madeBackup = false;
952 // make a backup if the file already exists
953 if (lyxrc.make_backup && fileName().exists()) {
954 backupName = FileName(absFileName() + '~');
955 if (!lyxrc.backupdir_path.empty()) {
956 string const mangledName =
957 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
958 backupName = FileName(addName(lyxrc.backupdir_path,
961 if (fileName().copyTo(backupName)) {
964 Alert::error(_("Backup failure"),
965 bformat(_("Cannot create backup file %1$s.\n"
966 "Please check whether the directory exists and is writeable."),
967 from_utf8(backupName.absFilename())));
968 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
972 // ask if the disk file has been externally modified (use checksum method)
973 if (fileName().exists() && isExternallyModified(checksum_method)) {
974 docstring const file = makeDisplayPath(absFileName(), 20);
975 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
976 "you want to overwrite this file?"), file);
977 int const ret = Alert::prompt(_("Overwrite modified file?"),
978 text, 1, 1, _("&Overwrite"), _("&Cancel"));
983 if (writeFile(d->filename)) {
987 // Saving failed, so backup is not backup
989 backupName.moveTo(d->filename);
995 bool Buffer::writeFile(FileName const & fname) const
997 if (d->read_only && fname == d->filename)
1000 bool retval = false;
1002 docstring const str = bformat(_("Saving document %1$s..."),
1003 makeDisplayPath(fname.absFilename()));
1006 if (params().compressed) {
1007 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1008 retval = ofs && write(ofs);
1010 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
1011 retval = ofs && write(ofs);
1015 message(str + _(" could not write file!"));
1019 removeAutosaveFile();
1021 saveCheckSum(d->filename);
1022 message(str + _(" done."));
1028 docstring Buffer::emergencyWrite()
1030 // No need to save if the buffer has not changed.
1034 string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1036 docstring user_message = bformat(
1037 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1039 // We try to save three places:
1040 // 1) Same place as document. Unless it is an unnamed doc.
1042 string s = absFileName();
1045 if (writeFile(FileName(s))) {
1047 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1048 return user_message;
1050 user_message += _(" Save failed! Trying again...\n");
1054 // 2) In HOME directory.
1055 string s = addName(package().home_dir().absFilename(), absFileName());
1057 lyxerr << ' ' << s << endl;
1058 if (writeFile(FileName(s))) {
1060 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1061 return user_message;
1064 user_message += _(" Save failed! Trying yet again...\n");
1066 // 3) In "/tmp" directory.
1067 // MakeAbsPath to prepend the current
1068 // drive letter on OS/2
1069 s = addName(package().temp_dir().absFilename(), absFileName());
1071 lyxerr << ' ' << s << endl;
1072 if (writeFile(FileName(s))) {
1074 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1075 return user_message;
1078 user_message += _(" Save failed! Bummer. Document is lost.");
1081 return user_message;
1085 bool Buffer::write(ostream & ofs) const
1088 // Use the standard "C" locale for file output.
1089 ofs.imbue(locale::classic());
1092 // The top of the file should not be written by params().
1094 // write out a comment in the top of the file
1095 ofs << "#LyX " << lyx_version
1096 << " created this file. For more info see http://www.lyx.org/\n"
1097 << "\\lyxformat " << LYX_FORMAT << "\n"
1098 << "\\begin_document\n";
1100 /// For each author, set 'used' to true if there is a change
1101 /// by this author in the document; otherwise set it to 'false'.
1102 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1103 AuthorList::Authors::const_iterator a_end = params().authors().end();
1104 for (; a_it != a_end; ++a_it)
1105 a_it->setUsed(false);
1107 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1108 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1109 for ( ; it != end; ++it)
1110 it->checkAuthors(params().authors());
1112 // now write out the buffer parameters.
1113 ofs << "\\begin_header\n";
1114 params().writeFile(ofs);
1115 ofs << "\\end_header\n";
1118 ofs << "\n\\begin_body\n";
1120 ofs << "\n\\end_body\n";
1122 // Write marker that shows file is complete
1123 ofs << "\\end_document" << endl;
1125 // Shouldn't really be needed....
1128 // how to check if close went ok?
1129 // Following is an attempt... (BE 20001011)
1131 // good() returns false if any error occured, including some
1132 // formatting error.
1133 // bad() returns true if something bad happened in the buffer,
1134 // which should include file system full errors.
1139 lyxerr << "File was not closed properly." << endl;
1146 bool Buffer::makeLaTeXFile(FileName const & fname,
1147 string const & original_path,
1148 OutputParams const & runparams_in,
1149 bool output_preamble, bool output_body) const
1151 OutputParams runparams = runparams_in;
1152 if (params().useXetex)
1153 runparams.flavor = OutputParams::XETEX;
1155 string const encoding = runparams.encoding->iconvName();
1156 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1159 try { ofs.reset(encoding); }
1160 catch (iconv_codecvt_facet_exception & e) {
1161 lyxerr << "Caught iconv exception: " << e.what() << endl;
1162 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1163 "verify that the support software for your encoding (%1$s) is "
1164 "properly installed"), from_ascii(encoding)));
1167 if (!openFileWrite(ofs, fname))
1170 //TexStream ts(ofs.rdbuf(), &texrow());
1171 ErrorList & errorList = d->errorLists["Export"];
1173 bool failed_export = false;
1176 writeLaTeXSource(ofs, original_path,
1177 runparams, output_preamble, output_body);
1179 catch (EncodingException & e) {
1180 odocstringstream ods;
1181 ods.put(e.failed_char);
1183 oss << "0x" << hex << e.failed_char << dec;
1184 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1185 " (code point %2$s)"),
1186 ods.str(), from_utf8(oss.str()));
1187 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1188 "representable in the chosen encoding.\n"
1189 "Changing the document encoding to utf8 could help."),
1190 e.par_id, e.pos, e.pos + 1));
1191 failed_export = true;
1193 catch (iconv_codecvt_facet_exception & e) {
1194 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1195 _(e.what()), -1, 0, 0));
1196 failed_export = true;
1198 catch (exception const & e) {
1199 errorList.push_back(ErrorItem(_("conversion failed"),
1200 _(e.what()), -1, 0, 0));
1201 failed_export = true;
1204 lyxerr << "Caught some really weird exception..." << endl;
1210 failed_export = true;
1211 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1215 return !failed_export;
1219 void Buffer::writeLaTeXSource(odocstream & os,
1220 string const & original_path,
1221 OutputParams const & runparams_in,
1222 bool const output_preamble, bool const output_body) const
1224 // The child documents, if any, shall be already loaded at this point.
1226 OutputParams runparams = runparams_in;
1228 // Classify the unicode characters appearing in math insets
1229 Encodings::initUnicodeMath(*this);
1231 // validate the buffer.
1232 LYXERR(Debug::LATEX, " Validating buffer...");
1233 LaTeXFeatures features(*this, params(), runparams);
1235 LYXERR(Debug::LATEX, " Buffer validation done.");
1237 // The starting paragraph of the coming rows is the
1238 // first paragraph of the document. (Asger)
1239 if (output_preamble && runparams.nice) {
1240 os << "%% LyX " << lyx_version << " created this file. "
1241 "For more info, see http://www.lyx.org/.\n"
1242 "%% Do not edit unless you really know what "
1244 d->texrow.newline();
1245 d->texrow.newline();
1247 LYXERR(Debug::INFO, "lyx document header finished");
1249 // Don't move this behind the parent_buffer=0 code below,
1250 // because then the macros will not get the right "redefinition"
1251 // flag as they don't see the parent macros which are output before.
1254 // fold macros if possible, still with parent buffer as the
1255 // macros will be put in the prefix anyway.
1256 updateMacroInstances();
1258 // There are a few differences between nice LaTeX and usual files:
1259 // usual is \batchmode and has a
1260 // special input@path to allow the including of figures
1261 // with either \input or \includegraphics (what figinsets do).
1262 // input@path is set when the actual parameter
1263 // original_path is set. This is done for usual tex-file, but not
1264 // for nice-latex-file. (Matthias 250696)
1265 // Note that input@path is only needed for something the user does
1266 // in the preamble, included .tex files or ERT, files included by
1267 // LyX work without it.
1268 if (output_preamble) {
1269 if (!runparams.nice) {
1270 // code for usual, NOT nice-latex-file
1271 os << "\\batchmode\n"; // changed
1272 // from \nonstopmode
1273 d->texrow.newline();
1275 if (!original_path.empty()) {
1277 // We don't know the encoding of inputpath
1278 docstring const inputpath = from_utf8(latex_path(original_path));
1279 os << "\\makeatletter\n"
1280 << "\\def\\input@path{{"
1281 << inputpath << "/}}\n"
1282 << "\\makeatother\n";
1283 d->texrow.newline();
1284 d->texrow.newline();
1285 d->texrow.newline();
1288 // get parent macros (if this buffer has a parent) which will be
1289 // written at the document begin further down.
1290 MacroSet parentMacros;
1291 listParentMacros(parentMacros, features);
1293 // Write the preamble
1294 runparams.use_babel = params().writeLaTeX(os, features,
1296 d->filename.onlyPath());
1298 runparams.use_japanese = features.isRequired("japanese");
1304 os << "\\begin{document}\n";
1305 d->texrow.newline();
1307 // output the parent macros
1308 MacroSet::iterator it = parentMacros.begin();
1309 MacroSet::iterator end = parentMacros.end();
1310 for (; it != end; ++it)
1311 (*it)->write(os, true);
1312 } // output_preamble
1314 d->texrow.start(paragraphs().begin()->id(), 0);
1316 LYXERR(Debug::INFO, "preamble finished, now the body.");
1318 // if we are doing a real file with body, even if this is the
1319 // child of some other buffer, let's cut the link here.
1320 // This happens for example if only a child document is printed.
1321 Buffer const * save_parent = 0;
1322 if (output_preamble) {
1323 save_parent = d->parent();
1328 latexParagraphs(*this, text(), os, d->texrow, runparams);
1330 // Restore the parenthood if needed
1331 if (output_preamble)
1332 d->setParent(save_parent);
1334 // add this just in case after all the paragraphs
1336 d->texrow.newline();
1338 if (output_preamble) {
1339 os << "\\end{document}\n";
1340 d->texrow.newline();
1341 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1343 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1345 runparams_in.encoding = runparams.encoding;
1347 // Just to be sure. (Asger)
1348 d->texrow.newline();
1350 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1351 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1355 bool Buffer::isLatex() const
1357 return params().documentClass().outputType() == LATEX;
1361 bool Buffer::isLiterate() const
1363 return params().documentClass().outputType() == LITERATE;
1367 bool Buffer::isDocBook() const
1369 return params().documentClass().outputType() == DOCBOOK;
1373 void Buffer::makeDocBookFile(FileName const & fname,
1374 OutputParams const & runparams,
1375 bool const body_only) const
1377 LYXERR(Debug::LATEX, "makeDocBookFile...");
1380 if (!openFileWrite(ofs, fname))
1383 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1387 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1391 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1392 OutputParams const & runparams,
1393 bool const only_body) const
1395 LaTeXFeatures features(*this, params(), runparams);
1400 DocumentClass const & tclass = params().documentClass();
1401 string const top_element = tclass.latexname();
1404 if (runparams.flavor == OutputParams::XML)
1405 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1408 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1411 if (! tclass.class_header().empty())
1412 os << from_ascii(tclass.class_header());
1413 else if (runparams.flavor == OutputParams::XML)
1414 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1415 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1417 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1419 docstring preamble = from_utf8(params().preamble);
1420 if (runparams.flavor != OutputParams::XML ) {
1421 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1422 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1423 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1424 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1427 string const name = runparams.nice
1428 ? changeExtension(absFileName(), ".sgml") : fname;
1429 preamble += features.getIncludedFiles(name);
1430 preamble += features.getLyXSGMLEntities();
1432 if (!preamble.empty()) {
1433 os << "\n [ " << preamble << " ]";
1438 string top = top_element;
1440 if (runparams.flavor == OutputParams::XML)
1441 top += params().language->code();
1443 top += params().language->code().substr(0, 2);
1446 if (!params().options.empty()) {
1448 top += params().options;
1451 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1452 << " file was created by LyX " << lyx_version
1453 << "\n See http://www.lyx.org/ for more information -->\n";
1455 params().documentClass().counters().reset();
1459 sgml::openTag(os, top);
1461 docbookParagraphs(text(), *this, os, runparams);
1462 sgml::closeTag(os, top_element);
1466 void Buffer::makeLyXHTMLFile(FileName const & fname,
1467 OutputParams const & runparams,
1468 bool const body_only) const
1470 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1473 if (!openFileWrite(ofs, fname))
1476 writeLyXHTMLSource(ofs, runparams, body_only);
1480 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1484 void Buffer::writeLyXHTMLSource(odocstream & os,
1485 OutputParams const & runparams,
1486 bool const only_body) const
1488 LaTeXFeatures features(*this, params(), runparams);
1490 updateLabels(UpdateMaster, true);
1491 checkBibInfoCache();
1492 d->bibinfo_.makeCitationLabels(*this);
1495 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1496 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
1497 // FIXME Language should be set properly.
1498 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1501 // FIXME Presumably need to set this right
1502 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1503 // FIXME Get this during validation? What about other meta-data?
1504 os << "<title>TBA</title>\n";
1506 os << "\n<!-- Text Class Preamble -->\n"
1507 << features.getTClassHTMLPreamble()
1508 << "\n<!-- Premable Snippets -->\n"
1509 << from_utf8(features.getPreambleSnippets());
1511 os << "\n<!-- Layout-provided Styles -->\n";
1512 docstring const styleinfo = features.getTClassHTMLStyles();
1513 if (!styleinfo.empty()) {
1514 os << "<style type='text/css'>\n"
1518 os << "</head>\n<body>\n";
1522 params().documentClass().counters().reset();
1523 xhtmlParagraphs(text(), *this, xs, runparams);
1525 os << "</body>\n</html>\n";
1529 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1530 // Other flags: -wall -v0 -x
1531 int Buffer::runChktex()
1535 // get LaTeX-Filename
1536 FileName const path(temppath());
1537 string const name = addName(path.absFilename(), latexName());
1538 string const org_path = filePath();
1540 PathChanger p(path); // path to LaTeX file
1541 message(_("Running chktex..."));
1543 // Generate the LaTeX file if neccessary
1544 OutputParams runparams(¶ms().encoding());
1545 runparams.flavor = OutputParams::LATEX;
1546 runparams.nice = false;
1547 makeLaTeXFile(FileName(name), org_path, runparams);
1550 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1551 int const res = chktex.run(terr); // run chktex
1554 Alert::error(_("chktex failure"),
1555 _("Could not run chktex successfully."));
1556 } else if (res > 0) {
1557 ErrorList & errlist = d->errorLists["ChkTeX"];
1559 bufferErrors(terr, errlist);
1570 void Buffer::validate(LaTeXFeatures & features) const
1572 params().validate(features);
1576 for_each(paragraphs().begin(), paragraphs().end(),
1577 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1579 if (lyxerr.debugging(Debug::LATEX)) {
1580 features.showStruct();
1585 void Buffer::getLabelList(vector<docstring> & list) const
1587 // If this is a child document, use the parent's list instead.
1588 Buffer const * const pbuf = d->parent();
1590 pbuf->getLabelList(list);
1595 Toc & toc = d->toc_backend.toc("label");
1596 TocIterator toc_it = toc.begin();
1597 TocIterator end = toc.end();
1598 for (; toc_it != end; ++toc_it) {
1599 if (toc_it->depth() == 0)
1600 list.push_back(toc_it->str());
1605 void Buffer::updateBibfilesCache(UpdateScope scope) const
1607 // If this is a child document, use the parent's cache instead.
1608 Buffer const * const pbuf = d->parent();
1609 if (pbuf && scope != UpdateChildOnly) {
1610 pbuf->updateBibfilesCache();
1614 d->bibfiles_cache_.clear();
1615 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1616 if (it->lyxCode() == BIBTEX_CODE) {
1617 InsetBibtex const & inset =
1618 static_cast<InsetBibtex const &>(*it);
1619 support::FileNameList const bibfiles = inset.getBibFiles();
1620 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1623 } else if (it->lyxCode() == INCLUDE_CODE) {
1624 InsetInclude & inset =
1625 static_cast<InsetInclude &>(*it);
1626 inset.updateBibfilesCache();
1627 support::FileNameList const & bibfiles =
1628 inset.getBibfilesCache();
1629 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1634 // the bibinfo cache is now invalid
1635 d->bibinfo_cache_valid_ = false;
1639 void Buffer::invalidateBibinfoCache()
1641 d->bibinfo_cache_valid_ = false;
1645 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1647 // If this is a child document, use the parent's cache instead.
1648 Buffer const * const pbuf = d->parent();
1649 if (pbuf && scope != UpdateChildOnly)
1650 return pbuf->getBibfilesCache();
1652 // We update the cache when first used instead of at loading time.
1653 if (d->bibfiles_cache_.empty())
1654 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1656 return d->bibfiles_cache_;
1660 BiblioInfo const & Buffer::masterBibInfo() const
1662 // if this is a child document and the parent is already loaded
1663 // use the parent's list instead [ale990412]
1664 Buffer const * const tmp = masterBuffer();
1667 return tmp->masterBibInfo();
1668 return localBibInfo();
1672 BiblioInfo const & Buffer::localBibInfo() const
1674 checkBibInfoCache();
1679 void Buffer::checkBibInfoCache() const
1681 support::FileNameList const & bibfilesCache = getBibfilesCache();
1682 // compare the cached timestamps with the actual ones.
1683 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1684 support::FileNameList::const_iterator en = bibfilesCache.end();
1685 for (; ei != en; ++ ei) {
1686 time_t lastw = ei->lastModified();
1687 time_t prevw = d->bibfile_status_[*ei];
1688 if (lastw != prevw) {
1689 d->bibinfo_cache_valid_ = false;
1690 d->bibfile_status_[*ei] = lastw;
1694 if (!d->bibinfo_cache_valid_) {
1695 d->bibinfo_.clear();
1696 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1697 it->fillWithBibKeys(d->bibinfo_, it);
1698 d->bibinfo_cache_valid_ = true;
1703 bool Buffer::isDepClean(string const & name) const
1705 DepClean::const_iterator const it = d->dep_clean.find(name);
1706 if (it == d->dep_clean.end())
1712 void Buffer::markDepClean(string const & name)
1714 d->dep_clean[name] = true;
1718 bool Buffer::isExportableFormat(string const & format) const
1720 typedef vector<Format const *> Formats;
1722 formats = exportableFormats(true);
1723 Formats::const_iterator fit = formats.begin();
1724 Formats::const_iterator end = formats.end();
1725 for (; fit != end ; ++fit) {
1726 if ((*fit)->name() == format)
1733 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1736 // FIXME? if there is an Buffer LFUN that can be dispatched even
1737 // if internal, put a switch '(cmd.action)' here.
1743 switch (cmd.action) {
1745 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1746 flag.setOnOff(isReadonly());
1749 // FIXME: There is need for a command-line import.
1750 //case LFUN_BUFFER_IMPORT:
1752 case LFUN_BUFFER_AUTO_SAVE:
1755 case LFUN_BUFFER_EXPORT_CUSTOM:
1756 // FIXME: Nothing to check here?
1759 case LFUN_BUFFER_EXPORT: {
1760 docstring const arg = cmd.argument();
1761 enable = arg == "custom" || isExportable(to_utf8(arg));
1763 flag.message(bformat(
1764 _("Don't know how to export to format: %1$s"), arg));
1768 case LFUN_BUFFER_CHKTEX:
1769 enable = isLatex() && !lyxrc.chktex_command.empty();
1772 case LFUN_BUILD_PROGRAM:
1773 enable = isExportable("program");
1776 case LFUN_BRANCH_ACTIVATE:
1777 case LFUN_BRANCH_DEACTIVATE: {
1778 BranchList const & branchList = params().branchlist();
1779 docstring const branchName = cmd.argument();
1780 enable = !branchName.empty() && branchList.find(branchName);
1784 case LFUN_BRANCH_ADD:
1785 case LFUN_BRANCHES_RENAME:
1786 case LFUN_BUFFER_PRINT:
1787 // if no Buffer is present, then of course we won't be called!
1790 case LFUN_BUFFER_LANGUAGE:
1791 enable = !isReadonly();
1797 flag.setEnabled(enable);
1802 void Buffer::dispatch(string const & command, DispatchResult & result)
1804 return dispatch(lyxaction.lookupFunc(command), result);
1808 // NOTE We can end up here even if we have no GUI, because we are called
1809 // by LyX::exec to handled command-line requests. So we may need to check
1810 // whether we have a GUI or not. The boolean use_gui holds this information.
1811 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1814 // FIXME? if there is an Buffer LFUN that can be dispatched even
1815 // if internal, put a switch '(cmd.action)' here.
1816 dr.dispatched(false);
1819 string const argument = to_utf8(func.argument());
1820 // We'll set this back to false if need be.
1821 bool dispatched = true;
1822 undo().beginUndoGroup();
1824 switch (func.action) {
1825 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1826 if (lyxvc().inUse())
1827 lyxvc().toggleReadOnly();
1829 setReadonly(!isReadonly());
1832 case LFUN_BUFFER_EXPORT: {
1833 bool success = doExport(argument, false);
1834 dr.setError(success);
1836 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1841 case LFUN_BUILD_PROGRAM:
1842 doExport("program", true);
1845 case LFUN_BUFFER_CHKTEX:
1849 case LFUN_BUFFER_EXPORT_CUSTOM: {
1851 string command = split(argument, format_name, ' ');
1852 Format const * format = formats.getFormat(format_name);
1854 lyxerr << "Format \"" << format_name
1855 << "\" not recognized!"
1860 // The name of the file created by the conversion process
1863 // Output to filename
1864 if (format->name() == "lyx") {
1865 string const latexname = latexName(false);
1866 filename = changeExtension(latexname,
1867 format->extension());
1868 filename = addName(temppath(), filename);
1870 if (!writeFile(FileName(filename)))
1874 doExport(format_name, true, filename);
1877 // Substitute $$FName for filename
1878 if (!contains(command, "$$FName"))
1879 command = "( " + command + " ) < $$FName";
1880 command = subst(command, "$$FName", filename);
1882 // Execute the command in the background
1884 call.startscript(Systemcall::DontWait, command);
1888 // FIXME: There is need for a command-line import.
1890 case LFUN_BUFFER_IMPORT:
1895 case LFUN_BUFFER_AUTO_SAVE:
1899 case LFUN_BRANCH_ADD: {
1900 docstring const branch_name = func.argument();
1901 if (branch_name.empty()) {
1905 BranchList & branch_list = params().branchlist();
1906 Branch * branch = branch_list.find(branch_name);
1908 LYXERR0("Branch " << branch_name << " already exists.");
1910 docstring const msg =
1911 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1914 branch_list.add(branch_name);
1915 branch = branch_list.find(branch_name);
1916 string const x11hexname = X11hexname(branch->color());
1917 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1918 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
1920 dr.update(Update::Force);
1925 case LFUN_BRANCH_ACTIVATE:
1926 case LFUN_BRANCH_DEACTIVATE: {
1927 BranchList & branchList = params().branchlist();
1928 docstring const branchName = func.argument();
1929 // the case without a branch name is handled elsewhere
1930 if (branchName.empty()) {
1934 Branch * branch = branchList.find(branchName);
1936 LYXERR0("Branch " << branchName << " does not exist.");
1938 docstring const msg =
1939 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1942 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1944 dr.update(Update::Force);
1949 case LFUN_BRANCHES_RENAME: {
1950 if (func.argument().empty())
1953 docstring const oldname = from_utf8(func.getArg(0));
1954 docstring const newname = from_utf8(func.getArg(1));
1955 InsetIterator it = inset_iterator_begin(inset());
1956 InsetIterator const end = inset_iterator_end(inset());
1957 bool success = false;
1958 for (; it != end; ++it) {
1959 if (it->lyxCode() == BRANCH_CODE) {
1960 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1961 if (ins.branch() == oldname) {
1962 undo().recordUndo(it);
1963 ins.rename(newname);
1968 if (it->lyxCode() == INCLUDE_CODE) {
1969 // get buffer of external file
1970 InsetInclude const & ins =
1971 static_cast<InsetInclude const &>(*it);
1972 Buffer * child = ins.getChildBuffer();
1975 child->dispatch(func, dr);
1980 dr.update(Update::Force);
1984 case LFUN_BUFFER_PRINT: {
1985 // we'll assume there's a problem until we succeed
1987 string target = func.getArg(0);
1988 string target_name = func.getArg(1);
1989 string command = func.getArg(2);
1992 || target_name.empty()
1993 || command.empty()) {
1994 LYXERR0("Unable to parse " << func.argument());
1995 docstring const msg =
1996 bformat(_("Unable to parse \"%1$s\""), func.argument());
2000 if (target != "printer" && target != "file") {
2001 LYXERR0("Unrecognized target \"" << target << '"');
2002 docstring const msg =
2003 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2008 if (!doExport("dvi", true)) {
2009 showPrintError(absFileName());
2010 dr.setMessage(_("Error exporting to DVI."));
2014 // Push directory path.
2015 string const path = temppath();
2016 // Prevent the compiler from optimizing away p
2020 // there are three cases here:
2021 // 1. we print to a file
2022 // 2. we print directly to a printer
2023 // 3. we print using a spool command (print to file first)
2026 string const dviname = changeExtension(latexName(true), "dvi");
2028 if (target == "printer") {
2029 if (!lyxrc.print_spool_command.empty()) {
2030 // case 3: print using a spool
2031 string const psname = changeExtension(dviname,".ps");
2032 command += ' ' + lyxrc.print_to_file
2035 + quoteName(dviname);
2037 string command2 = lyxrc.print_spool_command + ' ';
2038 if (target_name != "default") {
2039 command2 += lyxrc.print_spool_printerprefix
2043 command2 += quoteName(psname);
2045 // If successful, then spool command
2046 res = one.startscript(Systemcall::Wait, command);
2049 // If there's no GUI, we have to wait on this command. Otherwise,
2050 // LyX deletes the temporary directory, and with it the spooled
2051 // file, before it can be printed!!
2052 Systemcall::Starttype stype = use_gui ?
2053 Systemcall::DontWait : Systemcall::Wait;
2054 res = one.startscript(stype, command2);
2057 // case 2: print directly to a printer
2058 if (target_name != "default")
2059 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2061 Systemcall::Starttype stype = use_gui ?
2062 Systemcall::DontWait : Systemcall::Wait;
2063 res = one.startscript(stype, command + quoteName(dviname));
2067 // case 1: print to a file
2068 FileName const filename(makeAbsPath(target_name, filePath()));
2069 FileName const dvifile(makeAbsPath(dviname, path));
2070 if (filename.exists()) {
2071 docstring text = bformat(
2072 _("The file %1$s already exists.\n\n"
2073 "Do you want to overwrite that file?"),
2074 makeDisplayPath(filename.absFilename()));
2075 if (Alert::prompt(_("Overwrite file?"),
2076 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2079 command += ' ' + lyxrc.print_to_file
2080 + quoteName(filename.toFilesystemEncoding())
2082 + quoteName(dvifile.toFilesystemEncoding());
2084 Systemcall::Starttype stype = use_gui ?
2085 Systemcall::DontWait : Systemcall::Wait;
2086 res = one.startscript(stype, command);
2092 dr.setMessage(_("Error running external commands."));
2093 showPrintError(absFileName());
2098 case LFUN_BUFFER_LANGUAGE: {
2099 Language const * oldL = params().language;
2100 Language const * newL = languages.getLanguage(argument);
2101 if (!newL || oldL == newL)
2103 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2104 changeLanguage(oldL, newL);
2112 dr.dispatched(dispatched);
2113 undo().endUndoGroup();
2117 void Buffer::changeLanguage(Language const * from, Language const * to)
2119 LASSERT(from, /**/);
2122 for_each(par_iterator_begin(),
2124 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2128 bool Buffer::isMultiLingual() const
2130 ParConstIterator end = par_iterator_end();
2131 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2132 if (it->isMultiLingual(params()))
2139 DocIterator Buffer::getParFromID(int const id) const
2141 Buffer * buf = const_cast<Buffer *>(this);
2143 // John says this is called with id == -1 from undo
2144 lyxerr << "getParFromID(), id: " << id << endl;
2145 return doc_iterator_end(buf);
2148 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2149 if (it.paragraph().id() == id)
2152 return doc_iterator_end(buf);
2156 bool Buffer::hasParWithID(int const id) const
2158 return !getParFromID(id).atEnd();
2162 ParIterator Buffer::par_iterator_begin()
2164 return ParIterator(doc_iterator_begin(this));
2168 ParIterator Buffer::par_iterator_end()
2170 return ParIterator(doc_iterator_end(this));
2174 ParConstIterator Buffer::par_iterator_begin() const
2176 return ParConstIterator(doc_iterator_begin(this));
2180 ParConstIterator Buffer::par_iterator_end() const
2182 return ParConstIterator(doc_iterator_end(this));
2186 Language const * Buffer::language() const
2188 return params().language;
2192 docstring const Buffer::B_(string const & l10n) const
2194 return params().B_(l10n);
2198 bool Buffer::isClean() const
2200 return d->lyx_clean;
2204 bool Buffer::isBakClean() const
2206 return d->bak_clean;
2210 bool Buffer::isExternallyModified(CheckMethod method) const
2212 LASSERT(d->filename.exists(), /**/);
2213 // if method == timestamp, check timestamp before checksum
2214 return (method == checksum_method
2215 || d->timestamp_ != d->filename.lastModified())
2216 && d->checksum_ != d->filename.checksum();
2220 void Buffer::saveCheckSum(FileName const & file) const
2222 if (file.exists()) {
2223 d->timestamp_ = file.lastModified();
2224 d->checksum_ = file.checksum();
2226 // in the case of save to a new file.
2233 void Buffer::markClean() const
2235 if (!d->lyx_clean) {
2236 d->lyx_clean = true;
2239 // if the .lyx file has been saved, we don't need an
2241 d->bak_clean = true;
2245 void Buffer::markBakClean() const
2247 d->bak_clean = true;
2251 void Buffer::setUnnamed(bool flag)
2257 bool Buffer::isUnnamed() const
2264 /// Don't check unnamed, here: isInternal() is used in
2265 /// newBuffer(), where the unnamed flag has not been set by anyone
2266 /// yet. Also, for an internal buffer, there should be no need for
2267 /// retrieving fileName() nor for checking if it is unnamed or not.
2268 bool Buffer::isInternal() const
2270 return fileName().extension() == "internal";
2274 void Buffer::markDirty()
2277 d->lyx_clean = false;
2280 d->bak_clean = false;
2282 DepClean::iterator it = d->dep_clean.begin();
2283 DepClean::const_iterator const end = d->dep_clean.end();
2285 for (; it != end; ++it)
2290 FileName Buffer::fileName() const
2296 string Buffer::absFileName() const
2298 return d->filename.absFilename();
2302 string Buffer::filePath() const
2304 return d->filename.onlyPath().absFilename() + "/";
2308 bool Buffer::isReadonly() const
2310 return d->read_only;
2314 void Buffer::setParent(Buffer const * buffer)
2316 // Avoids recursive include.
2317 d->setParent(buffer == this ? 0 : buffer);
2322 Buffer const * Buffer::parent() const
2328 void Buffer::collectRelatives(BufferSet & bufs) const
2332 parent()->collectRelatives(bufs);
2334 // loop over children
2335 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2336 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2337 for (; it != end; ++it)
2338 bufs.insert(const_cast<Buffer *>(it->first));
2342 std::vector<Buffer const *> Buffer::allRelatives() const
2345 collectRelatives(bufs);
2346 BufferSet::iterator it = bufs.begin();
2347 std::vector<Buffer const *> ret;
2348 for (; it != bufs.end(); ++it)
2354 Buffer const * Buffer::masterBuffer() const
2356 Buffer const * const pbuf = d->parent();
2360 return pbuf->masterBuffer();
2364 bool Buffer::isChild(Buffer * child) const
2366 return d->children_positions.find(child) != d->children_positions.end();
2370 DocIterator Buffer::firstChildPosition(Buffer const * child)
2372 Impl::BufferPositionMap::iterator it;
2373 it = d->children_positions.find(child);
2374 if (it == d->children_positions.end())
2375 return DocIterator(this);
2380 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2382 // loop over children
2383 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2384 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2385 for (; it != end; ++it) {
2386 Buffer * child = const_cast<Buffer *>(it->first);
2387 clist.push_back(child);
2388 if (grand_children) {
2389 // there might be grandchildren
2390 std::vector<Buffer *> glist = child->getChildren();
2391 for (vector<Buffer *>::const_iterator git = glist.begin();
2392 git != glist.end(); ++git)
2393 clist.push_back(*git);
2399 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2401 std::vector<Buffer *> v;
2402 getChildren(v, grand_children);
2407 template<typename M>
2408 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2413 typename M::iterator it = m.lower_bound(x);
2414 if (it == m.begin())
2422 MacroData const * Buffer::getBufferMacro(docstring const & name,
2423 DocIterator const & pos) const
2425 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2427 // if paragraphs have no macro context set, pos will be empty
2431 // we haven't found anything yet
2432 DocIterator bestPos = par_iterator_begin();
2433 MacroData const * bestData = 0;
2435 // find macro definitions for name
2436 Impl::NamePositionScopeMacroMap::iterator nameIt
2437 = d->macros.find(name);
2438 if (nameIt != d->macros.end()) {
2439 // find last definition in front of pos or at pos itself
2440 Impl::PositionScopeMacroMap::const_iterator it
2441 = greatest_below(nameIt->second, pos);
2442 if (it != nameIt->second.end()) {
2444 // scope ends behind pos?
2445 if (pos < it->second.first) {
2446 // Looks good, remember this. If there
2447 // is no external macro behind this,
2448 // we found the right one already.
2449 bestPos = it->first;
2450 bestData = &it->second.second;
2454 // try previous macro if there is one
2455 if (it == nameIt->second.begin())
2462 // find macros in included files
2463 Impl::PositionScopeBufferMap::const_iterator it
2464 = greatest_below(d->position_to_children, pos);
2465 if (it == d->position_to_children.end())
2466 // no children before
2470 // do we know something better (i.e. later) already?
2471 if (it->first < bestPos )
2474 // scope ends behind pos?
2475 if (pos < it->second.first) {
2476 // look for macro in external file
2477 d->macro_lock = true;
2478 MacroData const * data
2479 = it->second.second->getMacro(name, false);
2480 d->macro_lock = false;
2482 bestPos = it->first;
2488 // try previous file if there is one
2489 if (it == d->position_to_children.begin())
2494 // return the best macro we have found
2499 MacroData const * Buffer::getMacro(docstring const & name,
2500 DocIterator const & pos, bool global) const
2505 // query buffer macros
2506 MacroData const * data = getBufferMacro(name, pos);
2510 // If there is a master buffer, query that
2511 Buffer const * const pbuf = d->parent();
2513 d->macro_lock = true;
2514 MacroData const * macro = pbuf->getMacro(
2515 name, *this, false);
2516 d->macro_lock = false;
2522 data = MacroTable::globalMacros().get(name);
2531 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2533 // set scope end behind the last paragraph
2534 DocIterator scope = par_iterator_begin();
2535 scope.pit() = scope.lastpit() + 1;
2537 return getMacro(name, scope, global);
2541 MacroData const * Buffer::getMacro(docstring const & name,
2542 Buffer const & child, bool global) const
2544 // look where the child buffer is included first
2545 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2546 if (it == d->children_positions.end())
2549 // check for macros at the inclusion position
2550 return getMacro(name, it->second, global);
2554 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2556 pit_type lastpit = it.lastpit();
2558 // look for macros in each paragraph
2559 while (it.pit() <= lastpit) {
2560 Paragraph & par = it.paragraph();
2562 // iterate over the insets of the current paragraph
2563 InsetList const & insets = par.insetList();
2564 InsetList::const_iterator iit = insets.begin();
2565 InsetList::const_iterator end = insets.end();
2566 for (; iit != end; ++iit) {
2567 it.pos() = iit->pos;
2569 // is it a nested text inset?
2570 if (iit->inset->asInsetText()) {
2571 // Inset needs its own scope?
2572 InsetText const * itext = iit->inset->asInsetText();
2573 bool newScope = itext->isMacroScope();
2575 // scope which ends just behind the inset
2576 DocIterator insetScope = it;
2579 // collect macros in inset
2580 it.push_back(CursorSlice(*iit->inset));
2581 updateMacros(it, newScope ? insetScope : scope);
2586 // is it an external file?
2587 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2588 // get buffer of external file
2589 InsetInclude const & inset =
2590 static_cast<InsetInclude const &>(*iit->inset);
2591 d->macro_lock = true;
2592 Buffer * child = inset.getChildBuffer();
2593 d->macro_lock = false;
2597 // register its position, but only when it is
2598 // included first in the buffer
2599 if (d->children_positions.find(child) ==
2600 d->children_positions.end())
2601 d->children_positions[child] = it;
2603 // register child with its scope
2604 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2608 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2612 MathMacroTemplate & macroTemplate =
2613 static_cast<MathMacroTemplate &>(*iit->inset);
2614 MacroContext mc(this, it);
2615 macroTemplate.updateToContext(mc);
2618 bool valid = macroTemplate.validMacro();
2619 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2620 // then the BufferView's cursor will be invalid in
2621 // some cases which leads to crashes.
2626 // FIXME (Abdel), I don't understandt why we pass 'it' here
2627 // instead of 'macroTemplate' defined above... is this correct?
2628 d->macros[macroTemplate.name()][it] =
2629 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2639 void Buffer::updateMacros() const
2644 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2646 // start with empty table
2648 d->children_positions.clear();
2649 d->position_to_children.clear();
2651 // Iterate over buffer, starting with first paragraph
2652 // The scope must be bigger than any lookup DocIterator
2653 // later. For the global lookup, lastpit+1 is used, hence
2654 // we use lastpit+2 here.
2655 DocIterator it = par_iterator_begin();
2656 DocIterator outerScope = it;
2657 outerScope.pit() = outerScope.lastpit() + 2;
2658 updateMacros(it, outerScope);
2662 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2664 InsetIterator it = inset_iterator_begin(inset());
2665 InsetIterator const end = inset_iterator_end(inset());
2666 for (; it != end; ++it) {
2667 if (it->lyxCode() == BRANCH_CODE) {
2668 InsetBranch & br = static_cast<InsetBranch &>(*it);
2669 docstring const name = br.branch();
2670 if (!from_master && !params().branchlist().find(name))
2671 result.push_back(name);
2672 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2673 result.push_back(name);
2676 if (it->lyxCode() == INCLUDE_CODE) {
2677 // get buffer of external file
2678 InsetInclude const & ins =
2679 static_cast<InsetInclude const &>(*it);
2680 Buffer * child = ins.getChildBuffer();
2683 child->getUsedBranches(result, true);
2686 // remove duplicates
2691 void Buffer::updateMacroInstances() const
2693 LYXERR(Debug::MACROS, "updateMacroInstances for "
2694 << d->filename.onlyFileName());
2695 DocIterator it = doc_iterator_begin(this);
2697 DocIterator const end = doc_iterator_end(this);
2698 for (; it != end; it.forwardInset()) {
2699 // look for MathData cells in InsetMathNest insets
2700 InsetMath * minset = it.nextInset()->asInsetMath();
2704 // update macro in all cells of the InsetMathNest
2705 DocIterator::idx_type n = minset->nargs();
2706 MacroContext mc = MacroContext(this, it);
2707 for (DocIterator::idx_type i = 0; i < n; ++i) {
2708 MathData & data = minset->cell(i);
2709 data.updateMacros(0, mc);
2715 void Buffer::listMacroNames(MacroNameSet & macros) const
2720 d->macro_lock = true;
2722 // loop over macro names
2723 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2724 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2725 for (; nameIt != nameEnd; ++nameIt)
2726 macros.insert(nameIt->first);
2728 // loop over children
2729 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2730 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2731 for (; it != end; ++it)
2732 it->first->listMacroNames(macros);
2735 Buffer const * const pbuf = d->parent();
2737 pbuf->listMacroNames(macros);
2739 d->macro_lock = false;
2743 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2745 Buffer const * const pbuf = d->parent();
2750 pbuf->listMacroNames(names);
2753 MacroNameSet::iterator it = names.begin();
2754 MacroNameSet::iterator end = names.end();
2755 for (; it != end; ++it) {
2757 MacroData const * data =
2758 pbuf->getMacro(*it, *this, false);
2760 macros.insert(data);
2762 // we cannot access the original MathMacroTemplate anymore
2763 // here to calls validate method. So we do its work here manually.
2764 // FIXME: somehow make the template accessible here.
2765 if (data->optionals() > 0)
2766 features.require("xargs");
2772 Buffer::References & Buffer::references(docstring const & label)
2775 return const_cast<Buffer *>(masterBuffer())->references(label);
2777 RefCache::iterator it = d->ref_cache_.find(label);
2778 if (it != d->ref_cache_.end())
2779 return it->second.second;
2781 static InsetLabel const * dummy_il = 0;
2782 static References const dummy_refs;
2783 it = d->ref_cache_.insert(
2784 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2785 return it->second.second;
2789 Buffer::References const & Buffer::references(docstring const & label) const
2791 return const_cast<Buffer *>(this)->references(label);
2795 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2797 masterBuffer()->d->ref_cache_[label].first = il;
2801 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2803 return masterBuffer()->d->ref_cache_[label].first;
2807 void Buffer::clearReferenceCache() const
2810 d->ref_cache_.clear();
2814 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2817 //FIXME: This does not work for child documents yet.
2818 LASSERT(code == CITE_CODE, /**/);
2819 // Check if the label 'from' appears more than once
2820 vector<docstring> labels;
2822 BiblioInfo const & keys = masterBibInfo();
2823 BiblioInfo::const_iterator bit = keys.begin();
2824 BiblioInfo::const_iterator bend = keys.end();
2826 for (; bit != bend; ++bit)
2828 labels.push_back(bit->first);
2831 if (count(labels.begin(), labels.end(), from) > 1)
2834 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2835 if (it->lyxCode() == code) {
2836 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2837 docstring const oldValue = inset.getParam(paramName);
2838 if (oldValue == from)
2839 inset.setParam(paramName, to);
2845 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2846 pit_type par_end, bool full_source) const
2848 OutputParams runparams(¶ms().encoding());
2849 runparams.nice = true;
2850 runparams.flavor = params().useXetex ?
2851 OutputParams::XETEX : OutputParams::LATEX;
2852 runparams.linelen = lyxrc.plaintext_linelen;
2853 // No side effect of file copying and image conversion
2854 runparams.dryrun = true;
2857 os << "% " << _("Preview source code") << "\n\n";
2859 d->texrow.newline();
2860 d->texrow.newline();
2862 writeDocBookSource(os, absFileName(), runparams, false);
2864 // latex or literate
2865 writeLaTeXSource(os, string(), runparams, true, true);
2867 runparams.par_begin = par_begin;
2868 runparams.par_end = par_end;
2869 if (par_begin + 1 == par_end) {
2871 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2875 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2876 convert<docstring>(par_begin),
2877 convert<docstring>(par_end - 1))
2884 // output paragraphs
2886 docbookParagraphs(text(), *this, os, runparams);
2888 // latex or literate
2889 latexParagraphs(*this, text(), os, texrow, runparams);
2894 ErrorList & Buffer::errorList(string const & type) const
2896 static ErrorList emptyErrorList;
2897 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2898 if (I == d->errorLists.end())
2899 return emptyErrorList;
2905 void Buffer::updateTocItem(std::string const & type,
2906 DocIterator const & dit) const
2909 gui_->updateTocItem(type, dit);
2913 void Buffer::structureChanged() const
2916 gui_->structureChanged();
2920 void Buffer::errors(string const & err, bool from_master) const
2923 gui_->errors(err, from_master);
2927 void Buffer::message(docstring const & msg) const
2934 void Buffer::setBusy(bool on) const
2941 void Buffer::setReadOnly(bool on) const
2944 d->wa_->setReadOnly(on);
2948 void Buffer::updateTitles() const
2951 d->wa_->updateTitles();
2955 void Buffer::resetAutosaveTimers() const
2958 gui_->resetAutosaveTimers();
2962 bool Buffer::hasGuiDelegate() const
2968 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2977 class AutoSaveBuffer : public ForkedProcess {
2980 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2981 : buffer_(buffer), fname_(fname) {}
2983 virtual boost::shared_ptr<ForkedProcess> clone() const
2985 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2990 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2991 from_utf8(fname_.absFilename())));
2992 return run(DontWait);
2996 virtual int generateChild();
2998 Buffer const & buffer_;
3003 int AutoSaveBuffer::generateChild()
3005 #if defined(__APPLE__)
3006 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3007 * We should use something else like threads.
3009 * Since I do not know how to determine at run time what is the OS X
3010 * version, I just disable forking altogether for now (JMarc)
3012 pid_t const pid = -1;
3014 // tmp_ret will be located (usually) in /tmp
3015 // will that be a problem?
3016 // Note that this calls ForkedCalls::fork(), so it's
3017 // ok cross-platform.
3018 pid_t const pid = fork();
3019 // If you want to debug the autosave
3020 // you should set pid to -1, and comment out the fork.
3021 if (pid != 0 && pid != -1)
3025 // pid = -1 signifies that lyx was unable
3026 // to fork. But we will do the save
3028 bool failed = false;
3029 FileName const tmp_ret = FileName::tempName("lyxauto");
3030 if (!tmp_ret.empty()) {
3031 buffer_.writeFile(tmp_ret);
3032 // assume successful write of tmp_ret
3033 if (!tmp_ret.moveTo(fname_))
3039 // failed to write/rename tmp_ret so try writing direct
3040 if (!buffer_.writeFile(fname_)) {
3041 // It is dangerous to do this in the child,
3042 // but safe in the parent, so...
3043 if (pid == -1) // emit message signal.
3044 buffer_.message(_("Autosave failed!"));
3048 if (pid == 0) // we are the child so...
3057 FileName Buffer::getAutosaveFilename() const
3059 // if the document is unnamed try to save in the backup dir, else
3060 // in the default document path, and as a last try in the filePath,
3061 // which will most often be the temporary directory
3064 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3065 : lyxrc.backupdir_path;
3066 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3069 string const fname = "#" + d->filename.onlyFileName() + "#";
3070 return makeAbsPath(fname, fpath);
3074 void Buffer::removeAutosaveFile() const
3076 FileName const f = getAutosaveFilename();
3082 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3084 FileName const newauto = getAutosaveFilename();
3085 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3086 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3090 // Perfect target for a thread...
3091 void Buffer::autoSave() const
3093 if (isBakClean() || isReadonly()) {
3094 // We don't save now, but we'll try again later
3095 resetAutosaveTimers();
3099 // emit message signal.
3100 message(_("Autosaving current document..."));
3101 AutoSaveBuffer autosave(*this, getAutosaveFilename());
3105 resetAutosaveTimers();
3109 string Buffer::bufferFormat() const
3111 string format = params().documentClass().outputFormat();
3112 if (format == "latex") {
3113 if (params().useXetex)
3115 if (params().encoding().package() == Encoding::japanese)
3122 string Buffer::getDefaultOutputFormat() const
3124 if (!params().defaultOutputFormat.empty()
3125 && params().defaultOutputFormat != "default")
3126 return params().defaultOutputFormat;
3127 typedef vector<Format const *> Formats;
3128 Formats formats = exportableFormats(true);
3131 || params().useXetex
3132 || params().encoding().package() == Encoding::japanese) {
3133 if (formats.empty())
3135 // return the first we find
3136 return formats.front()->name();
3138 return lyxrc.default_view_format;
3143 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3144 string & result_file) const
3146 string backend_format;
3147 OutputParams runparams(¶ms().encoding());
3148 runparams.flavor = OutputParams::LATEX;
3149 runparams.linelen = lyxrc.plaintext_linelen;
3150 vector<string> backs = backends();
3151 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3152 // Get shortest path to format
3153 Graph::EdgePath path;
3154 for (vector<string>::const_iterator it = backs.begin();
3155 it != backs.end(); ++it) {
3156 Graph::EdgePath p = theConverters().getPath(*it, format);
3157 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3158 backend_format = *it;
3163 if (!put_in_tempdir) {
3164 // Only show this alert if this is an export to a non-temporary
3165 // file (not for previewing).
3166 Alert::error(_("Couldn't export file"), bformat(
3167 _("No information for exporting the format %1$s."),
3168 formats.prettyName(format)));
3172 runparams.flavor = theConverters().getFlavor(path);
3175 backend_format = format;
3176 // FIXME: Don't hardcode format names here, but use a flag
3177 if (backend_format == "pdflatex")
3178 runparams.flavor = OutputParams::PDFLATEX;
3181 string filename = latexName(false);
3182 filename = addName(temppath(), filename);
3183 filename = changeExtension(filename,
3184 formats.extension(backend_format));
3187 updateMacroInstances();
3189 // Plain text backend
3190 if (backend_format == "text") {
3191 runparams.flavor = OutputParams::TEXT;
3192 writePlaintextFile(*this, FileName(filename), runparams);
3195 else if (backend_format == "xhtml") {
3196 runparams.flavor = OutputParams::HTML;
3197 makeLyXHTMLFile(FileName(filename), runparams);
3198 } else if (backend_format == "lyx")
3199 writeFile(FileName(filename));
3201 else if (isDocBook()) {
3202 runparams.nice = !put_in_tempdir;
3203 makeDocBookFile(FileName(filename), runparams);
3206 else if (backend_format == format) {
3207 runparams.nice = true;
3208 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3210 } else if (!lyxrc.tex_allows_spaces
3211 && contains(filePath(), ' ')) {
3212 Alert::error(_("File name error"),
3213 _("The directory path to the document cannot contain spaces."));
3216 runparams.nice = false;
3217 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3221 string const error_type = (format == "program")
3222 ? "Build" : bufferFormat();
3223 ErrorList & error_list = d->errorLists[error_type];
3224 string const ext = formats.extension(format);
3225 FileName const tmp_result_file(changeExtension(filename, ext));
3226 bool const success = theConverters().convert(this, FileName(filename),
3227 tmp_result_file, FileName(absFileName()), backend_format, format,
3229 // Emit the signal to show the error list.
3230 if (format != backend_format) {
3232 // also to the children, in case of master-buffer-view
3233 std::vector<Buffer *> clist = getChildren();
3234 for (vector<Buffer *>::const_iterator cit = clist.begin();
3235 cit != clist.end(); ++cit)
3236 (*cit)->errors(error_type, true);
3241 if (d->cloned_buffer_) {
3242 // Enable reverse dvi or pdf to work by copying back the texrow
3243 // object to the cloned buffer.
3244 // FIXME: There is a possibility of concurrent access to texrow
3245 // here from the main GUI thread that should be securized.
3246 d->cloned_buffer_->d->texrow = d->texrow;
3249 if (put_in_tempdir) {
3250 result_file = tmp_result_file.absFilename();
3254 result_file = changeExtension(exportFileName().absFilename(), ext);
3255 // We need to copy referenced files (e. g. included graphics
3256 // if format == "dvi") to the result dir.
3257 vector<ExportedFile> const files =
3258 runparams.exportdata->externalFiles(format);
3259 string const dest = onlyPath(result_file);
3260 CopyStatus status = SUCCESS;
3261 for (vector<ExportedFile>::const_iterator it = files.begin();
3262 it != files.end() && status != CANCEL; ++it) {
3263 string const fmt = formats.getFormatFromFile(it->sourceName);
3264 status = copyFile(fmt, it->sourceName,
3265 makeAbsPath(it->exportName, dest),
3266 it->exportName, status == FORCE);
3268 if (status == CANCEL) {
3269 message(_("Document export cancelled."));
3270 } else if (tmp_result_file.exists()) {
3271 // Finally copy the main file
3272 status = copyFile(format, tmp_result_file,
3273 FileName(result_file), result_file,
3275 message(bformat(_("Document exported as %1$s "
3277 formats.prettyName(format),
3278 makeDisplayPath(result_file)));
3280 // This must be a dummy converter like fax (bug 1888)
3281 message(bformat(_("Document exported as %1$s"),
3282 formats.prettyName(format)));
3289 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3292 return doExport(format, put_in_tempdir, result_file);
3296 bool Buffer::preview(string const & format) const
3299 if (!doExport(format, true, result_file))
3301 return formats.view(*this, FileName(result_file), format);
3305 bool Buffer::isExportable(string const & format) const
3307 vector<string> backs = backends();
3308 for (vector<string>::const_iterator it = backs.begin();
3309 it != backs.end(); ++it)
3310 if (theConverters().isReachable(*it, format))
3316 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3318 vector<string> const backs = backends();
3319 vector<Format const *> result =
3320 theConverters().getReachable(backs[0], only_viewable, true);
3321 for (vector<string>::const_iterator it = backs.begin() + 1;
3322 it != backs.end(); ++it) {
3323 vector<Format const *> r =
3324 theConverters().getReachable(*it, only_viewable, false);
3325 result.insert(result.end(), r.begin(), r.end());
3331 vector<string> Buffer::backends() const
3334 v.push_back(bufferFormat());
3335 // FIXME: Don't hardcode format names here, but use a flag
3336 if (v.back() == "latex")
3337 v.push_back("pdflatex");
3338 v.push_back("xhtml");
3339 v.push_back("text");
3345 bool Buffer::readFileHelper(FileName const & s)
3347 // File information about normal file
3349 docstring const file = makeDisplayPath(s.absFilename(), 50);
3350 docstring text = bformat(_("The specified document\n%1$s"
3351 "\ncould not be read."), file);
3352 Alert::error(_("Could not read document"), text);
3356 // Check if emergency save file exists and is newer.
3357 FileName const e(s.absFilename() + ".emergency");
3359 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3360 docstring const file = makeDisplayPath(s.absFilename(), 20);
3361 docstring const text =
3362 bformat(_("An emergency save of the document "
3364 "Recover emergency save?"), file);
3365 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3366 _("&Recover"), _("&Load Original"),
3370 // the file is not saved if we load the emergency file.
3375 if ((res = readFile(e)) == success)
3376 str = _("Document was successfully recovered.");
3378 str = _("Document was NOT successfully recovered.");
3379 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3380 from_utf8(e.absFilename()));
3382 if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3383 _("&Remove"), _("&Keep it"))) {
3386 Alert::warning(_("Emergency file deleted"),
3387 _("Do not forget to save your file now!"), true);
3392 if (!Alert::prompt(_("Delete emergency file?"),
3393 _("Remove emergency file now?"), 1, 1,
3394 _("&Remove"), _("&Keep it")))
3402 // Now check if autosave file is newer.
3403 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3405 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3406 docstring const file = makeDisplayPath(s.absFilename(), 20);
3407 docstring const text =
3408 bformat(_("The backup of the document "
3409 "%1$s is newer.\n\nLoad the "
3410 "backup instead?"), file);
3411 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3412 _("&Load backup"), _("Load &original"),
3416 // the file is not saved if we load the autosave file.
3420 // Here we delete the autosave
3431 bool Buffer::loadLyXFile(FileName const & s)
3433 // If the file is not readable, we try to
3434 // retrieve the file from version control.
3435 if (!s.isReadableFile()
3436 && !LyXVC::file_not_found_hook(s))
3439 if (s.isReadableFile()
3440 && readFileHelper(s)) {
3441 lyxvc().file_found_hook(s);
3442 setReadonly(!s.isWritable());
3449 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3451 TeXErrors::Errors::const_iterator cit = terr.begin();
3452 TeXErrors::Errors::const_iterator end = terr.end();
3454 for (; cit != end; ++cit) {
3457 int errorRow = cit->error_in_line;
3458 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3464 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3465 } while (found && id_start == id_end && pos_start == pos_end);
3467 errorList.push_back(ErrorItem(cit->error_desc,
3468 cit->error_text, id_start, pos_start, pos_end));
3473 void Buffer::setBuffersForInsets() const
3475 inset().setBuffer(const_cast<Buffer &>(*this));
3479 void Buffer::updateLabels(UpdateScope scope, bool out) const
3481 // Use the master text class also for child documents
3482 Buffer const * const master = masterBuffer();
3483 DocumentClass const & textclass = master->params().documentClass();
3485 // keep the buffers to be children in this set. If the call from the
3486 // master comes back we can see which of them were actually seen (i.e.
3487 // via an InsetInclude). The remaining ones in the set need still be updated.
3488 static std::set<Buffer const *> bufToUpdate;
3489 if (scope == UpdateMaster) {
3490 // If this is a child document start with the master
3491 if (master != this) {
3492 bufToUpdate.insert(this);
3493 master->updateLabels(UpdateMaster, out);
3494 // Do this here in case the master has no gui associated with it. Then,
3495 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3499 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3500 if (bufToUpdate.find(this) == bufToUpdate.end())
3504 // start over the counters in the master
3505 textclass.counters().reset();
3508 // update will be done below for this buffer
3509 bufToUpdate.erase(this);
3511 // update all caches
3512 clearReferenceCache();
3515 Buffer & cbuf = const_cast<Buffer &>(*this);
3517 LASSERT(!text().paragraphs().empty(), /**/);
3520 ParIterator parit = cbuf.par_iterator_begin();
3521 updateLabels(parit, out);
3524 // TocBackend update will be done later.
3527 cbuf.tocBackend().update();
3528 if (scope == UpdateMaster)
3529 cbuf.structureChanged();
3533 static depth_type getDepth(DocIterator const & it)
3535 depth_type depth = 0;
3536 for (size_t i = 0 ; i < it.depth() ; ++i)
3537 if (!it[i].inset().inMathed())
3538 depth += it[i].paragraph().getDepth() + 1;
3539 // remove 1 since the outer inset does not count
3543 static depth_type getItemDepth(ParIterator const & it)
3545 Paragraph const & par = *it;
3546 LabelType const labeltype = par.layout().labeltype;
3548 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3551 // this will hold the lowest depth encountered up to now.
3552 depth_type min_depth = getDepth(it);
3553 ParIterator prev_it = it;
3556 --prev_it.top().pit();
3558 // start of nested inset: go to outer par
3560 if (prev_it.empty()) {
3561 // start of document: nothing to do
3566 // We search for the first paragraph with same label
3567 // that is not more deeply nested.
3568 Paragraph & prev_par = *prev_it;
3569 depth_type const prev_depth = getDepth(prev_it);
3570 if (labeltype == prev_par.layout().labeltype) {
3571 if (prev_depth < min_depth)
3572 return prev_par.itemdepth + 1;
3573 if (prev_depth == min_depth)
3574 return prev_par.itemdepth;
3576 min_depth = min(min_depth, prev_depth);
3577 // small optimization: if we are at depth 0, we won't
3578 // find anything else
3579 if (prev_depth == 0)
3585 static bool needEnumCounterReset(ParIterator const & it)
3587 Paragraph const & par = *it;
3588 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3589 depth_type const cur_depth = par.getDepth();
3590 ParIterator prev_it = it;
3591 while (prev_it.pit()) {
3592 --prev_it.top().pit();
3593 Paragraph const & prev_par = *prev_it;
3594 if (prev_par.getDepth() <= cur_depth)
3595 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3597 // start of nested inset: reset
3602 // set the label of a paragraph. This includes the counters.
3603 void Buffer::setLabel(ParIterator & it) const
3605 BufferParams const & bp = this->masterBuffer()->params();
3606 DocumentClass const & textclass = bp.documentClass();
3607 Paragraph & par = it.paragraph();
3608 Layout const & layout = par.layout();
3609 Counters & counters = textclass.counters();
3611 if (par.params().startOfAppendix()) {
3612 // FIXME: only the counter corresponding to toplevel
3613 // sectioning should be reset
3615 counters.appendix(true);
3617 par.params().appendix(counters.appendix());
3619 // Compute the item depth of the paragraph
3620 par.itemdepth = getItemDepth(it);
3622 if (layout.margintype == MARGIN_MANUAL
3623 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3624 if (par.params().labelWidthString().empty())
3625 par.params().labelWidthString(par.expandLabel(layout, bp));
3627 par.params().labelWidthString(docstring());
3630 switch(layout.labeltype) {
3632 if (layout.toclevel <= bp.secnumdepth
3633 && (layout.latextype != LATEX_ENVIRONMENT
3634 || it.text()->isFirstInSequence(it.pit()))) {
3635 counters.step(layout.counter);
3636 par.params().labelString(
3637 par.expandLabel(layout, bp));
3639 par.params().labelString(docstring());
3642 case LABEL_ITEMIZE: {
3643 // At some point of time we should do something more
3644 // clever here, like:
3645 // par.params().labelString(
3646 // bp.user_defined_bullet(par.itemdepth).getText());
3647 // for now, use a simple hardcoded label
3648 docstring itemlabel;
3649 switch (par.itemdepth) {
3651 itemlabel = char_type(0x2022);
3654 itemlabel = char_type(0x2013);
3657 itemlabel = char_type(0x2217);
3660 itemlabel = char_type(0x2219); // or 0x00b7
3663 par.params().labelString(itemlabel);
3667 case LABEL_ENUMERATE: {
3668 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3670 switch (par.itemdepth) {
3679 enumcounter += "iv";
3682 // not a valid enumdepth...
3686 // Maybe we have to reset the enumeration counter.
3687 if (needEnumCounterReset(it))
3688 counters.reset(enumcounter);
3689 counters.step(enumcounter);
3691 string const & lang = par.getParLanguage(bp)->code();
3692 par.params().labelString(counters.theCounter(enumcounter, lang));
3697 case LABEL_SENSITIVE: {
3698 string const & type = counters.current_float();
3699 docstring full_label;
3701 full_label = this->B_("Senseless!!! ");
3703 docstring name = this->B_(textclass.floats().getType(type).name());
3704 if (counters.hasCounter(from_utf8(type))) {
3705 string const & lang = par.getParLanguage(bp)->code();
3706 counters.step(from_utf8(type));
3707 full_label = bformat(from_ascii("%1$s %2$s:"),
3709 counters.theCounter(from_utf8(type), lang));
3711 full_label = bformat(from_ascii("%1$s #:"), name);
3713 par.params().labelString(full_label);
3717 case LABEL_NO_LABEL:
3718 par.params().labelString(docstring());
3722 case LABEL_TOP_ENVIRONMENT:
3723 case LABEL_CENTERED_TOP_ENVIRONMENT:
3726 par.params().labelString(par.expandLabel(layout, bp));
3732 void Buffer::updateLabels(ParIterator & parit, bool out) const
3734 LASSERT(parit.pit() == 0, /**/);
3736 // set the position of the text in the buffer to be able
3737 // to resolve macros in it. This has nothing to do with
3738 // labels, but by putting it here we avoid implementing
3739 // a whole bunch of traversal routines just for this call.
3740 parit.text()->setMacrocontextPosition(parit);
3742 depth_type maxdepth = 0;
3743 pit_type const lastpit = parit.lastpit();
3744 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3745 // reduce depth if necessary
3746 parit->params().depth(min(parit->params().depth(), maxdepth));
3747 maxdepth = parit->getMaxDepthAfter();
3749 // set the counter for this paragraph
3753 InsetList::const_iterator iit = parit->insetList().begin();
3754 InsetList::const_iterator end = parit->insetList().end();
3755 for (; iit != end; ++iit) {
3756 parit.pos() = iit->pos;
3757 iit->inset->updateLabels(parit, out);
3763 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3764 WordLangTuple & word_lang, docstring_list & suggestions) const
3768 suggestions.clear();
3769 word_lang = WordLangTuple();
3770 // OK, we start from here.
3771 DocIterator const end = doc_iterator_end(this);
3772 for (; from != end; from.forwardPos()) {
3773 // We are only interested in text so remove the math CursorSlice.
3774 while (from.inMathed()) {
3778 // If from is at the end of the document (which is possible
3779 // when leaving the mathed) LyX will crash later.
3783 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3788 // Do not increase progress when from == to, otherwise the word
3789 // count will be wrong.
3799 bool Buffer::reload()
3802 // e.g., read-only status could have changed due to version control
3803 d->filename.refresh();
3804 docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3806 bool const success = loadLyXFile(d->filename);
3811 message(bformat(_("Document %1$s reloaded."), disp_fn));
3813 message(bformat(_("Could not reload document %1$s."), disp_fn));