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 = 408; // gb add script inset
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
150 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
161 /// search for macro in local (buffer) table or in children
162 MacroData const * getBufferMacro(docstring const & name,
163 DocIterator const & pos) const;
165 /// Update macro table starting with position of it \param it in some
167 void updateMacros(DocIterator & it, DocIterator & scope);
169 void setLabel(ParIterator & it, UpdateType utype) const;
171 /** If we have branches that use the file suffix
172 feature, return the file name with suffix appended.
174 support::FileName exportFileName() const;
181 mutable TexRow texrow;
183 /// need to regenerate .tex?
187 mutable bool lyx_clean;
189 /// is autosave needed?
190 mutable bool bak_clean;
192 /// is this an unnamed file (New...)?
198 /// name of the file the buffer is associated with.
201 /** Set to true only when the file is fully loaded.
202 * Used to prevent the premature generation of previews
203 * and by the citation inset.
205 bool file_fully_loaded;
208 mutable TocBackend toc_backend;
211 typedef pair<DocIterator, MacroData> ScopeMacro;
212 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
213 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
214 /// map from the macro name to the position map,
215 /// which maps the macro definition position to the scope and the MacroData.
216 NamePositionScopeMacroMap macros;
217 /// This seem to change the way Buffer::getMacro() works
218 mutable bool macro_lock;
220 /// positions of child buffers in the buffer
221 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
222 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
223 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
224 /// position of children buffers in this buffer
225 BufferPositionMap children_positions;
226 /// map from children inclusion positions to their scope and their buffer
227 PositionScopeBufferMap position_to_children;
229 /// Container for all sort of Buffer dependant errors.
230 map<string, ErrorList> errorLists;
232 /// timestamp and checksum used to test if the file has been externally
233 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
235 unsigned long checksum_;
238 frontend::WorkAreaManager * wa_;
240 frontend::GuiBufferDelegate * gui_;
245 /// A cache for the bibfiles (including bibfiles of loaded child
246 /// documents), needed for appropriate update of natbib labels.
247 mutable support::FileNameList bibfiles_cache_;
249 // FIXME The caching mechanism could be improved. At present, we have a
250 // cache for each Buffer, that caches all the bibliography info for that
251 // Buffer. A more efficient solution would be to have a global cache per
252 // file, and then to construct the Buffer's bibinfo from that.
253 /// A cache for bibliography info
254 mutable BiblioInfo bibinfo_;
255 /// whether the bibinfo cache is valid
256 mutable bool bibinfo_cache_valid_;
257 /// whether the bibfile cache is valid
258 mutable bool bibfile_cache_valid_;
259 /// Cache of timestamps of .bib files
260 map<FileName, time_t> bibfile_status_;
262 mutable RefCache ref_cache_;
264 /// our Text that should be wrapped in an InsetText
267 /// This is here to force the test to be done whenever parent_buffer
269 Buffer const * parent() const {
270 // if parent_buffer is not loaded, then it has been unloaded,
271 // which means that parent_buffer is an invalid pointer. So we
272 // set it to null in that case.
273 // however, the BufferList doesn't know about cloned buffers, so
274 // they will always be regarded as unloaded. in that case, we hope
276 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
278 return parent_buffer;
282 void setParent(Buffer const * pb) {
283 if (parent_buffer == pb)
286 if (!cloned_buffer_ && parent_buffer && pb)
287 LYXERR0("Warning: a buffer should not have two parents!");
289 if (!cloned_buffer_ && parent_buffer) {
290 parent_buffer->invalidateBibfileCache();
291 parent_buffer->invalidateBibinfoCache();
295 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
296 /// This one is useful for preview detached in a thread.
297 Buffer const * cloned_buffer_;
298 /// are we in the process of exporting this buffer?
299 mutable bool doing_export;
302 /// So we can force access via the accessors.
303 mutable Buffer const * parent_buffer;
308 /// Creates the per buffer temporary directory
309 static FileName createBufferTmpDir()
312 // We are in our own directory. Why bother to mangle name?
313 // In fact I wrote this code to circumvent a problematic behaviour
314 // (bug?) of EMX mkstemp().
315 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
316 convert<string>(count++));
318 if (!tmpfl.createDirectory(0777)) {
319 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
320 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
321 from_utf8(tmpfl.absFileName())));
327 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
328 Buffer const * cloned_buffer)
329 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
330 read_only(readonly_), filename(file), file_fully_loaded(false),
331 toc_backend(owner), macro_lock(false), timestamp_(0),
332 checksum_(0), wa_(0), gui_(0), undo_(*owner), bibinfo_cache_valid_(false),
333 bibfile_cache_valid_(false), cloned_buffer_(cloned_buffer),
334 doing_export(false), parent_buffer(0)
336 if (!cloned_buffer_) {
337 temppath = createBufferTmpDir();
338 lyxvc.setBuffer(owner_);
340 wa_ = new frontend::WorkAreaManager;
343 temppath = cloned_buffer_->d->temppath;
344 file_fully_loaded = true;
345 params = cloned_buffer_->d->params;
346 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
347 bibinfo_ = cloned_buffer_->d->bibinfo_;
348 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
349 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
350 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
354 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
355 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
357 LYXERR(Debug::INFO, "Buffer::Buffer()");
359 d->inset = new InsetText(*cloned_buffer->d->inset);
360 d->inset->setBuffer(*this);
361 // FIXME: optimize this loop somewhat, maybe by creating a new
362 // general recursive Inset::setId().
363 DocIterator it = doc_iterator_begin(this);
364 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
365 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
366 it.paragraph().setId(cloned_it.paragraph().id());
368 d->inset = new InsetText(this);
369 d->inset->setAutoBreakRows(true);
370 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
376 LYXERR(Debug::INFO, "Buffer::~Buffer()");
377 // here the buffer should take care that it is
378 // saved properly, before it goes into the void.
380 // GuiView already destroyed
384 // No need to do additional cleanups for internal buffer.
389 // loop over children
390 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
391 Impl::BufferPositionMap::iterator end = d->children_positions.end();
392 for (; it != end; ++it) {
393 Buffer * child = const_cast<Buffer *>(it->first);
394 if (d->cloned_buffer_)
396 // The child buffer might have been closed already.
397 else if (theBufferList().isLoaded(child))
398 theBufferList().releaseChild(this, child);
402 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
403 msg += emergencyWrite();
404 Alert::warning(_("Attempting to close changed document!"), msg);
407 // clear references to children in macro tables
408 d->children_positions.clear();
409 d->position_to_children.clear();
411 if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
412 Alert::warning(_("Could not remove temporary directory"),
413 bformat(_("Could not remove the temporary directory %1$s"),
414 from_utf8(d->temppath.absFileName())));
424 Buffer * Buffer::clone() const
426 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
427 buffer_clone->d->macro_lock = true;
428 buffer_clone->d->children_positions.clear();
429 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
430 // math macro caches need to be rethought and simplified.
431 // I am not sure wether we should handle Buffer cloning here or in BufferList.
432 // Right now BufferList knows nothing about buffer clones.
433 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
434 Impl::BufferPositionMap::iterator end = d->children_positions.end();
435 for (; it != end; ++it) {
436 DocIterator dit = it->second.clone(buffer_clone);
437 dit.setBuffer(buffer_clone);
438 Buffer * child = const_cast<Buffer *>(it->first);
439 Buffer * child_clone = child->clone();
440 Inset * inset = dit.nextInset();
441 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
442 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
443 inset_inc->setChildBuffer(child_clone);
444 child_clone->d->setParent(buffer_clone);
445 buffer_clone->setChild(dit, child_clone);
447 buffer_clone->d->macro_lock = false;
452 bool Buffer::isClone() const
454 return d->cloned_buffer_;
458 void Buffer::changed(bool update_metrics) const
461 d->wa_->redrawAll(update_metrics);
465 frontend::WorkAreaManager & Buffer::workAreaManager() const
467 LASSERT(d->wa_, /**/);
472 Text & Buffer::text() const
474 return d->inset->text();
478 Inset & Buffer::inset() const
484 BufferParams & Buffer::params()
490 BufferParams const & Buffer::params() const
496 ParagraphList & Buffer::paragraphs()
498 return text().paragraphs();
502 ParagraphList const & Buffer::paragraphs() const
504 return text().paragraphs();
508 LyXVC & Buffer::lyxvc()
514 LyXVC const & Buffer::lyxvc() const
520 string const Buffer::temppath() const
522 return d->temppath.absFileName();
526 TexRow & Buffer::texrow()
532 TexRow const & Buffer::texrow() const
538 TocBackend & Buffer::tocBackend() const
540 return d->toc_backend;
544 Undo & Buffer::undo()
550 void Buffer::setChild(DocIterator const & dit, Buffer * child)
552 d->children_positions[child] = dit;
556 string Buffer::latexName(bool const no_path) const
558 FileName latex_name =
559 makeLatexName(d->exportFileName());
560 return no_path ? latex_name.onlyFileName()
561 : latex_name.absFileName();
565 FileName Buffer::Impl::exportFileName() const
567 docstring const branch_suffix =
568 params.branchlist().getFileNameSuffix();
569 if (branch_suffix.empty())
572 string const name = filename.onlyFileNameWithoutExt()
573 + to_utf8(branch_suffix);
574 FileName res(filename.onlyPath().absFileName() + "/" + name);
575 res.changeExtension(filename.extension());
581 string Buffer::logName(LogType * type) const
583 string const filename = latexName(false);
585 if (filename.empty()) {
591 string const path = temppath();
593 FileName const fname(addName(temppath(),
594 onlyFileName(changeExtension(filename,
597 // FIXME: how do we know this is the name of the build log?
598 FileName const bname(
599 addName(path, onlyFileName(
600 changeExtension(filename,
601 formats.extension(bufferFormat()) + ".out"))));
603 // Also consider the master buffer log file
604 FileName masterfname = fname;
606 if (masterBuffer() != this) {
607 string const mlogfile = masterBuffer()->logName(&mtype);
608 masterfname = FileName(mlogfile);
611 // If no Latex log or Build log is newer, show Build log
612 if (bname.exists() &&
613 ((!fname.exists() && !masterfname.exists())
614 || (fname.lastModified() < bname.lastModified()
615 && masterfname.lastModified() < bname.lastModified()))) {
616 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
619 return bname.absFileName();
620 // If we have a newer master file log or only a master log, show this
621 } else if (fname != masterfname
622 && (!fname.exists() && (masterfname.exists()
623 || fname.lastModified() < masterfname.lastModified()))) {
624 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
627 return masterfname.absFileName();
629 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
632 return fname.absFileName();
636 void Buffer::setReadonly(bool const flag)
638 if (d->read_only != flag) {
645 void Buffer::setFileName(FileName const & fname)
648 setReadonly(d->filename.isReadOnly());
654 int Buffer::readHeader(Lexer & lex)
656 int unknown_tokens = 0;
658 int begin_header_line = -1;
660 // Initialize parameters that may be/go lacking in header:
661 params().branchlist().clear();
662 params().preamble.erase();
663 params().options.erase();
664 params().master.erase();
665 params().float_placement.erase();
666 params().paperwidth.erase();
667 params().paperheight.erase();
668 params().leftmargin.erase();
669 params().rightmargin.erase();
670 params().topmargin.erase();
671 params().bottommargin.erase();
672 params().headheight.erase();
673 params().headsep.erase();
674 params().footskip.erase();
675 params().columnsep.erase();
676 params().fontsCJK.erase();
677 params().listings_params.clear();
678 params().clearLayoutModules();
679 params().clearRemovedModules();
680 params().clearIncludedChildren();
681 params().pdfoptions().clear();
682 params().indiceslist().clear();
683 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
684 params().isbackgroundcolor = false;
685 params().fontcolor = lyx::rgbFromHexName("#000000");
686 params().isfontcolor = false;
687 params().notefontcolor = lyx::rgbFromHexName("#cccccc");
688 params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
689 params().html_latex_start.clear();
690 params().html_latex_end.clear();
691 params().html_math_img_scale = 1.0;
692 params().output_sync_macro.erase();
694 for (int i = 0; i < 4; ++i) {
695 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
696 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
699 ErrorList & errorList = d->errorLists["Parse"];
708 if (token == "\\end_header")
712 if (token == "\\begin_header") {
713 begin_header_line = line;
717 LYXERR(Debug::PARSER, "Handling document header token: `"
720 string unknown = params().readToken(lex, token, d->filename.onlyPath());
721 if (!unknown.empty()) {
722 if (unknown[0] != '\\' && token == "\\textclass") {
723 Alert::warning(_("Unknown document class"),
724 bformat(_("Using the default document class, because the "
725 "class %1$s is unknown."), from_utf8(unknown)));
728 docstring const s = bformat(_("Unknown token: "
732 errorList.push_back(ErrorItem(_("Document header error"),
737 if (begin_header_line) {
738 docstring const s = _("\\begin_header is missing");
739 errorList.push_back(ErrorItem(_("Document header error"),
743 params().makeDocumentClass();
745 return unknown_tokens;
750 // changed to be public and have one parameter
751 // Returns true if "\end_document" is not read (Asger)
752 bool Buffer::readDocument(Lexer & lex)
754 ErrorList & errorList = d->errorLists["Parse"];
757 // remove dummy empty par
758 paragraphs().clear();
760 if (!lex.checkFor("\\begin_document")) {
761 docstring const s = _("\\begin_document is missing");
762 errorList.push_back(ErrorItem(_("Document header error"),
768 if (params().outputChanges) {
769 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
770 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
771 LaTeXFeatures::isAvailable("xcolor");
773 if (!dvipost && !xcolorulem) {
774 Alert::warning(_("Changes not shown in LaTeX output"),
775 _("Changes will not be highlighted in LaTeX output, "
776 "because neither dvipost nor xcolor/ulem are installed.\n"
777 "Please install these packages or redefine "
778 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
779 } else if (!xcolorulem) {
780 Alert::warning(_("Changes not shown in LaTeX output"),
781 _("Changes will not be highlighted in LaTeX output "
782 "when using pdflatex, because xcolor and ulem are not installed.\n"
783 "Please install both packages or redefine "
784 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
788 if (!params().master.empty()) {
789 FileName const master_file = makeAbsPath(params().master,
790 onlyPath(absFileName()));
791 if (isLyXFileName(master_file.absFileName())) {
793 checkAndLoadLyXFile(master_file, true);
795 // necessary e.g. after a reload
796 // to re-register the child (bug 5873)
797 // FIXME: clean up updateMacros (here, only
798 // child registering is needed).
799 master->updateMacros();
800 // set master as master buffer, but only
801 // if we are a real child
802 if (master->isChild(this))
804 // if the master is not fully loaded
805 // it is probably just loading this
806 // child. No warning needed then.
807 else if (master->isFullyLoaded())
808 LYXERR0("The master '"
810 << "' assigned to this document ("
812 << ") does not include "
813 "this document. Ignoring the master assignment.");
818 // assure we have a default index
819 params().indiceslist().addDefault(B_("Index"));
822 bool const res = text().read(lex, errorList, d->inset);
826 updateMacroInstances();
831 bool Buffer::readString(string const & s)
833 params().compressed = false;
838 FileName const fn = FileName::tempName("Buffer_readString");
841 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
842 if (ret_plf != ReadSuccess)
845 if (file_format != LYX_FORMAT) {
846 // We need to call lyx2lyx, so write the input to a file
847 ofstream os(fn.toFilesystemEncoding().c_str());
851 return readFile(fn) == ReadSuccess;
854 if (readDocument(lex))
860 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
867 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
868 if (ret_plf != ReadSuccess)
871 if (file_format != LYX_FORMAT) {
873 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
874 if (ret_clf != ReadSuccess)
876 return readFile(tmpFile);
879 // FIXME: InsetInfo needs to know whether the file is under VCS
880 // during the parse process, so this has to be done before.
881 lyxvc().file_found_hook(d->filename);
883 if (readDocument(lex)) {
884 Alert::error(_("Document format failure"),
885 bformat(_("%1$s ended unexpectedly, which means"
886 " that it is probably corrupted."),
887 from_utf8(fn.absFileName())));
888 return ReadDocumentFailure;
891 d->file_fully_loaded = true;
892 d->read_only = !fname.isWritable();
893 params().compressed = fname.isZippedFile();
899 bool Buffer::isFullyLoaded() const
901 return d->file_fully_loaded;
905 void Buffer::setFullyLoaded(bool value)
907 d->file_fully_loaded = value;
911 void Buffer::updatePreviews() const
913 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
914 thePreviews().generateBufferPreviews(*this);
918 void Buffer::removePreviews() const
920 thePreviews().removeLoader(*this);
924 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
925 FileName const & fn, int & file_format) const
927 if(!lex.checkFor("\\lyxformat")) {
928 Alert::error(_("Document format failure"),
929 bformat(_("%1$s is not a readable LyX document."),
930 from_utf8(fn.absFileName())));
931 return ReadNoLyXFormat;
937 // LyX formats 217 and earlier were written as 2.17. This corresponds
938 // to files from LyX versions < 1.1.6.3. We just remove the dot in
939 // these cases. See also: www.lyx.org/trac/changeset/1313.
940 size_t dot = tmp_format.find_first_of(".,");
941 if (dot != string::npos)
942 tmp_format.erase(dot, 1);
944 file_format = convert<int>(tmp_format);
949 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
950 FileName & tmpfile, int from_format)
952 tmpfile = FileName::tempName("Buffer_convertLyXFormat");
953 if(tmpfile.empty()) {
954 Alert::error(_("Conversion failed"),
955 bformat(_("%1$s is from a different"
956 " version of LyX, but a temporary"
957 " file for converting it could"
959 from_utf8(fn.absFileName())));
960 return LyX2LyXNoTempFile;
963 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
964 if (lyx2lyx.empty()) {
965 Alert::error(_("Conversion script not found"),
966 bformat(_("%1$s is from a different"
967 " version of LyX, but the"
968 " conversion script lyx2lyx"
969 " could not be found."),
970 from_utf8(fn.absFileName())));
971 return LyX2LyXNotFound;
975 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
976 ostringstream command;
977 command << os::python()
978 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
979 << " -t " << convert<string>(LYX_FORMAT)
980 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
981 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
982 string const command_str = command.str();
984 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
986 cmd_ret const ret = runCommand(command_str);
987 if (ret.first != 0) {
988 if (from_format < LYX_FORMAT) {
989 Alert::error(_("Conversion script failed"),
990 bformat(_("%1$s is from an older version"
991 " of LyX, but the lyx2lyx script"
992 " failed to convert it."),
993 from_utf8(fn.absFileName())));
994 return LyX2LyXOlderFormat;
996 Alert::error(_("Conversion script failed"),
997 bformat(_("%1$s is from an newer version"
998 " of LyX, but the lyx2lyx script"
999 " failed to convert it."),
1000 from_utf8(fn.absFileName())));
1001 return LyX2LyXNewerFormat;
1008 // Should probably be moved to somewhere else: BufferView? GuiView?
1009 bool Buffer::save() const
1011 // ask if the disk file has been externally modified (use checksum method)
1012 if (fileName().exists() && isExternallyModified(checksum_method)) {
1013 docstring const file = makeDisplayPath(absFileName(), 20);
1014 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1015 "you want to overwrite this file?"), file);
1016 int const ret = Alert::prompt(_("Overwrite modified file?"),
1017 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1022 // We don't need autosaves in the immediate future. (Asger)
1023 resetAutosaveTimers();
1025 FileName backupName;
1026 bool madeBackup = false;
1028 // make a backup if the file already exists
1029 if (lyxrc.make_backup && fileName().exists()) {
1030 backupName = FileName(absFileName() + '~');
1031 if (!lyxrc.backupdir_path.empty()) {
1032 string const mangledName =
1033 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1034 backupName = FileName(addName(lyxrc.backupdir_path,
1037 // do not copy because of #6587
1038 if (fileName().moveTo(backupName)) {
1041 Alert::error(_("Backup failure"),
1042 bformat(_("Cannot create backup file %1$s.\n"
1043 "Please check whether the directory exists and is writeable."),
1044 from_utf8(backupName.absFileName())));
1045 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1049 if (writeFile(d->filename)) {
1053 // Saving failed, so backup is not backup
1055 backupName.moveTo(d->filename);
1061 bool Buffer::writeFile(FileName const & fname) const
1063 if (d->read_only && fname == d->filename)
1066 bool retval = false;
1068 docstring const str = bformat(_("Saving document %1$s..."),
1069 makeDisplayPath(fname.absFileName()));
1072 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1074 if (params().compressed) {
1075 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1076 retval = ofs && write(ofs);
1078 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1079 retval = ofs && write(ofs);
1083 message(str + _(" could not write file!"));
1088 // removeAutosaveFile();
1091 message(str + _(" done."));
1097 docstring Buffer::emergencyWrite()
1099 // No need to save if the buffer has not changed.
1103 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1105 docstring user_message = bformat(
1106 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1108 // We try to save three places:
1109 // 1) Same place as document. Unless it is an unnamed doc.
1111 string s = absFileName();
1114 if (writeFile(FileName(s))) {
1116 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1117 return user_message;
1119 user_message += _(" Save failed! Trying again...\n");
1123 // 2) In HOME directory.
1124 string s = addName(package().home_dir().absFileName(), absFileName());
1126 lyxerr << ' ' << s << endl;
1127 if (writeFile(FileName(s))) {
1129 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1130 return user_message;
1133 user_message += _(" Save failed! Trying yet again...\n");
1135 // 3) In "/tmp" directory.
1136 // MakeAbsPath to prepend the current
1137 // drive letter on OS/2
1138 s = addName(package().temp_dir().absFileName(), absFileName());
1140 lyxerr << ' ' << s << endl;
1141 if (writeFile(FileName(s))) {
1143 user_message += bformat(_(" Saved to %1$s. Phew.\n"), from_utf8(s));
1144 return user_message;
1147 user_message += _(" Save failed! Bummer. Document is lost.");
1150 return user_message;
1154 bool Buffer::write(ostream & ofs) const
1157 // Use the standard "C" locale for file output.
1158 ofs.imbue(locale::classic());
1161 // The top of the file should not be written by params().
1163 // write out a comment in the top of the file
1164 ofs << "#LyX " << lyx_version
1165 << " created this file. For more info see http://www.lyx.org/\n"
1166 << "\\lyxformat " << LYX_FORMAT << "\n"
1167 << "\\begin_document\n";
1169 /// For each author, set 'used' to true if there is a change
1170 /// by this author in the document; otherwise set it to 'false'.
1171 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1172 AuthorList::Authors::const_iterator a_end = params().authors().end();
1173 for (; a_it != a_end; ++a_it)
1174 a_it->setUsed(false);
1176 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1177 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1178 for ( ; it != end; ++it)
1179 it->checkAuthors(params().authors());
1181 // now write out the buffer parameters.
1182 ofs << "\\begin_header\n";
1183 params().writeFile(ofs);
1184 ofs << "\\end_header\n";
1187 ofs << "\n\\begin_body\n";
1189 ofs << "\n\\end_body\n";
1191 // Write marker that shows file is complete
1192 ofs << "\\end_document" << endl;
1194 // Shouldn't really be needed....
1197 // how to check if close went ok?
1198 // Following is an attempt... (BE 20001011)
1200 // good() returns false if any error occured, including some
1201 // formatting error.
1202 // bad() returns true if something bad happened in the buffer,
1203 // which should include file system full errors.
1208 lyxerr << "File was not closed properly." << endl;
1215 bool Buffer::makeLaTeXFile(FileName const & fname,
1216 string const & original_path,
1217 OutputParams const & runparams_in,
1218 bool output_preamble, bool output_body) const
1220 OutputParams runparams = runparams_in;
1221 if (params().useXetex)
1222 runparams.flavor = OutputParams::XETEX;
1224 string const encoding = runparams.encoding->iconvName();
1225 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1228 try { ofs.reset(encoding); }
1229 catch (iconv_codecvt_facet_exception & e) {
1230 lyxerr << "Caught iconv exception: " << e.what() << endl;
1231 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1232 "verify that the support software for your encoding (%1$s) is "
1233 "properly installed"), from_ascii(encoding)));
1236 if (!openFileWrite(ofs, fname))
1239 //TexStream ts(ofs.rdbuf(), &texrow());
1240 ErrorList & errorList = d->errorLists["Export"];
1242 bool failed_export = false;
1245 writeLaTeXSource(ofs, original_path,
1246 runparams, output_preamble, output_body);
1248 catch (EncodingException & e) {
1249 odocstringstream ods;
1250 ods.put(e.failed_char);
1252 oss << "0x" << hex << e.failed_char << dec;
1253 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1254 " (code point %2$s)"),
1255 ods.str(), from_utf8(oss.str()));
1256 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1257 "representable in the chosen encoding.\n"
1258 "Changing the document encoding to utf8 could help."),
1259 e.par_id, e.pos, e.pos + 1));
1260 failed_export = true;
1262 catch (iconv_codecvt_facet_exception & e) {
1263 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1264 _(e.what()), -1, 0, 0));
1265 failed_export = true;
1267 catch (exception const & e) {
1268 errorList.push_back(ErrorItem(_("conversion failed"),
1269 _(e.what()), -1, 0, 0));
1270 failed_export = true;
1273 lyxerr << "Caught some really weird exception..." << endl;
1279 failed_export = true;
1280 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1284 return !failed_export;
1288 void Buffer::writeLaTeXSource(odocstream & os,
1289 string const & original_path,
1290 OutputParams const & runparams_in,
1291 bool const output_preamble, bool const output_body) const
1293 // The child documents, if any, shall be already loaded at this point.
1295 OutputParams runparams = runparams_in;
1297 // Classify the unicode characters appearing in math insets
1298 Encodings::initUnicodeMath(*this);
1300 // validate the buffer.
1301 LYXERR(Debug::LATEX, " Validating buffer...");
1302 LaTeXFeatures features(*this, params(), runparams);
1304 LYXERR(Debug::LATEX, " Buffer validation done.");
1306 // The starting paragraph of the coming rows is the
1307 // first paragraph of the document. (Asger)
1308 if (output_preamble && runparams.nice) {
1309 os << "%% LyX " << lyx_version << " created this file. "
1310 "For more info, see http://www.lyx.org/.\n"
1311 "%% Do not edit unless you really know what "
1313 d->texrow.newline();
1314 d->texrow.newline();
1316 LYXERR(Debug::INFO, "lyx document header finished");
1318 // Don't move this behind the parent_buffer=0 code below,
1319 // because then the macros will not get the right "redefinition"
1320 // flag as they don't see the parent macros which are output before.
1323 // fold macros if possible, still with parent buffer as the
1324 // macros will be put in the prefix anyway.
1325 updateMacroInstances();
1327 // There are a few differences between nice LaTeX and usual files:
1328 // usual is \batchmode and has a
1329 // special input@path to allow the including of figures
1330 // with either \input or \includegraphics (what figinsets do).
1331 // input@path is set when the actual parameter
1332 // original_path is set. This is done for usual tex-file, but not
1333 // for nice-latex-file. (Matthias 250696)
1334 // Note that input@path is only needed for something the user does
1335 // in the preamble, included .tex files or ERT, files included by
1336 // LyX work without it.
1337 if (output_preamble) {
1338 if (!runparams.nice) {
1339 // code for usual, NOT nice-latex-file
1340 os << "\\batchmode\n"; // changed
1341 // from \nonstopmode
1342 d->texrow.newline();
1344 if (!original_path.empty()) {
1346 // We don't know the encoding of inputpath
1347 docstring const inputpath = from_utf8(support::latex_path(original_path));
1348 docstring uncodable_glyphs;
1349 Encoding const * const enc = runparams.encoding;
1351 for (size_t n = 0; n < inputpath.size(); ++n) {
1352 docstring const glyph =
1353 docstring(1, inputpath[n]);
1354 if (enc->latexChar(inputpath[n], true) != glyph) {
1355 LYXERR0("Uncodable character '"
1357 << "' in input path!");
1358 uncodable_glyphs += glyph;
1363 // warn user if we found uncodable glyphs.
1364 if (!uncodable_glyphs.empty()) {
1365 frontend::Alert::warning(_("Uncodable character in file path"),
1366 support::bformat(_("The path of your document\n"
1368 "contains glyphs that are unknown in the\n"
1369 "current document encoding (namely %2$s).\n"
1370 "This will likely result in incomplete output.\n\n"
1371 "Choose an appropriate document encoding (such as utf8)\n"
1372 "or change the file path name."), inputpath, uncodable_glyphs));
1374 os << "\\makeatletter\n"
1375 << "\\def\\input@path{{"
1376 << inputpath << "/}}\n"
1377 << "\\makeatother\n";
1378 d->texrow.newline();
1379 d->texrow.newline();
1380 d->texrow.newline();
1384 // get parent macros (if this buffer has a parent) which will be
1385 // written at the document begin further down.
1386 MacroSet parentMacros;
1387 listParentMacros(parentMacros, features);
1389 runparams.use_polyglossia = features.usePolyglossia();
1390 // Write the preamble
1391 runparams.use_babel = params().writeLaTeX(os, features,
1393 d->filename.onlyPath());
1395 runparams.use_japanese = features.isRequired("japanese");
1401 os << "\\begin{document}\n";
1402 d->texrow.newline();
1404 // output the parent macros
1405 MacroSet::iterator it = parentMacros.begin();
1406 MacroSet::iterator end = parentMacros.end();
1407 for (; it != end; ++it) {
1408 int num_lines = (*it)->write(os, true);
1409 d->texrow.newlines(num_lines);
1412 } // output_preamble
1414 d->texrow.start(paragraphs().begin()->id(), 0);
1416 LYXERR(Debug::INFO, "preamble finished, now the body.");
1418 // if we are doing a real file with body, even if this is the
1419 // child of some other buffer, let's cut the link here.
1420 // This happens for example if only a child document is printed.
1421 Buffer const * save_parent = 0;
1422 if (output_preamble) {
1423 save_parent = d->parent();
1428 latexParagraphs(*this, text(), os, d->texrow, runparams);
1430 // Restore the parenthood if needed
1431 if (output_preamble)
1432 d->setParent(save_parent);
1434 // add this just in case after all the paragraphs
1436 d->texrow.newline();
1438 if (output_preamble) {
1439 os << "\\end{document}\n";
1440 d->texrow.newline();
1441 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1443 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1445 runparams_in.encoding = runparams.encoding;
1447 // Just to be sure. (Asger)
1448 d->texrow.newline();
1450 //for (int i = 0; i<d->texrow.rows(); i++) {
1452 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1453 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1456 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1457 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1461 bool Buffer::isLatex() const
1463 return params().documentClass().outputType() == LATEX;
1467 bool Buffer::isLiterate() const
1469 return params().documentClass().outputType() == LITERATE;
1473 bool Buffer::isDocBook() const
1475 return params().documentClass().outputType() == DOCBOOK;
1479 void Buffer::makeDocBookFile(FileName const & fname,
1480 OutputParams const & runparams,
1481 bool const body_only) const
1483 LYXERR(Debug::LATEX, "makeDocBookFile...");
1486 if (!openFileWrite(ofs, fname))
1489 writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1493 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1497 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1498 OutputParams const & runparams,
1499 bool const only_body) const
1501 LaTeXFeatures features(*this, params(), runparams);
1506 DocumentClass const & tclass = params().documentClass();
1507 string const top_element = tclass.latexname();
1510 if (runparams.flavor == OutputParams::XML)
1511 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1514 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1517 if (! tclass.class_header().empty())
1518 os << from_ascii(tclass.class_header());
1519 else if (runparams.flavor == OutputParams::XML)
1520 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1521 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1523 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1525 docstring preamble = from_utf8(params().preamble);
1526 if (runparams.flavor != OutputParams::XML ) {
1527 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1528 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1529 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1530 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1533 string const name = runparams.nice
1534 ? changeExtension(absFileName(), ".sgml") : fname;
1535 preamble += features.getIncludedFiles(name);
1536 preamble += features.getLyXSGMLEntities();
1538 if (!preamble.empty()) {
1539 os << "\n [ " << preamble << " ]";
1544 string top = top_element;
1546 if (runparams.flavor == OutputParams::XML)
1547 top += params().language->code();
1549 top += params().language->code().substr(0, 2);
1552 if (!params().options.empty()) {
1554 top += params().options;
1557 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1558 << " file was created by LyX " << lyx_version
1559 << "\n See http://www.lyx.org/ for more information -->\n";
1561 params().documentClass().counters().reset();
1565 sgml::openTag(os, top);
1567 docbookParagraphs(text(), *this, os, runparams);
1568 sgml::closeTag(os, top_element);
1572 void Buffer::makeLyXHTMLFile(FileName const & fname,
1573 OutputParams const & runparams,
1574 bool const body_only) const
1576 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1579 if (!openFileWrite(ofs, fname))
1582 writeLyXHTMLSource(ofs, runparams, body_only);
1586 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1590 void Buffer::writeLyXHTMLSource(odocstream & os,
1591 OutputParams const & runparams,
1592 bool const only_body) const
1594 LaTeXFeatures features(*this, params(), runparams);
1596 updateBuffer(UpdateMaster, OutputUpdate);
1597 d->bibinfo_.makeCitationLabels(*this);
1599 updateMacroInstances();
1602 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1603 << "<!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"
1604 // FIXME Language should be set properly.
1605 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1607 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1608 // FIXME Presumably need to set this right
1609 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1611 docstring const & doctitle = features.htmlTitle();
1613 << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1616 os << "\n<!-- Text Class Preamble -->\n"
1617 << features.getTClassHTMLPreamble()
1618 << "\n<!-- Preamble Snippets -->\n"
1619 << from_utf8(features.getPreambleSnippets());
1621 os << "\n<!-- Layout-provided Styles -->\n";
1622 docstring const styleinfo = features.getTClassHTMLStyles();
1623 if (!styleinfo.empty()) {
1624 os << "<style type='text/css'>\n"
1628 os << "</head>\n<body>\n";
1632 params().documentClass().counters().reset();
1633 xhtmlParagraphs(text(), *this, xs, runparams);
1635 os << "</body>\n</html>\n";
1639 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1640 // Other flags: -wall -v0 -x
1641 int Buffer::runChktex()
1645 // get LaTeX-Filename
1646 FileName const path(temppath());
1647 string const name = addName(path.absFileName(), latexName());
1648 string const org_path = filePath();
1650 PathChanger p(path); // path to LaTeX file
1651 message(_("Running chktex..."));
1653 // Generate the LaTeX file if neccessary
1654 OutputParams runparams(¶ms().encoding());
1655 runparams.flavor = OutputParams::LATEX;
1656 runparams.nice = false;
1657 runparams.linelen = lyxrc.plaintext_linelen;
1658 makeLaTeXFile(FileName(name), org_path, runparams);
1661 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1662 int const res = chktex.run(terr); // run chktex
1665 Alert::error(_("chktex failure"),
1666 _("Could not run chktex successfully."));
1667 } else if (res > 0) {
1668 ErrorList & errlist = d->errorLists["ChkTeX"];
1670 bufferErrors(terr, errlist);
1681 void Buffer::validate(LaTeXFeatures & features) const
1683 params().validate(features);
1687 for_each(paragraphs().begin(), paragraphs().end(),
1688 bind(&Paragraph::validate, _1, ref(features)));
1690 if (lyxerr.debugging(Debug::LATEX)) {
1691 features.showStruct();
1696 void Buffer::getLabelList(vector<docstring> & list) const
1698 // If this is a child document, use the master's list instead.
1700 masterBuffer()->getLabelList(list);
1705 Toc & toc = d->toc_backend.toc("label");
1706 TocIterator toc_it = toc.begin();
1707 TocIterator end = toc.end();
1708 for (; toc_it != end; ++toc_it) {
1709 if (toc_it->depth() == 0)
1710 list.push_back(toc_it->str());
1715 void Buffer::updateBibfilesCache(UpdateScope scope) const
1717 // FIXME This is probably unnecssary, given where we call this.
1718 // If this is a child document, use the parent's cache instead.
1719 if (parent() && scope != UpdateChildOnly) {
1720 masterBuffer()->updateBibfilesCache();
1724 d->bibfiles_cache_.clear();
1725 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1726 if (it->lyxCode() == BIBTEX_CODE) {
1727 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1728 support::FileNameList const bibfiles = inset.getBibFiles();
1729 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1732 } else if (it->lyxCode() == INCLUDE_CODE) {
1733 InsetInclude & inset = static_cast<InsetInclude &>(*it);
1734 Buffer const * const incbuf = inset.getChildBuffer();
1737 support::FileNameList const & bibfiles =
1738 incbuf->getBibfilesCache(UpdateChildOnly);
1739 if (!bibfiles.empty()) {
1740 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1746 d->bibfile_cache_valid_ = true;
1747 d->bibinfo_cache_valid_ = false;
1751 void Buffer::invalidateBibinfoCache() const
1753 d->bibinfo_cache_valid_ = false;
1754 // also invalidate the cache for the parent buffer
1755 Buffer const * const pbuf = d->parent();
1757 pbuf->invalidateBibinfoCache();
1761 void Buffer::invalidateBibfileCache() const
1763 d->bibfile_cache_valid_ = false;
1764 d->bibinfo_cache_valid_ = false;
1765 // also invalidate the cache for the parent buffer
1766 Buffer const * const pbuf = d->parent();
1768 pbuf->invalidateBibfileCache();
1772 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1774 // FIXME This is probably unnecessary, given where we call this.
1775 // If this is a child document, use the master's cache instead.
1776 Buffer const * const pbuf = masterBuffer();
1777 if (pbuf != this && scope != UpdateChildOnly)
1778 return pbuf->getBibfilesCache();
1780 if (!d->bibfile_cache_valid_)
1781 this->updateBibfilesCache(scope);
1783 return d->bibfiles_cache_;
1787 BiblioInfo const & Buffer::masterBibInfo() const
1789 Buffer const * const tmp = masterBuffer();
1791 return tmp->masterBibInfo();
1796 void Buffer::checkBibInfoCache() const
1798 // use the master's cache
1799 Buffer const * const tmp = masterBuffer();
1801 tmp->checkBibInfoCache();
1805 // this will also reload the cache if it is invalid
1806 support::FileNameList const & bibfiles_cache = getBibfilesCache();
1808 // compare the cached timestamps with the actual ones.
1809 support::FileNameList::const_iterator ei = bibfiles_cache.begin();
1810 support::FileNameList::const_iterator en = bibfiles_cache.end();
1811 for (; ei != en; ++ ei) {
1812 time_t lastw = ei->lastModified();
1813 time_t prevw = d->bibfile_status_[*ei];
1814 if (lastw != prevw) {
1815 d->bibinfo_cache_valid_ = false;
1816 d->bibfile_status_[*ei] = lastw;
1820 // if not valid, then reload the info
1821 if (!d->bibinfo_cache_valid_) {
1822 d->bibinfo_.clear();
1823 fillWithBibKeys(d->bibinfo_);
1824 d->bibinfo_cache_valid_ = true;
1829 void Buffer::fillWithBibKeys(BiblioInfo & keys) const
1831 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1832 it->fillWithBibKeys(keys, it);
1836 bool Buffer::isDepClean(string const & name) const
1838 DepClean::const_iterator const it = d->dep_clean.find(name);
1839 if (it == d->dep_clean.end())
1845 void Buffer::markDepClean(string const & name)
1847 d->dep_clean[name] = true;
1851 bool Buffer::isExportableFormat(string const & format) const
1853 typedef vector<Format const *> Formats;
1855 formats = exportableFormats(true);
1856 Formats::const_iterator fit = formats.begin();
1857 Formats::const_iterator end = formats.end();
1858 for (; fit != end ; ++fit) {
1859 if ((*fit)->name() == format)
1866 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1869 // FIXME? if there is an Buffer LFUN that can be dispatched even
1870 // if internal, put a switch '(cmd.action)' here.
1876 switch (cmd.action()) {
1878 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1879 flag.setOnOff(isReadonly());
1882 // FIXME: There is need for a command-line import.
1883 //case LFUN_BUFFER_IMPORT:
1885 case LFUN_BUFFER_AUTO_SAVE:
1888 case LFUN_BUFFER_EXPORT_CUSTOM:
1889 // FIXME: Nothing to check here?
1892 case LFUN_BUFFER_EXPORT: {
1893 docstring const arg = cmd.argument();
1894 enable = arg == "custom" || isExportable(to_utf8(arg));
1896 flag.message(bformat(
1897 _("Don't know how to export to format: %1$s"), arg));
1901 case LFUN_BUFFER_CHKTEX:
1902 enable = isLatex() && !lyxrc.chktex_command.empty();
1905 case LFUN_BUILD_PROGRAM:
1906 enable = isExportable("program");
1909 case LFUN_BRANCH_ACTIVATE:
1910 case LFUN_BRANCH_DEACTIVATE: {
1911 BranchList const & branchList = params().branchlist();
1912 docstring const branchName = cmd.argument();
1913 enable = !branchName.empty() && branchList.find(branchName);
1917 case LFUN_BRANCH_ADD:
1918 case LFUN_BRANCHES_RENAME:
1919 case LFUN_BUFFER_PRINT:
1920 // if no Buffer is present, then of course we won't be called!
1923 case LFUN_BUFFER_LANGUAGE:
1924 enable = !isReadonly();
1930 flag.setEnabled(enable);
1935 void Buffer::dispatch(string const & command, DispatchResult & result)
1937 return dispatch(lyxaction.lookupFunc(command), result);
1941 // NOTE We can end up here even if we have no GUI, because we are called
1942 // by LyX::exec to handled command-line requests. So we may need to check
1943 // whether we have a GUI or not. The boolean use_gui holds this information.
1944 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1947 // FIXME? if there is an Buffer LFUN that can be dispatched even
1948 // if internal, put a switch '(cmd.action())' here.
1949 dr.dispatched(false);
1952 string const argument = to_utf8(func.argument());
1953 // We'll set this back to false if need be.
1954 bool dispatched = true;
1955 undo().beginUndoGroup();
1957 switch (func.action()) {
1958 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1959 if (lyxvc().inUse())
1960 lyxvc().toggleReadOnly();
1962 setReadonly(!isReadonly());
1965 case LFUN_BUFFER_EXPORT: {
1966 bool success = doExport(argument, false, false);
1967 dr.setError(!success);
1969 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1974 case LFUN_BUILD_PROGRAM:
1975 doExport("program", true, false);
1978 case LFUN_BUFFER_CHKTEX:
1982 case LFUN_BUFFER_EXPORT_CUSTOM: {
1984 string command = split(argument, format_name, ' ');
1985 Format const * format = formats.getFormat(format_name);
1987 lyxerr << "Format \"" << format_name
1988 << "\" not recognized!"
1993 // The name of the file created by the conversion process
1996 // Output to filename
1997 if (format->name() == "lyx") {
1998 string const latexname = latexName(false);
1999 filename = changeExtension(latexname,
2000 format->extension());
2001 filename = addName(temppath(), filename);
2003 if (!writeFile(FileName(filename)))
2007 doExport(format_name, true, false, filename);
2010 // Substitute $$FName for filename
2011 if (!contains(command, "$$FName"))
2012 command = "( " + command + " ) < $$FName";
2013 command = subst(command, "$$FName", filename);
2015 // Execute the command in the background
2017 call.startscript(Systemcall::DontWait, command);
2021 // FIXME: There is need for a command-line import.
2023 case LFUN_BUFFER_IMPORT:
2028 case LFUN_BUFFER_AUTO_SAVE:
2030 resetAutosaveTimers();
2033 case LFUN_BRANCH_ADD: {
2034 docstring branch_name = func.argument();
2035 if (branch_name.empty()) {
2039 BranchList & branch_list = params().branchlist();
2040 vector<docstring> const branches =
2041 getVectorFromString(branch_name, branch_list.separator());
2043 for (vector<docstring>::const_iterator it = branches.begin();
2044 it != branches.end(); ++it) {
2046 Branch * branch = branch_list.find(branch_name);
2048 LYXERR0("Branch " << branch_name << " already exists.");
2052 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2054 branch_list.add(branch_name);
2055 branch = branch_list.find(branch_name);
2056 string const x11hexname = X11hexname(branch->color());
2057 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2058 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2060 dr.screenUpdate(Update::Force);
2068 case LFUN_BRANCH_ACTIVATE:
2069 case LFUN_BRANCH_DEACTIVATE: {
2070 BranchList & branchList = params().branchlist();
2071 docstring const branchName = func.argument();
2072 // the case without a branch name is handled elsewhere
2073 if (branchName.empty()) {
2077 Branch * branch = branchList.find(branchName);
2079 LYXERR0("Branch " << branchName << " does not exist.");
2081 docstring const msg =
2082 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2085 branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2087 dr.screenUpdate(Update::Force);
2088 dr.forceBufferUpdate();
2093 case LFUN_BRANCHES_RENAME: {
2094 if (func.argument().empty())
2097 docstring const oldname = from_utf8(func.getArg(0));
2098 docstring const newname = from_utf8(func.getArg(1));
2099 InsetIterator it = inset_iterator_begin(inset());
2100 InsetIterator const end = inset_iterator_end(inset());
2101 bool success = false;
2102 for (; it != end; ++it) {
2103 if (it->lyxCode() == BRANCH_CODE) {
2104 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2105 if (ins.branch() == oldname) {
2106 undo().recordUndo(it);
2107 ins.rename(newname);
2112 if (it->lyxCode() == INCLUDE_CODE) {
2113 // get buffer of external file
2114 InsetInclude const & ins =
2115 static_cast<InsetInclude const &>(*it);
2116 Buffer * child = ins.getChildBuffer();
2119 child->dispatch(func, dr);
2124 dr.screenUpdate(Update::Force);
2125 dr.forceBufferUpdate();
2130 case LFUN_BUFFER_PRINT: {
2131 // we'll assume there's a problem until we succeed
2133 string target = func.getArg(0);
2134 string target_name = func.getArg(1);
2135 string command = func.getArg(2);
2138 || target_name.empty()
2139 || command.empty()) {
2140 LYXERR0("Unable to parse " << func.argument());
2141 docstring const msg =
2142 bformat(_("Unable to parse \"%1$s\""), func.argument());
2146 if (target != "printer" && target != "file") {
2147 LYXERR0("Unrecognized target \"" << target << '"');
2148 docstring const msg =
2149 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2154 bool const update_unincluded =
2155 params().maintain_unincluded_children
2156 && !params().getIncludedChildren().empty();
2157 if (!doExport("dvi", true, update_unincluded)) {
2158 showPrintError(absFileName());
2159 dr.setMessage(_("Error exporting to DVI."));
2163 // Push directory path.
2164 string const path = temppath();
2165 // Prevent the compiler from optimizing away p
2169 // there are three cases here:
2170 // 1. we print to a file
2171 // 2. we print directly to a printer
2172 // 3. we print using a spool command (print to file first)
2175 string const dviname = changeExtension(latexName(true), "dvi");
2177 if (target == "printer") {
2178 if (!lyxrc.print_spool_command.empty()) {
2179 // case 3: print using a spool
2180 string const psname = changeExtension(dviname,".ps");
2181 command += ' ' + lyxrc.print_to_file
2184 + quoteName(dviname);
2186 string command2 = lyxrc.print_spool_command + ' ';
2187 if (target_name != "default") {
2188 command2 += lyxrc.print_spool_printerprefix
2192 command2 += quoteName(psname);
2194 // If successful, then spool command
2195 res = one.startscript(Systemcall::Wait, command);
2198 // If there's no GUI, we have to wait on this command. Otherwise,
2199 // LyX deletes the temporary directory, and with it the spooled
2200 // file, before it can be printed!!
2201 Systemcall::Starttype stype = use_gui ?
2202 Systemcall::DontWait : Systemcall::Wait;
2203 res = one.startscript(stype, command2);
2206 // case 2: print directly to a printer
2207 if (target_name != "default")
2208 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2210 Systemcall::Starttype stype = use_gui ?
2211 Systemcall::DontWait : Systemcall::Wait;
2212 res = one.startscript(stype, command + quoteName(dviname));
2216 // case 1: print to a file
2217 FileName const filename(makeAbsPath(target_name, filePath()));
2218 FileName const dvifile(makeAbsPath(dviname, path));
2219 if (filename.exists()) {
2220 docstring text = bformat(
2221 _("The file %1$s already exists.\n\n"
2222 "Do you want to overwrite that file?"),
2223 makeDisplayPath(filename.absFileName()));
2224 if (Alert::prompt(_("Overwrite file?"),
2225 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2228 command += ' ' + lyxrc.print_to_file
2229 + quoteName(filename.toFilesystemEncoding())
2231 + quoteName(dvifile.toFilesystemEncoding());
2233 Systemcall::Starttype stype = use_gui ?
2234 Systemcall::DontWait : Systemcall::Wait;
2235 res = one.startscript(stype, command);
2241 dr.setMessage(_("Error running external commands."));
2242 showPrintError(absFileName());
2247 case LFUN_BUFFER_LANGUAGE: {
2248 Language const * oldL = params().language;
2249 Language const * newL = languages.getLanguage(argument);
2250 if (!newL || oldL == newL)
2252 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2253 changeLanguage(oldL, newL);
2254 dr.forceBufferUpdate();
2263 dr.dispatched(dispatched);
2264 undo().endUndoGroup();
2268 void Buffer::changeLanguage(Language const * from, Language const * to)
2270 LASSERT(from, /**/);
2273 for_each(par_iterator_begin(),
2275 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2279 bool Buffer::isMultiLingual() const
2281 ParConstIterator end = par_iterator_end();
2282 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2283 if (it->isMultiLingual(params()))
2290 std::set<Language const *> Buffer::getLanguages() const
2292 std::set<Language const *> languages;
2293 getLanguages(languages);
2298 void Buffer::getLanguages(std::set<Language const *> & languages) const
2300 ParConstIterator end = par_iterator_end();
2301 // add the buffer language, even if it's not actively used
2302 languages.insert(language());
2303 // iterate over the paragraphs
2304 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2305 it->getLanguages(languages);
2307 ListOfBuffers clist = getDescendents();
2308 ListOfBuffers::const_iterator cit = clist.begin();
2309 ListOfBuffers::const_iterator const cen = clist.end();
2310 for (; cit != cen; ++cit)
2311 (*cit)->getLanguages(languages);
2315 DocIterator Buffer::getParFromID(int const id) const
2317 Buffer * buf = const_cast<Buffer *>(this);
2319 // John says this is called with id == -1 from undo
2320 lyxerr << "getParFromID(), id: " << id << endl;
2321 return doc_iterator_end(buf);
2324 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2325 if (it.paragraph().id() == id)
2328 return doc_iterator_end(buf);
2332 bool Buffer::hasParWithID(int const id) const
2334 return !getParFromID(id).atEnd();
2338 ParIterator Buffer::par_iterator_begin()
2340 return ParIterator(doc_iterator_begin(this));
2344 ParIterator Buffer::par_iterator_end()
2346 return ParIterator(doc_iterator_end(this));
2350 ParConstIterator Buffer::par_iterator_begin() const
2352 return ParConstIterator(doc_iterator_begin(this));
2356 ParConstIterator Buffer::par_iterator_end() const
2358 return ParConstIterator(doc_iterator_end(this));
2362 Language const * Buffer::language() const
2364 return params().language;
2368 docstring const Buffer::B_(string const & l10n) const
2370 return params().B_(l10n);
2374 bool Buffer::isClean() const
2376 return d->lyx_clean;
2380 bool Buffer::isExternallyModified(CheckMethod method) const
2382 LASSERT(d->filename.exists(), /**/);
2383 // if method == timestamp, check timestamp before checksum
2384 return (method == checksum_method
2385 || d->timestamp_ != d->filename.lastModified())
2386 && d->checksum_ != d->filename.checksum();
2390 void Buffer::saveCheckSum() const
2392 FileName const & file = d->filename;
2393 if (file.exists()) {
2394 d->timestamp_ = file.lastModified();
2395 d->checksum_ = file.checksum();
2397 // in the case of save to a new file.
2404 void Buffer::markClean() const
2406 if (!d->lyx_clean) {
2407 d->lyx_clean = true;
2410 // if the .lyx file has been saved, we don't need an
2412 d->bak_clean = true;
2413 d->undo_.markDirty();
2417 void Buffer::setUnnamed(bool flag)
2423 bool Buffer::isUnnamed() const
2430 /// Don't check unnamed, here: isInternal() is used in
2431 /// newBuffer(), where the unnamed flag has not been set by anyone
2432 /// yet. Also, for an internal buffer, there should be no need for
2433 /// retrieving fileName() nor for checking if it is unnamed or not.
2434 bool Buffer::isInternal() const
2436 return fileName().extension() == "internal";
2440 void Buffer::markDirty()
2443 d->lyx_clean = false;
2446 d->bak_clean = false;
2448 DepClean::iterator it = d->dep_clean.begin();
2449 DepClean::const_iterator const end = d->dep_clean.end();
2451 for (; it != end; ++it)
2456 FileName Buffer::fileName() const
2462 string Buffer::absFileName() const
2464 return d->filename.absFileName();
2468 string Buffer::filePath() const
2470 return d->filename.onlyPath().absFileName() + "/";
2474 bool Buffer::isReadonly() const
2476 return d->read_only;
2480 void Buffer::setParent(Buffer const * buffer)
2482 // Avoids recursive include.
2483 d->setParent(buffer == this ? 0 : buffer);
2488 Buffer const * Buffer::parent() const
2494 ListOfBuffers Buffer::allRelatives() const
2496 ListOfBuffers lb = masterBuffer()->getDescendents();
2497 lb.push_front(const_cast<Buffer *>(this));
2502 Buffer const * Buffer::masterBuffer() const
2504 // FIXME Should be make sure we are not in some kind
2505 // of recursive include? A -> B -> A will crash this.
2506 Buffer const * const pbuf = d->parent();
2510 return pbuf->masterBuffer();
2514 bool Buffer::isChild(Buffer * child) const
2516 return d->children_positions.find(child) != d->children_positions.end();
2520 DocIterator Buffer::firstChildPosition(Buffer const * child)
2522 Impl::BufferPositionMap::iterator it;
2523 it = d->children_positions.find(child);
2524 if (it == d->children_positions.end())
2525 return DocIterator(this);
2530 bool Buffer::hasChildren() const
2532 return !d->children_positions.empty();
2536 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2538 // loop over children
2539 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2540 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2541 for (; it != end; ++it) {
2542 Buffer * child = const_cast<Buffer *>(it->first);
2544 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2545 if (bit != clist.end())
2547 clist.push_back(child);
2549 // there might be grandchildren
2550 child->collectChildren(clist, true);
2555 ListOfBuffers Buffer::getChildren() const
2558 collectChildren(v, false);
2563 ListOfBuffers Buffer::getDescendents() const
2566 collectChildren(v, true);
2571 template<typename M>
2572 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2577 typename M::const_iterator it = m.lower_bound(x);
2578 if (it == m.begin())
2586 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2587 DocIterator const & pos) const
2589 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2591 // if paragraphs have no macro context set, pos will be empty
2595 // we haven't found anything yet
2596 DocIterator bestPos = owner_->par_iterator_begin();
2597 MacroData const * bestData = 0;
2599 // find macro definitions for name
2600 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2601 if (nameIt != macros.end()) {
2602 // find last definition in front of pos or at pos itself
2603 PositionScopeMacroMap::const_iterator it
2604 = greatest_below(nameIt->second, pos);
2605 if (it != nameIt->second.end()) {
2607 // scope ends behind pos?
2608 if (pos < it->second.first) {
2609 // Looks good, remember this. If there
2610 // is no external macro behind this,
2611 // we found the right one already.
2612 bestPos = it->first;
2613 bestData = &it->second.second;
2617 // try previous macro if there is one
2618 if (it == nameIt->second.begin())
2625 // find macros in included files
2626 PositionScopeBufferMap::const_iterator it
2627 = greatest_below(position_to_children, pos);
2628 if (it == position_to_children.end())
2629 // no children before
2633 // do we know something better (i.e. later) already?
2634 if (it->first < bestPos )
2637 // scope ends behind pos?
2638 if (pos < it->second.first) {
2639 // look for macro in external file
2641 MacroData const * data
2642 = it->second.second->getMacro(name, false);
2645 bestPos = it->first;
2651 // try previous file if there is one
2652 if (it == position_to_children.begin())
2657 // return the best macro we have found
2662 MacroData const * Buffer::getMacro(docstring const & name,
2663 DocIterator const & pos, bool global) const
2668 // query buffer macros
2669 MacroData const * data = d->getBufferMacro(name, pos);
2673 // If there is a master buffer, query that
2674 Buffer const * const pbuf = d->parent();
2676 d->macro_lock = true;
2677 MacroData const * macro = pbuf->getMacro(
2678 name, *this, false);
2679 d->macro_lock = false;
2685 data = MacroTable::globalMacros().get(name);
2694 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2696 // set scope end behind the last paragraph
2697 DocIterator scope = par_iterator_begin();
2698 scope.pit() = scope.lastpit() + 1;
2700 return getMacro(name, scope, global);
2704 MacroData const * Buffer::getMacro(docstring const & name,
2705 Buffer const & child, bool global) const
2707 // look where the child buffer is included first
2708 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2709 if (it == d->children_positions.end())
2712 // check for macros at the inclusion position
2713 return getMacro(name, it->second, global);
2717 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2719 pit_type const lastpit = it.lastpit();
2721 // look for macros in each paragraph
2722 while (it.pit() <= lastpit) {
2723 Paragraph & par = it.paragraph();
2725 // iterate over the insets of the current paragraph
2726 InsetList const & insets = par.insetList();
2727 InsetList::const_iterator iit = insets.begin();
2728 InsetList::const_iterator end = insets.end();
2729 for (; iit != end; ++iit) {
2730 it.pos() = iit->pos;
2732 // is it a nested text inset?
2733 if (iit->inset->asInsetText()) {
2734 // Inset needs its own scope?
2735 InsetText const * itext = iit->inset->asInsetText();
2736 bool newScope = itext->isMacroScope();
2738 // scope which ends just behind the inset
2739 DocIterator insetScope = it;
2742 // collect macros in inset
2743 it.push_back(CursorSlice(*iit->inset));
2744 updateMacros(it, newScope ? insetScope : scope);
2749 if (iit->inset->asInsetTabular()) {
2750 CursorSlice slice(*iit->inset);
2751 size_t const numcells = slice.nargs();
2752 for (; slice.idx() < numcells; slice.forwardIdx()) {
2753 it.push_back(slice);
2754 updateMacros(it, scope);
2760 // is it an external file?
2761 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2762 // get buffer of external file
2763 InsetInclude const & inset =
2764 static_cast<InsetInclude const &>(*iit->inset);
2766 Buffer * child = inset.getChildBuffer();
2771 // register its position, but only when it is
2772 // included first in the buffer
2773 if (children_positions.find(child) ==
2774 children_positions.end())
2775 children_positions[child] = it;
2777 // register child with its scope
2778 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2782 InsetMath * im = iit->inset->asInsetMath();
2783 if (doing_export && im) {
2784 InsetMathHull * hull = im->asHullInset();
2786 hull->recordLocation(it);
2789 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2793 MathMacroTemplate & macroTemplate =
2794 *iit->inset->asInsetMath()->asMacroTemplate();
2795 MacroContext mc(owner_, it);
2796 macroTemplate.updateToContext(mc);
2799 bool valid = macroTemplate.validMacro();
2800 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2801 // then the BufferView's cursor will be invalid in
2802 // some cases which leads to crashes.
2807 // FIXME (Abdel), I don't understandt why we pass 'it' here
2808 // instead of 'macroTemplate' defined above... is this correct?
2809 macros[macroTemplate.name()][it] =
2810 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2820 void Buffer::updateMacros() const
2825 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2827 // start with empty table
2829 d->children_positions.clear();
2830 d->position_to_children.clear();
2832 // Iterate over buffer, starting with first paragraph
2833 // The scope must be bigger than any lookup DocIterator
2834 // later. For the global lookup, lastpit+1 is used, hence
2835 // we use lastpit+2 here.
2836 DocIterator it = par_iterator_begin();
2837 DocIterator outerScope = it;
2838 outerScope.pit() = outerScope.lastpit() + 2;
2839 d->updateMacros(it, outerScope);
2843 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2845 InsetIterator it = inset_iterator_begin(inset());
2846 InsetIterator const end = inset_iterator_end(inset());
2847 for (; it != end; ++it) {
2848 if (it->lyxCode() == BRANCH_CODE) {
2849 InsetBranch & br = static_cast<InsetBranch &>(*it);
2850 docstring const name = br.branch();
2851 if (!from_master && !params().branchlist().find(name))
2852 result.push_back(name);
2853 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2854 result.push_back(name);
2857 if (it->lyxCode() == INCLUDE_CODE) {
2858 // get buffer of external file
2859 InsetInclude const & ins =
2860 static_cast<InsetInclude const &>(*it);
2861 Buffer * child = ins.getChildBuffer();
2864 child->getUsedBranches(result, true);
2867 // remove duplicates
2872 void Buffer::updateMacroInstances() const
2874 LYXERR(Debug::MACROS, "updateMacroInstances for "
2875 << d->filename.onlyFileName());
2876 DocIterator it = doc_iterator_begin(this);
2878 DocIterator const end = doc_iterator_end(this);
2879 for (; it != end; it.forwardInset()) {
2880 // look for MathData cells in InsetMathNest insets
2881 InsetMath * minset = it.nextInset()->asInsetMath();
2885 // update macro in all cells of the InsetMathNest
2886 DocIterator::idx_type n = minset->nargs();
2887 MacroContext mc = MacroContext(this, it);
2888 for (DocIterator::idx_type i = 0; i < n; ++i) {
2889 MathData & data = minset->cell(i);
2890 data.updateMacros(0, mc);
2896 void Buffer::listMacroNames(MacroNameSet & macros) const
2901 d->macro_lock = true;
2903 // loop over macro names
2904 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2905 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2906 for (; nameIt != nameEnd; ++nameIt)
2907 macros.insert(nameIt->first);
2909 // loop over children
2910 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2911 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2912 for (; it != end; ++it)
2913 it->first->listMacroNames(macros);
2916 Buffer const * const pbuf = d->parent();
2918 pbuf->listMacroNames(macros);
2920 d->macro_lock = false;
2924 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2926 Buffer const * const pbuf = d->parent();
2931 pbuf->listMacroNames(names);
2934 MacroNameSet::iterator it = names.begin();
2935 MacroNameSet::iterator end = names.end();
2936 for (; it != end; ++it) {
2938 MacroData const * data =
2939 pbuf->getMacro(*it, *this, false);
2941 macros.insert(data);
2943 // we cannot access the original MathMacroTemplate anymore
2944 // here to calls validate method. So we do its work here manually.
2945 // FIXME: somehow make the template accessible here.
2946 if (data->optionals() > 0)
2947 features.require("xargs");
2953 Buffer::References & Buffer::references(docstring const & label)
2956 return const_cast<Buffer *>(masterBuffer())->references(label);
2958 RefCache::iterator it = d->ref_cache_.find(label);
2959 if (it != d->ref_cache_.end())
2960 return it->second.second;
2962 static InsetLabel const * dummy_il = 0;
2963 static References const dummy_refs;
2964 it = d->ref_cache_.insert(
2965 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2966 return it->second.second;
2970 Buffer::References const & Buffer::references(docstring const & label) const
2972 return const_cast<Buffer *>(this)->references(label);
2976 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2978 masterBuffer()->d->ref_cache_[label].first = il;
2982 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2984 return masterBuffer()->d->ref_cache_[label].first;
2988 void Buffer::clearReferenceCache() const
2991 d->ref_cache_.clear();
2995 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2998 //FIXME: This does not work for child documents yet.
2999 LASSERT(code == CITE_CODE, /**/);
3000 // Check if the label 'from' appears more than once
3001 vector<docstring> labels;
3003 checkBibInfoCache();
3004 BiblioInfo const & keys = masterBibInfo();
3005 BiblioInfo::const_iterator bit = keys.begin();
3006 BiblioInfo::const_iterator bend = keys.end();
3008 for (; bit != bend; ++bit)
3010 labels.push_back(bit->first);
3013 if (count(labels.begin(), labels.end(), from) > 1)
3016 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3017 if (it->lyxCode() == code) {
3018 InsetCommand * inset = it->asInsetCommand();
3021 docstring const oldValue = inset->getParam(paramName);
3022 if (oldValue == from)
3023 inset->setParam(paramName, to);
3029 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
3030 pit_type par_end, bool full_source) const
3032 OutputParams runparams(¶ms().encoding());
3033 runparams.nice = true;
3034 runparams.flavor = params().useXetex ?
3035 OutputParams::XETEX : OutputParams::LATEX;
3036 runparams.linelen = lyxrc.plaintext_linelen;
3037 // No side effect of file copying and image conversion
3038 runparams.dryrun = true;
3041 os << "% " << _("Preview source code") << "\n\n";
3043 d->texrow.newline();
3044 d->texrow.newline();
3046 writeDocBookSource(os, absFileName(), runparams, false);
3048 // latex or literate
3049 writeLaTeXSource(os, string(), runparams, true, true);
3051 runparams.par_begin = par_begin;
3052 runparams.par_end = par_end;
3053 if (par_begin + 1 == par_end) {
3055 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3059 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3060 convert<docstring>(par_begin),
3061 convert<docstring>(par_end - 1))
3068 // output paragraphs
3070 docbookParagraphs(text(), *this, os, runparams);
3072 // latex or literate
3073 latexParagraphs(*this, text(), os, texrow, runparams);
3078 ErrorList & Buffer::errorList(string const & type) const
3080 static ErrorList emptyErrorList;
3081 map<string, ErrorList>::iterator it = d->errorLists.find(type);
3082 if (it == d->errorLists.end())
3083 return emptyErrorList;
3089 void Buffer::updateTocItem(std::string const & type,
3090 DocIterator const & dit) const
3093 d->gui_->updateTocItem(type, dit);
3097 void Buffer::structureChanged() const
3100 d->gui_->structureChanged();
3104 void Buffer::errors(string const & err, bool from_master) const
3107 d->gui_->errors(err, from_master);
3111 void Buffer::message(docstring const & msg) const
3114 d->gui_->message(msg);
3118 void Buffer::setBusy(bool on) const
3121 d->gui_->setBusy(on);
3125 void Buffer::updateTitles() const
3128 d->wa_->updateTitles();
3132 void Buffer::resetAutosaveTimers() const
3135 d->gui_->resetAutosaveTimers();
3139 bool Buffer::hasGuiDelegate() const
3145 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3154 class AutoSaveBuffer : public ForkedProcess {
3157 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3158 : buffer_(buffer), fname_(fname) {}
3160 virtual shared_ptr<ForkedProcess> clone() const
3162 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3167 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3168 from_utf8(fname_.absFileName())));
3169 return run(DontWait);
3173 virtual int generateChild();
3175 Buffer const & buffer_;
3180 int AutoSaveBuffer::generateChild()
3182 #if defined(__APPLE__)
3183 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3184 * We should use something else like threads.
3186 * Since I do not know how to determine at run time what is the OS X
3187 * version, I just disable forking altogether for now (JMarc)
3189 pid_t const pid = -1;
3191 // tmp_ret will be located (usually) in /tmp
3192 // will that be a problem?
3193 // Note that this calls ForkedCalls::fork(), so it's
3194 // ok cross-platform.
3195 pid_t const pid = fork();
3196 // If you want to debug the autosave
3197 // you should set pid to -1, and comment out the fork.
3198 if (pid != 0 && pid != -1)
3202 // pid = -1 signifies that lyx was unable
3203 // to fork. But we will do the save
3205 bool failed = false;
3206 FileName const tmp_ret = FileName::tempName("lyxauto");
3207 if (!tmp_ret.empty()) {
3208 buffer_.writeFile(tmp_ret);
3209 // assume successful write of tmp_ret
3210 if (!tmp_ret.moveTo(fname_))
3216 // failed to write/rename tmp_ret so try writing direct
3217 if (!buffer_.writeFile(fname_)) {
3218 // It is dangerous to do this in the child,
3219 // but safe in the parent, so...
3220 if (pid == -1) // emit message signal.
3221 buffer_.message(_("Autosave failed!"));
3225 if (pid == 0) // we are the child so...
3234 FileName Buffer::getEmergencyFileName() const
3236 return FileName(d->filename.absFileName() + ".emergency");
3240 FileName Buffer::getAutosaveFileName() const
3242 // if the document is unnamed try to save in the backup dir, else
3243 // in the default document path, and as a last try in the filePath,
3244 // which will most often be the temporary directory
3247 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3248 : lyxrc.backupdir_path;
3249 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3252 string const fname = "#" + d->filename.onlyFileName() + "#";
3254 return makeAbsPath(fname, fpath);
3258 void Buffer::removeAutosaveFile() const
3260 FileName const f = getAutosaveFileName();
3266 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3268 FileName const newauto = getAutosaveFileName();
3270 if (newauto != oldauto && oldauto.exists())
3271 if (!oldauto.moveTo(newauto))
3272 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3276 bool Buffer::autoSave() const
3278 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3279 if (buf->d->bak_clean || isReadonly())
3282 message(_("Autosaving current document..."));
3283 buf->d->bak_clean = true;
3285 FileName const fname = getAutosaveFileName();
3286 if (d->cloned_buffer_) {
3287 // If this buffer is cloned, we assume that
3288 // we are running in a separate thread already.
3289 FileName const tmp_ret = FileName::tempName("lyxauto");
3290 if (!tmp_ret.empty()) {
3292 // assume successful write of tmp_ret
3293 if (tmp_ret.moveTo(fname))
3296 // failed to write/rename tmp_ret so try writing direct
3297 return writeFile(fname);
3299 /// This function is deprecated as the frontend needs to take care
3300 /// of cloning the buffer and autosaving it in another thread. It
3301 /// is still here to allow (QT_VERSION < 0x040400).
3302 AutoSaveBuffer autosave(*this, fname);
3309 string Buffer::bufferFormat() const
3311 string format = params().documentClass().outputFormat();
3312 if (format == "latex") {
3313 if (params().useXetex)
3315 if (params().encoding().package() == Encoding::japanese)
3322 string Buffer::getDefaultOutputFormat() const
3324 if (!params().defaultOutputFormat.empty()
3325 && params().defaultOutputFormat != "default")
3326 return params().defaultOutputFormat;
3327 typedef vector<Format const *> Formats;
3328 Formats formats = exportableFormats(true);
3331 || params().useXetex
3332 || params().encoding().package() == Encoding::japanese) {
3333 if (formats.empty())
3335 // return the first we find
3336 return formats.front()->name();
3338 return lyxrc.default_view_format;
3343 // helper class, to guarantee this gets reset properly
3344 class MarkAsExporting {
3346 MarkAsExporting(Buffer const * buf) : buf_(buf)
3348 LASSERT(buf_, /* */);
3349 buf_->setExportStatus(true);
3353 buf_->setExportStatus(false);
3356 Buffer const * const buf_;
3361 void Buffer::setExportStatus(bool e) const
3363 d->doing_export = e;
3367 bool Buffer::isExporting() const
3369 return d->doing_export;
3373 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3374 bool includeall, string & result_file) const
3376 MarkAsExporting exporting(this);
3377 string backend_format;
3378 OutputParams runparams(¶ms().encoding());
3379 runparams.flavor = OutputParams::LATEX;
3380 runparams.linelen = lyxrc.plaintext_linelen;
3381 runparams.includeall = includeall;
3382 vector<string> backs = backends();
3383 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3384 // Get shortest path to format
3385 Graph::EdgePath path;
3386 for (vector<string>::const_iterator it = backs.begin();
3387 it != backs.end(); ++it) {
3388 Graph::EdgePath p = theConverters().getPath(*it, format);
3389 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3390 backend_format = *it;
3395 if (!put_in_tempdir) {
3396 // Only show this alert if this is an export to a non-temporary
3397 // file (not for previewing).
3398 Alert::error(_("Couldn't export file"), bformat(
3399 _("No information for exporting the format %1$s."),
3400 formats.prettyName(format)));
3404 runparams.flavor = theConverters().getFlavor(path);
3407 backend_format = format;
3408 // FIXME: Don't hardcode format names here, but use a flag
3409 if (backend_format == "pdflatex")
3410 runparams.flavor = OutputParams::PDFLATEX;
3413 string filename = latexName(false);
3414 filename = addName(temppath(), filename);
3415 filename = changeExtension(filename,
3416 formats.extension(backend_format));
3419 updateMacroInstances();
3421 // Plain text backend
3422 if (backend_format == "text") {
3423 runparams.flavor = OutputParams::TEXT;
3424 writePlaintextFile(*this, FileName(filename), runparams);
3427 else if (backend_format == "xhtml") {
3428 runparams.flavor = OutputParams::HTML;
3429 switch (params().html_math_output) {
3430 case BufferParams::MathML:
3431 runparams.math_flavor = OutputParams::MathAsMathML;
3433 case BufferParams::HTML:
3434 runparams.math_flavor = OutputParams::MathAsHTML;
3436 case BufferParams::Images:
3437 runparams.math_flavor = OutputParams::MathAsImages;
3439 case BufferParams::LaTeX:
3440 runparams.math_flavor = OutputParams::MathAsLaTeX;
3444 makeLyXHTMLFile(FileName(filename), runparams);
3445 } else if (backend_format == "lyx")
3446 writeFile(FileName(filename));
3448 else if (isDocBook()) {
3449 runparams.nice = !put_in_tempdir;
3450 makeDocBookFile(FileName(filename), runparams);
3453 else if (backend_format == format) {
3454 runparams.nice = true;
3455 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3457 } else if (!lyxrc.tex_allows_spaces
3458 && contains(filePath(), ' ')) {
3459 Alert::error(_("File name error"),
3460 _("The directory path to the document cannot contain spaces."));
3463 runparams.nice = false;
3464 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3468 string const error_type = (format == "program")
3469 ? "Build" : bufferFormat();
3470 ErrorList & error_list = d->errorLists[error_type];
3471 string const ext = formats.extension(format);
3472 FileName const tmp_result_file(changeExtension(filename, ext));
3473 bool const success = theConverters().convert(this, FileName(filename),
3474 tmp_result_file, FileName(absFileName()), backend_format, format,
3477 // Emit the signal to show the error list or copy it back to the
3478 // cloned Buffer so that it cab be emitted afterwards.
3479 if (format != backend_format) {
3480 if (d->cloned_buffer_) {
3481 d->cloned_buffer_->d->errorLists[error_type] =
3482 d->errorLists[error_type];
3485 // also to the children, in case of master-buffer-view
3486 ListOfBuffers clist = getDescendents();
3487 ListOfBuffers::const_iterator cit = clist.begin();
3488 ListOfBuffers::const_iterator const cen = clist.end();
3489 for (; cit != cen; ++cit) {
3490 if (d->cloned_buffer_) {
3491 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3492 (*cit)->d->errorLists[error_type];
3494 (*cit)->errors(error_type, true);
3498 if (d->cloned_buffer_) {
3499 // Enable reverse dvi or pdf to work by copying back the texrow
3500 // object to the cloned buffer.
3501 // FIXME: There is a possibility of concurrent access to texrow
3502 // here from the main GUI thread that should be securized.
3503 d->cloned_buffer_->d->texrow = d->texrow;
3504 string const error_type = bufferFormat();
3505 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3511 if (put_in_tempdir) {
3512 result_file = tmp_result_file.absFileName();
3516 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3517 // We need to copy referenced files (e. g. included graphics
3518 // if format == "dvi") to the result dir.
3519 vector<ExportedFile> const files =
3520 runparams.exportdata->externalFiles(format);
3521 string const dest = onlyPath(result_file);
3522 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3523 : force_overwrite == ALL_FILES;
3524 CopyStatus status = use_force ? FORCE : SUCCESS;
3526 vector<ExportedFile>::const_iterator it = files.begin();
3527 vector<ExportedFile>::const_iterator const en = files.end();
3528 for (; it != en && status != CANCEL; ++it) {
3529 string const fmt = formats.getFormatFromFile(it->sourceName);
3530 status = copyFile(fmt, it->sourceName,
3531 makeAbsPath(it->exportName, dest),
3532 it->exportName, status == FORCE);
3535 if (status == CANCEL) {
3536 message(_("Document export cancelled."));
3537 } else if (tmp_result_file.exists()) {
3538 // Finally copy the main file
3539 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3540 : force_overwrite != NO_FILES;
3541 if (status == SUCCESS && use_force)
3543 status = copyFile(format, tmp_result_file,
3544 FileName(result_file), result_file,
3546 message(bformat(_("Document exported as %1$s "
3548 formats.prettyName(format),
3549 makeDisplayPath(result_file)));
3551 // This must be a dummy converter like fax (bug 1888)
3552 message(bformat(_("Document exported as %1$s"),
3553 formats.prettyName(format)));
3560 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3561 bool includeall) const
3564 // (1) export with all included children (omit \includeonly)
3565 if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3567 // (2) export with included children only
3568 return doExport(format, put_in_tempdir, false, result_file);
3572 bool Buffer::preview(string const & format, bool includeall) const
3574 MarkAsExporting exporting(this);
3576 // (1) export with all included children (omit \includeonly)
3577 if (includeall && !doExport(format, true, true))
3579 // (2) export with included children only
3580 if (!doExport(format, true, false, result_file))
3582 return formats.view(*this, FileName(result_file), format);
3586 bool Buffer::isExportable(string const & format) const
3588 vector<string> backs = backends();
3589 for (vector<string>::const_iterator it = backs.begin();
3590 it != backs.end(); ++it)
3591 if (theConverters().isReachable(*it, format))
3597 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3599 vector<string> const backs = backends();
3600 vector<Format const *> result =
3601 theConverters().getReachable(backs[0], only_viewable, true);
3602 for (vector<string>::const_iterator it = backs.begin() + 1;
3603 it != backs.end(); ++it) {
3604 vector<Format const *> r =
3605 theConverters().getReachable(*it, only_viewable, false);
3606 result.insert(result.end(), r.begin(), r.end());
3612 vector<string> Buffer::backends() const
3615 v.push_back(bufferFormat());
3616 // FIXME: Don't hardcode format names here, but use a flag
3617 if (v.back() == "latex")
3618 v.push_back("pdflatex");
3619 v.push_back("xhtml");
3620 v.push_back("text");
3626 Buffer::ReadStatus Buffer::extractFromVC()
3628 bool const found = LyXVC::file_not_found_hook(d->filename);
3630 return ReadFileNotFound;
3631 if (!d->filename.isReadableFile())
3637 Buffer::ReadStatus Buffer::loadEmergency()
3639 FileName const emergencyFile = getEmergencyFileName();
3640 if (!emergencyFile.exists()
3641 || emergencyFile.lastModified() <= d->filename.lastModified())
3642 return ReadFileNotFound;
3644 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3645 docstring const text = bformat(_("An emergency save of the document "
3646 "%1$s exists.\n\nRecover emergency save?"), file);
3648 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3649 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3655 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3656 bool const success = (ret_llf == ReadSuccess);
3659 str = _("Document was successfully recovered.");
3661 str = _("Document was NOT successfully recovered.");
3662 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3663 makeDisplayPath(emergencyFile.absFileName()));
3665 int const del_emerg =
3666 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3667 _("&Remove"), _("&Keep"));
3668 if (del_emerg == 0) {
3669 emergencyFile.removeFile();
3671 Alert::warning(_("Emergency file deleted"),
3672 _("Do not forget to save your file now!"), true);
3674 return success ? ReadSuccess : ReadEmergencyFailure;
3677 int const del_emerg =
3678 Alert::prompt(_("Delete emergency file?"),
3679 _("Remove emergency file now?"), 1, 1,
3680 _("&Remove"), _("&Keep"));
3682 emergencyFile.removeFile();
3683 return ReadOriginal;
3693 Buffer::ReadStatus Buffer::loadAutosave()
3695 // Now check if autosave file is newer.
3696 FileName const autosaveFile = getAutosaveFileName();
3697 if (!autosaveFile.exists()
3698 || autosaveFile.lastModified() <= d->filename.lastModified())
3699 return ReadFileNotFound;
3701 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3702 docstring const text = bformat(_("The backup of the document %1$s "
3703 "is newer.\n\nLoad the backup instead?"), file);
3704 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3705 _("&Load backup"), _("Load &original"), _("&Cancel"));
3710 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3711 // the file is not saved if we load the autosave file.
3712 if (ret_llf == ReadSuccess) {
3716 return ReadAutosaveFailure;
3719 // Here we delete the autosave
3720 autosaveFile.removeFile();
3721 return ReadOriginal;
3729 Buffer::ReadStatus Buffer::loadLyXFile()
3731 if (!d->filename.isReadableFile()) {
3732 ReadStatus const ret_rvc = extractFromVC();
3733 if (ret_rvc != ReadSuccess)
3737 ReadStatus const ret_re = loadEmergency();
3738 if (ret_re == ReadSuccess || ret_re == ReadCancel)
3741 ReadStatus const ret_ra = loadAutosave();
3742 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3745 return loadThisLyXFile(d->filename);
3749 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3751 return readFile(fn);
3755 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3757 TeXErrors::Errors::const_iterator cit = terr.begin();
3758 TeXErrors::Errors::const_iterator end = terr.end();
3760 for (; cit != end; ++cit) {
3763 int errorRow = cit->error_in_line;
3764 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3770 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3771 } while (found && id_start == id_end && pos_start == pos_end);
3773 errorList.push_back(ErrorItem(cit->error_desc,
3774 cit->error_text, id_start, pos_start, pos_end));
3779 void Buffer::setBuffersForInsets() const
3781 inset().setBuffer(const_cast<Buffer &>(*this));
3785 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3787 // Use the master text class also for child documents
3788 Buffer const * const master = masterBuffer();
3789 DocumentClass const & textclass = master->params().documentClass();
3791 // do this only if we are the top-level Buffer
3793 checkBibInfoCache();
3795 // keep the buffers to be children in this set. If the call from the
3796 // master comes back we can see which of them were actually seen (i.e.
3797 // via an InsetInclude). The remaining ones in the set need still be updated.
3798 static std::set<Buffer const *> bufToUpdate;
3799 if (scope == UpdateMaster) {
3800 // If this is a child document start with the master
3801 if (master != this) {
3802 bufToUpdate.insert(this);
3803 master->updateBuffer(UpdateMaster, utype);
3804 // Do this here in case the master has no gui associated with it. Then,
3805 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3806 if (!master->d->gui_)
3809 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3810 if (bufToUpdate.find(this) == bufToUpdate.end())
3814 // start over the counters in the master
3815 textclass.counters().reset();
3818 // update will be done below for this buffer
3819 bufToUpdate.erase(this);
3821 // update all caches
3822 clearReferenceCache();
3825 Buffer & cbuf = const_cast<Buffer &>(*this);
3827 LASSERT(!text().paragraphs().empty(), /**/);
3830 ParIterator parit = cbuf.par_iterator_begin();
3831 updateBuffer(parit, utype);
3834 // TocBackend update will be done later.
3837 cbuf.tocBackend().update();
3838 if (scope == UpdateMaster)
3839 cbuf.structureChanged();
3843 static depth_type getDepth(DocIterator const & it)
3845 depth_type depth = 0;
3846 for (size_t i = 0 ; i < it.depth() ; ++i)
3847 if (!it[i].inset().inMathed())
3848 depth += it[i].paragraph().getDepth() + 1;
3849 // remove 1 since the outer inset does not count
3853 static depth_type getItemDepth(ParIterator const & it)
3855 Paragraph const & par = *it;
3856 LabelType const labeltype = par.layout().labeltype;
3858 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3861 // this will hold the lowest depth encountered up to now.
3862 depth_type min_depth = getDepth(it);
3863 ParIterator prev_it = it;
3866 --prev_it.top().pit();
3868 // start of nested inset: go to outer par
3870 if (prev_it.empty()) {
3871 // start of document: nothing to do
3876 // We search for the first paragraph with same label
3877 // that is not more deeply nested.
3878 Paragraph & prev_par = *prev_it;
3879 depth_type const prev_depth = getDepth(prev_it);
3880 if (labeltype == prev_par.layout().labeltype) {
3881 if (prev_depth < min_depth)
3882 return prev_par.itemdepth + 1;
3883 if (prev_depth == min_depth)
3884 return prev_par.itemdepth;
3886 min_depth = min(min_depth, prev_depth);
3887 // small optimization: if we are at depth 0, we won't
3888 // find anything else
3889 if (prev_depth == 0)
3895 static bool needEnumCounterReset(ParIterator const & it)
3897 Paragraph const & par = *it;
3898 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3899 depth_type const cur_depth = par.getDepth();
3900 ParIterator prev_it = it;
3901 while (prev_it.pit()) {
3902 --prev_it.top().pit();
3903 Paragraph const & prev_par = *prev_it;
3904 if (prev_par.getDepth() <= cur_depth)
3905 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3907 // start of nested inset: reset
3912 // set the label of a paragraph. This includes the counters.
3913 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3915 BufferParams const & bp = owner_->masterBuffer()->params();
3916 DocumentClass const & textclass = bp.documentClass();
3917 Paragraph & par = it.paragraph();
3918 Layout const & layout = par.layout();
3919 Counters & counters = textclass.counters();
3921 if (par.params().startOfAppendix()) {
3922 // FIXME: only the counter corresponding to toplevel
3923 // sectioning should be reset
3925 counters.appendix(true);
3927 par.params().appendix(counters.appendix());
3929 // Compute the item depth of the paragraph
3930 par.itemdepth = getItemDepth(it);
3932 if (layout.margintype == MARGIN_MANUAL
3933 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3934 if (par.params().labelWidthString().empty())
3935 par.params().labelWidthString(par.expandLabel(layout, bp));
3937 par.params().labelWidthString(docstring());
3940 switch(layout.labeltype) {
3942 if (layout.toclevel <= bp.secnumdepth
3943 && (layout.latextype != LATEX_ENVIRONMENT
3944 || it.text()->isFirstInSequence(it.pit()))) {
3945 counters.step(layout.counter, utype);
3946 par.params().labelString(
3947 par.expandLabel(layout, bp));
3949 par.params().labelString(docstring());
3952 case LABEL_ITEMIZE: {
3953 // At some point of time we should do something more
3954 // clever here, like:
3955 // par.params().labelString(
3956 // bp.user_defined_bullet(par.itemdepth).getText());
3957 // for now, use a simple hardcoded label
3958 docstring itemlabel;
3959 switch (par.itemdepth) {
3961 itemlabel = char_type(0x2022);
3964 itemlabel = char_type(0x2013);
3967 itemlabel = char_type(0x2217);
3970 itemlabel = char_type(0x2219); // or 0x00b7
3973 par.params().labelString(itemlabel);
3977 case LABEL_ENUMERATE: {
3978 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3980 switch (par.itemdepth) {
3989 enumcounter += "iv";
3992 // not a valid enumdepth...
3996 // Maybe we have to reset the enumeration counter.
3997 if (needEnumCounterReset(it))
3998 counters.reset(enumcounter);
3999 counters.step(enumcounter, utype);
4001 string const & lang = par.getParLanguage(bp)->code();
4002 par.params().labelString(counters.theCounter(enumcounter, lang));
4007 case LABEL_SENSITIVE: {
4008 string const & type = counters.current_float();
4009 docstring full_label;
4011 full_label = owner_->B_("Senseless!!! ");
4013 docstring name = owner_->B_(textclass.floats().getType(type).name());
4014 if (counters.hasCounter(from_utf8(type))) {
4015 string const & lang = par.getParLanguage(bp)->code();
4016 counters.step(from_utf8(type), utype);
4017 full_label = bformat(from_ascii("%1$s %2$s:"),
4019 counters.theCounter(from_utf8(type), lang));
4021 full_label = bformat(from_ascii("%1$s #:"), name);
4023 par.params().labelString(full_label);
4027 case LABEL_NO_LABEL:
4028 par.params().labelString(docstring());
4032 case LABEL_TOP_ENVIRONMENT:
4033 case LABEL_CENTERED_TOP_ENVIRONMENT:
4036 par.params().labelString(par.expandLabel(layout, bp));
4042 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4044 LASSERT(parit.pit() == 0, /**/);
4046 // Set the position of the text in the buffer to be able
4047 // to resolve macros in it.
4048 parit.text()->setMacrocontextPosition(parit);
4050 depth_type maxdepth = 0;
4051 pit_type const lastpit = parit.lastpit();
4052 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4053 // reduce depth if necessary
4054 parit->params().depth(min(parit->params().depth(), maxdepth));
4055 maxdepth = parit->getMaxDepthAfter();
4057 if (utype == OutputUpdate) {
4058 // track the active counters
4059 // we have to do this for the master buffer, since the local
4060 // buffer isn't tracking anything.
4061 masterBuffer()->params().documentClass().counters().
4062 setActiveLayout(parit->layout());
4065 // set the counter for this paragraph
4066 d->setLabel(parit, utype);
4069 InsetList::const_iterator iit = parit->insetList().begin();
4070 InsetList::const_iterator end = parit->insetList().end();
4071 for (; iit != end; ++iit) {
4072 parit.pos() = iit->pos;
4073 iit->inset->updateBuffer(parit, utype);
4079 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4080 WordLangTuple & word_lang, docstring_list & suggestions) const
4084 suggestions.clear();
4085 word_lang = WordLangTuple();
4086 // OK, we start from here.
4087 DocIterator const end = doc_iterator_end(this);
4088 for (; from != end; from.forwardPos()) {
4089 // We are only interested in text so remove the math CursorSlice.
4090 while (from.inMathed()) {
4094 // If from is at the end of the document (which is possible
4095 // when leaving the mathed) LyX will crash later.
4099 from.paragraph().spellCheck();
4100 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4101 if (SpellChecker::misspelled(res)) {
4106 // Do not increase progress when from == to, otherwise the word
4107 // count will be wrong.
4117 Buffer::ReadStatus Buffer::reload()
4120 // c.f. bug http://www.lyx.org/trac/ticket/6587
4121 removeAutosaveFile();
4122 // e.g., read-only status could have changed due to version control
4123 d->filename.refresh();
4124 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4126 ReadStatus const status = loadLyXFile();
4127 if (status == ReadSuccess) {
4132 message(bformat(_("Document %1$s reloaded."), disp_fn));
4134 message(bformat(_("Could not reload document %1$s."), disp_fn));
4144 bool Buffer::saveAs(FileName const & fn)
4146 FileName const old_name = fileName();
4147 FileName const old_auto = getAutosaveFileName();
4148 bool const old_unnamed = isUnnamed();
4155 // bring the autosave file with us, just in case.
4156 moveAutosaveFile(old_auto);
4157 // validate version control data and
4158 // correct buffer title
4159 lyxvc().file_found_hook(fileName());
4161 // the file has now been saved to the new location.
4162 // we need to check that the locations of child buffers
4164 checkChildBuffers();
4168 // reset the old filename and unnamed state
4169 setFileName(old_name);
4170 setUnnamed(old_unnamed);
4176 // FIXME We could do better here, but it is complicated. What would be
4177 // nice is to offer either (a) to save the child buffer to an appropriate
4178 // location, so that it would "move with the master", or else (b) to update
4179 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4180 // complicated, because the code for this lives in GuiView.
4181 void Buffer::checkChildBuffers()
4183 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4184 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4185 for (; it != en; ++it) {
4186 DocIterator dit = it->second;
4187 Buffer * cbuf = const_cast<Buffer *>(it->first);
4188 if (!cbuf || !theBufferList().isLoaded(cbuf))
4190 Inset * inset = dit.nextInset();
4191 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4192 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4193 docstring const & incfile = inset_inc->getParam("filename");
4194 string oldloc = cbuf->absFileName();
4195 string newloc = makeAbsPath(to_utf8(incfile),
4196 onlyPath(absFileName())).absFileName();
4197 if (oldloc == newloc)
4199 // the location of the child file is incorrect.
4200 Alert::warning(_("Included File Invalid"),
4201 bformat(_("Saving this document to a new location has made the file:\n"
4203 "inaccessible. You will need to update the included filename."),
4204 from_utf8(oldloc)));
4206 inset_inc->setChildBuffer(0);
4208 // invalidate cache of children
4209 d->children_positions.clear();
4210 d->position_to_children.clear();