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"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "frontends/alert.h"
82 #include "frontends/Delegates.h"
83 #include "frontends/WorkAreaManager.h"
85 #include "graphics/Previews.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/Path.h"
103 #include "support/Systemcall.h"
104 #include "support/textutils.h"
105 #include "support/types.h"
107 #include "support/bind.h"
108 #include "support/shared_ptr.h"
120 using namespace lyx::support;
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
129 // Do not remove the comment below, so we get merge conflict in
130 // independent branches. Instead add your own.
131 int const LYX_FORMAT = 410; // rgh: dummy format for list->labeling
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this an unnamed file (New...)?
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
208 mutable TocBackend toc_backend;
211 typedef pair<DocIterator, MacroData> ScopeMacro;
212 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
213 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
214 /// map from the macro name to the position map,
215 /// which maps the macro definition position to the scope and the MacroData.
216 NamePositionScopeMacroMap macros;
217 /// This seem to change the way Buffer::getMacro() works
218 mutable bool macro_lock;
220 /// positions of child buffers in the buffer
221 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
222 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
223 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
224 /// position of children buffers in this buffer
225 BufferPositionMap children_positions;
226 /// map from children inclusion positions to their scope and their buffer
227 PositionScopeBufferMap position_to_children;
229 /// Container for all sort of Buffer dependant errors.
230 map<string, ErrorList> errorLists;
232 /// timestamp and checksum used to test if the file has been externally
233 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
235 unsigned long checksum_;
238 frontend::WorkAreaManager * wa_;
240 frontend::GuiBufferDelegate * gui_;
245 /// A cache for the bibfiles (including bibfiles of loaded child
246 /// documents), needed for appropriate update of natbib labels.
247 mutable support::FileNameList bibfiles_cache_;
249 // FIXME The caching mechanism could be improved. At present, we have a
250 // cache for each Buffer, that caches all the bibliography info for that
251 // Buffer. A more efficient solution would be to have a global cache per
252 // file, and then to construct the Buffer's bibinfo from that.
253 /// A cache for bibliography info
254 mutable BiblioInfo bibinfo_;
255 /// whether the bibinfo cache is valid
256 mutable bool bibinfo_cache_valid_;
257 /// whether the bibfile cache is valid
258 mutable bool bibfile_cache_valid_;
259 /// Cache of timestamps of .bib files
260 map<FileName, time_t> bibfile_status_;
262 mutable RefCache ref_cache_;
264 /// our Text that should be wrapped in an InsetText
267 /// This is here to force the test to be done whenever parent_buffer
269 Buffer const * parent() const {
270 // if parent_buffer is not loaded, then it has been unloaded,
271 // which means that parent_buffer is an invalid pointer. So we
272 // set it to null in that case.
273 // however, the BufferList doesn't know about cloned buffers, so
274 // they will always be regarded as unloaded. in that case, we hope
276 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
278 return parent_buffer;
282 void setParent(Buffer const * pb) {
283 if (parent_buffer == pb)
286 if (!cloned_buffer_ && parent_buffer && pb)
287 LYXERR0("Warning: a buffer should not have two parents!");
289 if (!cloned_buffer_ && parent_buffer) {
290 parent_buffer->invalidateBibfileCache();
291 parent_buffer->invalidateBibinfoCache();
295 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
296 /// This one is useful for preview detached in a thread.
297 Buffer const * cloned_buffer_;
298 /// are we in the process of exporting this buffer?
299 mutable bool doing_export;
302 /// So we can force access via the accessors.
303 mutable Buffer const * parent_buffer;
308 /// Creates the per buffer temporary directory
309 static FileName createBufferTmpDir()
312 // We are in our own directory. Why bother to mangle name?
313 // In fact I wrote this code to circumvent a problematic behaviour
314 // (bug?) of EMX mkstemp().
315 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
316 convert<string>(count++));
318 if (!tmpfl.createDirectory(0777)) {
319 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
320 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
321 from_utf8(tmpfl.absFileName())));
327 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
328 Buffer const * cloned_buffer)
329 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
330 read_only(readonly_), filename(file), file_fully_loaded(false),
331 toc_backend(owner), macro_lock(false), timestamp_(0),
332 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
333 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
334 doing_export(false), parent_buffer(0)
336 if (!cloned_buffer_) {
337 temppath = createBufferTmpDir();
338 lyxvc.setBuffer(owner_);
340 wa_ = new frontend::WorkAreaManager;
343 temppath = cloned_buffer_->d->temppath;
344 file_fully_loaded = true;
345 params = cloned_buffer_->d->params;
346 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
347 bibinfo_ = cloned_buffer_->d->bibinfo_;
348 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
349 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
350 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
354 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
355 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
357 LYXERR(Debug::INFO, "Buffer::Buffer()");
359 d->inset = new InsetText(*cloned_buffer->d->inset);
360 d->inset->setBuffer(*this);
361 // FIXME: optimize this loop somewhat, maybe by creating a new
362 // general recursive Inset::setId().
363 DocIterator it = doc_iterator_begin(this);
364 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
365 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
366 it.paragraph().setId(cloned_it.paragraph().id());
368 d->inset = new InsetText(this);
369 d->inset->setAutoBreakRows(true);
370 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
376 LYXERR(Debug::INFO, "Buffer::~Buffer()");
377 // here the buffer should take care that it is
378 // saved properly, before it goes into the void.
380 // GuiView already destroyed
384 // No need to do additional cleanups for internal buffer.
389 // loop over children
390 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
391 Impl::BufferPositionMap::iterator end = d->children_positions.end();
392 for (; it != end; ++it) {
393 Buffer * child = const_cast<Buffer *>(it->first);
394 if (d->cloned_buffer_)
396 // The child buffer might have been closed already.
397 else if (theBufferList().isLoaded(child))
398 theBufferList().releaseChild(this, child);
402 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
403 msg += emergencyWrite();
404 Alert::warning(_("Attempting to close changed document!"), msg);
407 // clear references to children in macro tables
408 d->children_positions.clear();
409 d->position_to_children.clear();
411 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
412 Alert::warning(_("Could not remove temporary directory"),
413 bformat(_("Could not remove the temporary directory %1$s"),
414 from_utf8(d->temppath.absFileName())));
424 Buffer * Buffer::clone() const
426 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
427 buffer_clone->d->macro_lock = true;
428 buffer_clone->d->children_positions.clear();
429 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
430 // math macro caches need to be rethought and simplified.
431 // I am not sure wether we should handle Buffer cloning here or in BufferList.
432 // Right now BufferList knows nothing about buffer clones.
433 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
434 Impl::BufferPositionMap::iterator end = d->children_positions.end();
435 for (; it != end; ++it) {
436 DocIterator dit = it->second.clone(buffer_clone);
437 dit.setBuffer(buffer_clone);
438 Buffer * child = const_cast<Buffer *>(it->first);
439 Buffer * child_clone = child->clone();
440 Inset * inset = dit.nextInset();
441 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
442 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
443 inset_inc->setChildBuffer(child_clone);
444 child_clone->d->setParent(buffer_clone);
445 buffer_clone->setChild(dit, child_clone);
447 buffer_clone->d->macro_lock = false;
452 bool Buffer::isClone() const
454 return d->cloned_buffer_;
458 void Buffer::changed(bool update_metrics) const
461 d->wa_->redrawAll(update_metrics);
465 frontend::WorkAreaManager & Buffer::workAreaManager() const
467 LASSERT(d->wa_, /**/);
472 Text & Buffer::text() const
474 return d->inset->text();
478 Inset & Buffer::inset() const
484 BufferParams & Buffer::params()
490 BufferParams const & Buffer::params() const
496 ParagraphList & Buffer::paragraphs()
498 return text().paragraphs();
502 ParagraphList const & Buffer::paragraphs() const
504 return text().paragraphs();
508 LyXVC & Buffer::lyxvc()
514 LyXVC const & Buffer::lyxvc() const
520 string const Buffer::temppath() const
522 return d->temppath.absFileName();
526 TexRow & Buffer::texrow()
532 TexRow const & Buffer::texrow() const
538 TocBackend & Buffer::tocBackend() const
540 return d->toc_backend;
544 Undo & Buffer::undo()
550 void Buffer::setChild(DocIterator const & dit, Buffer * child)
552 d->children_positions[child] = dit;
556 string Buffer::latexName(bool const no_path) const
558 FileName latex_name =
559 makeLatexName(d->exportFileName());
560 return no_path ? latex_name.onlyFileName()
561 : latex_name.absFileName();
565 FileName Buffer::Impl::exportFileName() const
567 docstring const branch_suffix =
568 params.branchlist().getFileNameSuffix();
569 if (branch_suffix.empty())
572 string const name = filename.onlyFileNameWithoutExt()
573 + to_utf8(branch_suffix);
574 FileName res(filename.onlyPath().absFileName() + "/" + name);
575 res.changeExtension(filename.extension());
581 string Buffer::logName(LogType * type) const
583 string const filename = latexName(false);
585 if (filename.empty()) {
591 string const path = temppath();
593 FileName const fname(addName(temppath(),
594 onlyFileName(changeExtension(filename,
597 // FIXME: how do we know this is the name of the build log?
598 FileName const bname(
599 addName(path, onlyFileName(
600 changeExtension(filename,
601 formats.extension(bufferFormat()) + ".out"))));
603 // Also consider the master buffer log file
604 FileName masterfname = fname;
606 if (masterBuffer() != this) {
607 string const mlogfile = masterBuffer()->logName(&mtype);
608 masterfname = FileName(mlogfile);
611 // If no Latex log or Build log is newer, show Build log
612 if (bname.exists() &&
613 ((!fname.exists() && !masterfname.exists())
614 || (fname.lastModified() < bname.lastModified()
615 && masterfname.lastModified() < bname.lastModified()))) {
616 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
619 return bname.absFileName();
620 // If we have a newer master file log or only a master log, show this
621 } else if (fname != masterfname
622 && (!fname.exists() && (masterfname.exists()
623 || fname.lastModified() < masterfname.lastModified()))) {
624 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
627 return masterfname.absFileName();
629 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
632 return fname.absFileName();
636 void Buffer::setReadonly(bool const flag)
638 if (d->read_only != flag) {
645 void Buffer::setFileName(FileName const & fname)
648 setReadonly(d->filename.isReadOnly());
654 int Buffer::readHeader(Lexer & lex)
656 int unknown_tokens = 0;
658 int begin_header_line = -1;
660 // Initialize parameters that may be/go lacking in header:
661 params().branchlist().clear();
662 params().preamble.erase();
663 params().options.erase();
664 params().master.erase();
665 params().float_placement.erase();
666 params().paperwidth.erase();
667 params().paperheight.erase();
668 params().leftmargin.erase();
669 params().rightmargin.erase();
670 params().topmargin.erase();
671 params().bottommargin.erase();
672 params().headheight.erase();
673 params().headsep.erase();
674 params().footskip.erase();
675 params().columnsep.erase();
676 params().fonts_cjk.erase();
677 params().listings_params.clear();
678 params().clearLayoutModules();
679 params().clearRemovedModules();
680 params().clearIncludedChildren();
681 params().pdfoptions().clear();
682 params().indiceslist().clear();
683 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
684 params().isbackgroundcolor = false;
685 params().fontcolor = lyx::rgbFromHexName("#000000");
686 params().isfontcolor = false;
687 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
688 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
689 params().html_latex_start.clear();
690 params().html_latex_end.clear();
691 params().html_math_img_scale = 1.0;
692 params().output_sync_macro.erase();
694 for (int i = 0; i < 4; ++i) {
695 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
696 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
699 ErrorList & errorList = d->errorLists["Parse"];
708 if (token == "\\end_header")
712 if (token == "\\begin_header") {
713 begin_header_line = line;
717 LYXERR(Debug::PARSER, "Handling document header token: `"
720 string unknown = params().readToken(lex, token, d->filename.onlyPath());
721 if (!unknown.empty()) {
722 if (unknown[0] != '\\' && token == "\\textclass") {
723 Alert::warning(_("Unknown document class"),
724 bformat(_("Using the default document class, because the "
725 "class %1$s is unknown."), from_utf8(unknown)));
728 docstring const s = bformat(_("Unknown token: "
732 errorList.push_back(ErrorItem(_("Document header error"),
737 if (begin_header_line) {
738 docstring const s = _("\\begin_header is missing");
739 errorList.push_back(ErrorItem(_("Document header error"),
743 params().makeDocumentClass();
745 return unknown_tokens;
750 // changed to be public and have one parameter
751 // Returns true if "\end_document" is not read (Asger)
752 bool Buffer::readDocument(Lexer & lex)
754 ErrorList & errorList = d->errorLists["Parse"];
757 // remove dummy empty par
758 paragraphs().clear();
760 if (!lex.checkFor("\\begin_document")) {
761 docstring const s = _("\\begin_document is missing");
762 errorList.push_back(ErrorItem(_("Document header error"),
768 if (params().outputChanges) {
769 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
770 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
771 LaTeXFeatures::isAvailable("xcolor");
773 if (!dvipost && !xcolorulem) {
774 Alert::warning(_("Changes not shown in LaTeX output"),
775 _("Changes will not be highlighted in LaTeX output, "
776 "because neither dvipost nor xcolor/ulem are installed.\n"
777 "Please install these packages or redefine "
778 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
779 } else if (!xcolorulem) {
780 Alert::warning(_("Changes not shown in LaTeX output"),
781 _("Changes will not be highlighted in LaTeX output "
782 "when using pdflatex, because xcolor and ulem are not installed.\n"
783 "Please install both packages or redefine "
784 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
788 if (!params().master.empty()) {
789 FileName const master_file = makeAbsPath(params().master,
790 onlyPath(absFileName()));
791 if (isLyXFileName(master_file.absFileName())) {
793 checkAndLoadLyXFile(master_file, true);
795 // necessary e.g. after a reload
796 // to re-register the child (bug 5873)
797 // FIXME: clean up updateMacros (here, only
798 // child registering is needed).
799 master->updateMacros();
800 // set master as master buffer, but only
801 // if we are a real child
802 if (master->isChild(this))
804 // if the master is not fully loaded
805 // it is probably just loading this
806 // child. No warning needed then.
807 else if (master->isFullyLoaded())
808 LYXERR0("The master '"
810 << "' assigned to this document ("
812 << ") does not include "
813 "this document. Ignoring the master assignment.");
818 // assure we have a default index
819 params().indiceslist().addDefault(B_("Index"));
822 bool const res = text().read(lex, errorList, d->inset);
826 updateMacroInstances();
831 bool Buffer::readString(string const & s)
833 params().compressed = false;
838 FileName const fn = FileName::tempName("Buffer_readString");
841 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
842 if (ret_plf != ReadSuccess)
845 if (file_format != LYX_FORMAT) {
846 // We need to call lyx2lyx, so write the input to a file
847 ofstream os(fn.toFilesystemEncoding().c_str());
851 return readFile(fn) == ReadSuccess;
854 if (readDocument(lex))
860 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
867 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
868 if (ret_plf != ReadSuccess)
871 if (file_format != LYX_FORMAT) {
873 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
874 if (ret_clf != ReadSuccess)
876 return readFile(tmpFile);
879 // FIXME: InsetInfo needs to know whether the file is under VCS
880 // during the parse process, so this has to be done before.
881 lyxvc().file_found_hook(d->filename);
883 if (readDocument(lex)) {
884 Alert::error(_("Document format failure"),
885 bformat(_("%1$s ended unexpectedly, which means"
886 " that it is probably corrupted."),
887 from_utf8(fn.absFileName())));
888 return ReadDocumentFailure;
891 d->file_fully_loaded = true;
892 d->read_only = !d->filename.isWritable();
893 params().compressed = d->filename.isZippedFile();
899 bool Buffer::isFullyLoaded() const
901 return d->file_fully_loaded;
905 void Buffer::setFullyLoaded(bool value)
907 d->file_fully_loaded = value;
911 void Buffer::updatePreviews() const
913 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
914 thePreviews().generateBufferPreviews(*this);
918 void Buffer::removePreviews() const
920 thePreviews().removeLoader(*this);
924 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
925 FileName const & fn, int & file_format) const
927 if(!lex.checkFor("\\lyxformat")) {
928 Alert::error(_("Document format failure"),
929 bformat(_("%1$s is not a readable LyX document."),
930 from_utf8(fn.absFileName())));
931 return ReadNoLyXFormat;
937 // LyX formats 217 and earlier were written as 2.17. This corresponds
938 // to files from LyX versions < 1.1.6.3. We just remove the dot in
939 // these cases. See also: www.lyx.org/trac/changeset/1313.
940 size_t dot = tmp_format.find_first_of(".,");
941 if (dot != string::npos)
942 tmp_format.erase(dot, 1);
944 file_format = convert<int>(tmp_format);
949 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
950 FileName & tmpfile, int from_format)
952 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
953 if(tmpfile.empty()) {
954 Alert::error(_("Conversion failed"),
955 bformat(_("%1$s is from a different"
956 " version of LyX, but a temporary"
957 " file for converting it could"
959 from_utf8(fn.absFileName())));
960 return LyX2LyXNoTempFile;
963 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
964 if (lyx2lyx.empty()) {
965 Alert::error(_("Conversion script not found"),
966 bformat(_("%1$s is from a different"
967 " version of LyX, but the"
968 " conversion script lyx2lyx"
969 " could not be found."),
970 from_utf8(fn.absFileName())));
971 return LyX2LyXNotFound;
975 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
976 ostringstream command;
977 command << os::python()
978 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
979 << " -t " << convert<string>(LYX_FORMAT)
980 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
981 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
982 string const command_str = command.str();
984 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
986 cmd_ret const ret = runCommand(command_str);
987 if (ret.first != 0) {
988 if (from_format < LYX_FORMAT) {
989 Alert::error(_("Conversion script failed"),
990 bformat(_("%1$s is from an older version"
991 " of LyX and the lyx2lyx script"
992 " failed to convert it."),
993 from_utf8(fn.absFileName())));
994 return LyX2LyXOlderFormat;
996 Alert::error(_("Conversion script failed"),
997 bformat(_("%1$s is from a newer version"
998 " of LyX and the lyx2lyx script"
999 " failed to convert it."),
1000 from_utf8(fn.absFileName())));
1001 return LyX2LyXNewerFormat;
1008 // Should probably be moved to somewhere else: BufferView? GuiView?
1009 bool Buffer::save() const
1011 docstring const file = makeDisplayPath(absFileName(), 20);
1012 d->filename.refresh();
1014 // check the read-only status before moving the file as a backup
1015 if (d->filename.exists()) {
1016 bool const read_only = !d->filename.isWritable();
1018 Alert::warning(_("File is read-only"),
1019 bformat(_("The file %1$s cannot be written because it "
1020 "is marked as read-only."), file));
1025 // ask if the disk file has been externally modified (use checksum method)
1026 if (fileName().exists() && isExternallyModified(checksum_method)) {
1028 bformat(_("Document %1$s has been externally modified. "
1029 "Are you sure you want to overwrite this file?"), file);
1030 int const ret = Alert::prompt(_("Overwrite modified file?"),
1031 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1036 // We don't need autosaves in the immediate future. (Asger)
1037 resetAutosaveTimers();
1039 FileName backupName;
1040 bool madeBackup = false;
1042 // make a backup if the file already exists
1043 if (lyxrc.make_backup && fileName().exists()) {
1044 backupName = FileName(absFileName() + '~');
1045 if (!lyxrc.backupdir_path.empty()) {
1046 string const mangledName =
1047 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1048 backupName = FileName(addName(lyxrc.backupdir_path,
1051 // do not copy because of #6587
1052 if (fileName().moveTo(backupName)) {
1055 Alert::error(_("Backup failure"),
1056 bformat(_("Cannot create backup file %1$s.\n"
1057 "Please check whether the directory exists and is writeable."),
1058 from_utf8(backupName.absFileName())));
1059 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1063 if (writeFile(d->filename)) {
1067 // Saving failed, so backup is not backup
1069 backupName.moveTo(d->filename);
1075 bool Buffer::writeFile(FileName const & fname) const
1077 if (d->read_only && fname == d->filename)
1080 bool retval = false;
1082 docstring const str = bformat(_("Saving document %1$s..."),
1083 makeDisplayPath(fname.absFileName()));
1086 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1088 if (params().compressed) {
1089 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1090 retval = ofs && write(ofs);
1092 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1093 retval = ofs && write(ofs);
1097 message(str + _(" could not write file!"));
1102 // removeAutosaveFile();
1105 message(str + _(" done."));
1111 docstring Buffer::emergencyWrite()
1113 // No need to save if the buffer has not changed.
1117 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1119 docstring user_message = bformat(
1120 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1122 // We try to save three places:
1123 // 1) Same place as document. Unless it is an unnamed doc.
1125 string s = absFileName();
1128 if (writeFile(FileName(s))) {
1130 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1131 return user_message;
1133 user_message += " " + _("Save failed! Trying again...\n");
1137 // 2) In HOME directory.
1138 string s = addName(package().home_dir().absFileName(), absFileName());
1140 lyxerr << ' ' << s << endl;
1141 if (writeFile(FileName(s))) {
1143 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1144 return user_message;
1147 user_message += " " + _("Save failed! Trying yet again...\n");
1149 // 3) In "/tmp" directory.
1150 // MakeAbsPath to prepend the current
1151 // drive letter on OS/2
1152 s = addName(package().temp_dir().absFileName(), absFileName());
1154 lyxerr << ' ' << s << endl;
1155 if (writeFile(FileName(s))) {
1157 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1158 return user_message;
1161 user_message += " " + _("Save failed! Bummer. Document is lost.");
1164 return user_message;
1168 bool Buffer::write(ostream & ofs) const
1171 // Use the standard "C" locale for file output.
1172 ofs.imbue(locale::classic());
1175 // The top of the file should not be written by params().
1177 // write out a comment in the top of the file
1178 ofs << "#LyX " << lyx_version
1179 << " created this file. For more info see http://www.lyx.org/\n"
1180 << "\\lyxformat " << LYX_FORMAT << "\n"
1181 << "\\begin_document\n";
1183 /// For each author, set 'used' to true if there is a change
1184 /// by this author in the document; otherwise set it to 'false'.
1185 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1186 AuthorList::Authors::const_iterator a_end = params().authors().end();
1187 for (; a_it != a_end; ++a_it)
1188 a_it->setUsed(false);
1190 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1191 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1192 for ( ; it != end; ++it)
1193 it->checkAuthors(params().authors());
1195 // now write out the buffer parameters.
1196 ofs << "\\begin_header\n";
1197 params().writeFile(ofs);
1198 ofs << "\\end_header\n";
1201 ofs << "\n\\begin_body\n";
1203 ofs << "\n\\end_body\n";
1205 // Write marker that shows file is complete
1206 ofs << "\\end_document" << endl;
1208 // Shouldn't really be needed....
1211 // how to check if close went ok?
1212 // Following is an attempt... (BE 20001011)
1214 // good() returns false if any error occured, including some
1215 // formatting error.
1216 // bad() returns true if something bad happened in the buffer,
1217 // which should include file system full errors.
1222 lyxerr << "File was not closed properly." << endl;
1229 bool Buffer::makeLaTeXFile(FileName const & fname,
1230 string const & original_path,
1231 OutputParams const & runparams_in,
1232 bool output_preamble, bool output_body) const
1234 OutputParams runparams = runparams_in;
1236 string const encoding = runparams.encoding->iconvName();
1237 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1240 try { ofs.reset(encoding); }
1241 catch (iconv_codecvt_facet_exception & e) {
1242 lyxerr << "Caught iconv exception: " << e.what() << endl;
1243 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1244 "verify that the support software for your encoding (%1$s) is "
1245 "properly installed"), from_ascii(encoding)));
1248 if (!openFileWrite(ofs, fname))
1251 //TexStream ts(ofs.rdbuf(), &texrow());
1252 ErrorList & errorList = d->errorLists["Export"];
1254 bool failed_export = false;
1257 writeLaTeXSource(ofs, original_path,
1258 runparams, output_preamble, output_body);
1260 catch (EncodingException & e) {
1261 odocstringstream ods;
1262 ods.put(e.failed_char);
1264 oss << "0x" << hex << e.failed_char << dec;
1265 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1266 " (code point %2$s)"),
1267 ods.str(), from_utf8(oss.str()));
1268 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1269 "representable in the chosen encoding.\n"
1270 "Changing the document encoding to utf8 could help."),
1271 e.par_id, e.pos, e.pos + 1));
1272 failed_export = true;
1274 catch (iconv_codecvt_facet_exception & e) {
1275 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1276 _(e.what()), -1, 0, 0));
1277 failed_export = true;
1279 catch (exception const & e) {
1280 errorList.push_back(ErrorItem(_("conversion failed"),
1281 _(e.what()), -1, 0, 0));
1282 failed_export = true;
1285 lyxerr << "Caught some really weird exception..." << endl;
1291 failed_export = true;
1292 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1296 return !failed_export;
1300 void Buffer::writeLaTeXSource(odocstream & os,
1301 string const & original_path,
1302 OutputParams const & runparams_in,
1303 bool const output_preamble, bool const output_body) const
1305 // The child documents, if any, shall be already loaded at this point.
1307 OutputParams runparams = runparams_in;
1309 // Classify the unicode characters appearing in math insets
1310 Encodings::initUnicodeMath(*this);
1312 // validate the buffer.
1313 LYXERR(Debug::LATEX, " Validating buffer...");
1314 LaTeXFeatures features(*this, params(), runparams);
1316 LYXERR(Debug::LATEX, " Buffer validation done.");
1318 // The starting paragraph of the coming rows is the
1319 // first paragraph of the document. (Asger)
1320 if (output_preamble && runparams.nice) {
1321 os << "%% LyX " << lyx_version << " created this file. "
1322 "For more info, see http://www.lyx.org/.\n"
1323 "%% Do not edit unless you really know what "
1325 d->texrow.newline();
1326 d->texrow.newline();
1328 LYXERR(Debug::INFO, "lyx document header finished");
1330 // Don't move this behind the parent_buffer=0 code below,
1331 // because then the macros will not get the right "redefinition"
1332 // flag as they don't see the parent macros which are output before.
1335 // fold macros if possible, still with parent buffer as the
1336 // macros will be put in the prefix anyway.
1337 updateMacroInstances();
1339 // There are a few differences between nice LaTeX and usual files:
1340 // usual is \batchmode and has a
1341 // special input@path to allow the including of figures
1342 // with either \input or \includegraphics (what figinsets do).
1343 // input@path is set when the actual parameter
1344 // original_path is set. This is done for usual tex-file, but not
1345 // for nice-latex-file. (Matthias 250696)
1346 // Note that input@path is only needed for something the user does
1347 // in the preamble, included .tex files or ERT, files included by
1348 // LyX work without it.
1349 if (output_preamble) {
1350 if (!runparams.nice) {
1351 // code for usual, NOT nice-latex-file
1352 os << "\\batchmode\n"; // changed
1353 // from \nonstopmode
1354 d->texrow.newline();
1356 if (!original_path.empty()) {
1358 // We don't know the encoding of inputpath
1359 docstring const inputpath = from_utf8(support::latex_path(original_path));
1360 docstring uncodable_glyphs;
1361 Encoding const * const enc = runparams.encoding;
1363 for (size_t n = 0; n < inputpath.size(); ++n) {
1364 docstring const glyph =
1365 docstring(1, inputpath[n]);
1366 if (enc->latexChar(inputpath[n], true) != glyph) {
1367 LYXERR0("Uncodable character '"
1369 << "' in input path!");
1370 uncodable_glyphs += glyph;
1375 // warn user if we found uncodable glyphs.
1376 if (!uncodable_glyphs.empty()) {
1377 frontend::Alert::warning(_("Uncodable character in file path"),
1378 support::bformat(_("The path of your document\n"
1380 "contains glyphs that are unknown in the\n"
1381 "current document encoding (namely %2$s).\n"
1382 "This will likely result in incomplete output.\n\n"
1383 "Choose an appropriate document encoding (such as utf8)\n"
1384 "or change the file path name."), inputpath, uncodable_glyphs));
1386 os << "\\makeatletter\n"
1387 << "\\def\\input@path{{"
1388 << inputpath << "/}}\n"
1389 << "\\makeatother\n";
1390 d->texrow.newline();
1391 d->texrow.newline();
1392 d->texrow.newline();
1396 // get parent macros (if this buffer has a parent) which will be
1397 // written at the document begin further down.
1398 MacroSet parentMacros;
1399 listParentMacros(parentMacros, features);
1401 runparams.use_polyglossia = features.usePolyglossia();
1402 // Write the preamble
1403 runparams.use_babel = params().writeLaTeX(os, features,
1405 d->filename.onlyPath());
1407 runparams.use_japanese = features.isRequired("japanese");
1413 os << "\\begin{document}\n";
1414 d->texrow.newline();
1416 // output the parent macros
1417 MacroSet::iterator it = parentMacros.begin();
1418 MacroSet::iterator end = parentMacros.end();
1419 for (; it != end; ++it) {
1420 int num_lines = (*it)->write(os, true);
1421 d->texrow.newlines(num_lines);
1424 } // output_preamble
1426 d->texrow.start(paragraphs().begin()->id(), 0);
1428 LYXERR(Debug::INFO, "preamble finished, now the body.");
1430 // if we are doing a real file with body, even if this is the
1431 // child of some other buffer, let's cut the link here.
1432 // This happens for example if only a child document is printed.
1433 Buffer const * save_parent = 0;
1434 if (output_preamble) {
1435 save_parent = d->parent();
1440 latexParagraphs(*this, text(), os, d->texrow, runparams);
1442 // Restore the parenthood if needed
1443 if (output_preamble)
1444 d->setParent(save_parent);
1446 // add this just in case after all the paragraphs
1448 d->texrow.newline();
1450 if (output_preamble) {
1451 os << "\\end{document}\n";
1452 d->texrow.newline();
1453 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1455 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1457 runparams_in.encoding = runparams.encoding;
1459 // Just to be sure. (Asger)
1460 d->texrow.newline();
1462 //for (int i = 0; i<d->texrow.rows(); i++) {
1464 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1465 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1468 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1469 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1473 bool Buffer::isLatex() const
1475 return params().documentClass().outputType() == LATEX;
1479 bool Buffer::isLiterate() const
1481 return params().documentClass().outputType() == LITERATE;
1485 bool Buffer::isDocBook() const
1487 return params().documentClass().outputType() == DOCBOOK;
1491 void Buffer::makeDocBookFile(FileName const & fname,
1492 OutputParams const & runparams,
1493 bool const body_only) const
1495 LYXERR(Debug::LATEX, "makeDocBookFile...");
1498 if (!openFileWrite(ofs, fname))
1501 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1505 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1509 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1510 OutputParams const & runparams,
1511 bool const only_body) const
1513 LaTeXFeatures features(*this, params(), runparams);
1518 DocumentClass const & tclass = params().documentClass();
1519 string const top_element = tclass.latexname();
1522 if (runparams.flavor == OutputParams::XML)
1523 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1526 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1529 if (! tclass.class_header().empty())
1530 os << from_ascii(tclass.class_header());
1531 else if (runparams.flavor == OutputParams::XML)
1532 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1533 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1535 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1537 docstring preamble = from_utf8(params().preamble);
1538 if (runparams.flavor != OutputParams::XML ) {
1539 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1540 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1541 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1542 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1545 string const name = runparams.nice
1546 ? changeExtension(absFileName(), ".sgml") : fname;
1547 preamble += features.getIncludedFiles(name);
1548 preamble += features.getLyXSGMLEntities();
1550 if (!preamble.empty()) {
1551 os << "\n [ " << preamble << " ]";
1556 string top = top_element;
1558 if (runparams.flavor == OutputParams::XML)
1559 top += params().language->code();
1561 top += params().language->code().substr(0, 2);
1564 if (!params().options.empty()) {
1566 top += params().options;
1569 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1570 << " file was created by LyX " << lyx_version
1571 << "\n See http://www.lyx.org/ for more information -->\n";
1573 params().documentClass().counters().reset();
1577 sgml::openTag(os, top);
1579 docbookParagraphs(text(), *this, os, runparams);
1580 sgml::closeTag(os, top_element);
1584 void Buffer::makeLyXHTMLFile(FileName const & fname,
1585 OutputParams const & runparams,
1586 bool const body_only) const
1588 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1591 if (!openFileWrite(ofs, fname))
1594 writeLyXHTMLSource(ofs, runparams, body_only);
1598 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1602 void Buffer::writeLyXHTMLSource(odocstream & os,
1603 OutputParams const & runparams,
1604 bool const only_body) const
1606 LaTeXFeatures features(*this, params(), runparams);
1608 updateBuffer(UpdateMaster, OutputUpdate);
1609 d->bibinfo_.makeCitationLabels(*this);
1611 updateMacroInstances();
1614 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1615 << "<!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"
1616 // FIXME Language should be set properly.
1617 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1619 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1620 // FIXME Presumably need to set this right
1621 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1623 docstring const & doctitle = features.htmlTitle();
1625 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1628 os << "\n<!-- Text Class Preamble -->\n"
1629 << features.getTClassHTMLPreamble()
1630 << "\n<!-- Preamble Snippets -->\n"
1631 << from_utf8(features.getPreambleSnippets());
1633 os << "\n<!-- Layout-provided Styles -->\n";
1634 docstring const styleinfo = features.getTClassHTMLStyles();
1635 if (!styleinfo.empty()) {
1636 os << "<style type='text/css'>\n"
1640 os << "</head>\n<body>\n";
1644 params().documentClass().counters().reset();
1645 xhtmlParagraphs(text(), *this, xs, runparams);
1647 os << "</body>\n</html>\n";
1651 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1652 // Other flags: -wall -v0 -x
1653 int Buffer::runChktex()
1657 // get LaTeX-Filename
1658 FileName const path(temppath());
1659 string const name = addName(path.absFileName(), latexName());
1660 string const org_path = filePath();
1662 PathChanger p(path); // path to LaTeX file
1663 message(_("Running chktex..."));
1665 // Generate the LaTeX file if neccessary
1666 OutputParams runparams(¶ms().encoding());
1667 runparams.flavor = OutputParams::LATEX;
1668 runparams.nice = false;
1669 runparams.linelen = lyxrc.plaintext_linelen;
1670 makeLaTeXFile(FileName(name), org_path, runparams);
1673 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1674 int const res = chktex.run(terr); // run chktex
1677 Alert::error(_("chktex failure"),
1678 _("Could not run chktex successfully."));
1679 } else if (res > 0) {
1680 ErrorList & errlist = d->errorLists["ChkTeX"];
1682 bufferErrors(terr, errlist);
1693 void Buffer::validate(LaTeXFeatures & features) const
1695 params().validate(features);
1699 for_each(paragraphs().begin(), paragraphs().end(),
1700 bind(&Paragraph::validate, _1, ref(features)));
1702 if (lyxerr.debugging(Debug::LATEX)) {
1703 features.showStruct();
1708 void Buffer::getLabelList(vector<docstring> & list) const
1710 // If this is a child document, use the master's list instead.
1712 masterBuffer()->getLabelList(list);
1717 Toc & toc = d->toc_backend.toc("label");
1718 TocIterator toc_it = toc.begin();
1719 TocIterator end = toc.end();
1720 for (; toc_it != end; ++toc_it) {
1721 if (toc_it->depth() == 0)
1722 list.push_back(toc_it->str());
1727 void Buffer::updateBibfilesCache(UpdateScope scope) const
1729 // FIXME This is probably unnecssary, given where we call this.
1730 // If this is a child document, use the parent's cache instead.
1731 if (parent() && scope != UpdateChildOnly) {
1732 masterBuffer()->updateBibfilesCache();
1736 d->bibfiles_cache_.clear();
1737 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1738 if (it->lyxCode() == BIBTEX_CODE) {
1739 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1740 support::FileNameList const bibfiles = inset.getBibFiles();
1741 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1744 } else if (it->lyxCode() == INCLUDE_CODE) {
1745 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1746 Buffer const * const incbuf = inset.getChildBuffer();
1749 support::FileNameList const & bibfiles =
1750 incbuf->getBibfilesCache(UpdateChildOnly);
1751 if (!bibfiles.empty()) {
1752 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1758 d->bibfile_cache_valid_ = true;
1759 d->bibinfo_cache_valid_ = false;
1763 void Buffer::invalidateBibinfoCache() const
1765 d->bibinfo_cache_valid_ = false;
1766 // also invalidate the cache for the parent buffer
1767 Buffer const * const pbuf = d->parent();
1769 pbuf->invalidateBibinfoCache();
1773 void Buffer::invalidateBibfileCache() const
1775 d->bibfile_cache_valid_ = false;
1776 d->bibinfo_cache_valid_ = false;
1777 // also invalidate the cache for the parent buffer
1778 Buffer const * const pbuf = d->parent();
1780 pbuf->invalidateBibfileCache();
1784 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1786 // FIXME This is probably unnecessary, given where we call this.
1787 // If this is a child document, use the master's cache instead.
1788 Buffer const * const pbuf = masterBuffer();
1789 if (pbuf != this && scope != UpdateChildOnly)
1790 return pbuf->getBibfilesCache();
1792 if (!d->bibfile_cache_valid_)
1793 this->updateBibfilesCache(scope);
1795 return d->bibfiles_cache_;
1799 BiblioInfo const & Buffer::masterBibInfo() const
1801 Buffer const * const tmp = masterBuffer();
1803 return tmp->masterBibInfo();
1808 void Buffer::checkBibInfoCache() const
1810 // use the master's cache
1811 Buffer const * const tmp = masterBuffer();
1813 tmp->checkBibInfoCache();
1817 // this will also reload the cache if it is invalid
1818 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1820 // compare the cached timestamps with the actual ones.
1821 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1822 support::FileNameList::const_iterator en = bibfiles_cache.end();
1823 for (; ei != en; ++ ei) {
1824 time_t lastw = ei->lastModified();
1825 time_t prevw = d->bibfile_status_[*ei];
1826 if (lastw != prevw) {
1827 d->bibinfo_cache_valid_ = false;
1828 d->bibfile_status_[*ei] = lastw;
1832 // if not valid, then reload the info
1833 if (!d->bibinfo_cache_valid_) {
1834 d->bibinfo_.clear();
1835 fillWithBibKeys(d->bibinfo_);
1836 d->bibinfo_cache_valid_ = true;
1841 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1843 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1844 it->fillWithBibKeys(keys, it);
1848 bool Buffer::isDepClean(string const & name) const
1850 DepClean::const_iterator const it = d->dep_clean.find(name);
1851 if (it == d->dep_clean.end())
1857 void Buffer::markDepClean(string const & name)
1859 d->dep_clean[name] = true;
1863 bool Buffer::isExportableFormat(string const & format) const
1865 typedef vector<Format const *> Formats;
1867 formats = exportableFormats(true);
1868 Formats::const_iterator fit = formats.begin();
1869 Formats::const_iterator end = formats.end();
1870 for (; fit != end ; ++fit) {
1871 if ((*fit)->name() == format)
1878 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1881 // FIXME? if there is an Buffer LFUN that can be dispatched even
1882 // if internal, put a switch '(cmd.action)' here.
1888 switch (cmd.action()) {
1890 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1891 flag.setOnOff(isReadonly());
1894 // FIXME: There is need for a command-line import.
1895 //case LFUN_BUFFER_IMPORT:
1897 case LFUN_BUFFER_AUTO_SAVE:
1900 case LFUN_BUFFER_EXPORT_CUSTOM:
1901 // FIXME: Nothing to check here?
1904 case LFUN_BUFFER_EXPORT: {
1905 docstring const arg = cmd.argument();
1906 enable = arg == "custom" || isExportable(to_utf8(arg));
1908 flag.message(bformat(
1909 _("Don't know how to export to format: %1$s"), arg));
1913 case LFUN_BUFFER_CHKTEX:
1914 enable = isLatex() && !lyxrc.chktex_command.empty();
1917 case LFUN_BUILD_PROGRAM:
1918 enable = isExportable("program");
1921 case LFUN_BRANCH_ACTIVATE:
1922 case LFUN_BRANCH_DEACTIVATE: {
1923 BranchList const & branchList = params().branchlist();
1924 docstring const branchName = cmd.argument();
1925 enable = !branchName.empty() && branchList.find(branchName);
1929 case LFUN_BRANCH_ADD:
1930 case LFUN_BRANCHES_RENAME:
1931 case LFUN_BUFFER_PRINT:
1932 // if no Buffer is present, then of course we won't be called!
1935 case LFUN_BUFFER_LANGUAGE:
1936 enable = !isReadonly();
1942 flag.setEnabled(enable);
1947 void Buffer::dispatch(string const & command, DispatchResult & result)
1949 return dispatch(lyxaction.lookupFunc(command), result);
1953 // NOTE We can end up here even if we have no GUI, because we are called
1954 // by LyX::exec to handled command-line requests. So we may need to check
1955 // whether we have a GUI or not. The boolean use_gui holds this information.
1956 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1959 // FIXME? if there is an Buffer LFUN that can be dispatched even
1960 // if internal, put a switch '(cmd.action())' here.
1961 dr.dispatched(false);
1964 string const argument = to_utf8(func.argument());
1965 // We'll set this back to false if need be.
1966 bool dispatched = true;
1967 undo().beginUndoGroup();
1969 switch (func.action()) {
1970 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1971 if (lyxvc().inUse())
1972 lyxvc().toggleReadOnly();
1974 setReadonly(!isReadonly());
1977 case LFUN_BUFFER_EXPORT: {
1978 bool success = doExport(argument, false, false);
1979 dr.setError(!success);
1981 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1986 case LFUN_BUILD_PROGRAM:
1987 doExport("program", true, false);
1990 case LFUN_BUFFER_CHKTEX:
1994 case LFUN_BUFFER_EXPORT_CUSTOM: {
1996 string command = split(argument, format_name, ' ');
1997 Format const * format = formats.getFormat(format_name);
1999 lyxerr << "Format \"" << format_name
2000 << "\" not recognized!"
2005 // The name of the file created by the conversion process
2008 // Output to filename
2009 if (format->name() == "lyx") {
2010 string const latexname = latexName(false);
2011 filename = changeExtension(latexname,
2012 format->extension());
2013 filename = addName(temppath(), filename);
2015 if (!writeFile(FileName(filename)))
2019 doExport(format_name, true, false, filename);
2022 // Substitute $$FName for filename
2023 if (!contains(command, "$$FName"))
2024 command = "( " + command + " ) < $$FName";
2025 command = subst(command, "$$FName", filename);
2027 // Execute the command in the background
2029 call.startscript(Systemcall::DontWait, command);
2033 // FIXME: There is need for a command-line import.
2035 case LFUN_BUFFER_IMPORT:
2040 case LFUN_BUFFER_AUTO_SAVE:
2042 resetAutosaveTimers();
2045 case LFUN_BRANCH_ADD: {
2046 docstring branch_name = func.argument();
2047 if (branch_name.empty()) {
2051 BranchList & branch_list = params().branchlist();
2052 vector<docstring> const branches =
2053 getVectorFromString(branch_name, branch_list.separator());
2055 for (vector<docstring>::const_iterator it = branches.begin();
2056 it != branches.end(); ++it) {
2058 Branch * branch = branch_list.find(branch_name);
2060 LYXERR0("Branch " << branch_name << " already exists.");
2064 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2066 branch_list.add(branch_name);
2067 branch = branch_list.find(branch_name);
2068 string const x11hexname = X11hexname(branch->color());
2069 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2070 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2072 dr.screenUpdate(Update::Force);
2080 case LFUN_BRANCH_ACTIVATE:
2081 case LFUN_BRANCH_DEACTIVATE: {
2082 BranchList & branchList = params().branchlist();
2083 docstring const branchName = func.argument();
2084 // the case without a branch name is handled elsewhere
2085 if (branchName.empty()) {
2089 Branch * branch = branchList.find(branchName);
2091 LYXERR0("Branch " << branchName << " does not exist.");
2093 docstring const msg =
2094 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2097 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2099 dr.screenUpdate(Update::Force);
2100 dr.forceBufferUpdate();
2105 case LFUN_BRANCHES_RENAME: {
2106 if (func.argument().empty())
2109 docstring const oldname = from_utf8(func.getArg(0));
2110 docstring const newname = from_utf8(func.getArg(1));
2111 InsetIterator it = inset_iterator_begin(inset());
2112 InsetIterator const end = inset_iterator_end(inset());
2113 bool success = false;
2114 for (; it != end; ++it) {
2115 if (it->lyxCode() == BRANCH_CODE) {
2116 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2117 if (ins.branch() == oldname) {
2118 undo().recordUndo(it);
2119 ins.rename(newname);
2124 if (it->lyxCode() == INCLUDE_CODE) {
2125 // get buffer of external file
2126 InsetInclude const & ins =
2127 static_cast<InsetInclude const &>(*it);
2128 Buffer * child = ins.getChildBuffer();
2131 child->dispatch(func, dr);
2136 dr.screenUpdate(Update::Force);
2137 dr.forceBufferUpdate();
2142 case LFUN_BUFFER_PRINT: {
2143 // we'll assume there's a problem until we succeed
2145 string target = func.getArg(0);
2146 string target_name = func.getArg(1);
2147 string command = func.getArg(2);
2150 || target_name.empty()
2151 || command.empty()) {
2152 LYXERR0("Unable to parse " << func.argument());
2153 docstring const msg =
2154 bformat(_("Unable to parse \"%1$s\""), func.argument());
2158 if (target != "printer" && target != "file") {
2159 LYXERR0("Unrecognized target \"" << target << '"');
2160 docstring const msg =
2161 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2166 bool const update_unincluded =
2167 params().maintain_unincluded_children
2168 && !params().getIncludedChildren().empty();
2169 if (!doExport("dvi", true, update_unincluded)) {
2170 showPrintError(absFileName());
2171 dr.setMessage(_("Error exporting to DVI."));
2175 // Push directory path.
2176 string const path = temppath();
2177 // Prevent the compiler from optimizing away p
2181 // there are three cases here:
2182 // 1. we print to a file
2183 // 2. we print directly to a printer
2184 // 3. we print using a spool command (print to file first)
2187 string const dviname = changeExtension(latexName(true), "dvi");
2189 if (target == "printer") {
2190 if (!lyxrc.print_spool_command.empty()) {
2191 // case 3: print using a spool
2192 string const psname = changeExtension(dviname,".ps");
2193 command += ' ' + lyxrc.print_to_file
2196 + quoteName(dviname);
2198 string command2 = lyxrc.print_spool_command + ' ';
2199 if (target_name != "default") {
2200 command2 += lyxrc.print_spool_printerprefix
2204 command2 += quoteName(psname);
2206 // If successful, then spool command
2207 res = one.startscript(Systemcall::Wait, command);
2210 // If there's no GUI, we have to wait on this command. Otherwise,
2211 // LyX deletes the temporary directory, and with it the spooled
2212 // file, before it can be printed!!
2213 Systemcall::Starttype stype = use_gui ?
2214 Systemcall::DontWait : Systemcall::Wait;
2215 res = one.startscript(stype, command2);
2218 // case 2: print directly to a printer
2219 if (target_name != "default")
2220 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2222 Systemcall::Starttype stype = use_gui ?
2223 Systemcall::DontWait : Systemcall::Wait;
2224 res = one.startscript(stype, command + quoteName(dviname));
2228 // case 1: print to a file
2229 FileName const filename(makeAbsPath(target_name, filePath()));
2230 FileName const dvifile(makeAbsPath(dviname, path));
2231 if (filename.exists()) {
2232 docstring text = bformat(
2233 _("The file %1$s already exists.\n\n"
2234 "Do you want to overwrite that file?"),
2235 makeDisplayPath(filename.absFileName()));
2236 if (Alert::prompt(_("Overwrite file?"),
2237 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2240 command += ' ' + lyxrc.print_to_file
2241 + quoteName(filename.toFilesystemEncoding())
2243 + quoteName(dvifile.toFilesystemEncoding());
2245 Systemcall::Starttype stype = use_gui ?
2246 Systemcall::DontWait : Systemcall::Wait;
2247 res = one.startscript(stype, command);
2253 dr.setMessage(_("Error running external commands."));
2254 showPrintError(absFileName());
2259 case LFUN_BUFFER_LANGUAGE: {
2260 Language const * oldL = params().language;
2261 Language const * newL = languages.getLanguage(argument);
2262 if (!newL || oldL == newL)
2264 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2265 changeLanguage(oldL, newL);
2266 dr.forceBufferUpdate();
2275 dr.dispatched(dispatched);
2276 undo().endUndoGroup();
2280 void Buffer::changeLanguage(Language const * from, Language const * to)
2282 LASSERT(from, /**/);
2285 for_each(par_iterator_begin(),
2287 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2291 bool Buffer::isMultiLingual() const
2293 ParConstIterator end = par_iterator_end();
2294 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2295 if (it->isMultiLingual(params()))
2302 std::set<Language const *> Buffer::getLanguages() const
2304 std::set<Language const *> languages;
2305 getLanguages(languages);
2310 void Buffer::getLanguages(std::set<Language const *> & languages) const
2312 ParConstIterator end = par_iterator_end();
2313 // add the buffer language, even if it's not actively used
2314 languages.insert(language());
2315 // iterate over the paragraphs
2316 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2317 it->getLanguages(languages);
2319 ListOfBuffers clist = getDescendents();
2320 ListOfBuffers::const_iterator cit = clist.begin();
2321 ListOfBuffers::const_iterator const cen = clist.end();
2322 for (; cit != cen; ++cit)
2323 (*cit)->getLanguages(languages);
2327 DocIterator Buffer::getParFromID(int const id) const
2329 Buffer * buf = const_cast<Buffer *>(this);
2331 // John says this is called with id == -1 from undo
2332 lyxerr << "getParFromID(), id: " << id << endl;
2333 return doc_iterator_end(buf);
2336 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2337 if (it.paragraph().id() == id)
2340 return doc_iterator_end(buf);
2344 bool Buffer::hasParWithID(int const id) const
2346 return !getParFromID(id).atEnd();
2350 ParIterator Buffer::par_iterator_begin()
2352 return ParIterator(doc_iterator_begin(this));
2356 ParIterator Buffer::par_iterator_end()
2358 return ParIterator(doc_iterator_end(this));
2362 ParConstIterator Buffer::par_iterator_begin() const
2364 return ParConstIterator(doc_iterator_begin(this));
2368 ParConstIterator Buffer::par_iterator_end() const
2370 return ParConstIterator(doc_iterator_end(this));
2374 Language const * Buffer::language() const
2376 return params().language;
2380 docstring const Buffer::B_(string const & l10n) const
2382 return params().B_(l10n);
2386 bool Buffer::isClean() const
2388 return d->lyx_clean;
2392 bool Buffer::isExternallyModified(CheckMethod method) const
2394 LASSERT(d->filename.exists(), /**/);
2395 // if method == timestamp, check timestamp before checksum
2396 return (method == checksum_method
2397 || d->timestamp_ != d->filename.lastModified())
2398 && d->checksum_ != d->filename.checksum();
2402 void Buffer::saveCheckSum() const
2404 FileName const & file = d->filename;
2405 if (file.exists()) {
2406 d->timestamp_ = file.lastModified();
2407 d->checksum_ = file.checksum();
2409 // in the case of save to a new file.
2416 void Buffer::markClean() const
2418 if (!d->lyx_clean) {
2419 d->lyx_clean = true;
2422 // if the .lyx file has been saved, we don't need an
2424 d->bak_clean = true;
2425 d->undo_.markDirty();
2429 void Buffer::setUnnamed(bool flag)
2435 bool Buffer::isUnnamed() const
2442 /// Don't check unnamed, here: isInternal() is used in
2443 /// newBuffer(), where the unnamed flag has not been set by anyone
2444 /// yet. Also, for an internal buffer, there should be no need for
2445 /// retrieving fileName() nor for checking if it is unnamed or not.
2446 bool Buffer::isInternal() const
2448 return fileName().extension() == "internal";
2452 void Buffer::markDirty()
2455 d->lyx_clean = false;
2458 d->bak_clean = false;
2460 DepClean::iterator it = d->dep_clean.begin();
2461 DepClean::const_iterator const end = d->dep_clean.end();
2463 for (; it != end; ++it)
2468 FileName Buffer::fileName() const
2474 string Buffer::absFileName() const
2476 return d->filename.absFileName();
2480 string Buffer::filePath() const
2482 return d->filename.onlyPath().absFileName() + "/";
2486 bool Buffer::isReadonly() const
2488 return d->read_only;
2492 void Buffer::setParent(Buffer const * buffer)
2494 // Avoids recursive include.
2495 d->setParent(buffer == this ? 0 : buffer);
2500 Buffer const * Buffer::parent() const
2506 ListOfBuffers Buffer::allRelatives() const
2508 ListOfBuffers lb = masterBuffer()->getDescendents();
2509 lb.push_front(const_cast<Buffer *>(this));
2514 Buffer const * Buffer::masterBuffer() const
2516 // FIXME Should be make sure we are not in some kind
2517 // of recursive include? A -> B -> A will crash this.
2518 Buffer const * const pbuf = d->parent();
2522 return pbuf->masterBuffer();
2526 bool Buffer::isChild(Buffer * child) const
2528 return d->children_positions.find(child) != d->children_positions.end();
2532 DocIterator Buffer::firstChildPosition(Buffer const * child)
2534 Impl::BufferPositionMap::iterator it;
2535 it = d->children_positions.find(child);
2536 if (it == d->children_positions.end())
2537 return DocIterator(this);
2542 bool Buffer::hasChildren() const
2544 return !d->children_positions.empty();
2548 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2550 // loop over children
2551 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2552 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2553 for (; it != end; ++it) {
2554 Buffer * child = const_cast<Buffer *>(it->first);
2556 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2557 if (bit != clist.end())
2559 clist.push_back(child);
2561 // there might be grandchildren
2562 child->collectChildren(clist, true);
2567 ListOfBuffers Buffer::getChildren() const
2570 collectChildren(v, false);
2575 ListOfBuffers Buffer::getDescendents() const
2578 collectChildren(v, true);
2583 template<typename M>
2584 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2589 typename M::const_iterator it = m.lower_bound(x);
2590 if (it == m.begin())
2598 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2599 DocIterator const & pos) const
2601 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2603 // if paragraphs have no macro context set, pos will be empty
2607 // we haven't found anything yet
2608 DocIterator bestPos = owner_->par_iterator_begin();
2609 MacroData const * bestData = 0;
2611 // find macro definitions for name
2612 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2613 if (nameIt != macros.end()) {
2614 // find last definition in front of pos or at pos itself
2615 PositionScopeMacroMap::const_iterator it
2616 = greatest_below(nameIt->second, pos);
2617 if (it != nameIt->second.end()) {
2619 // scope ends behind pos?
2620 if (pos < it->second.first) {
2621 // Looks good, remember this. If there
2622 // is no external macro behind this,
2623 // we found the right one already.
2624 bestPos = it->first;
2625 bestData = &it->second.second;
2629 // try previous macro if there is one
2630 if (it == nameIt->second.begin())
2637 // find macros in included files
2638 PositionScopeBufferMap::const_iterator it
2639 = greatest_below(position_to_children, pos);
2640 if (it == position_to_children.end())
2641 // no children before
2645 // do we know something better (i.e. later) already?
2646 if (it->first < bestPos )
2649 // scope ends behind pos?
2650 if (pos < it->second.first) {
2651 // look for macro in external file
2653 MacroData const * data
2654 = it->second.second->getMacro(name, false);
2657 bestPos = it->first;
2663 // try previous file if there is one
2664 if (it == position_to_children.begin())
2669 // return the best macro we have found
2674 MacroData const * Buffer::getMacro(docstring const & name,
2675 DocIterator const & pos, bool global) const
2680 // query buffer macros
2681 MacroData const * data = d->getBufferMacro(name, pos);
2685 // If there is a master buffer, query that
2686 Buffer const * const pbuf = d->parent();
2688 d->macro_lock = true;
2689 MacroData const * macro = pbuf->getMacro(
2690 name, *this, false);
2691 d->macro_lock = false;
2697 data = MacroTable::globalMacros().get(name);
2706 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2708 // set scope end behind the last paragraph
2709 DocIterator scope = par_iterator_begin();
2710 scope.pit() = scope.lastpit() + 1;
2712 return getMacro(name, scope, global);
2716 MacroData const * Buffer::getMacro(docstring const & name,
2717 Buffer const & child, bool global) const
2719 // look where the child buffer is included first
2720 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2721 if (it == d->children_positions.end())
2724 // check for macros at the inclusion position
2725 return getMacro(name, it->second, global);
2729 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2731 pit_type const lastpit = it.lastpit();
2733 // look for macros in each paragraph
2734 while (it.pit() <= lastpit) {
2735 Paragraph & par = it.paragraph();
2737 // iterate over the insets of the current paragraph
2738 InsetList const & insets = par.insetList();
2739 InsetList::const_iterator iit = insets.begin();
2740 InsetList::const_iterator end = insets.end();
2741 for (; iit != end; ++iit) {
2742 it.pos() = iit->pos;
2744 // is it a nested text inset?
2745 if (iit->inset->asInsetText()) {
2746 // Inset needs its own scope?
2747 InsetText const * itext = iit->inset->asInsetText();
2748 bool newScope = itext->isMacroScope();
2750 // scope which ends just behind the inset
2751 DocIterator insetScope = it;
2754 // collect macros in inset
2755 it.push_back(CursorSlice(*iit->inset));
2756 updateMacros(it, newScope ? insetScope : scope);
2761 if (iit->inset->asInsetTabular()) {
2762 CursorSlice slice(*iit->inset);
2763 size_t const numcells = slice.nargs();
2764 for (; slice.idx() < numcells; slice.forwardIdx()) {
2765 it.push_back(slice);
2766 updateMacros(it, scope);
2772 // is it an external file?
2773 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2774 // get buffer of external file
2775 InsetInclude const & inset =
2776 static_cast<InsetInclude const &>(*iit->inset);
2778 Buffer * child = inset.getChildBuffer();
2783 // register its position, but only when it is
2784 // included first in the buffer
2785 if (children_positions.find(child) ==
2786 children_positions.end())
2787 children_positions[child] = it;
2789 // register child with its scope
2790 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2794 InsetMath * im = iit->inset->asInsetMath();
2795 if (doing_export && im) {
2796 InsetMathHull * hull = im->asHullInset();
2798 hull->recordLocation(it);
2801 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2805 MathMacroTemplate & macroTemplate =
2806 *iit->inset->asInsetMath()->asMacroTemplate();
2807 MacroContext mc(owner_, it);
2808 macroTemplate.updateToContext(mc);
2811 bool valid = macroTemplate.validMacro();
2812 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2813 // then the BufferView's cursor will be invalid in
2814 // some cases which leads to crashes.
2819 // FIXME (Abdel), I don't understandt why we pass 'it' here
2820 // instead of 'macroTemplate' defined above... is this correct?
2821 macros[macroTemplate.name()][it] =
2822 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2832 void Buffer::updateMacros() const
2837 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2839 // start with empty table
2841 d->children_positions.clear();
2842 d->position_to_children.clear();
2844 // Iterate over buffer, starting with first paragraph
2845 // The scope must be bigger than any lookup DocIterator
2846 // later. For the global lookup, lastpit+1 is used, hence
2847 // we use lastpit+2 here.
2848 DocIterator it = par_iterator_begin();
2849 DocIterator outerScope = it;
2850 outerScope.pit() = outerScope.lastpit() + 2;
2851 d->updateMacros(it, outerScope);
2855 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2857 InsetIterator it = inset_iterator_begin(inset());
2858 InsetIterator const end = inset_iterator_end(inset());
2859 for (; it != end; ++it) {
2860 if (it->lyxCode() == BRANCH_CODE) {
2861 InsetBranch & br = static_cast<InsetBranch &>(*it);
2862 docstring const name = br.branch();
2863 if (!from_master && !params().branchlist().find(name))
2864 result.push_back(name);
2865 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2866 result.push_back(name);
2869 if (it->lyxCode() == INCLUDE_CODE) {
2870 // get buffer of external file
2871 InsetInclude const & ins =
2872 static_cast<InsetInclude const &>(*it);
2873 Buffer * child = ins.getChildBuffer();
2876 child->getUsedBranches(result, true);
2879 // remove duplicates
2884 void Buffer::updateMacroInstances() const
2886 LYXERR(Debug::MACROS, "updateMacroInstances for "
2887 << d->filename.onlyFileName());
2888 DocIterator it = doc_iterator_begin(this);
2890 DocIterator const end = doc_iterator_end(this);
2891 for (; it != end; it.forwardInset()) {
2892 // look for MathData cells in InsetMathNest insets
2893 InsetMath * minset = it.nextInset()->asInsetMath();
2897 // update macro in all cells of the InsetMathNest
2898 DocIterator::idx_type n = minset->nargs();
2899 MacroContext mc = MacroContext(this, it);
2900 for (DocIterator::idx_type i = 0; i < n; ++i) {
2901 MathData & data = minset->cell(i);
2902 data.updateMacros(0, mc);
2908 void Buffer::listMacroNames(MacroNameSet & macros) const
2913 d->macro_lock = true;
2915 // loop over macro names
2916 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2917 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2918 for (; nameIt != nameEnd; ++nameIt)
2919 macros.insert(nameIt->first);
2921 // loop over children
2922 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2923 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2924 for (; it != end; ++it)
2925 it->first->listMacroNames(macros);
2928 Buffer const * const pbuf = d->parent();
2930 pbuf->listMacroNames(macros);
2932 d->macro_lock = false;
2936 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2938 Buffer const * const pbuf = d->parent();
2943 pbuf->listMacroNames(names);
2946 MacroNameSet::iterator it = names.begin();
2947 MacroNameSet::iterator end = names.end();
2948 for (; it != end; ++it) {
2950 MacroData const * data =
2951 pbuf->getMacro(*it, *this, false);
2953 macros.insert(data);
2955 // we cannot access the original MathMacroTemplate anymore
2956 // here to calls validate method. So we do its work here manually.
2957 // FIXME: somehow make the template accessible here.
2958 if (data->optionals() > 0)
2959 features.require("xargs");
2965 Buffer::References & Buffer::references(docstring const & label)
2968 return const_cast<Buffer *>(masterBuffer())->references(label);
2970 RefCache::iterator it = d->ref_cache_.find(label);
2971 if (it != d->ref_cache_.end())
2972 return it->second.second;
2974 static InsetLabel const * dummy_il = 0;
2975 static References const dummy_refs;
2976 it = d->ref_cache_.insert(
2977 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2978 return it->second.second;
2982 Buffer::References const & Buffer::references(docstring const & label) const
2984 return const_cast<Buffer *>(this)->references(label);
2988 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2990 masterBuffer()->d->ref_cache_[label].first = il;
2994 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2996 return masterBuffer()->d->ref_cache_[label].first;
3000 void Buffer::clearReferenceCache() const
3003 d->ref_cache_.clear();
3007 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3010 //FIXME: This does not work for child documents yet.
3011 LASSERT(code == CITE_CODE, /**/);
3012 // Check if the label 'from' appears more than once
3013 vector<docstring> labels;
3015 checkBibInfoCache();
3016 BiblioInfo const & keys = masterBibInfo();
3017 BiblioInfo::const_iterator bit = keys.begin();
3018 BiblioInfo::const_iterator bend = keys.end();
3020 for (; bit != bend; ++bit)
3022 labels.push_back(bit->first);
3025 if (count(labels.begin(), labels.end(), from) > 1)
3028 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3029 if (it->lyxCode() == code) {
3030 InsetCommand * inset = it->asInsetCommand();
3033 docstring const oldValue = inset->getParam(paramName);
3034 if (oldValue == from)
3035 inset->setParam(paramName, to);
3041 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3042 pit_type par_end, bool full_source) const
3044 OutputParams runparams(¶ms().encoding());
3045 runparams.nice = true;
3046 runparams.flavor = params().useNonTeXFonts ?
3047 OutputParams::XETEX : OutputParams::LATEX;
3048 runparams.linelen = lyxrc.plaintext_linelen;
3049 // No side effect of file copying and image conversion
3050 runparams.dryrun = true;
3053 os << "% " << _("Preview source code") << "\n\n";
3055 d->texrow.newline();
3056 d->texrow.newline();
3058 writeDocBookSource(os, absFileName(), runparams, false);
3060 // latex or literate
3061 writeLaTeXSource(os, string(), runparams, true, true);
3063 runparams.par_begin = par_begin;
3064 runparams.par_end = par_end;
3065 if (par_begin + 1 == par_end) {
3067 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3071 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3072 convert<docstring>(par_begin),
3073 convert<docstring>(par_end - 1))
3080 // output paragraphs
3082 docbookParagraphs(text(), *this, os, runparams);
3084 // latex or literate
3085 latexParagraphs(*this, text(), os, texrow, runparams);
3090 ErrorList & Buffer::errorList(string const & type) const
3092 static ErrorList emptyErrorList;
3093 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3094 if (it == d->errorLists.end())
3095 return emptyErrorList;
3101 void Buffer::updateTocItem(std::string const & type,
3102 DocIterator const & dit) const
3105 d->gui_->updateTocItem(type, dit);
3109 void Buffer::structureChanged() const
3112 d->gui_->structureChanged();
3116 void Buffer::errors(string const & err, bool from_master) const
3119 d->gui_->errors(err, from_master);
3123 void Buffer::message(docstring const & msg) const
3126 d->gui_->message(msg);
3130 void Buffer::setBusy(bool on) const
3133 d->gui_->setBusy(on);
3137 void Buffer::updateTitles() const
3140 d->wa_->updateTitles();
3144 void Buffer::resetAutosaveTimers() const
3147 d->gui_->resetAutosaveTimers();
3151 bool Buffer::hasGuiDelegate() const
3157 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3166 class AutoSaveBuffer : public ForkedProcess {
3169 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3170 : buffer_(buffer), fname_(fname) {}
3172 virtual shared_ptr<ForkedProcess> clone() const
3174 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3179 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3180 from_utf8(fname_.absFileName())));
3181 return run(DontWait);
3185 virtual int generateChild();
3187 Buffer const & buffer_;
3192 int AutoSaveBuffer::generateChild()
3194 #if defined(__APPLE__)
3195 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3196 * We should use something else like threads.
3198 * Since I do not know how to determine at run time what is the OS X
3199 * version, I just disable forking altogether for now (JMarc)
3201 pid_t const pid = -1;
3203 // tmp_ret will be located (usually) in /tmp
3204 // will that be a problem?
3205 // Note that this calls ForkedCalls::fork(), so it's
3206 // ok cross-platform.
3207 pid_t const pid = fork();
3208 // If you want to debug the autosave
3209 // you should set pid to -1, and comment out the fork.
3210 if (pid != 0 && pid != -1)
3214 // pid = -1 signifies that lyx was unable
3215 // to fork. But we will do the save
3217 bool failed = false;
3218 FileName const tmp_ret = FileName::tempName("lyxauto");
3219 if (!tmp_ret.empty()) {
3220 buffer_.writeFile(tmp_ret);
3221 // assume successful write of tmp_ret
3222 if (!tmp_ret.moveTo(fname_))
3228 // failed to write/rename tmp_ret so try writing direct
3229 if (!buffer_.writeFile(fname_)) {
3230 // It is dangerous to do this in the child,
3231 // but safe in the parent, so...
3232 if (pid == -1) // emit message signal.
3233 buffer_.message(_("Autosave failed!"));
3237 if (pid == 0) // we are the child so...
3246 FileName Buffer::getEmergencyFileName() const
3248 return FileName(d->filename.absFileName() + ".emergency");
3252 FileName Buffer::getAutosaveFileName() const
3254 // if the document is unnamed try to save in the backup dir, else
3255 // in the default document path, and as a last try in the filePath,
3256 // which will most often be the temporary directory
3259 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3260 : lyxrc.backupdir_path;
3261 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3264 string const fname = "#" + d->filename.onlyFileName() + "#";
3266 return makeAbsPath(fname, fpath);
3270 void Buffer::removeAutosaveFile() const
3272 FileName const f = getAutosaveFileName();
3278 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3280 FileName const newauto = getAutosaveFileName();
3282 if (newauto != oldauto && oldauto.exists())
3283 if (!oldauto.moveTo(newauto))
3284 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3288 bool Buffer::autoSave() const
3290 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3291 if (buf->d->bak_clean || isReadonly())
3294 message(_("Autosaving current document..."));
3295 buf->d->bak_clean = true;
3297 FileName const fname = getAutosaveFileName();
3298 if (d->cloned_buffer_) {
3299 // If this buffer is cloned, we assume that
3300 // we are running in a separate thread already.
3301 FileName const tmp_ret = FileName::tempName("lyxauto");
3302 if (!tmp_ret.empty()) {
3304 // assume successful write of tmp_ret
3305 if (tmp_ret.moveTo(fname))
3308 // failed to write/rename tmp_ret so try writing direct
3309 return writeFile(fname);
3311 /// This function is deprecated as the frontend needs to take care
3312 /// of cloning the buffer and autosaving it in another thread. It
3313 /// is still here to allow (QT_VERSION < 0x040400).
3314 AutoSaveBuffer autosave(*this, fname);
3321 string Buffer::bufferFormat() const
3323 string format = params().documentClass().outputFormat();
3324 if (format == "latex") {
3325 if (params().useNonTeXFonts)
3327 if (params().encoding().package() == Encoding::japanese)
3334 string Buffer::getDefaultOutputFormat() const
3336 if (!params().default_output_format.empty()
3337 && params().default_output_format != "default")
3338 return params().default_output_format;
3339 typedef vector<Format const *> Formats;
3340 Formats formats = exportableFormats(true);
3343 || params().useNonTeXFonts
3344 || params().encoding().package() == Encoding::japanese) {
3345 if (formats.empty())
3347 // return the first we find
3348 return formats.front()->name();
3350 return lyxrc.default_view_format;
3355 // helper class, to guarantee this gets reset properly
3356 class MarkAsExporting {
3358 MarkAsExporting(Buffer const * buf) : buf_(buf)
3360 LASSERT(buf_, /* */);
3361 buf_->setExportStatus(true);
3365 buf_->setExportStatus(false);
3368 Buffer const * const buf_;
3373 void Buffer::setExportStatus(bool e) const
3375 d->doing_export = e;
3379 bool Buffer::isExporting() const
3381 return d->doing_export;
3385 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3386 bool includeall, string & result_file) const
3388 MarkAsExporting exporting(this);
3389 string backend_format;
3390 OutputParams runparams(¶ms().encoding());
3391 runparams.flavor = OutputParams::LATEX;
3392 runparams.linelen = lyxrc.plaintext_linelen;
3393 runparams.includeall = includeall;
3394 vector<string> backs = backends();
3395 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3396 // Get shortest path to format
3397 Graph::EdgePath path;
3398 for (vector<string>::const_iterator it = backs.begin();
3399 it != backs.end(); ++it) {
3400 Graph::EdgePath p = theConverters().getPath(*it, format);
3401 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3402 backend_format = *it;
3407 if (!put_in_tempdir) {
3408 // Only show this alert if this is an export to a non-temporary
3409 // file (not for previewing).
3410 Alert::error(_("Couldn't export file"), bformat(
3411 _("No information for exporting the format %1$s."),
3412 formats.prettyName(format)));
3416 runparams.flavor = theConverters().getFlavor(path);
3419 backend_format = format;
3420 // FIXME: Don't hardcode format names here, but use a flag
3421 if (backend_format == "pdflatex")
3422 runparams.flavor = OutputParams::PDFLATEX;
3423 else if (backend_format == "luatex")
3424 runparams.flavor = OutputParams::LUATEX;
3425 else if (backend_format == "xetex")
3426 runparams.flavor = OutputParams::XETEX;
3429 string filename = latexName(false);
3430 filename = addName(temppath(), filename);
3431 filename = changeExtension(filename,
3432 formats.extension(backend_format));
3435 updateMacroInstances();
3437 // Plain text backend
3438 if (backend_format == "text") {
3439 runparams.flavor = OutputParams::TEXT;
3440 writePlaintextFile(*this, FileName(filename), runparams);
3443 else if (backend_format == "xhtml") {
3444 runparams.flavor = OutputParams::HTML;
3445 switch (params().html_math_output) {
3446 case BufferParams::MathML:
3447 runparams.math_flavor = OutputParams::MathAsMathML;
3449 case BufferParams::HTML:
3450 runparams.math_flavor = OutputParams::MathAsHTML;
3452 case BufferParams::Images:
3453 runparams.math_flavor = OutputParams::MathAsImages;
3455 case BufferParams::LaTeX:
3456 runparams.math_flavor = OutputParams::MathAsLaTeX;
3460 makeLyXHTMLFile(FileName(filename), runparams);
3461 } else if (backend_format == "lyx")
3462 writeFile(FileName(filename));
3464 else if (isDocBook()) {
3465 runparams.nice = !put_in_tempdir;
3466 makeDocBookFile(FileName(filename), runparams);
3469 else if (backend_format == format) {
3470 runparams.nice = true;
3471 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3473 } else if (!lyxrc.tex_allows_spaces
3474 && contains(filePath(), ' ')) {
3475 Alert::error(_("File name error"),
3476 _("The directory path to the document cannot contain spaces."));
3479 runparams.nice = false;
3480 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3484 string const error_type = (format == "program")
3485 ? "Build" : bufferFormat();
3486 ErrorList & error_list = d->errorLists[error_type];
3487 string const ext = formats.extension(format);
3488 FileName const tmp_result_file(changeExtension(filename, ext));
3489 bool const success = theConverters().convert(this, FileName(filename),
3490 tmp_result_file, FileName(absFileName()), backend_format, format,
3493 // Emit the signal to show the error list or copy it back to the
3494 // cloned Buffer so that it cab be emitted afterwards.
3495 if (format != backend_format) {
3496 if (d->cloned_buffer_) {
3497 d->cloned_buffer_->d->errorLists[error_type] =
3498 d->errorLists[error_type];
3501 // also to the children, in case of master-buffer-view
3502 ListOfBuffers clist = getDescendents();
3503 ListOfBuffers::const_iterator cit = clist.begin();
3504 ListOfBuffers::const_iterator const cen = clist.end();
3505 for (; cit != cen; ++cit) {
3506 if (d->cloned_buffer_) {
3507 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3508 (*cit)->d->errorLists[error_type];
3510 (*cit)->errors(error_type, true);
3514 if (d->cloned_buffer_) {
3515 // Enable reverse dvi or pdf to work by copying back the texrow
3516 // object to the cloned buffer.
3517 // FIXME: There is a possibility of concurrent access to texrow
3518 // here from the main GUI thread that should be securized.
3519 d->cloned_buffer_->d->texrow = d->texrow;
3520 string const error_type = bufferFormat();
3521 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3527 if (put_in_tempdir) {
3528 result_file = tmp_result_file.absFileName();
3532 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3533 // We need to copy referenced files (e. g. included graphics
3534 // if format == "dvi") to the result dir.
3535 vector<ExportedFile> const files =
3536 runparams.exportdata->externalFiles(format);
3537 string const dest = onlyPath(result_file);
3538 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3539 : force_overwrite == ALL_FILES;
3540 CopyStatus status = use_force ? FORCE : SUCCESS;
3542 vector<ExportedFile>::const_iterator it = files.begin();
3543 vector<ExportedFile>::const_iterator const en = files.end();
3544 for (; it != en && status != CANCEL; ++it) {
3545 string const fmt = formats.getFormatFromFile(it->sourceName);
3546 status = copyFile(fmt, it->sourceName,
3547 makeAbsPath(it->exportName, dest),
3548 it->exportName, status == FORCE);
3551 if (status == CANCEL) {
3552 message(_("Document export cancelled."));
3553 } else if (tmp_result_file.exists()) {
3554 // Finally copy the main file
3555 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3556 : force_overwrite != NO_FILES;
3557 if (status == SUCCESS && use_force)
3559 status = copyFile(format, tmp_result_file,
3560 FileName(result_file), result_file,
3562 message(bformat(_("Document exported as %1$s "
3564 formats.prettyName(format),
3565 makeDisplayPath(result_file)));
3567 // This must be a dummy converter like fax (bug 1888)
3568 message(bformat(_("Document exported as %1$s"),
3569 formats.prettyName(format)));
3576 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3577 bool includeall) const
3580 // (1) export with all included children (omit \includeonly)
3581 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3583 // (2) export with included children only
3584 return doExport(format, put_in_tempdir, false, result_file);
3588 bool Buffer::preview(string const & format, bool includeall) const
3590 MarkAsExporting exporting(this);
3592 // (1) export with all included children (omit \includeonly)
3593 if (includeall && !doExport(format, true, true))
3595 // (2) export with included children only
3596 if (!doExport(format, true, false, result_file))
3598 return formats.view(*this, FileName(result_file), format);
3602 bool Buffer::isExportable(string const & format) const
3604 vector<string> backs = backends();
3605 for (vector<string>::const_iterator it = backs.begin();
3606 it != backs.end(); ++it)
3607 if (theConverters().isReachable(*it, format))
3613 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3615 vector<string> const backs = backends();
3616 vector<Format const *> result =
3617 theConverters().getReachable(backs[0], only_viewable, true);
3618 for (vector<string>::const_iterator it = backs.begin() + 1;
3619 it != backs.end(); ++it) {
3620 vector<Format const *> r =
3621 theConverters().getReachable(*it, only_viewable, false);
3622 result.insert(result.end(), r.begin(), r.end());
3628 vector<string> Buffer::backends() const
3631 v.push_back(bufferFormat());
3632 // FIXME: Don't hardcode format names here, but use a flag
3633 if (v.back() == "latex") {
3634 v.push_back("pdflatex");
3635 v.push_back("luatex");
3636 v.push_back("xetex");
3637 } else if (v.back() == "xetex")
3638 v.push_back("luatex");
3639 v.push_back("xhtml");
3640 v.push_back("text");
3646 Buffer::ReadStatus Buffer::extractFromVC()
3648 bool const found = LyXVC::file_not_found_hook(d->filename);
3650 return ReadFileNotFound;
3651 if (!d->filename.isReadableFile())
3657 Buffer::ReadStatus Buffer::loadEmergency()
3659 FileName const emergencyFile = getEmergencyFileName();
3660 if (!emergencyFile.exists()
3661 || emergencyFile.lastModified() <= d->filename.lastModified())
3662 return ReadFileNotFound;
3664 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3665 docstring const text = bformat(_("An emergency save of the document "
3666 "%1$s exists.\n\nRecover emergency save?"), file);
3668 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3669 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3675 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3676 bool const success = (ret_llf == ReadSuccess);
3679 Alert::warning(_("File is read-only"),
3680 bformat(_("An emergency file is succesfully loaded, "
3681 "but the original file %1$s is marked read-only. "
3682 "Please make sure to save the document as a different "
3683 "file."), from_utf8(d->filename.absFileName())));
3686 str = _("Document was successfully recovered.");
3688 str = _("Document was NOT successfully recovered.");
3689 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3690 makeDisplayPath(emergencyFile.absFileName()));
3692 int const del_emerg =
3693 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3694 _("&Remove"), _("&Keep"));
3695 if (del_emerg == 0) {
3696 emergencyFile.removeFile();
3698 Alert::warning(_("Emergency file deleted"),
3699 _("Do not forget to save your file now!"), true);
3701 return success ? ReadSuccess : ReadEmergencyFailure;
3704 int const del_emerg =
3705 Alert::prompt(_("Delete emergency file?"),
3706 _("Remove emergency file now?"), 1, 1,
3707 _("&Remove"), _("&Keep"));
3709 emergencyFile.removeFile();
3710 return ReadOriginal;
3720 Buffer::ReadStatus Buffer::loadAutosave()
3722 // Now check if autosave file is newer.
3723 FileName const autosaveFile = getAutosaveFileName();
3724 if (!autosaveFile.exists()
3725 || autosaveFile.lastModified() <= d->filename.lastModified())
3726 return ReadFileNotFound;
3728 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3729 docstring const text = bformat(_("The backup of the document %1$s "
3730 "is newer.\n\nLoad the backup instead?"), file);
3731 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3732 _("&Load backup"), _("Load &original"), _("&Cancel"));
3737 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3738 // the file is not saved if we load the autosave file.
3739 if (ret_llf == ReadSuccess) {
3741 Alert::warning(_("File is read-only"),
3742 bformat(_("A backup file is succesfully loaded, "
3743 "but the original file %1$s is marked read-only. "
3744 "Please make sure to save the document as a "
3746 from_utf8(d->filename.absFileName())));
3751 return ReadAutosaveFailure;
3754 // Here we delete the autosave
3755 autosaveFile.removeFile();
3756 return ReadOriginal;
3764 Buffer::ReadStatus Buffer::loadLyXFile()
3766 if (!d->filename.isReadableFile()) {
3767 ReadStatus const ret_rvc = extractFromVC();
3768 if (ret_rvc != ReadSuccess)
3772 ReadStatus const ret_re = loadEmergency();
3773 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3776 ReadStatus const ret_ra = loadAutosave();
3777 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3780 return loadThisLyXFile(d->filename);
3784 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3786 return readFile(fn);
3790 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3792 TeXErrors::Errors::const_iterator cit = terr.begin();
3793 TeXErrors::Errors::const_iterator end = terr.end();
3795 for (; cit != end; ++cit) {
3798 int errorRow = cit->error_in_line;
3799 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3805 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3806 } while (found && id_start == id_end && pos_start == pos_end);
3808 errorList.push_back(ErrorItem(cit->error_desc,
3809 cit->error_text, id_start, pos_start, pos_end));
3814 void Buffer::setBuffersForInsets() const
3816 inset().setBuffer(const_cast<Buffer &>(*this));
3820 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3822 // Use the master text class also for child documents
3823 Buffer const * const master = masterBuffer();
3824 DocumentClass const & textclass = master->params().documentClass();
3826 // do this only if we are the top-level Buffer
3828 checkBibInfoCache();
3830 // keep the buffers to be children in this set. If the call from the
3831 // master comes back we can see which of them were actually seen (i.e.
3832 // via an InsetInclude). The remaining ones in the set need still be updated.
3833 static std::set<Buffer const *> bufToUpdate;
3834 if (scope == UpdateMaster) {
3835 // If this is a child document start with the master
3836 if (master != this) {
3837 bufToUpdate.insert(this);
3838 master->updateBuffer(UpdateMaster, utype);
3839 // Do this here in case the master has no gui associated with it. Then,
3840 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3841 if (!master->d->gui_)
3844 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3845 if (bufToUpdate.find(this) == bufToUpdate.end())
3849 // start over the counters in the master
3850 textclass.counters().reset();
3853 // update will be done below for this buffer
3854 bufToUpdate.erase(this);
3856 // update all caches
3857 clearReferenceCache();
3860 Buffer & cbuf = const_cast<Buffer &>(*this);
3862 LASSERT(!text().paragraphs().empty(), /**/);
3865 ParIterator parit = cbuf.par_iterator_begin();
3866 updateBuffer(parit, utype);
3869 // TocBackend update will be done later.
3872 cbuf.tocBackend().update();
3873 if (scope == UpdateMaster)
3874 cbuf.structureChanged();
3878 static depth_type getDepth(DocIterator const & it)
3880 depth_type depth = 0;
3881 for (size_t i = 0 ; i < it.depth() ; ++i)
3882 if (!it[i].inset().inMathed())
3883 depth += it[i].paragraph().getDepth() + 1;
3884 // remove 1 since the outer inset does not count
3888 static depth_type getItemDepth(ParIterator const & it)
3890 Paragraph const & par = *it;
3891 LabelType const labeltype = par.layout().labeltype;
3893 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3896 // this will hold the lowest depth encountered up to now.
3897 depth_type min_depth = getDepth(it);
3898 ParIterator prev_it = it;
3901 --prev_it.top().pit();
3903 // start of nested inset: go to outer par
3905 if (prev_it.empty()) {
3906 // start of document: nothing to do
3911 // We search for the first paragraph with same label
3912 // that is not more deeply nested.
3913 Paragraph & prev_par = *prev_it;
3914 depth_type const prev_depth = getDepth(prev_it);
3915 if (labeltype == prev_par.layout().labeltype) {
3916 if (prev_depth < min_depth)
3917 return prev_par.itemdepth + 1;
3918 if (prev_depth == min_depth)
3919 return prev_par.itemdepth;
3921 min_depth = min(min_depth, prev_depth);
3922 // small optimization: if we are at depth 0, we won't
3923 // find anything else
3924 if (prev_depth == 0)
3930 static bool needEnumCounterReset(ParIterator const & it)
3932 Paragraph const & par = *it;
3933 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3934 depth_type const cur_depth = par.getDepth();
3935 ParIterator prev_it = it;
3936 while (prev_it.pit()) {
3937 --prev_it.top().pit();
3938 Paragraph const & prev_par = *prev_it;
3939 if (prev_par.getDepth() <= cur_depth)
3940 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3942 // start of nested inset: reset
3947 // set the label of a paragraph. This includes the counters.
3948 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3950 BufferParams const & bp = owner_->masterBuffer()->params();
3951 DocumentClass const & textclass = bp.documentClass();
3952 Paragraph & par = it.paragraph();
3953 Layout const & layout = par.layout();
3954 Counters & counters = textclass.counters();
3956 if (par.params().startOfAppendix()) {
3957 // FIXME: only the counter corresponding to toplevel
3958 // sectioning should be reset
3960 counters.appendix(true);
3962 par.params().appendix(counters.appendix());
3964 // Compute the item depth of the paragraph
3965 par.itemdepth = getItemDepth(it);
3967 if (layout.margintype == MARGIN_MANUAL
3968 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3969 if (par.params().labelWidthString().empty())
3970 par.params().labelWidthString(par.expandLabel(layout, bp));
3972 par.params().labelWidthString(docstring());
3975 switch(layout.labeltype) {
3977 if (layout.toclevel <= bp.secnumdepth
3978 && (layout.latextype != LATEX_ENVIRONMENT
3979 || it.text()->isFirstInSequence(it.pit()))) {
3980 counters.step(layout.counter, utype);
3981 par.params().labelString(
3982 par.expandLabel(layout, bp));
3984 par.params().labelString(docstring());
3987 case LABEL_ITEMIZE: {
3988 // At some point of time we should do something more
3989 // clever here, like:
3990 // par.params().labelString(
3991 // bp.user_defined_bullet(par.itemdepth).getText());
3992 // for now, use a simple hardcoded label
3993 docstring itemlabel;
3994 switch (par.itemdepth) {
3996 itemlabel = char_type(0x2022);
3999 itemlabel = char_type(0x2013);
4002 itemlabel = char_type(0x2217);
4005 itemlabel = char_type(0x2219); // or 0x00b7
4008 par.params().labelString(itemlabel);
4012 case LABEL_ENUMERATE: {
4013 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4015 switch (par.itemdepth) {
4024 enumcounter += "iv";
4027 // not a valid enumdepth...
4031 // Maybe we have to reset the enumeration counter.
4032 if (needEnumCounterReset(it))
4033 counters.reset(enumcounter);
4034 counters.step(enumcounter, utype);
4036 string const & lang = par.getParLanguage(bp)->code();
4037 par.params().labelString(counters.theCounter(enumcounter, lang));
4042 case LABEL_SENSITIVE: {
4043 string const & type = counters.current_float();
4044 docstring full_label;
4046 full_label = owner_->B_("Senseless!!! ");
4048 docstring name = owner_->B_(textclass.floats().getType(type).name());
4049 if (counters.hasCounter(from_utf8(type))) {
4050 string const & lang = par.getParLanguage(bp)->code();
4051 counters.step(from_utf8(type), utype);
4052 full_label = bformat(from_ascii("%1$s %2$s:"),
4054 counters.theCounter(from_utf8(type), lang));
4056 full_label = bformat(from_ascii("%1$s #:"), name);
4058 par.params().labelString(full_label);
4062 case LABEL_NO_LABEL:
4063 par.params().labelString(docstring());
4067 case LABEL_TOP_ENVIRONMENT:
4068 case LABEL_CENTERED_TOP_ENVIRONMENT:
4071 par.params().labelString(par.expandLabel(layout, bp));
4077 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4079 LASSERT(parit.pit() == 0, /**/);
4081 // Set the position of the text in the buffer to be able
4082 // to resolve macros in it.
4083 parit.text()->setMacrocontextPosition(parit);
4085 depth_type maxdepth = 0;
4086 pit_type const lastpit = parit.lastpit();
4087 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4088 // reduce depth if necessary
4089 parit->params().depth(min(parit->params().depth(), maxdepth));
4090 maxdepth = parit->getMaxDepthAfter();
4092 if (utype == OutputUpdate) {
4093 // track the active counters
4094 // we have to do this for the master buffer, since the local
4095 // buffer isn't tracking anything.
4096 masterBuffer()->params().documentClass().counters().
4097 setActiveLayout(parit->layout());
4100 // set the counter for this paragraph
4101 d->setLabel(parit, utype);
4104 InsetList::const_iterator iit = parit->insetList().begin();
4105 InsetList::const_iterator end = parit->insetList().end();
4106 for (; iit != end; ++iit) {
4107 parit.pos() = iit->pos;
4108 iit->inset->updateBuffer(parit, utype);
4114 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4115 WordLangTuple & word_lang, docstring_list & suggestions) const
4119 suggestions.clear();
4120 word_lang = WordLangTuple();
4121 // OK, we start from here.
4122 DocIterator const end = doc_iterator_end(this);
4123 for (; from != end; from.forwardPos()) {
4124 // We are only interested in text so remove the math CursorSlice.
4125 while (from.inMathed()) {
4129 // If from is at the end of the document (which is possible
4130 // when leaving the mathed) LyX will crash later.
4134 from.paragraph().spellCheck();
4135 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4136 if (SpellChecker::misspelled(res)) {
4141 // Do not increase progress when from == to, otherwise the word
4142 // count will be wrong.
4152 Buffer::ReadStatus Buffer::reload()
4155 // c.f. bug http://www.lyx.org/trac/ticket/6587
4156 removeAutosaveFile();
4157 // e.g., read-only status could have changed due to version control
4158 d->filename.refresh();
4159 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4161 ReadStatus const status = loadLyXFile();
4162 if (status == ReadSuccess) {
4167 message(bformat(_("Document %1$s reloaded."), disp_fn));
4169 message(bformat(_("Could not reload document %1$s."), disp_fn));
4179 bool Buffer::saveAs(FileName const & fn)
4181 FileName const old_name = fileName();
4182 FileName const old_auto = getAutosaveFileName();
4183 bool const old_unnamed = isUnnamed();
4190 // bring the autosave file with us, just in case.
4191 moveAutosaveFile(old_auto);
4192 // validate version control data and
4193 // correct buffer title
4194 lyxvc().file_found_hook(fileName());
4196 // the file has now been saved to the new location.
4197 // we need to check that the locations of child buffers
4199 checkChildBuffers();
4203 // reset the old filename and unnamed state
4204 setFileName(old_name);
4205 setUnnamed(old_unnamed);
4211 // FIXME We could do better here, but it is complicated. What would be
4212 // nice is to offer either (a) to save the child buffer to an appropriate
4213 // location, so that it would "move with the master", or else (b) to update
4214 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4215 // complicated, because the code for this lives in GuiView.
4216 void Buffer::checkChildBuffers()
4218 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4219 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4220 for (; it != en; ++it) {
4221 DocIterator dit = it->second;
4222 Buffer * cbuf = const_cast<Buffer *>(it->first);
4223 if (!cbuf || !theBufferList().isLoaded(cbuf))
4225 Inset * inset = dit.nextInset();
4226 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4227 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4228 docstring const & incfile = inset_inc->getParam("filename");
4229 string oldloc = cbuf->absFileName();
4230 string newloc = makeAbsPath(to_utf8(incfile),
4231 onlyPath(absFileName())).absFileName();
4232 if (oldloc == newloc)
4234 // the location of the child file is incorrect.
4235 Alert::warning(_("Included File Invalid"),
4236 bformat(_("Saving this document to a new location has made the file:\n"
4238 "inaccessible. You will need to update the included filename."),
4239 from_utf8(oldloc)));
4241 inset_inc->setChildBuffer(0);
4243 // invalidate cache of children
4244 d->children_positions.clear();
4245 d->position_to_children.clear();