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 = 404; // rgh: refstyle
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 a 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(string const & newfile)
647 d->filename = makeAbsPath(newfile);
648 setReadonly(d->filename.isReadOnly());
653 int Buffer::readHeader(Lexer & lex)
655 int unknown_tokens = 0;
657 int begin_header_line = -1;
659 // Initialize parameters that may be/go lacking in header:
660 params().branchlist().clear();
661 params().preamble.erase();
662 params().options.erase();
663 params().master.erase();
664 params().float_placement.erase();
665 params().paperwidth.erase();
666 params().paperheight.erase();
667 params().leftmargin.erase();
668 params().rightmargin.erase();
669 params().topmargin.erase();
670 params().bottommargin.erase();
671 params().headheight.erase();
672 params().headsep.erase();
673 params().footskip.erase();
674 params().columnsep.erase();
675 params().fontsCJK.erase();
676 params().listings_params.clear();
677 params().clearLayoutModules();
678 params().clearRemovedModules();
679 params().clearIncludedChildren();
680 params().pdfoptions().clear();
681 params().indiceslist().clear();
682 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
683 params().isbackgroundcolor = false;
684 params().fontcolor = lyx::rgbFromHexName("#000000");
685 params().isfontcolor = false;
686 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
687 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
688 params().html_latex_start.clear();
689 params().html_latex_end.clear();
690 params().html_math_img_scale = 1.0;
691 params().output_sync_macro.erase();
693 for (int i = 0; i < 4; ++i) {
694 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
695 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
698 ErrorList & errorList = d->errorLists["Parse"];
707 if (token == "\\end_header")
711 if (token == "\\begin_header") {
712 begin_header_line = line;
716 LYXERR(Debug::PARSER, "Handling document header token: `"
719 string unknown = params().readToken(lex, token, d->filename.onlyPath());
720 if (!unknown.empty()) {
721 if (unknown[0] != '\\' && token == "\\textclass") {
722 Alert::warning(_("Unknown document class"),
723 bformat(_("Using the default document class, because the "
724 "class %1$s is unknown."), from_utf8(unknown)));
727 docstring const s = bformat(_("Unknown token: "
731 errorList.push_back(ErrorItem(_("Document header error"),
736 if (begin_header_line) {
737 docstring const s = _("\\begin_header is missing");
738 errorList.push_back(ErrorItem(_("Document header error"),
742 params().makeDocumentClass();
744 return unknown_tokens;
749 // changed to be public and have one parameter
750 // Returns true if "\end_document" is not read (Asger)
751 bool Buffer::readDocument(Lexer & lex)
753 ErrorList & errorList = d->errorLists["Parse"];
756 // remove dummy empty par
757 paragraphs().clear();
759 if (!lex.checkFor("\\begin_document")) {
760 docstring const s = _("\\begin_document is missing");
761 errorList.push_back(ErrorItem(_("Document header error"),
767 if (params().outputChanges) {
768 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
769 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
770 LaTeXFeatures::isAvailable("xcolor");
772 if (!dvipost && !xcolorulem) {
773 Alert::warning(_("Changes not shown in LaTeX output"),
774 _("Changes will not be highlighted in LaTeX output, "
775 "because neither dvipost nor xcolor/ulem are installed.\n"
776 "Please install these packages or redefine "
777 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
778 } else if (!xcolorulem) {
779 Alert::warning(_("Changes not shown in LaTeX output"),
780 _("Changes will not be highlighted in LaTeX output "
781 "when using pdflatex, because xcolor and ulem are not installed.\n"
782 "Please install both packages or redefine "
783 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
787 if (!params().master.empty()) {
788 FileName const master_file = makeAbsPath(params().master,
789 onlyPath(absFileName()));
790 if (isLyXFileName(master_file.absFileName())) {
792 checkAndLoadLyXFile(master_file, true);
794 // necessary e.g. after a reload
795 // to re-register the child (bug 5873)
796 // FIXME: clean up updateMacros (here, only
797 // child registering is needed).
798 master->updateMacros();
799 // set master as master buffer, but only
800 // if we are a real child
801 if (master->isChild(this))
803 // if the master is not fully loaded
804 // it is probably just loading this
805 // child. No warning needed then.
806 else if (master->isFullyLoaded())
807 LYXERR0("The master '"
809 << "' assigned to this document ("
811 << ") does not include "
812 "this document. Ignoring the master assignment.");
817 // assure we have a default index
818 params().indiceslist().addDefault(B_("Index"));
821 bool const res = text().read(lex, errorList, d->inset);
825 updateMacroInstances();
830 bool Buffer::readString(string const & s)
832 params().compressed = false;
837 FileName const fn = FileName::tempName("Buffer_readString");
840 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
841 if (ret_plf != ReadSuccess)
844 if (file_format != LYX_FORMAT) {
845 // We need to call lyx2lyx, so write the input to a file
846 ofstream os(fn.toFilesystemEncoding().c_str());
850 return readFile(fn) == ReadSuccess;
853 if (readDocument(lex))
859 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
866 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
867 if (ret_plf != ReadSuccess)
870 if (file_format != LYX_FORMAT) {
872 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
873 if (ret_clf != ReadSuccess)
875 return readFile(tmpFile);
878 // InsetInfo needs to know if file is under VCS
879 lyxvc().file_found_hook(fn);
881 if (readDocument(lex)) {
882 Alert::error(_("Document format failure"),
883 bformat(_("%1$s ended unexpectedly, which means"
884 " that it is probably corrupted."),
885 from_utf8(fn.absFileName())));
886 return ReadDocumentFailure;
889 d->file_fully_loaded = true;
890 d->read_only = !fname.isWritable();
891 params().compressed = fname.isZippedFile();
897 bool Buffer::isFullyLoaded() const
899 return d->file_fully_loaded;
903 void Buffer::setFullyLoaded(bool value)
905 d->file_fully_loaded = value;
909 void Buffer::updatePreviews() const
911 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
912 thePreviews().generateBufferPreviews(*this);
916 void Buffer::removePreviews() const
918 thePreviews().removeLoader(*this);
922 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
923 FileName const & fn, int & file_format) const
925 if(!lex.checkFor("\\lyxformat")) {
926 Alert::error(_("Document format failure"),
927 bformat(_("%1$s is not a readable LyX document."),
928 from_utf8(fn.absFileName())));
929 return ReadNoLyXFormat;
935 // LyX formats 217 and earlier were written as 2.17. This corresponds
936 // to files from LyX versions < 1.1.6.3. We just remove the dot in
937 // these cases. See also: www.lyx.org/trac/changeset/1313.
938 size_t dot = tmp_format.find_first_of(".,");
939 if (dot != string::npos)
940 tmp_format.erase(dot, 1);
942 file_format = convert<int>(tmp_format);
947 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
948 FileName & tmpfile, int from_format)
950 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
951 if(tmpfile.empty()) {
952 Alert::error(_("Conversion failed"),
953 bformat(_("%1$s is from a different"
954 " version of LyX, but a temporary"
955 " file for converting it could"
957 from_utf8(fn.absFileName())));
958 return LyX2LyXNoTempFile;
961 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
962 if (lyx2lyx.empty()) {
963 Alert::error(_("Conversion script not found"),
964 bformat(_("%1$s is from a different"
965 " version of LyX, but the"
966 " conversion script lyx2lyx"
967 " could not be found."),
968 from_utf8(fn.absFileName())));
969 return LyX2LyXNotFound;
973 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
974 ostringstream command;
975 command << os::python()
976 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
977 << " -t " << convert<string>(LYX_FORMAT)
978 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
979 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
980 string const command_str = command.str();
982 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
984 cmd_ret const ret = runCommand(command_str);
985 if (ret.first != 0) {
986 if (from_format < LYX_FORMAT) {
987 Alert::error(_("Conversion script failed"),
988 bformat(_("%1$s is from an older version"
989 " of LyX, but the lyx2lyx script"
990 " failed to convert it."),
991 from_utf8(fn.absFileName())));
992 return LyX2LyXOlderFormat;
994 Alert::error(_("Conversion script failed"),
995 bformat(_("%1$s is from an newer version"
996 " of LyX, but the lyx2lyx script"
997 " failed to convert it."),
998 from_utf8(fn.absFileName())));
999 return LyX2LyXNewerFormat;
1006 // Should probably be moved to somewhere else: BufferView? GuiView?
1007 bool Buffer::save() const
1009 // ask if the disk file has been externally modified (use checksum method)
1010 if (fileName().exists() && isExternallyModified(checksum_method)) {
1011 docstring const file = makeDisplayPath(absFileName(), 20);
1012 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1013 "you want to overwrite this file?"), file);
1014 int const ret = Alert::prompt(_("Overwrite modified file?"),
1015 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1020 // We don't need autosaves in the immediate future. (Asger)
1021 resetAutosaveTimers();
1023 FileName backupName;
1024 bool madeBackup = false;
1026 // make a backup if the file already exists
1027 if (lyxrc.make_backup && fileName().exists()) {
1028 backupName = FileName(absFileName() + '~');
1029 if (!lyxrc.backupdir_path.empty()) {
1030 string const mangledName =
1031 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1032 backupName = FileName(addName(lyxrc.backupdir_path,
1035 // do not copy because of #6587
1036 if (fileName().moveTo(backupName)) {
1039 Alert::error(_("Backup failure"),
1040 bformat(_("Cannot create backup file %1$s.\n"
1041 "Please check whether the directory exists and is writeable."),
1042 from_utf8(backupName.absFileName())));
1043 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1047 if (writeFile(d->filename)) {
1051 // Saving failed, so backup is not backup
1053 backupName.moveTo(d->filename);
1059 bool Buffer::writeFile(FileName const & fname) const
1061 if (d->read_only && fname == d->filename)
1064 bool retval = false;
1066 docstring const str = bformat(_("Saving document %1$s..."),
1067 makeDisplayPath(fname.absFileName()));
1070 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1072 if (params().compressed) {
1073 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1074 retval = ofs && write(ofs);
1076 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1077 retval = ofs && write(ofs);
1081 message(str + _(" could not write file!"));
1086 // removeAutosaveFile();
1089 message(str + _(" done."));
1095 docstring Buffer::emergencyWrite()
1097 // No need to save if the buffer has not changed.
1101 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1103 docstring user_message = bformat(
1104 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1106 // We try to save three places:
1107 // 1) Same place as document. Unless it is an unnamed doc.
1109 string s = absFileName();
1112 if (writeFile(FileName(s))) {
1114 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1115 return user_message;
1117 user_message += _(" Save failed! Trying again...\n");
1121 // 2) In HOME directory.
1122 string s = addName(package().home_dir().absFileName(), absFileName());
1124 lyxerr << ' ' << s << endl;
1125 if (writeFile(FileName(s))) {
1127 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1128 return user_message;
1131 user_message += _(" Save failed! Trying yet again...\n");
1133 // 3) In "/tmp" directory.
1134 // MakeAbsPath to prepend the current
1135 // drive letter on OS/2
1136 s = addName(package().temp_dir().absFileName(), absFileName());
1138 lyxerr << ' ' << s << endl;
1139 if (writeFile(FileName(s))) {
1141 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1142 return user_message;
1145 user_message += _(" Save failed! Bummer. Document is lost.");
1148 return user_message;
1152 bool Buffer::write(ostream & ofs) const
1155 // Use the standard "C" locale for file output.
1156 ofs.imbue(locale::classic());
1159 // The top of the file should not be written by params().
1161 // write out a comment in the top of the file
1162 ofs << "#LyX " << lyx_version
1163 << " created this file. For more info see http://www.lyx.org/\n"
1164 << "\\lyxformat " << LYX_FORMAT << "\n"
1165 << "\\begin_document\n";
1167 /// For each author, set 'used' to true if there is a change
1168 /// by this author in the document; otherwise set it to 'false'.
1169 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1170 AuthorList::Authors::const_iterator a_end = params().authors().end();
1171 for (; a_it != a_end; ++a_it)
1172 a_it->setUsed(false);
1174 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1175 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1176 for ( ; it != end; ++it)
1177 it->checkAuthors(params().authors());
1179 // now write out the buffer parameters.
1180 ofs << "\\begin_header\n";
1181 params().writeFile(ofs);
1182 ofs << "\\end_header\n";
1185 ofs << "\n\\begin_body\n";
1187 ofs << "\n\\end_body\n";
1189 // Write marker that shows file is complete
1190 ofs << "\\end_document" << endl;
1192 // Shouldn't really be needed....
1195 // how to check if close went ok?
1196 // Following is an attempt... (BE 20001011)
1198 // good() returns false if any error occured, including some
1199 // formatting error.
1200 // bad() returns true if something bad happened in the buffer,
1201 // which should include file system full errors.
1206 lyxerr << "File was not closed properly." << endl;
1213 bool Buffer::makeLaTeXFile(FileName const & fname,
1214 string const & original_path,
1215 OutputParams const & runparams_in,
1216 bool output_preamble, bool output_body) const
1218 OutputParams runparams = runparams_in;
1219 if (params().useXetex)
1220 runparams.flavor = OutputParams::XETEX;
1222 string const encoding = runparams.encoding->iconvName();
1223 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1226 try { ofs.reset(encoding); }
1227 catch (iconv_codecvt_facet_exception & e) {
1228 lyxerr << "Caught iconv exception: " << e.what() << endl;
1229 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1230 "verify that the support software for your encoding (%1$s) is "
1231 "properly installed"), from_ascii(encoding)));
1234 if (!openFileWrite(ofs, fname))
1237 //TexStream ts(ofs.rdbuf(), &texrow());
1238 ErrorList & errorList = d->errorLists["Export"];
1240 bool failed_export = false;
1243 writeLaTeXSource(ofs, original_path,
1244 runparams, output_preamble, output_body);
1246 catch (EncodingException & e) {
1247 odocstringstream ods;
1248 ods.put(e.failed_char);
1250 oss << "0x" << hex << e.failed_char << dec;
1251 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1252 " (code point %2$s)"),
1253 ods.str(), from_utf8(oss.str()));
1254 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1255 "representable in the chosen encoding.\n"
1256 "Changing the document encoding to utf8 could help."),
1257 e.par_id, e.pos, e.pos + 1));
1258 failed_export = true;
1260 catch (iconv_codecvt_facet_exception & e) {
1261 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1262 _(e.what()), -1, 0, 0));
1263 failed_export = true;
1265 catch (exception const & e) {
1266 errorList.push_back(ErrorItem(_("conversion failed"),
1267 _(e.what()), -1, 0, 0));
1268 failed_export = true;
1271 lyxerr << "Caught some really weird exception..." << endl;
1277 failed_export = true;
1278 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1282 return !failed_export;
1286 void Buffer::writeLaTeXSource(odocstream & os,
1287 string const & original_path,
1288 OutputParams const & runparams_in,
1289 bool const output_preamble, bool const output_body) const
1291 // The child documents, if any, shall be already loaded at this point.
1293 OutputParams runparams = runparams_in;
1295 // Classify the unicode characters appearing in math insets
1296 Encodings::initUnicodeMath(*this);
1298 // validate the buffer.
1299 LYXERR(Debug::LATEX, " Validating buffer...");
1300 LaTeXFeatures features(*this, params(), runparams);
1302 LYXERR(Debug::LATEX, " Buffer validation done.");
1304 // The starting paragraph of the coming rows is the
1305 // first paragraph of the document. (Asger)
1306 if (output_preamble && runparams.nice) {
1307 os << "%% LyX " << lyx_version << " created this file. "
1308 "For more info, see http://www.lyx.org/.\n"
1309 "%% Do not edit unless you really know what "
1311 d->texrow.newline();
1312 d->texrow.newline();
1314 LYXERR(Debug::INFO, "lyx document header finished");
1316 // Don't move this behind the parent_buffer=0 code below,
1317 // because then the macros will not get the right "redefinition"
1318 // flag as they don't see the parent macros which are output before.
1321 // fold macros if possible, still with parent buffer as the
1322 // macros will be put in the prefix anyway.
1323 updateMacroInstances();
1325 // There are a few differences between nice LaTeX and usual files:
1326 // usual is \batchmode and has a
1327 // special input@path to allow the including of figures
1328 // with either \input or \includegraphics (what figinsets do).
1329 // input@path is set when the actual parameter
1330 // original_path is set. This is done for usual tex-file, but not
1331 // for nice-latex-file. (Matthias 250696)
1332 // Note that input@path is only needed for something the user does
1333 // in the preamble, included .tex files or ERT, files included by
1334 // LyX work without it.
1335 if (output_preamble) {
1336 if (!runparams.nice) {
1337 // code for usual, NOT nice-latex-file
1338 os << "\\batchmode\n"; // changed
1339 // from \nonstopmode
1340 d->texrow.newline();
1342 if (!original_path.empty()) {
1344 // We don't know the encoding of inputpath
1345 docstring const inputpath = from_utf8(support::latex_path(original_path));
1346 docstring uncodable_glyphs;
1347 Encoding const * const enc = runparams.encoding;
1349 for (size_t n = 0; n < inputpath.size(); ++n) {
1350 docstring const glyph =
1351 docstring(1, inputpath[n]);
1352 if (enc->latexChar(inputpath[n], true) != glyph) {
1353 LYXERR0("Uncodable character '"
1355 << "' in input path!");
1356 uncodable_glyphs += glyph;
1361 // warn user if we found uncodable glyphs.
1362 if (!uncodable_glyphs.empty()) {
1363 frontend::Alert::warning(_("Uncodable character in file path"),
1364 support::bformat(_("The path of your document\n"
1366 "contains glyphs that are unknown in the\n"
1367 "current document encoding (namely %2$s).\n"
1368 "This will likely result in incomplete output.\n\n"
1369 "Choose an appropriate document encoding (such as utf8)\n"
1370 "or change the file path name."), inputpath, uncodable_glyphs));
1372 os << "\\makeatletter\n"
1373 << "\\def\\input@path{{"
1374 << inputpath << "/}}\n"
1375 << "\\makeatother\n";
1376 d->texrow.newline();
1377 d->texrow.newline();
1378 d->texrow.newline();
1382 // get parent macros (if this buffer has a parent) which will be
1383 // written at the document begin further down.
1384 MacroSet parentMacros;
1385 listParentMacros(parentMacros, features);
1387 // Write the preamble
1388 runparams.use_babel = params().writeLaTeX(os, features,
1390 d->filename.onlyPath());
1392 runparams.use_japanese = features.isRequired("japanese");
1398 os << "\\begin{document}\n";
1399 d->texrow.newline();
1401 // output the parent macros
1402 MacroSet::iterator it = parentMacros.begin();
1403 MacroSet::iterator end = parentMacros.end();
1404 for (; it != end; ++it) {
1405 int num_lines = (*it)->write(os, true);
1406 d->texrow.newlines(num_lines);
1409 } // output_preamble
1411 d->texrow.start(paragraphs().begin()->id(), 0);
1413 LYXERR(Debug::INFO, "preamble finished, now the body.");
1415 // if we are doing a real file with body, even if this is the
1416 // child of some other buffer, let's cut the link here.
1417 // This happens for example if only a child document is printed.
1418 Buffer const * save_parent = 0;
1419 if (output_preamble) {
1420 save_parent = d->parent();
1425 latexParagraphs(*this, text(), os, d->texrow, runparams);
1427 // Restore the parenthood if needed
1428 if (output_preamble)
1429 d->setParent(save_parent);
1431 // add this just in case after all the paragraphs
1433 d->texrow.newline();
1435 if (output_preamble) {
1436 os << "\\end{document}\n";
1437 d->texrow.newline();
1438 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1440 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1442 runparams_in.encoding = runparams.encoding;
1444 // Just to be sure. (Asger)
1445 d->texrow.newline();
1447 //for (int i = 0; i<d->texrow.rows(); i++) {
1449 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1450 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1453 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1454 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1458 bool Buffer::isLatex() const
1460 return params().documentClass().outputType() == LATEX;
1464 bool Buffer::isLiterate() const
1466 return params().documentClass().outputType() == LITERATE;
1470 bool Buffer::isDocBook() const
1472 return params().documentClass().outputType() == DOCBOOK;
1476 void Buffer::makeDocBookFile(FileName const & fname,
1477 OutputParams const & runparams,
1478 bool const body_only) const
1480 LYXERR(Debug::LATEX, "makeDocBookFile...");
1483 if (!openFileWrite(ofs, fname))
1486 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1490 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1494 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1495 OutputParams const & runparams,
1496 bool const only_body) const
1498 LaTeXFeatures features(*this, params(), runparams);
1503 DocumentClass const & tclass = params().documentClass();
1504 string const top_element = tclass.latexname();
1507 if (runparams.flavor == OutputParams::XML)
1508 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1511 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1514 if (! tclass.class_header().empty())
1515 os << from_ascii(tclass.class_header());
1516 else if (runparams.flavor == OutputParams::XML)
1517 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1518 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1520 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1522 docstring preamble = from_utf8(params().preamble);
1523 if (runparams.flavor != OutputParams::XML ) {
1524 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1525 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1526 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1527 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1530 string const name = runparams.nice
1531 ? changeExtension(absFileName(), ".sgml") : fname;
1532 preamble += features.getIncludedFiles(name);
1533 preamble += features.getLyXSGMLEntities();
1535 if (!preamble.empty()) {
1536 os << "\n [ " << preamble << " ]";
1541 string top = top_element;
1543 if (runparams.flavor == OutputParams::XML)
1544 top += params().language->code();
1546 top += params().language->code().substr(0, 2);
1549 if (!params().options.empty()) {
1551 top += params().options;
1554 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1555 << " file was created by LyX " << lyx_version
1556 << "\n See http://www.lyx.org/ for more information -->\n";
1558 params().documentClass().counters().reset();
1562 sgml::openTag(os, top);
1564 docbookParagraphs(text(), *this, os, runparams);
1565 sgml::closeTag(os, top_element);
1569 void Buffer::makeLyXHTMLFile(FileName const & fname,
1570 OutputParams const & runparams,
1571 bool const body_only) const
1573 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1576 if (!openFileWrite(ofs, fname))
1579 writeLyXHTMLSource(ofs, runparams, body_only);
1583 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1587 void Buffer::writeLyXHTMLSource(odocstream & os,
1588 OutputParams const & runparams,
1589 bool const only_body) const
1591 LaTeXFeatures features(*this, params(), runparams);
1593 updateBuffer(UpdateMaster, OutputUpdate);
1594 d->bibinfo_.makeCitationLabels(*this);
1596 updateMacroInstances();
1599 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1600 << "<!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"
1601 // FIXME Language should be set properly.
1602 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1604 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1605 // FIXME Presumably need to set this right
1606 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1608 docstring const & doctitle = features.htmlTitle();
1610 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1613 os << "\n<!-- Text Class Preamble -->\n"
1614 << features.getTClassHTMLPreamble()
1615 << "\n<!-- Premable Snippets -->\n"
1616 << from_utf8(features.getPreambleSnippets());
1618 os << "\n<!-- Layout-provided Styles -->\n";
1619 docstring const styleinfo = features.getTClassHTMLStyles();
1620 if (!styleinfo.empty()) {
1621 os << "<style type='text/css'>\n"
1625 os << "</head>\n<body>\n";
1629 params().documentClass().counters().reset();
1630 xhtmlParagraphs(text(), *this, xs, runparams);
1632 os << "</body>\n</html>\n";
1636 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1637 // Other flags: -wall -v0 -x
1638 int Buffer::runChktex()
1642 // get LaTeX-Filename
1643 FileName const path(temppath());
1644 string const name = addName(path.absFileName(), latexName());
1645 string const org_path = filePath();
1647 PathChanger p(path); // path to LaTeX file
1648 message(_("Running chktex..."));
1650 // Generate the LaTeX file if neccessary
1651 OutputParams runparams(¶ms().encoding());
1652 runparams.flavor = OutputParams::LATEX;
1653 runparams.nice = false;
1654 runparams.linelen = lyxrc.plaintext_linelen;
1655 makeLaTeXFile(FileName(name), org_path, runparams);
1658 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1659 int const res = chktex.run(terr); // run chktex
1662 Alert::error(_("chktex failure"),
1663 _("Could not run chktex successfully."));
1664 } else if (res > 0) {
1665 ErrorList & errlist = d->errorLists["ChkTeX"];
1667 bufferErrors(terr, errlist);
1678 void Buffer::validate(LaTeXFeatures & features) const
1680 params().validate(features);
1684 for_each(paragraphs().begin(), paragraphs().end(),
1685 bind(&Paragraph::validate, _1, ref(features)));
1687 if (lyxerr.debugging(Debug::LATEX)) {
1688 features.showStruct();
1693 void Buffer::getLabelList(vector<docstring> & list) const
1695 // If this is a child document, use the master's list instead.
1697 masterBuffer()->getLabelList(list);
1702 Toc & toc = d->toc_backend.toc("label");
1703 TocIterator toc_it = toc.begin();
1704 TocIterator end = toc.end();
1705 for (; toc_it != end; ++toc_it) {
1706 if (toc_it->depth() == 0)
1707 list.push_back(toc_it->str());
1712 void Buffer::updateBibfilesCache(UpdateScope scope) const
1714 // FIXME This is probably unnecssary, given where we call this.
1715 // If this is a child document, use the parent's cache instead.
1716 if (parent() && scope != UpdateChildOnly) {
1717 masterBuffer()->updateBibfilesCache();
1721 d->bibfiles_cache_.clear();
1722 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1723 if (it->lyxCode() == BIBTEX_CODE) {
1724 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1725 support::FileNameList const bibfiles = inset.getBibFiles();
1726 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1729 } else if (it->lyxCode() == INCLUDE_CODE) {
1730 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1731 Buffer const * const incbuf = inset.getChildBuffer();
1734 support::FileNameList const & bibfiles =
1735 incbuf->getBibfilesCache(UpdateChildOnly);
1736 if (!bibfiles.empty()) {
1737 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1743 d->bibfile_cache_valid_ = true;
1744 d->bibinfo_cache_valid_ = false;
1748 void Buffer::invalidateBibinfoCache() const
1750 d->bibinfo_cache_valid_ = false;
1751 // also invalidate the cache for the parent buffer
1752 Buffer const * const pbuf = d->parent();
1754 pbuf->invalidateBibinfoCache();
1758 void Buffer::invalidateBibfileCache() const
1760 d->bibfile_cache_valid_ = false;
1761 d->bibinfo_cache_valid_ = false;
1762 // also invalidate the cache for the parent buffer
1763 Buffer const * const pbuf = d->parent();
1765 pbuf->invalidateBibfileCache();
1769 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1771 // FIXME This is probably unnecessary, given where we call this.
1772 // If this is a child document, use the master's cache instead.
1773 Buffer const * const pbuf = masterBuffer();
1774 if (pbuf != this && scope != UpdateChildOnly)
1775 return pbuf->getBibfilesCache();
1777 if (!d->bibfile_cache_valid_)
1778 this->updateBibfilesCache(scope);
1780 return d->bibfiles_cache_;
1784 BiblioInfo const & Buffer::masterBibInfo() const
1786 Buffer const * const tmp = masterBuffer();
1788 return tmp->masterBibInfo();
1793 void Buffer::checkBibInfoCache() const
1795 // use the master's cache
1796 Buffer const * const tmp = masterBuffer();
1798 tmp->checkBibInfoCache();
1802 // this will also reload the cache if it is invalid
1803 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1805 // compare the cached timestamps with the actual ones.
1806 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1807 support::FileNameList::const_iterator en = bibfiles_cache.end();
1808 for (; ei != en; ++ ei) {
1809 time_t lastw = ei->lastModified();
1810 time_t prevw = d->bibfile_status_[*ei];
1811 if (lastw != prevw) {
1812 d->bibinfo_cache_valid_ = false;
1813 d->bibfile_status_[*ei] = lastw;
1817 // if not valid, then reload the info
1818 if (!d->bibinfo_cache_valid_) {
1819 d->bibinfo_.clear();
1820 fillWithBibKeys(d->bibinfo_);
1821 d->bibinfo_cache_valid_ = true;
1826 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1828 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1829 it->fillWithBibKeys(keys, it);
1833 bool Buffer::isDepClean(string const & name) const
1835 DepClean::const_iterator const it = d->dep_clean.find(name);
1836 if (it == d->dep_clean.end())
1842 void Buffer::markDepClean(string const & name)
1844 d->dep_clean[name] = true;
1848 bool Buffer::isExportableFormat(string const & format) const
1850 typedef vector<Format const *> Formats;
1852 formats = exportableFormats(true);
1853 Formats::const_iterator fit = formats.begin();
1854 Formats::const_iterator end = formats.end();
1855 for (; fit != end ; ++fit) {
1856 if ((*fit)->name() == format)
1863 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1866 // FIXME? if there is an Buffer LFUN that can be dispatched even
1867 // if internal, put a switch '(cmd.action)' here.
1873 switch (cmd.action()) {
1875 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1876 flag.setOnOff(isReadonly());
1879 // FIXME: There is need for a command-line import.
1880 //case LFUN_BUFFER_IMPORT:
1882 case LFUN_BUFFER_AUTO_SAVE:
1885 case LFUN_BUFFER_EXPORT_CUSTOM:
1886 // FIXME: Nothing to check here?
1889 case LFUN_BUFFER_EXPORT: {
1890 docstring const arg = cmd.argument();
1891 enable = arg == "custom" || isExportable(to_utf8(arg));
1893 flag.message(bformat(
1894 _("Don't know how to export to format: %1$s"), arg));
1898 case LFUN_BUFFER_CHKTEX:
1899 enable = isLatex() && !lyxrc.chktex_command.empty();
1902 case LFUN_BUILD_PROGRAM:
1903 enable = isExportable("program");
1906 case LFUN_BRANCH_ACTIVATE:
1907 case LFUN_BRANCH_DEACTIVATE: {
1908 BranchList const & branchList = params().branchlist();
1909 docstring const branchName = cmd.argument();
1910 enable = !branchName.empty() && branchList.find(branchName);
1914 case LFUN_BRANCH_ADD:
1915 case LFUN_BRANCHES_RENAME:
1916 case LFUN_BUFFER_PRINT:
1917 // if no Buffer is present, then of course we won't be called!
1920 case LFUN_BUFFER_LANGUAGE:
1921 enable = !isReadonly();
1927 flag.setEnabled(enable);
1932 void Buffer::dispatch(string const & command, DispatchResult & result)
1934 return dispatch(lyxaction.lookupFunc(command), result);
1938 // NOTE We can end up here even if we have no GUI, because we are called
1939 // by LyX::exec to handled command-line requests. So we may need to check
1940 // whether we have a GUI or not. The boolean use_gui holds this information.
1941 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1944 // FIXME? if there is an Buffer LFUN that can be dispatched even
1945 // if internal, put a switch '(cmd.action())' here.
1946 dr.dispatched(false);
1949 string const argument = to_utf8(func.argument());
1950 // We'll set this back to false if need be.
1951 bool dispatched = true;
1952 undo().beginUndoGroup();
1954 switch (func.action()) {
1955 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1956 if (lyxvc().inUse())
1957 lyxvc().toggleReadOnly();
1959 setReadonly(!isReadonly());
1962 case LFUN_BUFFER_EXPORT: {
1963 bool success = doExport(argument, false, false);
1964 dr.setError(!success);
1966 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1971 case LFUN_BUILD_PROGRAM:
1972 doExport("program", true, false);
1975 case LFUN_BUFFER_CHKTEX:
1979 case LFUN_BUFFER_EXPORT_CUSTOM: {
1981 string command = split(argument, format_name, ' ');
1982 Format const * format = formats.getFormat(format_name);
1984 lyxerr << "Format \"" << format_name
1985 << "\" not recognized!"
1990 // The name of the file created by the conversion process
1993 // Output to filename
1994 if (format->name() == "lyx") {
1995 string const latexname = latexName(false);
1996 filename = changeExtension(latexname,
1997 format->extension());
1998 filename = addName(temppath(), filename);
2000 if (!writeFile(FileName(filename)))
2004 doExport(format_name, true, false, filename);
2007 // Substitute $$FName for filename
2008 if (!contains(command, "$$FName"))
2009 command = "( " + command + " ) < $$FName";
2010 command = subst(command, "$$FName", filename);
2012 // Execute the command in the background
2014 call.startscript(Systemcall::DontWait, command);
2018 // FIXME: There is need for a command-line import.
2020 case LFUN_BUFFER_IMPORT:
2025 case LFUN_BUFFER_AUTO_SAVE:
2029 case LFUN_BRANCH_ADD: {
2030 docstring branch_name = func.argument();
2031 if (branch_name.empty()) {
2035 BranchList & branch_list = params().branchlist();
2036 vector<docstring> const branches =
2037 getVectorFromString(branch_name, branch_list.separator());
2039 for (vector<docstring>::const_iterator it = branches.begin();
2040 it != branches.end(); ++it) {
2042 Branch * branch = branch_list.find(branch_name);
2044 LYXERR0("Branch " << branch_name << " already exists.");
2048 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2050 branch_list.add(branch_name);
2051 branch = branch_list.find(branch_name);
2052 string const x11hexname = X11hexname(branch->color());
2053 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2054 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2056 dr.screenUpdate(Update::Force);
2064 case LFUN_BRANCH_ACTIVATE:
2065 case LFUN_BRANCH_DEACTIVATE: {
2066 BranchList & branchList = params().branchlist();
2067 docstring const branchName = func.argument();
2068 // the case without a branch name is handled elsewhere
2069 if (branchName.empty()) {
2073 Branch * branch = branchList.find(branchName);
2075 LYXERR0("Branch " << branchName << " does not exist.");
2077 docstring const msg =
2078 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2081 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2083 dr.screenUpdate(Update::Force);
2084 dr.forceBufferUpdate();
2089 case LFUN_BRANCHES_RENAME: {
2090 if (func.argument().empty())
2093 docstring const oldname = from_utf8(func.getArg(0));
2094 docstring const newname = from_utf8(func.getArg(1));
2095 InsetIterator it = inset_iterator_begin(inset());
2096 InsetIterator const end = inset_iterator_end(inset());
2097 bool success = false;
2098 for (; it != end; ++it) {
2099 if (it->lyxCode() == BRANCH_CODE) {
2100 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2101 if (ins.branch() == oldname) {
2102 undo().recordUndo(it);
2103 ins.rename(newname);
2108 if (it->lyxCode() == INCLUDE_CODE) {
2109 // get buffer of external file
2110 InsetInclude const & ins =
2111 static_cast<InsetInclude const &>(*it);
2112 Buffer * child = ins.getChildBuffer();
2115 child->dispatch(func, dr);
2120 dr.screenUpdate(Update::Force);
2121 dr.forceBufferUpdate();
2126 case LFUN_BUFFER_PRINT: {
2127 // we'll assume there's a problem until we succeed
2129 string target = func.getArg(0);
2130 string target_name = func.getArg(1);
2131 string command = func.getArg(2);
2134 || target_name.empty()
2135 || command.empty()) {
2136 LYXERR0("Unable to parse " << func.argument());
2137 docstring const msg =
2138 bformat(_("Unable to parse \"%1$s\""), func.argument());
2142 if (target != "printer" && target != "file") {
2143 LYXERR0("Unrecognized target \"" << target << '"');
2144 docstring const msg =
2145 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2150 bool const update_unincluded =
2151 params().maintain_unincluded_children
2152 && !params().getIncludedChildren().empty();
2153 if (!doExport("dvi", true, update_unincluded)) {
2154 showPrintError(absFileName());
2155 dr.setMessage(_("Error exporting to DVI."));
2159 // Push directory path.
2160 string const path = temppath();
2161 // Prevent the compiler from optimizing away p
2165 // there are three cases here:
2166 // 1. we print to a file
2167 // 2. we print directly to a printer
2168 // 3. we print using a spool command (print to file first)
2171 string const dviname = changeExtension(latexName(true), "dvi");
2173 if (target == "printer") {
2174 if (!lyxrc.print_spool_command.empty()) {
2175 // case 3: print using a spool
2176 string const psname = changeExtension(dviname,".ps");
2177 command += ' ' + lyxrc.print_to_file
2180 + quoteName(dviname);
2182 string command2 = lyxrc.print_spool_command + ' ';
2183 if (target_name != "default") {
2184 command2 += lyxrc.print_spool_printerprefix
2188 command2 += quoteName(psname);
2190 // If successful, then spool command
2191 res = one.startscript(Systemcall::Wait, command);
2194 // If there's no GUI, we have to wait on this command. Otherwise,
2195 // LyX deletes the temporary directory, and with it the spooled
2196 // file, before it can be printed!!
2197 Systemcall::Starttype stype = use_gui ?
2198 Systemcall::DontWait : Systemcall::Wait;
2199 res = one.startscript(stype, command2);
2202 // case 2: print directly to a printer
2203 if (target_name != "default")
2204 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2206 Systemcall::Starttype stype = use_gui ?
2207 Systemcall::DontWait : Systemcall::Wait;
2208 res = one.startscript(stype, command + quoteName(dviname));
2212 // case 1: print to a file
2213 FileName const filename(makeAbsPath(target_name, filePath()));
2214 FileName const dvifile(makeAbsPath(dviname, path));
2215 if (filename.exists()) {
2216 docstring text = bformat(
2217 _("The file %1$s already exists.\n\n"
2218 "Do you want to overwrite that file?"),
2219 makeDisplayPath(filename.absFileName()));
2220 if (Alert::prompt(_("Overwrite file?"),
2221 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2224 command += ' ' + lyxrc.print_to_file
2225 + quoteName(filename.toFilesystemEncoding())
2227 + quoteName(dvifile.toFilesystemEncoding());
2229 Systemcall::Starttype stype = use_gui ?
2230 Systemcall::DontWait : Systemcall::Wait;
2231 res = one.startscript(stype, command);
2237 dr.setMessage(_("Error running external commands."));
2238 showPrintError(absFileName());
2243 case LFUN_BUFFER_LANGUAGE: {
2244 Language const * oldL = params().language;
2245 Language const * newL = languages.getLanguage(argument);
2246 if (!newL || oldL == newL)
2248 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2249 changeLanguage(oldL, newL);
2250 dr.forceBufferUpdate();
2259 dr.dispatched(dispatched);
2260 undo().endUndoGroup();
2264 void Buffer::changeLanguage(Language const * from, Language const * to)
2266 LASSERT(from, /**/);
2269 for_each(par_iterator_begin(),
2271 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2275 bool Buffer::isMultiLingual() const
2277 ParConstIterator end = par_iterator_end();
2278 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2279 if (it->isMultiLingual(params()))
2286 std::set<Language const *> Buffer::getLanguages() const
2288 std::set<Language const *> languages;
2289 getLanguages(languages);
2294 void Buffer::getLanguages(std::set<Language const *> & languages) const
2296 ParConstIterator end = par_iterator_end();
2297 // add the buffer language, even if it's not actively used
2298 languages.insert(language());
2299 // iterate over the paragraphs
2300 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2301 it->getLanguages(languages);
2303 ListOfBuffers clist = getDescendents();
2304 ListOfBuffers::const_iterator cit = clist.begin();
2305 ListOfBuffers::const_iterator const cen = clist.end();
2306 for (; cit != cen; ++cit)
2307 (*cit)->getLanguages(languages);
2311 DocIterator Buffer::getParFromID(int const id) const
2313 Buffer * buf = const_cast<Buffer *>(this);
2315 // John says this is called with id == -1 from undo
2316 lyxerr << "getParFromID(), id: " << id << endl;
2317 return doc_iterator_end(buf);
2320 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2321 if (it.paragraph().id() == id)
2324 return doc_iterator_end(buf);
2328 bool Buffer::hasParWithID(int const id) const
2330 return !getParFromID(id).atEnd();
2334 ParIterator Buffer::par_iterator_begin()
2336 return ParIterator(doc_iterator_begin(this));
2340 ParIterator Buffer::par_iterator_end()
2342 return ParIterator(doc_iterator_end(this));
2346 ParConstIterator Buffer::par_iterator_begin() const
2348 return ParConstIterator(doc_iterator_begin(this));
2352 ParConstIterator Buffer::par_iterator_end() const
2354 return ParConstIterator(doc_iterator_end(this));
2358 Language const * Buffer::language() const
2360 return params().language;
2364 docstring const Buffer::B_(string const & l10n) const
2366 return params().B_(l10n);
2370 bool Buffer::isClean() const
2372 return d->lyx_clean;
2376 bool Buffer::isExternallyModified(CheckMethod method) const
2378 LASSERT(d->filename.exists(), /**/);
2379 // if method == timestamp, check timestamp before checksum
2380 return (method == checksum_method
2381 || d->timestamp_ != d->filename.lastModified())
2382 && d->checksum_ != d->filename.checksum();
2386 void Buffer::saveCheckSum() const
2388 FileName const & file = d->filename;
2389 if (file.exists()) {
2390 d->timestamp_ = file.lastModified();
2391 d->checksum_ = file.checksum();
2393 // in the case of save to a new file.
2400 void Buffer::markClean() const
2402 if (!d->lyx_clean) {
2403 d->lyx_clean = true;
2406 // if the .lyx file has been saved, we don't need an
2408 d->bak_clean = true;
2409 d->undo_.markDirty();
2413 void Buffer::setUnnamed(bool flag)
2419 bool Buffer::isUnnamed() const
2426 /// Don't check unnamed, here: isInternal() is used in
2427 /// newBuffer(), where the unnamed flag has not been set by anyone
2428 /// yet. Also, for an internal buffer, there should be no need for
2429 /// retrieving fileName() nor for checking if it is unnamed or not.
2430 bool Buffer::isInternal() const
2432 return fileName().extension() == "internal";
2436 void Buffer::markDirty()
2439 d->lyx_clean = false;
2442 d->bak_clean = false;
2444 DepClean::iterator it = d->dep_clean.begin();
2445 DepClean::const_iterator const end = d->dep_clean.end();
2447 for (; it != end; ++it)
2452 FileName Buffer::fileName() const
2458 string Buffer::absFileName() const
2460 return d->filename.absFileName();
2464 string Buffer::filePath() const
2466 return d->filename.onlyPath().absFileName() + "/";
2470 bool Buffer::isReadonly() const
2472 return d->read_only;
2476 void Buffer::setParent(Buffer const * buffer)
2478 // Avoids recursive include.
2479 d->setParent(buffer == this ? 0 : buffer);
2484 Buffer const * Buffer::parent() const
2490 ListOfBuffers Buffer::allRelatives() const
2492 ListOfBuffers lb = masterBuffer()->getDescendents();
2493 lb.push_front(const_cast<Buffer *>(this));
2498 Buffer const * Buffer::masterBuffer() const
2500 // FIXME Should be make sure we are not in some kind
2501 // of recursive include? A -> B -> A will crash this.
2502 Buffer const * const pbuf = d->parent();
2506 return pbuf->masterBuffer();
2510 bool Buffer::isChild(Buffer * child) const
2512 return d->children_positions.find(child) != d->children_positions.end();
2516 DocIterator Buffer::firstChildPosition(Buffer const * child)
2518 Impl::BufferPositionMap::iterator it;
2519 it = d->children_positions.find(child);
2520 if (it == d->children_positions.end())
2521 return DocIterator(this);
2526 bool Buffer::hasChildren() const
2528 return !d->children_positions.empty();
2532 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2534 // loop over children
2535 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2536 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2537 for (; it != end; ++it) {
2538 Buffer * child = const_cast<Buffer *>(it->first);
2540 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2541 if (bit != clist.end())
2543 clist.push_back(child);
2545 // there might be grandchildren
2546 child->collectChildren(clist, true);
2551 ListOfBuffers Buffer::getChildren() const
2554 collectChildren(v, false);
2559 ListOfBuffers Buffer::getDescendents() const
2562 collectChildren(v, true);
2567 template<typename M>
2568 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2573 typename M::const_iterator it = m.lower_bound(x);
2574 if (it == m.begin())
2582 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2583 DocIterator const & pos) const
2585 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2587 // if paragraphs have no macro context set, pos will be empty
2591 // we haven't found anything yet
2592 DocIterator bestPos = owner_->par_iterator_begin();
2593 MacroData const * bestData = 0;
2595 // find macro definitions for name
2596 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2597 if (nameIt != macros.end()) {
2598 // find last definition in front of pos or at pos itself
2599 PositionScopeMacroMap::const_iterator it
2600 = greatest_below(nameIt->second, pos);
2601 if (it != nameIt->second.end()) {
2603 // scope ends behind pos?
2604 if (pos < it->second.first) {
2605 // Looks good, remember this. If there
2606 // is no external macro behind this,
2607 // we found the right one already.
2608 bestPos = it->first;
2609 bestData = &it->second.second;
2613 // try previous macro if there is one
2614 if (it == nameIt->second.begin())
2621 // find macros in included files
2622 PositionScopeBufferMap::const_iterator it
2623 = greatest_below(position_to_children, pos);
2624 if (it == position_to_children.end())
2625 // no children before
2629 // do we know something better (i.e. later) already?
2630 if (it->first < bestPos )
2633 // scope ends behind pos?
2634 if (pos < it->second.first) {
2635 // look for macro in external file
2637 MacroData const * data
2638 = it->second.second->getMacro(name, false);
2641 bestPos = it->first;
2647 // try previous file if there is one
2648 if (it == position_to_children.begin())
2653 // return the best macro we have found
2658 MacroData const * Buffer::getMacro(docstring const & name,
2659 DocIterator const & pos, bool global) const
2664 // query buffer macros
2665 MacroData const * data = d->getBufferMacro(name, pos);
2669 // If there is a master buffer, query that
2670 Buffer const * const pbuf = d->parent();
2672 d->macro_lock = true;
2673 MacroData const * macro = pbuf->getMacro(
2674 name, *this, false);
2675 d->macro_lock = false;
2681 data = MacroTable::globalMacros().get(name);
2690 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2692 // set scope end behind the last paragraph
2693 DocIterator scope = par_iterator_begin();
2694 scope.pit() = scope.lastpit() + 1;
2696 return getMacro(name, scope, global);
2700 MacroData const * Buffer::getMacro(docstring const & name,
2701 Buffer const & child, bool global) const
2703 // look where the child buffer is included first
2704 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2705 if (it == d->children_positions.end())
2708 // check for macros at the inclusion position
2709 return getMacro(name, it->second, global);
2713 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2715 pit_type const lastpit = it.lastpit();
2717 // look for macros in each paragraph
2718 while (it.pit() <= lastpit) {
2719 Paragraph & par = it.paragraph();
2721 // iterate over the insets of the current paragraph
2722 InsetList const & insets = par.insetList();
2723 InsetList::const_iterator iit = insets.begin();
2724 InsetList::const_iterator end = insets.end();
2725 for (; iit != end; ++iit) {
2726 it.pos() = iit->pos;
2728 // is it a nested text inset?
2729 if (iit->inset->asInsetText()) {
2730 // Inset needs its own scope?
2731 InsetText const * itext = iit->inset->asInsetText();
2732 bool newScope = itext->isMacroScope();
2734 // scope which ends just behind the inset
2735 DocIterator insetScope = it;
2738 // collect macros in inset
2739 it.push_back(CursorSlice(*iit->inset));
2740 updateMacros(it, newScope ? insetScope : scope);
2745 if (iit->inset->asInsetTabular()) {
2746 CursorSlice slice(*iit->inset);
2747 size_t const numcells = slice.nargs();
2748 for (; slice.idx() < numcells; slice.forwardIdx()) {
2749 it.push_back(slice);
2750 updateMacros(it, scope);
2756 // is it an external file?
2757 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2758 // get buffer of external file
2759 InsetInclude const & inset =
2760 static_cast<InsetInclude const &>(*iit->inset);
2762 Buffer * child = inset.getChildBuffer();
2767 // register its position, but only when it is
2768 // included first in the buffer
2769 if (children_positions.find(child) ==
2770 children_positions.end())
2771 children_positions[child] = it;
2773 // register child with its scope
2774 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2778 InsetMath * im = iit->inset->asInsetMath();
2779 if (doing_export && im) {
2780 InsetMathHull * hull = im->asHullInset();
2782 hull->recordLocation(it);
2785 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2789 MathMacroTemplate & macroTemplate =
2790 *iit->inset->asInsetMath()->asMacroTemplate();
2791 MacroContext mc(owner_, it);
2792 macroTemplate.updateToContext(mc);
2795 bool valid = macroTemplate.validMacro();
2796 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2797 // then the BufferView's cursor will be invalid in
2798 // some cases which leads to crashes.
2803 // FIXME (Abdel), I don't understandt why we pass 'it' here
2804 // instead of 'macroTemplate' defined above... is this correct?
2805 macros[macroTemplate.name()][it] =
2806 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2816 void Buffer::updateMacros() const
2821 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2823 // start with empty table
2825 d->children_positions.clear();
2826 d->position_to_children.clear();
2828 // Iterate over buffer, starting with first paragraph
2829 // The scope must be bigger than any lookup DocIterator
2830 // later. For the global lookup, lastpit+1 is used, hence
2831 // we use lastpit+2 here.
2832 DocIterator it = par_iterator_begin();
2833 DocIterator outerScope = it;
2834 outerScope.pit() = outerScope.lastpit() + 2;
2835 d->updateMacros(it, outerScope);
2839 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2841 InsetIterator it = inset_iterator_begin(inset());
2842 InsetIterator const end = inset_iterator_end(inset());
2843 for (; it != end; ++it) {
2844 if (it->lyxCode() == BRANCH_CODE) {
2845 InsetBranch & br = static_cast<InsetBranch &>(*it);
2846 docstring const name = br.branch();
2847 if (!from_master && !params().branchlist().find(name))
2848 result.push_back(name);
2849 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2850 result.push_back(name);
2853 if (it->lyxCode() == INCLUDE_CODE) {
2854 // get buffer of external file
2855 InsetInclude const & ins =
2856 static_cast<InsetInclude const &>(*it);
2857 Buffer * child = ins.getChildBuffer();
2860 child->getUsedBranches(result, true);
2863 // remove duplicates
2868 void Buffer::updateMacroInstances() const
2870 LYXERR(Debug::MACROS, "updateMacroInstances for "
2871 << d->filename.onlyFileName());
2872 DocIterator it = doc_iterator_begin(this);
2874 DocIterator const end = doc_iterator_end(this);
2875 for (; it != end; it.forwardInset()) {
2876 // look for MathData cells in InsetMathNest insets
2877 InsetMath * minset = it.nextInset()->asInsetMath();
2881 // update macro in all cells of the InsetMathNest
2882 DocIterator::idx_type n = minset->nargs();
2883 MacroContext mc = MacroContext(this, it);
2884 for (DocIterator::idx_type i = 0; i < n; ++i) {
2885 MathData & data = minset->cell(i);
2886 data.updateMacros(0, mc);
2892 void Buffer::listMacroNames(MacroNameSet & macros) const
2897 d->macro_lock = true;
2899 // loop over macro names
2900 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2901 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2902 for (; nameIt != nameEnd; ++nameIt)
2903 macros.insert(nameIt->first);
2905 // loop over children
2906 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2907 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2908 for (; it != end; ++it)
2909 it->first->listMacroNames(macros);
2912 Buffer const * const pbuf = d->parent();
2914 pbuf->listMacroNames(macros);
2916 d->macro_lock = false;
2920 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2922 Buffer const * const pbuf = d->parent();
2927 pbuf->listMacroNames(names);
2930 MacroNameSet::iterator it = names.begin();
2931 MacroNameSet::iterator end = names.end();
2932 for (; it != end; ++it) {
2934 MacroData const * data =
2935 pbuf->getMacro(*it, *this, false);
2937 macros.insert(data);
2939 // we cannot access the original MathMacroTemplate anymore
2940 // here to calls validate method. So we do its work here manually.
2941 // FIXME: somehow make the template accessible here.
2942 if (data->optionals() > 0)
2943 features.require("xargs");
2949 Buffer::References & Buffer::references(docstring const & label)
2952 return const_cast<Buffer *>(masterBuffer())->references(label);
2954 RefCache::iterator it = d->ref_cache_.find(label);
2955 if (it != d->ref_cache_.end())
2956 return it->second.second;
2958 static InsetLabel const * dummy_il = 0;
2959 static References const dummy_refs;
2960 it = d->ref_cache_.insert(
2961 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2962 return it->second.second;
2966 Buffer::References const & Buffer::references(docstring const & label) const
2968 return const_cast<Buffer *>(this)->references(label);
2972 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2974 masterBuffer()->d->ref_cache_[label].first = il;
2978 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2980 return masterBuffer()->d->ref_cache_[label].first;
2984 void Buffer::clearReferenceCache() const
2987 d->ref_cache_.clear();
2991 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2994 //FIXME: This does not work for child documents yet.
2995 LASSERT(code == CITE_CODE, /**/);
2996 // Check if the label 'from' appears more than once
2997 vector<docstring> labels;
2999 checkBibInfoCache();
3000 BiblioInfo const & keys = masterBibInfo();
3001 BiblioInfo::const_iterator bit = keys.begin();
3002 BiblioInfo::const_iterator bend = keys.end();
3004 for (; bit != bend; ++bit)
3006 labels.push_back(bit->first);
3009 if (count(labels.begin(), labels.end(), from) > 1)
3012 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3013 if (it->lyxCode() == code) {
3014 InsetCommand * inset = it->asInsetCommand();
3017 docstring const oldValue = inset->getParam(paramName);
3018 if (oldValue == from)
3019 inset->setParam(paramName, to);
3025 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3026 pit_type par_end, bool full_source) const
3028 OutputParams runparams(¶ms().encoding());
3029 runparams.nice = true;
3030 runparams.flavor = params().useXetex ?
3031 OutputParams::XETEX : OutputParams::LATEX;
3032 runparams.linelen = lyxrc.plaintext_linelen;
3033 // No side effect of file copying and image conversion
3034 runparams.dryrun = true;
3037 os << "% " << _("Preview source code") << "\n\n";
3039 d->texrow.newline();
3040 d->texrow.newline();
3042 writeDocBookSource(os, absFileName(), runparams, false);
3044 // latex or literate
3045 writeLaTeXSource(os, string(), runparams, true, true);
3047 runparams.par_begin = par_begin;
3048 runparams.par_end = par_end;
3049 if (par_begin + 1 == par_end) {
3051 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3055 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3056 convert<docstring>(par_begin),
3057 convert<docstring>(par_end - 1))
3064 // output paragraphs
3066 docbookParagraphs(text(), *this, os, runparams);
3068 // latex or literate
3069 latexParagraphs(*this, text(), os, texrow, runparams);
3074 ErrorList & Buffer::errorList(string const & type) const
3076 static ErrorList emptyErrorList;
3077 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3078 if (it == d->errorLists.end())
3079 return emptyErrorList;
3085 void Buffer::updateTocItem(std::string const & type,
3086 DocIterator const & dit) const
3089 d->gui_->updateTocItem(type, dit);
3093 void Buffer::structureChanged() const
3096 d->gui_->structureChanged();
3100 void Buffer::errors(string const & err, bool from_master) const
3103 d->gui_->errors(err, from_master);
3107 void Buffer::message(docstring const & msg) const
3110 d->gui_->message(msg);
3114 void Buffer::setBusy(bool on) const
3117 d->gui_->setBusy(on);
3121 void Buffer::updateTitles() const
3124 d->wa_->updateTitles();
3128 void Buffer::resetAutosaveTimers() const
3131 d->gui_->resetAutosaveTimers();
3135 bool Buffer::hasGuiDelegate() const
3141 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3150 class AutoSaveBuffer : public ForkedProcess {
3153 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3154 : buffer_(buffer), fname_(fname) {}
3156 virtual shared_ptr<ForkedProcess> clone() const
3158 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3163 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3164 from_utf8(fname_.absFileName())));
3165 return run(DontWait);
3169 virtual int generateChild();
3171 Buffer const & buffer_;
3176 int AutoSaveBuffer::generateChild()
3178 #if defined(__APPLE__)
3179 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3180 * We should use something else like threads.
3182 * Since I do not know how to determine at run time what is the OS X
3183 * version, I just disable forking altogether for now (JMarc)
3185 pid_t const pid = -1;
3187 // tmp_ret will be located (usually) in /tmp
3188 // will that be a problem?
3189 // Note that this calls ForkedCalls::fork(), so it's
3190 // ok cross-platform.
3191 pid_t const pid = fork();
3192 // If you want to debug the autosave
3193 // you should set pid to -1, and comment out the fork.
3194 if (pid != 0 && pid != -1)
3198 // pid = -1 signifies that lyx was unable
3199 // to fork. But we will do the save
3201 bool failed = false;
3202 FileName const tmp_ret = FileName::tempName("lyxauto");
3203 if (!tmp_ret.empty()) {
3204 buffer_.writeFile(tmp_ret);
3205 // assume successful write of tmp_ret
3206 if (!tmp_ret.moveTo(fname_))
3212 // failed to write/rename tmp_ret so try writing direct
3213 if (!buffer_.writeFile(fname_)) {
3214 // It is dangerous to do this in the child,
3215 // but safe in the parent, so...
3216 if (pid == -1) // emit message signal.
3217 buffer_.message(_("Autosave failed!"));
3221 if (pid == 0) // we are the child so...
3230 FileName Buffer::getEmergencyFileName() const
3232 return getEmergencyFileNameFor(d->filename);
3236 FileName Buffer::getEmergencyFileNameFor(FileName const & fn) const
3238 return FileName(fn.absFileName() + ".emergency");
3242 FileName Buffer::getAutosaveFileName() const
3244 // if the document is unnamed try to save in the backup dir, else
3245 // in the default document path, and as a last try in the filePath,
3246 // which will most often be the temporary directory
3249 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3250 : lyxrc.backupdir_path;
3251 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3254 string const fname = d->filename.onlyFileName();
3255 return getAutosaveFileNameFor(makeAbsPath(fname, fpath));
3259 FileName Buffer::getAutosaveFileNameFor(FileName const & fn) const
3261 string const fname = "#" + onlyFileName(fn.absFileName()) + "#";
3262 return FileName(onlyPath(fn.absFileName()) + fname);
3266 void Buffer::removeAutosaveFile() const
3268 FileName const f = getAutosaveFileName();
3274 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3276 FileName const newauto = getAutosaveFileName();
3278 if (newauto != oldauto && oldauto.exists())
3279 if (!oldauto.moveTo(newauto))
3280 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3284 // Perfect target for a thread...
3285 void Buffer::autoSave() const
3287 if (d->bak_clean || isReadonly()) {
3288 // We don't save now, but we'll try again later
3289 resetAutosaveTimers();
3293 // emit message signal.
3294 message(_("Autosaving current document..."));
3295 AutoSaveBuffer autosave(*this, getAutosaveFileName());
3298 d->bak_clean = true;
3300 resetAutosaveTimers();
3304 string Buffer::bufferFormat() const
3306 string format = params().documentClass().outputFormat();
3307 if (format == "latex") {
3308 if (params().useXetex)
3310 if (params().encoding().package() == Encoding::japanese)
3317 string Buffer::getDefaultOutputFormat() const
3319 if (!params().defaultOutputFormat.empty()
3320 && params().defaultOutputFormat != "default")
3321 return params().defaultOutputFormat;
3322 typedef vector<Format const *> Formats;
3323 Formats formats = exportableFormats(true);
3326 || params().useXetex
3327 || params().encoding().package() == Encoding::japanese) {
3328 if (formats.empty())
3330 // return the first we find
3331 return formats.front()->name();
3333 return lyxrc.default_view_format;
3338 // helper class, to guarantee this gets reset properly
3339 class MarkAsExporting {
3341 MarkAsExporting(Buffer const * buf) : buf_(buf)
3343 LASSERT(buf_, /* */);
3344 buf_->setExportStatus(true);
3348 buf_->setExportStatus(false);
3351 Buffer const * const buf_;
3356 void Buffer::setExportStatus(bool e) const
3358 d->doing_export = e;
3362 bool Buffer::isExporting() const
3364 return d->doing_export;
3368 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3369 bool includeall, string & result_file) const
3371 MarkAsExporting exporting(this);
3372 string backend_format;
3373 OutputParams runparams(¶ms().encoding());
3374 runparams.flavor = OutputParams::LATEX;
3375 runparams.linelen = lyxrc.plaintext_linelen;
3376 runparams.includeall = includeall;
3377 vector<string> backs = backends();
3378 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3379 // Get shortest path to format
3380 Graph::EdgePath path;
3381 for (vector<string>::const_iterator it = backs.begin();
3382 it != backs.end(); ++it) {
3383 Graph::EdgePath p = theConverters().getPath(*it, format);
3384 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3385 backend_format = *it;
3390 if (!put_in_tempdir) {
3391 // Only show this alert if this is an export to a non-temporary
3392 // file (not for previewing).
3393 Alert::error(_("Couldn't export file"), bformat(
3394 _("No information for exporting the format %1$s."),
3395 formats.prettyName(format)));
3399 runparams.flavor = theConverters().getFlavor(path);
3402 backend_format = format;
3403 // FIXME: Don't hardcode format names here, but use a flag
3404 if (backend_format == "pdflatex")
3405 runparams.flavor = OutputParams::PDFLATEX;
3408 string filename = latexName(false);
3409 filename = addName(temppath(), filename);
3410 filename = changeExtension(filename,
3411 formats.extension(backend_format));
3414 updateMacroInstances();
3416 // Plain text backend
3417 if (backend_format == "text") {
3418 runparams.flavor = OutputParams::TEXT;
3419 writePlaintextFile(*this, FileName(filename), runparams);
3422 else if (backend_format == "xhtml") {
3423 runparams.flavor = OutputParams::HTML;
3424 switch (params().html_math_output) {
3425 case BufferParams::MathML:
3426 runparams.math_flavor = OutputParams::MathAsMathML;
3428 case BufferParams::HTML:
3429 runparams.math_flavor = OutputParams::MathAsHTML;
3431 case BufferParams::Images:
3432 runparams.math_flavor = OutputParams::MathAsImages;
3434 case BufferParams::LaTeX:
3435 runparams.math_flavor = OutputParams::MathAsLaTeX;
3439 makeLyXHTMLFile(FileName(filename), runparams);
3440 } else if (backend_format == "lyx")
3441 writeFile(FileName(filename));
3443 else if (isDocBook()) {
3444 runparams.nice = !put_in_tempdir;
3445 makeDocBookFile(FileName(filename), runparams);
3448 else if (backend_format == format) {
3449 runparams.nice = true;
3450 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3452 } else if (!lyxrc.tex_allows_spaces
3453 && contains(filePath(), ' ')) {
3454 Alert::error(_("File name error"),
3455 _("The directory path to the document cannot contain spaces."));
3458 runparams.nice = false;
3459 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3463 string const error_type = (format == "program")
3464 ? "Build" : bufferFormat();
3465 ErrorList & error_list = d->errorLists[error_type];
3466 string const ext = formats.extension(format);
3467 FileName const tmp_result_file(changeExtension(filename, ext));
3468 bool const success = theConverters().convert(this, FileName(filename),
3469 tmp_result_file, FileName(absFileName()), backend_format, format,
3472 // Emit the signal to show the error list or copy it back to the
3473 // cloned Buffer so that it cab be emitted afterwards.
3474 if (format != backend_format) {
3475 if (d->cloned_buffer_) {
3476 d->cloned_buffer_->d->errorLists[error_type] =
3477 d->errorLists[error_type];
3480 // also to the children, in case of master-buffer-view
3481 ListOfBuffers clist = getDescendents();
3482 ListOfBuffers::const_iterator cit = clist.begin();
3483 ListOfBuffers::const_iterator const cen = clist.end();
3484 for (; cit != cen; ++cit) {
3485 if (d->cloned_buffer_) {
3486 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3487 (*cit)->d->errorLists[error_type];
3489 (*cit)->errors(error_type, true);
3493 if (d->cloned_buffer_) {
3494 // Enable reverse dvi or pdf to work by copying back the texrow
3495 // object to the cloned buffer.
3496 // FIXME: There is a possibility of concurrent access to texrow
3497 // here from the main GUI thread that should be securized.
3498 d->cloned_buffer_->d->texrow = d->texrow;
3499 string const error_type = bufferFormat();
3500 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3506 if (put_in_tempdir) {
3507 result_file = tmp_result_file.absFileName();
3511 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3512 // We need to copy referenced files (e. g. included graphics
3513 // if format == "dvi") to the result dir.
3514 vector<ExportedFile> const files =
3515 runparams.exportdata->externalFiles(format);
3516 string const dest = onlyPath(result_file);
3517 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3518 : force_overwrite == ALL_FILES;
3519 CopyStatus status = use_force ? FORCE : SUCCESS;
3521 vector<ExportedFile>::const_iterator it = files.begin();
3522 vector<ExportedFile>::const_iterator const en = files.end();
3523 for (; it != en && status != CANCEL; ++it) {
3524 string const fmt = formats.getFormatFromFile(it->sourceName);
3525 status = copyFile(fmt, it->sourceName,
3526 makeAbsPath(it->exportName, dest),
3527 it->exportName, status == FORCE);
3530 if (status == CANCEL) {
3531 message(_("Document export cancelled."));
3532 } else if (tmp_result_file.exists()) {
3533 // Finally copy the main file
3534 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3535 : force_overwrite != NO_FILES;
3536 if (status == SUCCESS && use_force)
3538 status = copyFile(format, tmp_result_file,
3539 FileName(result_file), result_file,
3541 message(bformat(_("Document exported as %1$s "
3543 formats.prettyName(format),
3544 makeDisplayPath(result_file)));
3546 // This must be a dummy converter like fax (bug 1888)
3547 message(bformat(_("Document exported as %1$s"),
3548 formats.prettyName(format)));
3555 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3556 bool includeall) const
3559 // (1) export with all included children (omit \includeonly)
3560 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3562 // (2) export with included children only
3563 return doExport(format, put_in_tempdir, false, result_file);
3567 bool Buffer::preview(string const & format, bool includeall) const
3569 MarkAsExporting exporting(this);
3571 // (1) export with all included children (omit \includeonly)
3572 if (includeall && !doExport(format, true, true))
3574 // (2) export with included children only
3575 if (!doExport(format, true, false, result_file))
3577 return formats.view(*this, FileName(result_file), format);
3581 bool Buffer::isExportable(string const & format) const
3583 vector<string> backs = backends();
3584 for (vector<string>::const_iterator it = backs.begin();
3585 it != backs.end(); ++it)
3586 if (theConverters().isReachable(*it, format))
3592 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3594 vector<string> const backs = backends();
3595 vector<Format const *> result =
3596 theConverters().getReachable(backs[0], only_viewable, true);
3597 for (vector<string>::const_iterator it = backs.begin() + 1;
3598 it != backs.end(); ++it) {
3599 vector<Format const *> r =
3600 theConverters().getReachable(*it, only_viewable, false);
3601 result.insert(result.end(), r.begin(), r.end());
3607 vector<string> Buffer::backends() const
3610 v.push_back(bufferFormat());
3611 // FIXME: Don't hardcode format names here, but use a flag
3612 if (v.back() == "latex")
3613 v.push_back("pdflatex");
3614 v.push_back("xhtml");
3615 v.push_back("text");
3621 Buffer::ReadStatus Buffer::extractFromVC(FileName const & fn)
3623 bool const found = LyXVC::file_not_found_hook(fn);
3625 return ReadFileNotFound;
3626 if (!fn.isReadableFile())
3632 Buffer::ReadStatus Buffer::loadEmergency(FileName const & fn)
3634 FileName const emergencyFile = getEmergencyFileNameFor(fn);
3635 if (!emergencyFile.exists()
3636 || emergencyFile.lastModified() <= fn.lastModified())
3637 return ReadFileNotFound;
3639 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3640 docstring const text = bformat(_("An emergency save of the document "
3641 "%1$s exists.\n\nRecover emergency save?"), file);
3643 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3644 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3650 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3651 bool const success = (ret_llf == ReadSuccess);
3654 lyxvc().file_found_hook(fn);
3655 str = _("Document was successfully recovered.");
3657 str = _("Document was NOT successfully recovered.");
3658 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3659 makeDisplayPath(emergencyFile.absFileName()));
3661 int const del_emerg =
3662 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3663 _("&Remove"), _("&Keep"));
3664 if (del_emerg == 0) {
3665 emergencyFile.removeFile();
3667 Alert::warning(_("Emergency file deleted"),
3668 _("Do not forget to save your file now!"), true);
3670 return success ? ReadSuccess : ReadEmergencyFailure;
3673 int const del_emerg =
3674 Alert::prompt(_("Delete emergency file?"),
3675 _("Remove emergency file now?"), 1, 1,
3676 _("&Remove"), _("&Keep"));
3678 emergencyFile.removeFile();
3679 return ReadOriginal;
3689 Buffer::ReadStatus Buffer::loadAutosave(FileName const & fn)
3691 // Now check if autosave file is newer.
3692 FileName const autosaveFile = getAutosaveFileNameFor(fn);
3693 if (!autosaveFile.exists()
3694 || autosaveFile.lastModified() <= fn.lastModified())
3695 return ReadFileNotFound;
3697 docstring const file = makeDisplayPath(fn.absFileName(), 20);
3698 docstring const text = bformat(_("The backup of the document %1$s "
3699 "is newer.\n\nLoad the backup instead?"), file);
3700 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3701 _("&Load backup"), _("Load &original"), _("&Cancel"));
3706 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3707 // the file is not saved if we load the autosave file.
3708 if (ret_llf == ReadSuccess) {
3710 lyxvc().file_found_hook(fn);
3713 return ReadAutosaveFailure;
3716 // Here we delete the autosave
3717 autosaveFile.removeFile();
3718 return ReadOriginal;
3726 Buffer::ReadStatus Buffer::loadLyXFile(FileName const & fn)
3728 if (!fn.isReadableFile()) {
3729 ReadStatus const ret_rvc = extractFromVC(fn);
3730 if (ret_rvc != ReadSuccess)
3734 ReadStatus const ret_re = loadEmergency(fn);
3735 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3738 ReadStatus const ret_ra = loadAutosave(fn);
3739 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3742 return loadThisLyXFile(fn);
3746 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3748 return readFile(fn);
3752 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3754 TeXErrors::Errors::const_iterator cit = terr.begin();
3755 TeXErrors::Errors::const_iterator end = terr.end();
3757 for (; cit != end; ++cit) {
3760 int errorRow = cit->error_in_line;
3761 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3767 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3768 } while (found && id_start == id_end && pos_start == pos_end);
3770 errorList.push_back(ErrorItem(cit->error_desc,
3771 cit->error_text, id_start, pos_start, pos_end));
3776 void Buffer::setBuffersForInsets() const
3778 inset().setBuffer(const_cast<Buffer &>(*this));
3782 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3784 // Use the master text class also for child documents
3785 Buffer const * const master = masterBuffer();
3786 DocumentClass const & textclass = master->params().documentClass();
3788 // do this only if we are the top-level Buffer
3790 checkBibInfoCache();
3792 // keep the buffers to be children in this set. If the call from the
3793 // master comes back we can see which of them were actually seen (i.e.
3794 // via an InsetInclude). The remaining ones in the set need still be updated.
3795 static std::set<Buffer const *> bufToUpdate;
3796 if (scope == UpdateMaster) {
3797 // If this is a child document start with the master
3798 if (master != this) {
3799 bufToUpdate.insert(this);
3800 master->updateBuffer(UpdateMaster, utype);
3801 // Do this here in case the master has no gui associated with it. Then,
3802 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3803 if (!master->d->gui_)
3806 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3807 if (bufToUpdate.find(this) == bufToUpdate.end())
3811 // start over the counters in the master
3812 textclass.counters().reset();
3815 // update will be done below for this buffer
3816 bufToUpdate.erase(this);
3818 // update all caches
3819 clearReferenceCache();
3822 Buffer & cbuf = const_cast<Buffer &>(*this);
3824 LASSERT(!text().paragraphs().empty(), /**/);
3827 ParIterator parit = cbuf.par_iterator_begin();
3828 updateBuffer(parit, utype);
3831 // TocBackend update will be done later.
3834 cbuf.tocBackend().update();
3835 if (scope == UpdateMaster)
3836 cbuf.structureChanged();
3840 static depth_type getDepth(DocIterator const & it)
3842 depth_type depth = 0;
3843 for (size_t i = 0 ; i < it.depth() ; ++i)
3844 if (!it[i].inset().inMathed())
3845 depth += it[i].paragraph().getDepth() + 1;
3846 // remove 1 since the outer inset does not count
3850 static depth_type getItemDepth(ParIterator const & it)
3852 Paragraph const & par = *it;
3853 LabelType const labeltype = par.layout().labeltype;
3855 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3858 // this will hold the lowest depth encountered up to now.
3859 depth_type min_depth = getDepth(it);
3860 ParIterator prev_it = it;
3863 --prev_it.top().pit();
3865 // start of nested inset: go to outer par
3867 if (prev_it.empty()) {
3868 // start of document: nothing to do
3873 // We search for the first paragraph with same label
3874 // that is not more deeply nested.
3875 Paragraph & prev_par = *prev_it;
3876 depth_type const prev_depth = getDepth(prev_it);
3877 if (labeltype == prev_par.layout().labeltype) {
3878 if (prev_depth < min_depth)
3879 return prev_par.itemdepth + 1;
3880 if (prev_depth == min_depth)
3881 return prev_par.itemdepth;
3883 min_depth = min(min_depth, prev_depth);
3884 // small optimization: if we are at depth 0, we won't
3885 // find anything else
3886 if (prev_depth == 0)
3892 static bool needEnumCounterReset(ParIterator const & it)
3894 Paragraph const & par = *it;
3895 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3896 depth_type const cur_depth = par.getDepth();
3897 ParIterator prev_it = it;
3898 while (prev_it.pit()) {
3899 --prev_it.top().pit();
3900 Paragraph const & prev_par = *prev_it;
3901 if (prev_par.getDepth() <= cur_depth)
3902 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3904 // start of nested inset: reset
3909 // set the label of a paragraph. This includes the counters.
3910 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3912 BufferParams const & bp = owner_->masterBuffer()->params();
3913 DocumentClass const & textclass = bp.documentClass();
3914 Paragraph & par = it.paragraph();
3915 Layout const & layout = par.layout();
3916 Counters & counters = textclass.counters();
3918 if (par.params().startOfAppendix()) {
3919 // FIXME: only the counter corresponding to toplevel
3920 // sectioning should be reset
3922 counters.appendix(true);
3924 par.params().appendix(counters.appendix());
3926 // Compute the item depth of the paragraph
3927 par.itemdepth = getItemDepth(it);
3929 if (layout.margintype == MARGIN_MANUAL
3930 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3931 if (par.params().labelWidthString().empty())
3932 par.params().labelWidthString(par.expandLabel(layout, bp));
3934 par.params().labelWidthString(docstring());
3937 switch(layout.labeltype) {
3939 if (layout.toclevel <= bp.secnumdepth
3940 && (layout.latextype != LATEX_ENVIRONMENT
3941 || it.text()->isFirstInSequence(it.pit()))) {
3942 counters.step(layout.counter, utype);
3943 par.params().labelString(
3944 par.expandLabel(layout, bp));
3946 par.params().labelString(docstring());
3949 case LABEL_ITEMIZE: {
3950 // At some point of time we should do something more
3951 // clever here, like:
3952 // par.params().labelString(
3953 // bp.user_defined_bullet(par.itemdepth).getText());
3954 // for now, use a simple hardcoded label
3955 docstring itemlabel;
3956 switch (par.itemdepth) {
3958 itemlabel = char_type(0x2022);
3961 itemlabel = char_type(0x2013);
3964 itemlabel = char_type(0x2217);
3967 itemlabel = char_type(0x2219); // or 0x00b7
3970 par.params().labelString(itemlabel);
3974 case LABEL_ENUMERATE: {
3975 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3977 switch (par.itemdepth) {
3986 enumcounter += "iv";
3989 // not a valid enumdepth...
3993 // Maybe we have to reset the enumeration counter.
3994 if (needEnumCounterReset(it))
3995 counters.reset(enumcounter);
3996 counters.step(enumcounter, utype);
3998 string const & lang = par.getParLanguage(bp)->code();
3999 par.params().labelString(counters.theCounter(enumcounter, lang));
4004 case LABEL_SENSITIVE: {
4005 string const & type = counters.current_float();
4006 docstring full_label;
4008 full_label = owner_->B_("Senseless!!! ");
4010 docstring name = owner_->B_(textclass.floats().getType(type).name());
4011 if (counters.hasCounter(from_utf8(type))) {
4012 string const & lang = par.getParLanguage(bp)->code();
4013 counters.step(from_utf8(type), utype);
4014 full_label = bformat(from_ascii("%1$s %2$s:"),
4016 counters.theCounter(from_utf8(type), lang));
4018 full_label = bformat(from_ascii("%1$s #:"), name);
4020 par.params().labelString(full_label);
4024 case LABEL_NO_LABEL:
4025 par.params().labelString(docstring());
4029 case LABEL_TOP_ENVIRONMENT:
4030 case LABEL_CENTERED_TOP_ENVIRONMENT:
4033 par.params().labelString(par.expandLabel(layout, bp));
4039 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4041 LASSERT(parit.pit() == 0, /**/);
4043 // Set the position of the text in the buffer to be able
4044 // to resolve macros in it.
4045 parit.text()->setMacrocontextPosition(parit);
4047 depth_type maxdepth = 0;
4048 pit_type const lastpit = parit.lastpit();
4049 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4050 // reduce depth if necessary
4051 parit->params().depth(min(parit->params().depth(), maxdepth));
4052 maxdepth = parit->getMaxDepthAfter();
4054 if (utype == OutputUpdate) {
4055 // track the active counters
4056 // we have to do this for the master buffer, since the local
4057 // buffer isn't tracking anything.
4058 masterBuffer()->params().documentClass().counters().
4059 setActiveLayout(parit->layout());
4062 // set the counter for this paragraph
4063 d->setLabel(parit, utype);
4066 InsetList::const_iterator iit = parit->insetList().begin();
4067 InsetList::const_iterator end = parit->insetList().end();
4068 for (; iit != end; ++iit) {
4069 parit.pos() = iit->pos;
4070 iit->inset->updateBuffer(parit, utype);
4076 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4077 WordLangTuple & word_lang, docstring_list & suggestions) const
4081 suggestions.clear();
4082 word_lang = WordLangTuple();
4083 // OK, we start from here.
4084 DocIterator const end = doc_iterator_end(this);
4085 for (; from != end; from.forwardPos()) {
4086 // We are only interested in text so remove the math CursorSlice.
4087 while (from.inMathed()) {
4091 // If from is at the end of the document (which is possible
4092 // when leaving the mathed) LyX will crash later.
4096 from.paragraph().spellCheck();
4097 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4098 if (SpellChecker::misspelled(res)) {
4103 // Do not increase progress when from == to, otherwise the word
4104 // count will be wrong.
4114 Buffer::ReadStatus Buffer::reload()
4118 removeAutosaveFile();
4119 // e.g., read-only status could have changed due to version control
4120 d->filename.refresh();
4121 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4123 ReadStatus const status = loadLyXFile(d->filename);
4124 if (status == ReadSuccess) {
4129 message(bformat(_("Document %1$s reloaded."), disp_fn));
4131 message(bformat(_("Could not reload document %1$s."), disp_fn));
4141 // FIXME We could do better here, but it is complicated. What would be
4142 // nice is to offer either (a) to save the child buffer to an appropriate
4143 // location, so that it would "move with the master", or else (b) to update
4144 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4145 // complicated, because the code for this lives in GuiView.
4146 void Buffer::checkChildBuffers()
4148 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4149 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4150 for (; it != en; ++it) {
4151 DocIterator dit = it->second;
4152 Buffer * cbuf = const_cast<Buffer *>(it->first);
4153 if (!cbuf || !theBufferList().isLoaded(cbuf))
4155 Inset * inset = dit.nextInset();
4156 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4157 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4158 docstring const & incfile = inset_inc->getParam("filename");
4159 string oldloc = cbuf->absFileName();
4160 string newloc = makeAbsPath(to_utf8(incfile),
4161 onlyPath(absFileName())).absFileName();
4162 if (oldloc == newloc)
4164 // the location of the child file is incorrect.
4165 Alert::warning(_("Included File Invalid"),
4166 bformat(_("Saving this document to a new location has made the file:\n"
4168 "inaccessible. You will need to update the included filename."),
4169 from_utf8(oldloc)));
4171 inset_inc->setChildBuffer(0);
4173 // invalidate cache of children
4174 d->children_positions.clear();
4175 d->position_to_children.clear();